text stringlengths 14 6.51M |
|---|
{$l-}
{*******************************************************************************
* *
* PASCAL-P6 PORTABLE INTERPRETER *
* *
* LICENSING: *
* *
* Copyright (c) 2022, Scott A. Franco *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" *
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE *
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR *
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF *
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS *
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN *
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) *
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
* The views and conclusions contained in the software and documentation are *
* those of the authors and should not be interpreted as representing official *
* policies, either expressed or implied, of the Pascal-P6 project. *
* *
* Portable Pascal assembler/interpreter *
* ************************************* *
* *
* Pascal P6 *
* *
* ETH May 76 *
* *
* Authors: *
* Urs Ammann *
* Kesav Nori *
* Christian Jacobi *
* K. Jensen *
* N. Wirth *
* *
* Address: *
* Institut Fuer Informatik *
* Eidg. Technische Hochschule *
* CH-8096 Zuerich *
* *
* This code is fully documented in the book *
* "Pascal Implementation" *
* by Steven Pemberton and Martin Daniels *
* published by Ellis Horwood, Chichester, UK *
* ISBN: 0-13-653-0311 *
* (also available in Japanese) *
* *
* Steven Pemberton, CWI/AA, *
* Kruislaan 413, 1098 SJ Amsterdam, NL *
* Steven.Pemberton@cwi.nl *
* *
* Adaption from P5 to P6 by: *
* *
* Scott A. Franco *
* samiam@moorecad.com *
* *
* The comments marked with brackets are mine [sam] *
* *
* Please see accompanying documentation concerning this software. *
* *
* ---------------------------------------------------------------------------- *
* *
* LICENSE *
* *
* ---------------------------------------------------------------------------- *
* *
* This software is based on, and represents an enhanced version, of Pascal-P5, *
* which is itself based on Pascal-P4, and was enhanced from that version *
* substantially. *
* *
* Pascal-P4 is unlicensed and exists in the public domain. It has: *
* *
* 1. Been acknowledged as public domain by the author, Niklaus Wirth at ETH *
* Zurich. *
* *
* 2. Has been freely distributed since 1976 with only charges for printing and *
* shipping costs. *
* *
* 3. Has been used as the basis for many projects, both paid and free, by *
* other authors. *
* *
* I, Scott Franco, have extensively expanded the original software. The *
* the changes made by me are held in copyright by me and released under the *
* BSD "2-clause" license, the least restrictive open source license available. *
* *
*******************************************************************************}
{ Set default configuration flags. This gives proper behavior even if no
preprocessor flags are passed in.
The defaults are:
WRDSIZ32 - 32 bit compiler.
ISO7185_PASCAL - uses ISO 7185 standard language only.
PASCALINE - uses the Pascaline standard language.
}
#if !defined(WRDSIZ16) && !defined(WRDSIZ32) && !defined(WRDSIZ64)
#define WRDSIZ32 1
#endif
#if !defined(LENDIAN) && !defined(BENDIAN)
#define LENDIAN
#endif
#if !defined(GNU_PASCAL) && !defined(ISO7185_PASCAL) && !defined(PASCALINE)
#define ISO7185_PASCAL
#endif
program pcom(output,prd,prr);
label 99; { terminate immediately }
const
{ ************************************************************************
Program object sizes and characteristics, sync with pint. These define
the machine specific characteristics of the target.
The configurations are as follows:
type #bits 16 #bits 32 #bits 64
===========================================================
integer 16 32 64
real 32 64 64
char 8 8
boolean 8 8
set 256 256
pointers 16 32 64
marks 16 32 64 (bytes)
File logical number 8 8 8
Both endian types are supported. There is no alignment needed, but you
may wish to use alignment to tune the runtime speed.
The machine characteristics dependent on byte accessable machines. This
table is all you should need to adapt to any byte addressable machine.
}
#ifdef WRDSIZ16
#include "mpb16.inc"
#endif
#ifdef WRDSIZ32
#include "mpb32.inc"
#endif
#ifdef WRDSIZ64
#include "mpb64.inc"
#endif
{ ******************* end of pcom and pint common parameters *********** }
displimit = 300;
maxlevel = 255;
{ strglgth used to define the size of all strings in pcom and pint. With the
string quanta system, string lengths are effectively unlimited, but there
it still sets the size of some buffers in pcom. }
strglgth = 250;
fileal = charal;
(* stackelsize = minimum size for 1 stackelement
= k*stackal
stackal = scm(all other al-constants)
charmax = scm(charsize,charal)
scm = smallest common multiple *)
parmal = stackal;
parmsize = stackelsize;
recal = stackal;
maxaddr = pmmaxint;
maxsp = 85; { number of standard procedures/functions }
maxins = 123; { maximum number of instructions }
maxids = 250; { maximum characters in id string (basically, a full line) }
maxstd = 82; { number of standard identifiers }
maxres = 66; { number of reserved words }
reslen = 9; { maximum length of reserved words }
maxopt = 26; { number of options }
optlen = 10; { maximum length of option words }
explen = 32; { length of exception names }
maxrld = 22; { maximum length of real in digit form }
varsqt = 10; { variable string quanta }
prtlln = 10; { number of label characters to print in dumps }
minocc = 50; { minimum occupancy for case tables }
varmax = 1000; { maximum number of logical variants to track }
cstoccmax=4000; cixmax=10000;
fillen = maxids;
extsrc = '.pas'; { extention for source file }
maxftl = 516; { maximum fatal error }
maxcmd = 250; { size of command line buffer }
maxlin = 250; { size of source line buffer }
{ default field sizes for write }
intdeff = 11; { default field length for integer }
reldeff = 22; { default field length for real }
chrdeff = 1; { default field length for char (usually 1) }
boldeff = 5; { default field length for boolean (usually 5 for 'false' }
#include "version.inc"
{ standard exceptions. Used for extension routines, this is a subset. }
CommandLineTooLong = 1;
FunctionNotImplemented = 2;
FileDeleteFail = 3;
FileNameChangeFail = 4;
type (*describing:*)
(*************)
(*basic symbols*)
(***************)
symbol = (ident,intconst,realconst,stringconst,notsy,mulop,addop,relop,
lparent,rparent,lbrack,rbrack,comma,semicolon,period,arrow,
colon,becomes,range,labelsy,constsy,typesy,varsy,funcsy,progsy,
procsy,setsy,packedsy,arraysy,recordsy,filesy,beginsy,ifsy,
casesy,repeatsy,whilesy,forsy,withsy,gotosy,endsy,elsesy,untilsy,
ofsy,dosy,tosy,downtosy,thensy,nilsy,forwardsy,modulesy,usessy,
privatesy,externalsy,viewsy,fixedsy,processsy,monitorsy,sharesy,
classsy,issy,overloadsy,overridesy,referencesy,joinssy,staticsy,
inheritedsy,selfsy,virtualsy,trysy,exceptsy,extendssy,onsy,
resultsy,operatorsy,outsy,propertysy,channelsy,streamsy,othersy,
hexsy,octsy,binsy,numsy);
operatort = (mul,rdiv,andop,idiv,imod,plus,minus,orop,ltop,leop,geop,gtop,
neop,eqop,inop,noop,xorop,notop,bcmop);
setofsys = set of symbol;
chtp = (letter,number,special,illegal,
chstrquo,chcolon,chperiod,chlt,chgt,chlparen,chspace,chlcmt,chrem,
chhex,choct,chbin);
{ Here is the variable length string containment to save on space. strings
strings are only stored in their length rounded to the nearest 10th. }
strvsp = ^strvs; { pointer to variable length id string }
strvs = record { id string variable length }
str: packed array [1..varsqt] of char; { data contained }
next: strvsp { next }
end;
(*constants*)
(***********)
setty = set of setlow..sethigh;
cstclass = (reel,pset,strg);
csp = ^ constant;
constant = record
next: csp; { next entry link }
case cclass: cstclass of
reel: (rval: real);
pset: (pval: setty);
strg: (slgth: 0..strglgth; sval: strvsp)
end;
valu = record case intval: boolean of
true: (ival: integer);
false: (valp: csp)
end;
(*data structures*)
(*****************)
levrange = 0..maxlevel; addrrange = -maxaddr..maxaddr; stkoff = -maxaddr..maxaddr;
structform = (scalar,subrange,pointer,power,arrays,arrayc,records,files,
tagfld,variant,exceptf);
declkind = (standard,declared);
varinx = 0..varmax;
vartbl = array [0..varmax] of integer; { variant value to logical table }
vartpt = ^vartbl;
stp = ^ structure;
ctp = ^ identifier;
structure = record
snm: integer; { serial number }
next: stp; { next entry link }
marked: boolean; (*for test phase only*)
size: addrrange;
packing: boolean; { packing status }
case form: structform of
scalar: (case scalkind: declkind of
declared: (fconst: ctp); standard: ());
subrange: (rangetype: stp; min,max: valu);
pointer: (eltype: stp);
power: (elset: stp; matchpack: boolean);
arrays: (aeltype,inxtype: stp; tmpl: integer);
arrayc: (abstype: stp);
records: (fstfld: ctp; recvar: stp; recyc: stp);
files: (filtype: stp);
tagfld: (tagfieldp: ctp; fstvar: stp; vart: vartpt;
varts: varinx);
variant: (nxtvar,subvar,caslst: stp; varfld: ctp;
varval: valu; varln: integer);
exceptf: ()
end;
(*names*)
(*******)
{ copyback buffers }
cbbufp =^cbbuf;
cbbuf = record next: cbbufp; { next link }
addr: addrrange; { global address of buffer }
id: ctp; { parameter occupying buffer }
size: addrrange { size of variable in buffer }
end;
idclass = (types,konst,fixedt,vars,field,proc,func,alias);
setofids = set of idclass;
idkind = (actual,formal);
idstr = packed array [1..maxids] of char;
restr = packed array [1..reslen] of char;
optinx = 1..optlen;
optstr = packed array [optinx] of char;
expstr = packed array [1..explen] of char;
csstr = packed array [1..strglgth] of char;
rlstr = packed array [1..maxrld] of char;
keyrng = 1..32; { range of standard call keys }
filnam = packed array [1..fillen] of char; { filename strings }
filptr = ^filrec;
filrec = record next: filptr; fn: filnam; mn: strvsp; f: text;
priv: boolean; linecounts, lineouts: integer end;
partyp = (ptval, ptvar, ptview, ptout);
{ procedure function attribute }
fpattr = (fpanone,fpaoverload,fpastatic,fpavirtual,fpaoverride);
identifier = record
snm: integer; { serial number }
name: strvsp; llink, rlink: ctp;
idtype: stp; next: ctp; keep: boolean;
refer: boolean; cbb: cbbufp;
case klass: idclass of
types: ();
konst: (values: valu);
vars: (vkind: idkind; vlev: levrange; vaddr: addrrange;
isloc: boolean; threat: boolean; forcnt: integer;
part: partyp; hdr: boolean; vext: boolean;
vmod: filptr; inilab: integer; skplab: integer;
ininxt: ctp; dblptr: boolean);
fixedt: (floc: integer; fext: boolean; fmod: filptr);
field: (fldaddr: addrrange; varnt: stp; varlb: ctp;
tagfield: boolean; taglvl: integer;
varsaddr: addrrange; varssize: addrrange;
vartl: integer);
proc, func: (pfaddr: addrrange; pflist: ctp; { param list }
locpar: addrrange; { size of parameters }
locstr: addrrange; { start of locals }
locspc: addrrange; { space occupied by locals }
asgn: boolean; { assigned }
pext: boolean; pmod: filptr; pfattr: fpattr;
pfvaddr: addrrange; pfvid: ctp;
grppar, grpnxt: ctp;
case pfdeckind: declkind of
standard: (key: keyrng);
declared: (pflev: levrange; pfname: integer;
case pfkind: idkind of
actual: (forwdecl, sysrot, extern: boolean);
formal: ()));
alias: (actid: ctp; { actual id })
end;
where = (blck,crec,vrec,rec);
(*expressions*)
(*************)
attrkind = (cst,varbl,expr);
vaccess = (drct,indrct,inxd);
attr = record symptr: ctp; typtr: stp; spv: boolean;
case kind: attrkind of
cst: (cval: valu);
varbl: (packing: boolean; packcom: boolean;
tagfield: boolean; taglvl: integer; varnt: stp;
ptrref: boolean; vartagoff: addrrange;
varssize: addrrange; vartl: integer; pickup: boolean;
dblptr: boolean;
case access: vaccess of
drct: (vlevel: levrange; dplmt: addrrange);
indrct: (idplmt: addrrange);
inxd: ());
expr: ()
end;
(*labels*)
(********)
lbp = ^ labl;
labl = record { 'goto' label }
nextlab: lbp; { next list link }
defined: boolean; { label defining point was seen }
labval, { numeric value of label }
labname: integer; { internal sequental name of label }
labid: strvsp; { id in case of identifier label }
vlevel: levrange; { procedure level of definition }
slevel: integer; { statement level of definition }
ipcref: boolean; { was referenced by another proc/func }
minlvl: integer; { minimum goto reference statement lvl }
bact: boolean; { containing block is active }
refer: boolean { was referred to }
end;
disprange = 0..displimit;
disprec = record (*=blck: id is variable id*)
fname: ctp; flabel: lbp; (*=crec: id is field id in record with*)
fconst: csp; fstruct: stp;
packing: boolean; { used for with derived from packed }
packcom: boolean; { used for with derived from packed }
ptrref: boolean; { used for with derived from pointer }
define: boolean; { is this a defining block? }
modnam: strvsp; { module name for block (if exists) }
inilst: ctp; { initializer list }
oprprc: array [operatort] of ctp; { operator functions }
case occur: where of (* constant address*)
crec: (clev: levrange; (*=vrec: id is field id in record with*)
cdspl: addrrange);(* variable address*)
vrec: (vdspl: addrrange);
blck: (bname: ctp); { block id }
rec: ()
end; (* --> procedure withstatement*)
{ external file tracking entries }
extfilep = ^filerec;
filerec = record filename:idstr; nextfile:extfilep end;
{ case statement tracking entries }
cip = ^caseinfo;
caseinfo = record next: cip;
csstart: integer;
cslabs,cslabe: integer
end;
{ tag tracking entries }
ttp = ^tagtrk;
tagtrk = record
ival: integer;
next: ttp
end;
{ 'with' tracking entries }
wtp = ^wthtrk;
wthtrk = record next: wtp;
sl: integer
end;
stdrng = 1..maxstd; { range of standard name entries }
oprange = 0..maxins;
modtyp = (mtprogram, mtmodule); { type of current module }
byte = 0..255; { 8-bit byte }
bytfil = packed file of byte; { untyped file of bytes }
cmdinx = 1..maxcmd; { index for command line buffer }
cmdnum = 0..maxcmd; { length of command line buffer }
cmdbuf = packed array [cmdinx] of char; { buffer for command line }
lininx = 1..maxlin; { index for source line buffer }
linbuf = packed array [lininx] of char; { buffer for source lines }
(*-------------------------------------------------------------------------*)
var
{ !!! remove this statement for self compile }
#ifndef SELF_COMPILE
prd: text; { input source file }
prr: text; { output code file }
#endif
(*returned by source program scanner
insymbol:
**********)
sy: symbol; (*last symbol*)
op: operatort; (*classification of last symbol*)
val: valu; (*value of last constant*)
lgth: integer; (*length of last string constant*)
id: idstr; (*last identifier (possibly truncated)*)
kk: 1..maxids; (*nr of chars in last identifier*)
ch: char; (*last character*)
eol: boolean; (*end of line flag*)
{ pushback system, last and next variables }
lsy: symbol; lop: operatort; lval: valu; llgth: integer;
lid: idstr; lkk: 1..maxids;
nsy: symbol; nop: operatort; nval: valu; nlgth: integer;
nid: idstr; nkk: 1..maxids; nvalid: boolean;
(*counters:*)
(***********)
chcnt: integer; (*character counter*)
ic,gc: addrrange; (*data location and instruction counter*)
lc,lcs: stkoff;
linecount: integer;
lineout: integer;
(*switches:*)
(***********)
dp: boolean; (*declaration part*)
list: boolean; { -- l: source program listing }
prcode: boolean; { -- c: print symbolic code }
prtables: boolean; { -- t: displaying ident and struct tables }
chkvar: boolean; { -- v: check variant records }
debug: boolean; { -- d: Debug checks }
chkref: boolean; { -- r: Reference checks }
chkudtc, chkudtf: boolean; { -- u: Check undefined tagfields, candidate
and final }
iso7185: boolean; { -- s: restrict to iso7185 language }
dodmplex: boolean; { -- x: dump lexical }
doprtryc: boolean; { -- z: dump recycling tracker counts }
doprtlab: boolean; { -- b: print labels }
dodmpdsp: boolean; { -- y: dump the display }
chkvbk: boolean; { -- i: check VAR block violations }
experr: boolean; { -- ee/experror: expanded error
descriptions }
{ switches passed through to pint }
{ -- o: check arithmetic overflow }
{ -- g: dump label definitions }
{ -- f: perform source level debugging }
{ -- m: break heap returned blocks as occupied }
{ -- h: add source line sets to code }
{ -- n: obey heap space recycle requests }
{ -- p: check reuse of freed entry }
{ -- q: check undefined accesses }
{ -- w: enter debugger on run }
{ -- a: enter debugger on fault }
{ -- e: output P-machine code deck and stop }
{ unused options }
{ -- j }
{ -- k }
{ -- z }
option: array [1..maxopt] of { option array }
boolean;
options: array [1..maxopt] of { option set array }
boolean;
(*pointers:*)
(***********)
parmptr,
intptr,crdptr,realptr,charptr,
boolptr,nilptr,textptr,
exceptptr,stringptr,pstringptr,
byteptr,vectorptr,matrixptr,
abyteptr,scharptr: stp; (*pointers to entries of standard ids*)
utypptr,ucstptr,uvarptr,
ufldptr,uprcptr,ufctptr, (*pointers to entries for undeclared ids*)
fwptr: ctp; (*head of chain of forw decl type ids*)
outputptr,inputptr,
prdptr,prrptr,errorptr,
listptr,commandptr: ctp; { pointers to default files }
usclrptr: ctp; { used to satisfy broken record tag fields }
fextfilep: extfilep; (*head of chain of external files*)
wthstk: wtp; { stack of with entries active }
(*bookkeeping of declaration levels:*)
(************************************)
level: levrange; (*current static level*)
disx, (*level of last id searched by searchid*)
top: disprange; (*top of display*)
ptop: disprange; { top of pile }
display: (*where: means:*)
array [disprange] of disprec;
pile: { pile of joined/class contexts }
array [disprange] of disprec;
(*error messages:*)
(*****************)
errinx: 0..10; (*nr of errors in current source line*)
errlist:
array [1..10] of
packed record pos: integer;
nmr: 1..maxftl
end;
(*expression compilation:*)
(*************************)
gattr: attr; (*describes the expr currently compiled*)
(*structured constants:*)
(***********************)
constbegsys,simptypebegsys,typebegsys,blockbegsys,selectsys,facbegsys,
statbegsys,typedels,pfbegsys: setofsys;
chartp : array[char] of chtp;
rw: array [1..maxres(*nr. of res. words*)] of restr;
rsy: array [1..maxres(*nr. of res. words*)] of symbol;
ssy: array [char] of symbol;
rop: array [1..maxres(*nr. of res. words*)] of operatort;
sop: array [char] of operatort;
na: array [stdrng] of restr;
mn: array [0..maxins] of packed array [1..3] of char;
sna: array [1..maxsp] of packed array [1..4] of char;
opts: array [1..maxopt] of optstr;
optsl: array [1..maxopt] of optstr;
cdx: array [0..maxins] of integer;
cdxs: array [1..6, 1..8] of integer;
pdx: array [1..maxsp] of integer;
ordint: array [char] of integer;
intlabel,mxint10,maxpow10: integer;
entname,extname,nxtname: integer;
errtbl: array [1..maxftl] of integer; { error occurence tracking }
toterr: integer; { total errors in program }
topnew, topmin: integer;
cstptr: array [1..cstoccmax] of csp;
cstptrix: 0..cstoccmax;
(*allows referencing of noninteger constants by an index
(instead of a pointer), which can be stored in the p2-field
of the instruction record until writeout.
--> procedure load, procedure writeout*)
curmod: modtyp; { type of current module }
nammod: strvsp; { name of current module }
incstk: filptr; { stack of included files }
inclst: filptr; { discard list for includes }
cbblst: cbbufp; { copyback buffer entry list }
srclin: linbuf; { buffer for input source lines }
srcinx: lininx; { index for input buffer }
srclen: 0..maxlin; { size of input line }
{ Recycling tracking counters, used to check for new/dispose mismatches. }
strcnt: integer; { strings }
cspcnt: integer; { constants }
stpcnt: integer; { structures }
ctpcnt: integer; { identifiers }
lbpcnt: integer; { label counts }
filcnt: integer; { file tracking counts }
cipcnt: integer; { case entry tracking counts }
ttpcnt: integer; { tag tracking entry counts }
wtpcnt: integer; { with tracking entry counts }
{ serial numbers to label structure and identifier entries for dumps }
ctpsnm: integer;
stpsnm: integer;
{ command line handling }
cmdlin: cmdbuf; { command line }
cmdlen: cmdnum; { length of command line }
cmdpos: cmdinx; { current position in command line }
breakflag: boolean; { user break signaled }
f: boolean; { flag for if error number list entries were printed }
i: 1..maxftl; { index for error number tracking array }
oi: 1..maxopt; oni: optinx;
(*-------------------------------------------------------------------------*)
{ recycling controls }
(*-------------------------------------------------------------------------*)
{ get string quanta }
procedure getstr(var p: strvsp);
begin
new(p); { get new entry }
strcnt := strcnt+1 { count }
end;
{ recycle string quanta list }
procedure putstrs(p: strvsp);
var p1: strvsp;
begin
while p <> nil do begin
p1 := p; p := p^.next; dispose(p1); strcnt := strcnt-1
end
end;
{ get label entry }
procedure getlab(var p: lbp);
begin
new(p); { get new entry }
lbpcnt := lbpcnt+1 { add to count }
end;
{ recycle label entry }
procedure putlab(p: lbp);
begin
putstrs(p^.labid); { release any id label }
dispose(p); { release entry }
lbpcnt := lbpcnt-1 { remove from count }
end;
{ push constant entry to list }
procedure pshcst(p: csp);
begin
{ push to constant list }
p^.next := display[top].fconst;
display[top].fconst := p;
cspcnt := cspcnt+1 { count entries }
end;
{ recycle constant entry }
procedure putcst(p: csp);
begin
{ recycle string if present }
if p^.cclass = strg then putstrs(p^.sval);
{ release entry }
case p^.cclass of
reel: dispose(p, reel);
pset: dispose(p, pset);
strg: dispose(p, strg)
end;
cspcnt := cspcnt-1 { remove from count }
end;
{ push structure entry to list }
procedure pshstc(p: stp);
begin
{ push to structures list }
p^.next := display[top].fstruct;
display[top].fstruct := p;
stpcnt := stpcnt+1; { count entries }
stpsnm := stpsnm+1; { identify entry in dumps }
p^.snm := stpsnm
end;
{ recycle structure entry }
procedure putstc(p: stp);
begin
{ release entry }
case p^.form of
scalar: if p^.scalkind = declared then dispose(p, scalar, declared)
else dispose(p, scalar, standard);
subrange: dispose(p, subrange);
pointer: dispose(p, pointer);
power: dispose(p, power);
arrays: dispose(p, arrays);
arrayc: dispose(p, arrayc);
records: dispose(p, records);
files: dispose(p, files);
tagfld: begin dispose(p^.vart); dispose(p, tagfld) end;
variant: dispose(p, variant);
exceptf: dispose(p, exceptf)
end;
stpcnt := stpcnt-1
end;
{ initialize and register identifier entry }
procedure ininam(p: ctp);
begin
ctpcnt := ctpcnt+1; { count entry }
{ clear fixed entries }
p^.idtype := nil; p^.keep := false; p^.refer := false;
p^.name := nil; p^.llink := nil; p^.rlink := nil; p^.next := nil;
p^.cbb := nil;
ctpsnm := ctpsnm+1; { identify entry in dumps }
p^.snm := ctpsnm
end;
procedure putnam(p: ctp); forward;
{ recycle parameter list }
procedure putparlst(p: ctp);
var p1: ctp;
begin
while p <> nil do begin
p1 := p; p := p^.next;
putnam(p1) { release }
end
end;
{ recycle identifier entry }
procedure putnam{(p: ctp)};
var p1: ctp;
begin
if (p^.klass = proc) or (p^.klass = func) then begin
putparlst(p^.pflist); p^.pflist := nil;
if p = p^.grppar then while p^.grpnxt <> nil do begin
{ scavenge the group list }
p1 := p^.grpnxt; p^.grpnxt := p1^.grpnxt;
putnam(p1) { release }
end
end;
if p^.klass <> alias then putstrs(p^.name); { release name string }
{ release entry according to class }
case p^.klass of
types: dispose(p, types);
konst: dispose(p, konst);
vars: dispose(p, vars);
fixedt: dispose(p, fixedt);
field: dispose(p, field);
proc: if p^.pfdeckind = standard then dispose(p, proc, standard)
else if p^.pfkind = actual then
dispose(p, proc, declared, actual)
else dispose(p, proc, declared, formal);
func: if p^.pfdeckind = standard then dispose(p, func, standard)
else if p^.pfkind = actual then
dispose(p, func, declared, actual)
else dispose(p, func, declared, formal);
alias: dispose(p, alias)
end;
ctpcnt := ctpcnt-1 { remove from count }
end;
{ recycle identifier tree }
procedure putnams(p: ctp);
begin
if p <> nil then begin
putnams(p^.llink); { release left }
putnams(p^.rlink); { release right }
{ "keep" means it is a parameter and stays with it's procedure or
function entry. }
if not p^.keep then putnam(p) { release the id entry }
end
end;
{ initialize display record }
procedure inidsp(var dr: disprec);
var oi: operatort;
begin
with dr do begin
fname := nil;
flabel := nil;
fconst := nil;
fstruct := nil;
packing := false;
packcom := false;
ptrref := false;
define := false;
modnam := nil;
inilst := nil;
for oi := mul to bcmop do oprprc[oi] := nil
end
end;
{ scrub display level }
procedure putdsp(var dr: disprec);
var llp: lbp; lvp: csp; lsp: stp; oi: operatort;
{ release substructure }
procedure putsub(p: stp);
var p1: stp;
begin
{ clear record recycle list if record }
if p^.form = records then begin
{ clear structure list }
while p^.recyc <> nil do begin
{ remove top of list }
p1 := p^.recyc; p^.recyc := p1^.next;
putsub(p1) { release that element }
end;
putnams(p^.fstfld) { clear id list }
end else if p^.form = tagfld then begin
if p^.tagfieldp <> nil then
{ recycle anonymous tag fields }
if p^.tagfieldp^.name = nil then putnam(p^.tagfieldp)
end;
putstc(p) { release head entry }
end;
begin { putdsp }
putnams(dr.fname); { dispose of identifier tree }
{ dispose of label list }
while dr.flabel <> nil do begin
llp := dr.flabel; dr.flabel := llp^.nextlab; putlab(llp)
end;
{ dispose of constant list }
while dr.fconst <> nil do begin
lvp := dr.fconst; dr.fconst := lvp^.next; putcst(lvp)
end;
{ dispose of structure list }
while dr.fstruct <> nil do begin
{ remove top from list }
lsp := dr.fstruct; dr.fstruct := lsp^.next; putsub(lsp)
end;
{ dispose of module name }
putstrs(dr.modnam);
for oi := mul to bcmop do
if dr.oprprc[oi] <> nil then putnam(dr.oprprc[oi]);
end; { putdsp }
{ scrub all display levels until given }
procedure putdsps(l: disprange);
var t: disprange;
begin
if l > top then begin
writeln('*** Error: Compiler internal error');
goto 99
end;
t := top;
while t > l do begin
putdsp(display[t]); t := t-1
end
end;
{ scrub the pile }
procedure putpile;
var t: disprange;
begin
if ptop > 0 then for t := ptop-1 downto 0 do putdsp(pile[t])
end;
{ get external file entry }
procedure getfil(var p: extfilep);
begin
new(p); { get new entry }
filcnt := filcnt+1 { count entry }
end;
{ recycle external file entry }
procedure putfil(p: extfilep);
begin
dispose(p); { release entry }
filcnt := filcnt-1 { count entry }
end;
{ get case tracking entry }
procedure getcas(var p: cip);
begin
new(p); { get new entry }
cipcnt := cipcnt+1 { count entry }
end;
{ recycle case tracking entry }
procedure putcas(p: cip);
begin
dispose(p); { release entry }
cipcnt := cipcnt-1 { count entry }
end;
{ get tag tracking entry }
procedure gettag(var p: ttp);
begin
new(p); { get new entry }
ttpcnt := ttpcnt+1 { count entry }
end;
{ recycle tag tracking entry }
procedure puttag(p: ttp);
begin
dispose(p); { release entry }
ttpcnt := ttpcnt-1 { count entry }
end;
{ push to with stack }
procedure pshwth(sl: integer);
var p: wtp;
begin
new(p); { get a new entry }
p^.next := wthstk; { push to stack }
wthstk := p;
p^.sl := sl; { mark level }
wtpcnt := wtpcnt+1 { count entry }
end;
{ pop from with stack }
procedure popwth;
var p: wtp;
begin
if wthstk = nil then begin
writeln; writeln('*** Compiler error: with stack underflow');
goto 99
end else begin
p := wthstk;
wthstk := p^.next;
dispose(p);
wtpcnt := wtpcnt-1
end
end;
{ get copyback buffer }
procedure getcbb(var p: cbbufp; id: ctp; size: integer);
var lp, fp: cbbufp;
begin p := nil;
if id <> nil then if id^.idtype <> nil then begin
lp := cbblst; fp := nil;
{ find a matching buffer }
while lp <> nil do begin
if (lp^.id = nil) and (lp^.size = size) then fp := lp;
lp := lp^.next
end;
if fp = nil then begin { no existing buffer, or all occupied, get new }
new(fp); fp^.next := lp; lp := fp; fp^.addr := gc;
gc := gc+size
end;
fp^.id := id;
fp^.size := size;
p := fp
end
end;
{ release copyback buffer }
procedure putcbb(p: cbbufp);
begin
if p <> nil then p^.id := nil
end;
(*-------------------------------------------------------------------------*)
{ character and string quanta functions }
(*-------------------------------------------------------------------------*)
{ find lower case of character }
function lcase(c: char): char;
begin
if c in ['A'..'Z'] then c := chr(ord(c)-ord('A')+ord('a'));
lcase := c
end { lcase };
{ find reserved word string equal to id string }
function strequri(a: restr; var b: idstr): boolean;
var m: boolean; i: integer;
begin
m := true;
for i := 1 to reslen do if lcase(a[i]) <> lcase(b[i]) then m := false;
for i := reslen+1 to maxids do if b[i] <> ' ' then m := false;
strequri := m
end { equstr };
{ write variable length id string to file }
procedure writev(var f: text; s: strvsp; fl: integer);
var i: integer; c: char;
begin i := 1;
while fl > 0 do begin
c := ' '; if s <> nil then begin c := s^.str[i]; i := i+1 end;
write(f, c); fl := fl-1;
if i > varsqt then begin s := s^.next; i := 1 end
end
end;
{ find padded length of variable length id string }
function lenpv(s: strvsp): integer;
var lc, cc, i: integer;
begin lc := 0; cc := 0;
while s <> nil do begin
for i := 1 to varsqt do begin
cc := cc+1; if s^.str[i] <> ' ' then lc := cc
end;
s := s^.next
end;
lenpv := lc
end;
{ write padded string to file }
procedure writevp(var f: text; s: strvsp);
var l, cc, i: integer;
begin l := lenpv(s); cc := 0;
while s <> nil do begin
for i := 1 to varsqt do begin
cc := cc+1; if cc <= l then write(f, s^.str[i])
end;
s := s^.next
end
end;
{ assign identifier fixed to variable length string, including allocation }
procedure strassvf(var a: strvsp; var b: idstr);
var i, j, l: integer; p, lp: strvsp;
begin l := maxids; p := nil; a := nil; j := 1;
while (l > 1) and (b[l] = ' ') do l := l-1; { find length of fixed string }
if b[l] = ' ' then l := 0;
for i := 1 to l do begin
if j > varsqt then p := nil;
if p = nil then begin
getstr(p); p^.next := nil; j := 1;
if a = nil then a := p else lp^.next := p; lp := p
end;
p^.str[j] := b[i]; j := j+1
end;
if p <> nil then for j := j to varsqt do p^.str[j] := ' '
end;
{ assign reserved word fixed to variable length string, including allocation }
procedure strassvr(var a: strvsp; b: restr);
var i, j, l: integer; p, lp: strvsp;
begin l := reslen; p := nil; a := nil; lp := nil; j := 1;
while (l > 1) and (b[l] = ' ') do l := l-1; { find length of fixed string }
if b[l] = ' ' then l := 0;
for i := 1 to l do begin
if j > varsqt then p := nil;
if p = nil then begin
getstr(p); p^.next := nil; j := 1;
if a = nil then a := p else lp^.next := p; lp := p
end;
p^.str[j] := b[i]; j := j+1
end;
if p <> nil then for j := j to varsqt do p^.str[j] := ' '
end;
{ assign exception word fixed to variable length string, including allocation }
procedure strassve(var a: strvsp; b: expstr);
var i, j, l: integer; p, lp: strvsp;
begin l := explen; p := nil; a := nil; lp := nil; j := 1;
while (l > 1) and (b[l] = ' ') do l := l-1; { find length of fixed string }
if b[l] = ' ' then l := 0;
for i := 1 to l do begin
if j > varsqt then p := nil;
if p = nil then begin
getstr(p); p^.next := nil; j := 1;
if a = nil then a := p else lp^.next := p; lp := p
end;
p^.str[j] := b[i]; j := j+1
end;
if p <> nil then for j := j to varsqt do p^.str[j] := ' '
end;
{ assign constant string fixed to variable length string, including allocation }
procedure strassvc(var a: strvsp; b: csstr; l: integer);
var i, j: integer; p, lp: strvsp;
begin p := nil; a := nil; lp := nil; j := 1;
for i := 1 to l do begin
if j > varsqt then p := nil;
if p = nil then begin
getstr(p); p^.next := nil; j := 1;
if a = nil then a := p else lp^.next := p; lp := p
end;
p^.str[j] := b[i]; j := j+1
end;
if p <> nil then for j := j to varsqt do p^.str[j] := ' '
end;
{ assign variable length string to fixed identifier }
procedure strassfv(var a: idstr; b: strvsp);
var i, j: integer;
begin for i := 1 to maxids do a[i] := ' '; i := 1;
while b <> nil do begin
for j := 1 to varsqt do begin a[i] := b^.str[j]; i := i+1 end;
b := b^.next
end
end;
{ compare variable length id strings }
function strequvv(a, b: strvsp): boolean;
var m: boolean; i: integer;
begin
m := true;
while (a <> nil) and (b <> nil) do begin
for i := 1 to varsqt do if lcase(a^.str[i]) <> lcase(b^.str[i]) then m := false;
a := a^.next; b := b^.next
end;
if a <> b then m := false;
strequvv := m
end;
{ compare variable length id strings, a < b }
function strltnvv(a, b: strvsp): boolean;
var i: integer; ca, cb: char;
begin ca := ' '; cb := ' ';
while (a <> nil) or (b <> nil) do begin
i := 1;
while (i <= varsqt) and ((a <> nil) or (b <> nil)) do begin
if a <> nil then ca := lcase(a^.str[i]) else ca := ' ';
if b <> nil then cb := lcase(b^.str[i]) else cb := ' ';
if ca <> cb then begin a := nil; b := nil end;
i := i+1
end;
if a <> nil then a := a^.next; if b <> nil then b := b^.next
end;
strltnvv := ca < cb
end;
{ compare variable length id string to fixed }
function strequvf(a: strvsp; var b: idstr): boolean;
var m: boolean; i, j: integer; c: char;
begin
m := true; j := 1;
for i := 1 to maxids do begin
c := ' '; if a <> nil then begin c := a^.str[j]; j := j+1 end;
if lcase(c) <> lcase(b[i]) then m := false;
if j > varsqt then begin a := a^.next; j := 1 end
end;
strequvf := m
end;
{ compare variable length id string to fixed, a < b }
function strltnvf(a: strvsp; var b: idstr): boolean;
var m: boolean; i, j, f: integer; c: char;
begin
m := true; i := 1; j := 1;
while i < maxids do begin
c := ' '; if a <> nil then begin c := a^.str[j]; j := j+1 end;
if lcase(c) <> lcase(b[i]) then begin f := i; i := maxids end else i := i+1;
if j > varsqt then begin a := a^.next; j := 1 end
end;
strltnvf := lcase(c) < lcase(b[f])
end;
{ get character from variable length string }
function strchr(a: strvsp; x: integer): char;
var c: char; i: integer; q: integer;
begin
c := ' '; i := 1; q := 1;
while i < x do begin
if q >= varsqt then begin q := 1; if a <> nil then a := a^.next end
else q := q+1;
i := i+1
end;
if a <> nil then c := a^.str[q];
strchr := c
end;
{ put character to variable length string }
procedure strchrass(var a: strvsp; x: integer; c: char);
var i: integer; q: integer; p, l: strvsp;
procedure getsqt;
var y: integer;
begin
if p = nil then begin getstr(p); for y := 1 to varsqt do p^.str[y] := ' ';
p^.next := nil; if a = nil then a := p else l^.next := p
end
end;
begin
i := 1; q := 1; p := a; l := nil;
getsqt;
while i < x do begin
if q >= varsqt then begin q := 1; l := p; p := p^.next; getsqt end
else q := q+1;
i := i+1
end;
p^.str[q] := c
end;
{ concatenate reserved word fixed to variable length string, including
allocation }
procedure strcatvr(var a: strvsp; b: restr);
var i, j, l: integer;
begin l := reslen;
while (l > 1) and (b[l] = ' ') do l := l-1; { find length of fixed string }
if b[l] = ' ' then l := 0;
j := lenpv(a); j := j+1;
for i := 1 to l do begin strchrass(a, j, b[i]); j := j+1 end
end;
(*-------------------------------------------------------------------------*)
{ Boolean integer emulation }
(*-------------------------------------------------------------------------*)
function bnot(a: integer): integer;
var i, r, p: integer;
begin
r := 0; p := 1; i := maxint;
while i <> 0 do begin
if not odd(a) then r := r+p;
a := a div 2; i := i div 2;
if i > 0 then p := p*2
end;
bnot := r
end;
function bor(a, b: integer): integer;
var i, r, p: integer;
begin
r := 0; p := 1; i := maxint;
while i <> 0 do begin
if odd(a) or odd(b) then r := r+p;
a := a div 2; b := b div 2; i := i div 2;
if i > 0 then p := p*2
end;
bor := r
end;
function band(a, b: integer): integer;
var i, r, p: integer;
begin
r := 0; p := 1; i := maxint;
while i <> 0 do begin
if odd(a) and odd(b) then r := r+p;
a := a div 2; b := b div 2; i := i div 2;
if i > 0 then p := p*2
end;
band := r
end;
function bxor(a, b: integer): integer;
var i, r, p: integer;
begin
r := 0; p := 1; i := maxint;
while i <> 0 do begin
if odd(a) <> odd(b) then r := r+p;
a := a div 2; b := b div 2; i := i div 2;
if i > 0 then p := p*2
end;
bxor := r
end;
(*--------------------------------------------------------------------*)
{ Language extension routines }
{ support I/O errors from extension library }
procedure errore(e: integer);
begin writeln; write('*** I/O error: ');
case e of
FileDeleteFail: writeln('File delete fail');
FileNameChangeFail: writeln('File name change fail');
CommandLineTooLong: writeln('Command line too long');
FunctionNotImplemented: writeln('Function not implemented');
end;
goto 99
end;
procedure errorv(v: integer);
begin
errore(v)
end;
{ "fileofy" routines for command line processing.
These routines implement the command header file by reading from a
buffer where the command line is stored. The assumption here is that
there is a fairly simple call to retrieve the command line.
If it is wanted, the command file primitives can be used to implement
another type of interface, say, reading from an actual file.
The command buffer is designed to never be completely full.
The last two locations indicate:
maxcmd: end of file
maxcmd-1: end of line
These locations are always left as space, thus eoln returns space as
the standard specifies.
}
function bufcommand: char;
begin bufcommand := cmdlin[cmdpos] end;
procedure getcommand;
begin if cmdpos <= cmdlen+1 then cmdpos := cmdpos+1 end;
function eofcommand: boolean;
begin eofcommand := cmdpos > cmdlen+1 end;
function eolncommand: boolean;
begin eolncommand := cmdpos >= cmdlen+1 end;
procedure readlncommand;
begin cmdpos := maxcmd end;
#ifdef GNU_PASCAL
#include "extend_gnu_pascal.inc"
#endif
#ifdef ISO7185_PASCAL
#include "extend_iso7185_pascal.inc"
#endif
#ifdef PASCALINE
#include "extend_pascaline.inc"
#endif
(*-------------------------------------------------------------------------*)
{ dump the display }
procedure prtdsp;
var i: integer;
procedure prtlnk(p: ctp; f: integer);
var i: integer;
begin
if p <> nil then begin
for i := 1 to f do write(' ');
writev(output, p^.name, 10); writeln;
if p^.llink <> nil then prtlnk(p^.llink, f+3);
if p^.rlink <> nil then prtlnk(p^.rlink, f+3)
end
end;
begin
writeln;
writeln('Display:');
writeln;
for i := 0 to displimit do if display[i].fname <> nil then begin
writeln('level ', i:1);
writeln;
prtlnk(display[i].fname, 0);
writeln
end;
writeln;
end;
{ this block of functions wraps source reads ******************************* }
function incact: boolean;
begin
incact := incstk <> nil
end;
function fileeof: boolean;
begin
if incact then fileeof := eof(incstk^.f) else fileeof := eof(prd);
end;
function fileeoln: boolean;
begin
if incact then fileeoln := eoln(incstk^.f)
else fileeoln := eoln(prd);
end;
procedure readline;
var ovf: boolean;
i: lininx;
begin
ovf := false;
srclen := 0; srcinx := 1; for i := 1 to maxlin do srclin[i] := ' ';
if not fileeof then begin
while not fileeoln do begin
if incact then read(incstk^.f, srclin[srcinx])
else read(prd, srclin[srcinx]);
if srclen = maxlin-1 then begin
if not ovf then
begin writeln; writeln('*** Input line too long, truncated') end;
ovf := true
end else begin srclen := srclen+1; srcinx := srcinx+1 end
end;
if incact then readln(incstk^.f)
else readln(prd);
end;
srcinx := 1;
if prcode then
if srclen = 0 then writeln(prr, '!')
else writeln(prr, '! ', srclin:srclen)
end;
function eofinp: boolean;
begin
if srclen <> 0 then eofinp := false else eofinp := fileeof
end;
function eolninp: boolean;
begin
if eofinp then eolninp := true
else if srcinx > srclen then eolninp := true
else eolninp := false
end;
function bufinp: char;
begin
if not eolninp then bufinp := srclin[srcinx] else bufinp := ' '
end;
procedure readinp(var c: char);
begin
c := bufinp;
if eolninp then readline else srcinx := srcinx+1
end;
{ ************************************************************************** }
procedure errmsg(ferrnr: integer);
begin case ferrnr of
1: write('Error in simple type');
2: write('Identifier expected');
3: write('''program'' expected');
4: write(''')'' expected');
5: write(''':'' expected');
6: write('Illegal symbol');
7: write('Error in parameter list');
8: write('''of'' expected');
9: write('''('' expected');
10: write('Error in type');
11: write('''['' expected');
12: write(''']'' expected');
13: write('''end'' expected');
14: write(''';'' expected');
15: write('Integer expected');
16: write('''='' expected');
17: write('''begin'' expected');
18: write('Error in declaration part');
19: write('Error in field-list');
20: write(''','' expected');
21: write('''.'' expected');
22: write('Integer or identifier expected');
23: write('''except'' expected');
24: write('''on'' or ''except'' expected');
25: write('Illegal source character');
26: write('String constant too long');
27: write(''','' or '')'' expected');
28: write('''array'' expected');
29: write(''','' or ''end'' expected');
30: write('''..'' expected');
50: write('Error in constant');
51: write(''':='' expected');
52: write('''then'' expected');
53: write('''until'' expected');
54: write('''do'' expected');
55: write('''to''/''downto'' expected');
56: write('''if'' expected');
57: write('''file'' expected');
58: write('Error in factor');
59: write('Error in variable');
101: write('Identifier declared twice');
102: write('Low bound exceeds highbound');
103: write('Identifier is not of appropriate class');
104: write('Identifier not declared');
105: write('Sign not allowed');
106: write('Number expected');
107: write('Incompatible subrange types');
109: write('Type must not be real');
110: write('Tagfield type must be scalar or subrange');
111: write('Incompatible with tagfield type');
112: write('Index type must not be real');
113: write('Index type must be scalar or subrange');
114: write('Base type must not be real');
115: write('Base type must be scalar or subrange');
116: write('Error in type of standard procedure parameter');
117: write('Unsatisfied forward reference');
118: write('Forward reference type identifier in variable declaration');
119: write('Forward declared; repetition of parameter list not allowed');
120: write('Function result type must be scalar, subrange or pointer');
121: write('File value parameter, or parameter containing file, not allowed');
122: write('Forward declared function; repetition of result type not allowed');
123: write('Missing result type in function declaration');
124: write('F-format for real only');
125: write('Error in type of standard function parameter');
126: write('Number of parameters does not agree with declaration');
127: write('Illegal parameter substitution');
128: write('Result type of parameter function does not agree with declaration');
129: write('Type conflict of operands');
130: write('Expression is not of set type');
131: write('Tests on equality allowed only');
132: write('Strict inclusion not allowed');
133: write('File comparison not allowed');
134: write('Illegal type of operand(s)');
135: write('Type of operand must be Boolean');
136: write('Set element type must be scalar or subrange');
137: write('Set element types not compatible');
138: write('Type of variable is not array');
139: write('Index type is not compatible with declaration');
140: write('Type of variable is not record');
141: write('Type of variable must be file or pointer');
142: write('Illegal parameter substitution');
143: write('Illegal type of loop control variable');
144: write('Illegal type of expression');
145: write('Type conflict');
146: write('Assignment of files not allowed');
147: write('Label type incompatible with selecting expression');
148: write('Subrange bounds must be scalar');
149: write('Index type must not be integer');
150: write('Assignment to standard function is not allowed');
151: write('Assignment to formal function is not allowed');
152: write('No such field in this record');
153: write('Type error in read');
154: write('Actual parameter must be a variable');
155: write('Control variable must not be declared on intermediate');
156: write('Multidefined case label');
157: write('Too many cases in case statement');
158: write('Missing corresponding variant declaration');
159: write('Real or string tagfields not allowed');
160: write('Previous declaration was not forward');
161: write('Again forward declared');
162: write('Parameter size must be constant');
163: write('Missing variant in declaration');
164: write('Substitution of standard proc/func not allowed');
165: write('Multidefined label');
166: write('Multideclared label');
167: write('Undeclared label');
168: write('Undefined label');
169: write('Error in base set');
170: write('Value parameter expected');
171: write('Standard file was redeclared');
172: write('Undeclared external file');
173: write('Fortran procedure or function expected');
174: write('Pascal procedure or function expected');
175: write('Missing file "input" in program heading');
176: write('Missing file "output" in program heading');
177: write('Assiqnment to function identifier not allowed here');
178: write('Multidefined record variant');
179: write('X-opt of actual proc/funcdoes not match formal declaration');
180: write('Control variable must not be formal');
181: write('Constant part of address out of ranqe');
182: write('identifier too long');
183: write('For index variable must be local to this block');
184: write('Interprocedure goto does not reference outter block of destination');
185: write('Goto references deeper nested statement');
186: begin write('Label referenced by goto at lesser statement level or ');
write('differently nested statement') end;
187: write('Goto references label in different nested statement');
188: write('Label referenced by goto in different nested statement');
189: write('Parameter lists of formal and actual parameters not congruous');
190: write('File component may not contain other files');
191: write('Cannot assign from file or component containing files');
192: write('Assignment to function that is not active');
193: write('Function does not assign to result');
194: write('Exponent too large');
195: write('For loop index is threatened');
197: write('Var parameter cannot be packed');
198: write('Var parameter cannot be a tagfield');
199: write('Var parameter must be same type');
200: write('Tagfield constants must cover entire tagfield type');
201: write('Error in real constant: digit expected');
202: write('String constant must not exceed source line');
203: write('Integer constant exceeds range');
204: write('8 or 9 in octal number');
205: write('Zero string not allowed');
206: write('Integer part of real constant exceeds ranqe');
207: write('Digit beyond radix');
208: write('Type must be string');
209: write('''procedure'' or ''function'' expected');
210: write('No function active to set result');
211: write('Anonymous function result must be at function end');
212: write('Function result assigned before result given');
213: write('Cannot take boolean integer operation on negative');
214: write('Must apply $, & or % posfix modifier to integer');
215: write('Must apply * (padded string field) to string');
216: write('Original and forwarded procedure/function parameters not congruous');
217: write('Missing file ''prd'' in program heading');
218: write('Missing file ''prr'' in program heading');
219: write('Missing file ''error'' in program heading');
220: write('Missing file ''list'' in program heading');
221: write('Missing file ''command'' in program heading');
222: write('Value out of character range');
223: write('Type converter/restrictor must be scalar or subrange');
224: write('Type to be converted must be scalar or subrange');
225: write('In constant range first value must be less than or equal to second');
226: write('Type of variable is not exception');
227: write('Type too complex to track');
228: write('Cannot apply ''virtual'' attribute to nested procedure or function');
229: write('Cannot apply ''override'' attribute to nested procedure or function');
230: write('Cannot override virtual from same module, must be external');
231: write('No virtual found to override');
232: write('Cannot overload virtual procedure or function');
233: write('Inherited not applied to user procedure/function call');
234: write('Inherited applied to non-virtual procedure/function');
235: write('Override not defined for inherited call');
236: write('Type error in write');
237: write('Array size too large');
238: write('Invalid array length, must be >= 1');
239: write('Variant case exceeds allowable range');
240: write('Header parameter already included');
241: write('Invalid tolken separator');
242: write('Identifier referenced before defining point');
243: write('Initializer expression must be integer');
244: write('Type incorrect for fixed');
245: write('Initializer incompatible with fixed element');
246: write('Initializer out of range of fixed element type');
247: write('Incorrect number of initializers for type');
248: write('Fixed cannot contain variant record');
249: write('New overload ambiguous with previous');
250: write('Too many nested scopes of identifiers');
251: write('Too many nested procedures and/or functions');
252: write('Too many forward references of procedure entries');
253: write('Procedure too long');
254: write('Too many long constants in this procedure');
255: write('Too many errors on this source line');
256: write('Too many external references');
257: write('Too many externals');
258: write('Too many local files');
259: write('Expression too complicated');
260: write('Too many exit labels');
261: write('Label beyond valid integral value (>9999)');
262: write('Function/procedure cannot be applied to text files');
263: write('No function to open/close external files');
264: write('External file not found');
265: write('Filename too long');
266: write('''private'' has no meaning here');
267: write('Too many nested module joins');
268: write('Qualified identifier not found');
269: write('Number of initializers for parameterised declaration do not ',
'match');
270: write('Container array type specified without initializer(s)');
271: write('Number of initializers does not match container array levels');
272: write('Cannot declare container array in fixed context');
273: write('Must be container array');
274: write('Function result type must be scalar, subrange, pointer, set, ',
'array or record');
275: write('Number of parameters does not agree with declaration of any ',
'overload');
276: write('Different overload parameters converge with different modes');
277: write('No overload found to match parameter');
278: write('Must be variable reference');
279: write('''procedure'', ''function'' or ''operator'' expected');
280: write('Attribute has no meaning used on operator overload');
281: write('Expression/assignment operator expected');
282: write('Overload operator is ambiguous with system operator');
283: write('New operator overload ambiguous with previous');
284: write('Different operator overload parameters converge with ',
'different modes');
285: write('Parameter type not allowed in operator overload parameter ');
286: write('Parameter mode not allowed in operator overload parameter ');
287: write('Variable reference is not addressable');
288: write('Left side of assignment overload operator must be out mode');
289: write('Var parameter must be compatible with parameter');
290: write('Cannot threaten view parameter');
291: write('Set element out of implementation range');
292: write('Function expected in this context');
293: write('Procedure expected in this context');
294: write('Cannot forward an external declaration');
295: write('procedure or function previously declared external');
300: write('Division by zero');
301: write('No case provided for this value');
302: write('Index expression out of bounds');
303: write('Value to be assigned is out of bounds');
304: write('Element expression out of range');
305: write('Cannot use non-decimal with real format');
306: write('Integer overflow');
397: write('Feature not valid in ISO 7185 Pascal');
398: write('Implementation restriction');
{ as of the implementation of full ISO 7185, this error is no longer used }
399: write('Feature not implemented');
{ * marks spared compiler errors }
400,401,402,403,404,406,407,
500,501,502,503,
504,505,506,507,508,509,510,511,512,513,514,515,516: write('Compiler internal error');
end
end;
procedure endofline;
var lastpos,freepos,currpos,currnmr,f,j,k: integer; df: boolean;
begin
if errinx > 0 then (*output error messages*)
begin write(linecount:6,' **** ':9);
lastpos := -1; freepos := 1;
for k := 1 to errinx do
begin
with errlist[k] do
begin currpos := pos; currnmr := nmr end;
if currpos = lastpos then write(',')
else
begin
while freepos < currpos do
begin write(' '); freepos := freepos + 1 end;
write('^');
lastpos := currpos
end;
if currnmr < 10 then f := 1
else if currnmr < 100 then f := 2
else f := 3;
write(currnmr:f);
freepos := freepos + f + 1
end;
writeln;
if experr then begin
for k := 1 to errinx do
begin df := false;
for j := 1 to k-1 do
if errlist[j].nmr = errlist[k].nmr then df := true;
if not df then begin
write(linecount:6,' **** ':9); write(errlist[k].nmr:3, ' ');
errmsg(errlist[k].nmr); writeln
end
end
end;
errinx := 0;
end;
linecount := linecount + 1;
if list and (not eofinp) then
begin write(linecount:6,' ':2);
if dp then write(lc:7) else write(ic:7);
write(' ')
end;
chcnt := 0
end (*endofline*) ;
{ output lines passed to intermediate }
procedure outline;
begin
while lineout < linecount do begin
lineout := lineout+1;
{ output line marker in intermediate file }
if not eofinp and prcode then begin
writeln(prr, ':', lineout:1);
end
end
end;
procedure markline;
begin
outline;
if prcode then writeln(prr, ':', linecount:1)
end;
{ check in private section }
function inpriv: boolean;
begin inpriv := false;
if incact then inpriv := incstk^.priv
end;
procedure error(ferrnr: integer);
begin
if not incact then begin { supress errors in includes }
{ This diagnostic is here because error buffers error numbers til the end
of line, and sometimes you need to know exactly where they occurred. }
#ifdef IMM_ERR
writeln; writeln('error: ', ferrnr:1);
#endif
errtbl[ferrnr] := errtbl[ferrnr]+1; { track this error }
if errinx >= 9 then
begin errlist[10].nmr := 255; errinx := 10 end
else
begin errinx := errinx + 1;
errlist[errinx].nmr := ferrnr
end;
errlist[errinx].pos := chcnt;
toterr := toterr+1
end
end (*error*) ;
{ chkstd: called whenever a non-ISO7185 construct is being processed }
procedure chkstd;
begin
if iso7185 then error(397)
end;
procedure prtsym(sy: symbol);
begin
case sy of
ident: write('ident'); intconst: write('intconst');
realconst: write('realconst'); stringconst: write('string const');
notsy: write('not'); mulop: write('*'); addop: write('+');
relop: write('<'); lparent: write('('); rparent: write(')');
lbrack: write('['); rbrack: write(']'); comma: write(',');
semicolon: write(';'); period: write('.'); arrow: write('^');
colon: write(':'); becomes: write(':='); range: write('..');
labelsy: write('label'); constsy: write('const'); typesy: write('type');
varsy: write('var'); funcsy: write('function'); progsy: write('program');
procsy: write('procedure'); setsy: write('set');
packedsy: write('packed'); arraysy: write('array');
recordsy: write('record'); filesy: write('file');
beginsy: write('begin'); ifsy: write('if'); casesy: write('case');
repeatsy: write('repeat'); whilesy: write('while');
forsy: write('for'); withsy: write('with'); gotosy: write('goto');
endsy: write('end'); elsesy: write('else'); untilsy: write('until');
ofsy: write('of'); dosy: write('do'); tosy: write('to');
downtosy: write('downto'); thensy: write('then');
forwardsy: write('forward'); modulesy: write('module');
usessy: write('uses'); privatesy:write('private');
externalsy: write('external'); viewsy: write('view');
fixedsy: write('fixed'); processsy: write('process');
monitorsy: write('monitor'); sharesy: write('share');
classsy: write('class'); issy: write('is');
overloadsy: write('overload'); overridesy: write('override');
referencesy: write('reference'); joinssy: write('joins');
staticsy: write('static'); inheritedsy: write('inherited');
selfsy: write('self'); virtualsy: write('virtual');
trysy: write('try'); exceptsy: write('except');
extendssy: write('extends'); onsy: write('on');
resultsy: write('result'); operatorsy: write('operator');
outsy: write('out'); propertysy: write('property');
channelsy: write('channel'); streamsy: write('stream');
othersy: write('<other>'); hexsy: write('$'); octsy: write('&');
binsy: write('%'); numsy: write('#');
end
end;
procedure insymbol;
(*read next basic symbol of source program and return its
description in the global variables sy, op, id, val and lgth*)
label 1, 2;
var i,j,k,v,r: integer;
string: csstr;
lvp: csp; test, ferr: boolean;
iscmte: boolean;
ev: integer;
rv: real;
sgn: integer;
strend: boolean;
procedure nextch;
begin if eol then
begin if list then writeln(output); endofline end;
if not eofinp then
begin eol := eolninp; readinp(ch);
if list then write(ch);
chcnt := chcnt + 1
end
else
begin writeln(' *** eof ','encountered');
test := false; eol := true
end
end;
procedure options;
var
ch1 : char; dummy: boolean;
optst: optstr; oni: optinx; oi: 1..maxopt;
procedure switch(var opt: boolean);
var oni: optinx;
begin
if (ch='+') or (ch='-') then begin
opt := ch = '+';
option[oi] := opt;
if prcode then begin
write(prr, 'o', ' ':7);
for oni := 1 to optlen do
if optsl[oi, oni] <> ' ' then write(prr, optsl[oi, oni]);
writeln(prr, ch)
end;
nextch;
end else begin { just default to on }
opt := true;
option[oi] := true;
if prcode then begin
write(prr, 'o', ' ':7);
for oni := 1 to optlen do
if optsl[oi, oni] <> ' ' then write(prr, optsl[oi, oni]);
writeln(prr, '+')
end
end
end; { switch() }
begin { options() }
nextch;
repeat
oni := 1; optst := ' ';
while ch in ['a'..'z', 'A'..'Z', '0'..'9'] do begin
ch1 := lcase(ch);
if optst[oni] = ' ' then optst[oni] := ch1;
if oni < optlen then oni := oni+1;
nextch
end;
oi := 1;
while (oi < maxopt) and (optst <> opts[oi]) and (optst <> optsl[oi]) do
oi := oi+1;
if (optst = opts[oi]) or (optst = optsl[oi]) then case oi of
1: switch(dummy);
2: switch(doprtlab);
3: switch(prcode);
4: switch(debug);
5: switch(dummy);
6: switch(dummy);
7: switch(dummy);
8: switch(dummy);
9: switch(chkvbk);
10: switch(experr);
11: switch(dummy);
12: if not incact then begin
switch(list); if not list then writeln(output)
end;
13: switch(dummy);
14: switch(dummy);
15: switch(dummy);
16: switch(dummy);
17: switch(dummy);
18: switch(chkref);
19: switch(iso7185);
20: switch(prtables);
21: switch(chkudtc);
22: switch(chkvar);
23: switch(dummy);
24: switch(dodmplex);
25: switch(dodmpdsp);
26: switch(dummy);
end else begin
{ skip all likely option chars }
while ch in ['a'..'z','A'..'Z','+','-','0'..'9','_'] do
nextch;
end;
ch1 := ch; if ch1 = ',' then nextch
until ch1 <> ','
end (*options*) ;
function pwrten(e: integer): real;
var t: real; { accumulator }
p: real; { current power }
begin
p := 1.0e+1; { set 1st power }
t := 1.0; { initalize result }
repeat
if odd(e) then t := t*p; { if bit set, add this power }
e := e div 2; { index next bit }
p := sqr(p) { find next power }
until e = 0;
pwrten := t
end;
procedure plcchr(c: char);
begin
if not eol then begin
lgth := lgth+1;
if lgth <= strglgth then string[lgth] := c
end
end;
procedure escchr;
type escstr = packed array [1..5] of char; { escape string }
var c: char; l: 0..4; si: lininx; i: 1..5;
function match(es: escstr): boolean;
var i: 1..5;
begin
i := 1;
{ move to first mismatch or end }
while (es[i] = srclin[si+i-1]) and (es[i] <> ' ') and (i <= 4) do i := i+1;
match := es[i] = ' '
end;
begin
si := srcinx-1; { move back to after '\' }
c := ' '; { set none found }
if match('xoff ') then begin c := chr(19); l := 4 end
else if match('dle ') then begin c := chr(16); l := 3 end
else if match('dc1 ') then begin c := chr(17); l := 3 end
else if match('xon ') then begin c := chr(17); l := 3 end
else if match('dc2 ') then begin c := chr(18); l := 3 end
else if match('dc3 ') then begin c := chr(19); l := 3 end
else if match('dc4 ') then begin c := chr(20); l := 3 end
else if match('nak ') then begin c := chr(21); l := 3 end
else if match('syn ') then begin c := chr(22); l := 3 end
else if match('etb ') then begin c := chr(23); l := 3 end
else if match('can ') then begin c := chr(24); l := 3 end
else if match('nul ') then begin c := chr(0); l := 3 end
else if match('soh ') then begin c := chr(1); l := 3 end
else if match('stx ') then begin c := chr(2); l := 3 end
else if match('etx ') then begin c := chr(3); l := 3 end
else if match('eot ') then begin c := chr(4); l := 3 end
else if match('enq ') then begin c := chr(5); l := 3 end
else if match('ack ') then begin c := chr(6); l := 3 end
else if match('bel ') then begin c := chr(7); l := 3 end
else if match('sub ') then begin c := chr(26); l := 3 end
else if match('esc ') then begin c := chr(27); l := 3 end
else if match('del ') then begin c := chr(127); l := 3 end
else if match('bs ') then begin c := chr(8); l := 2 end
else if match('ht ') then begin c := chr(9); l := 2 end
else if match('lf ') then begin c := chr(10); l := 2 end
else if match('vt ') then begin c := chr(11); l := 2 end
else if match('ff ') then begin c := chr(12); l := 2 end
else if match('cr ') then begin c := chr(13); l := 2 end
else if match('so ') then begin c := chr(14); l := 2 end
else if match('si ') then begin c := chr(15); l := 2 end
else if match('em ') then begin c := chr(25); l := 2 end
else if match('fs ') then begin c := chr(28); l := 2 end
else if match('gs ') then begin c := chr(29); l := 2 end
else if match('rs ') then begin c := chr(30); l := 2 end
else if match('us ') then begin c := chr(31); l := 2 end;
if c <> ' ' then begin { found escape }
plcchr(c);
for i := 1 to l do nextch { skip escape sequence }
end else { place common forced }
begin plcchr(ch); nextch end
end;
begin (*insymbol*)
{ copy current to last scanner block }
lsy := sy; lop := op; lval := val; llgth := lgth; lid := id; lkk := kk;
if nvalid then begin { there is a lookahead }
{ copy next to current }
sy := nsy; op := nop; val := nval; lgth := nlgth; id := nid; kk := nkk;
nvalid := false; { set no next now }
goto 2 { skip getting next tolken }
end;
outline;
1:
{ Skip both spaces and controls. This allows arbitrary formatting characters
in the source. }
repeat while (ch <= ' ') and not eol do nextch;
test := eol;
if test then nextch
until not test;
if chartp[ch] = illegal then
begin sy := othersy; op := noop;
error(25); nextch
end
else
case chartp[ch] of
letter:
begin k := 0; ferr := true; for i := 1 to maxids do id[i] := ' ';
repeat
if k < maxids then
begin k := k + 1; id[k] := ch end
else if ferr then begin error(182); ferr := false end;
nextch
until not (chartp[ch] in [letter, number]);
if k >= kk then kk := k
else
repeat id[kk] := ' '; kk := kk - 1
until kk = k;
sy := ident; op := noop;
if k <= reslen then
for i := 1 to maxres do
if strequri(rw[i], id) then
begin sy := rsy[i]; op := rop[i];
{ if in ISO 7185 mode and keyword is extended, then revert it
to label. Note that forward and external get demoted to
"word symbols" in ISO 7185 }
if iso7185 and ((sy >= forwardsy) or (op > noop)) then
begin sy := ident; op := noop end
end;
end;
chhex, choct, chbin, number:
begin op := noop; i := 0; r := 10;
if chartp[ch] = chhex then begin chkstd; r := 16; nextch end
else if chartp[ch] = choct then begin chkstd; r := 8; nextch end
else if chartp[ch] = chbin then begin chkstd; r := 2; nextch end;
if (r = 10) or (chartp[ch] = number) or (chartp[ch] = letter) then
begin
v := 0;
repeat
if ch <> '_' then
if v <= pmmaxint div r then
v := v*r+ordint[ch]
else begin error(203); v := 0 end;
nextch
until (chartp[ch] <> number) and ((ch <> '_') or iso7185) and
((chartp[ch] <> letter) or (r < 16) or iso7185);
{ separator must be non-alpha numeric or 'e' with decimal radix }
if ((chartp[ch] = letter) and not ((lcase(ch) = 'e') and (r = 10))) or
(chartp[ch] = number) then error(241);
val.intval := true;
val.ival := v;
sy := intconst;
if ((ch = '.') and (bufinp <> '.') and (bufinp <> ')')) or
(lcase(ch) = 'e') then
begin
{ its a real, reject non-decimal radixes }
if r <> 10 then error(305);
rv := v; ev := 0;
if ch = '.' then begin
nextch;
if chartp[ch] <> number then error(201);
repeat
rv := rv*10+ordint[ch]; nextch; ev := ev-1
until chartp[ch] <> number;
end;
if lcase(ch) = 'e' then
begin nextch; sgn := +1;
if (ch = '+') or (ch ='-') then begin
if ch = '-' then sgn := -1;
nextch
end;
if chartp[ch] <> number then error(201)
else begin ferr := true; i := 0;
repeat
if ferr then begin
if i <= mxint10 then i := i*10+ordint[ch]
else begin error(194); ferr := false end;
end;
nextch
until chartp[ch] <> number;
if i > maxexp then begin
i := 0;
if ferr then error(194)
end;
ev := ev+i*sgn
end
end;
if ev < 0 then rv := rv/pwrten(ev) else rv := rv*pwrten(ev);
new(lvp,reel); pshcst(lvp); sy:= realconst;
lvp^.cclass := reel;
with lvp^ do lvp^.rval := rv;
val.intval := false;
val.valp := lvp
end
end else { convert radix to symbol }
if r = 16 then sy := hexsy
else if r = 8 then sy := octsy
else sy := binsy
end;
chstrquo:
begin nextch; lgth := 0; sy := stringconst; op := noop; strend := false;
for i := 1 to strglgth do string[i] := ' ';
repeat
{ force character if '\' and not ISO 7185 mode }
if (ch = chr(92)) and not iso7185 then begin
nextch; { skip '\' }
if ch in ['$','&','%','0'..'9'] then begin
{ character code }
j := i+1; v := 0; k := 1;
{ parse in radix and only correct number of digits to keep from
eating follow on characters }
if ch = '$' then begin nextch;
if not (ch in ['0'..'9','a'..'f','A'..'F']) then error(207);
while (ch in ['0'..'9', 'a'..'f', 'A'..'F']) and
(k <= 2) do begin
v := v*16+ordint[ch]; nextch; k := k+1
end
end else if ch = '&' then begin nextch;
if not (ch in ['0'..'7']) then error(207);
while (ch in ['0'..'7']) and (k <= 3) do begin
v := v*8+ordint[ch]; nextch; k := k+1
end
end else if ch = '%' then begin nextch;
if not (ch in ['0'..'1']) then error(207);
while (ch in ['0'..'1']) and (k <= 8) do begin
v := v*2+ordint[ch]; nextch; k := k+1
end
end else begin
while (ch in ['0'..'9']) and (k <= 3) do begin
v := v*10+ordint[ch]; nextch; k := k+1
end
end;
if v > ordmaxchar then error(222);
plcchr(chr(v));
end else escchr { process force sequence }
end else if ch = '''' then
begin nextch;
if ch = '''' then
begin plcchr(ch); nextch end else strend := true
end
else begin plcchr(ch); nextch end { place regular char }
until eol or strend;
if eol and not strend then error(202);
if lgth = 1 then begin
{ this is an artifact of the original code. If the string is a
single character, we store it as an integer even though the
symbol stays a string }
val.intval := true; val.ival := ord(string[1])
end else begin
if (lgth = 0) and iso7185 then error(205);
new(lvp,strg); pshcst(lvp);
lvp^.cclass:=strg;
if lgth > strglgth then
begin error(26); lgth := strglgth end;
with lvp^ do
begin slgth := lgth; strassvc(sval, string, strglgth) end;
val.intval := false;
val.valp := lvp
end
end;
chcolon:
begin op := noop; nextch;
if ch = '=' then
begin sy := becomes; nextch end
else sy := colon
end;
chperiod:
begin op := noop; nextch;
if ch = '.' then begin sy := range; nextch end
else if ch = ')' then begin sy := rbrack; nextch end
else sy := period
end;
chlt:
begin nextch; sy := relop;
if ch = '=' then
begin op := leop; nextch end
else
if ch = '>' then
begin op := neop; nextch end
else op := ltop
end;
chgt:
begin nextch; sy := relop;
if ch = '=' then
begin op := geop; nextch end
else op := gtop
end;
chlparen:
begin nextch;
if ch = '*' then
begin nextch;
if (ch = '$') and not incact then options;
repeat
while (ch <> '}') and (ch <> '*') and not eofinp do nextch;
iscmte := ch = '}'; nextch
until iscmte or (ch = ')') or eofinp;
if not iscmte then nextch; goto 1
end
else if ch = '.' then begin sy := lbrack; nextch end
else sy := lparent;
op := noop
end;
chlcmt:
begin nextch;
if ch = '$' then options;
repeat
while (ch <> '}') and (ch <> '*') and not eofinp do nextch;
iscmte := ch = '}'; nextch
until iscmte or (ch = ')') or eofinp;
if not iscmte then nextch; goto 1
end;
chrem:
begin chkstd;
repeat nextch until eol; { '!' skip next line }
goto 1
end;
special:
begin sy := ssy[ch]; op := sop[ch];
nextch
end;
chspace: sy := othersy
end; (*case*)
if dodmplex then begin { lexical dump }
writeln;
write('symbol: '); prtsym(sy);
if sy in [ident,intconst,realconst,stringconst] then
case sy of
ident: write(': ', id:10);
intconst: write(': ', val.ival:1);
realconst: write(': ', val.valp^.rval: 9);
stringconst: begin write('string const: ''');
writev(output, val.valp^.sval, val.valp^.slgth);
write('''') end;
end;
writeln
end;
2:;
end (*insymbol*) ;
procedure pushback;
begin
if nvalid then error(506); { multiple pushbacks }
{ put current tolken to future }
nsy := sy; nop := op; nval := val; nlgth := lgth; nid := id; nkk := kk;
{ get current from last }
sy := lsy; op := lop; val := lval; lgth := llgth; id := lid; kk := lkk;
nvalid := true { set there is a next tolken }
end;
procedure prtclass(klass: idclass);
begin
case klass of
types: write('types');
konst: write('konst');
fixedt: write('fixedt');
vars: write('vars');
field: write('field');
proc: write('proc');
func: write('func');
alias: write('alias');
end
end;
procedure prtform(form: structform);
begin
case form of
scalar: write('scalar');
subrange: write('subrange');
pointer: write('pointer');
power: write('power');
arrays: write('arrays');
arrayc: write('arrayc');
records: write('records');
files: write('files');
tagfld: write('tagfld');
variant: write('variant');
exceptf: write('exceptf');
end
end;
procedure enterid(fcp: ctp);
(*enter id pointed at by fcp into the name-table,
which on each declaration level is organised as
an unbalanced binary tree*)
var lcp, lcp1: ctp; lleft: boolean;
begin
lcp := display[top].fname;
if lcp = nil then
display[top].fname := fcp
else
begin
repeat lcp1 := lcp;
if strequvv(lcp^.name, fcp^.name) then begin
(*name conflict, follow right link*)
if incact then begin
writeln; write('*** Duplicate in uses/joins: ');
writevp(output, fcp^.name);
writeln
end;
{ give appropriate error }
if lcp^.klass = alias then error(242) else error(101);
lcp := lcp^.rlink; lleft := false
end else
if strltnvv(lcp^.name, fcp^.name) then
begin lcp := lcp^.rlink; lleft := false end
else begin lcp := lcp^.llink; lleft := true end
until lcp = nil;
if lleft then lcp1^.llink := fcp else lcp1^.rlink := fcp
end;
fcp^.llink := nil; fcp^.rlink := nil
end (*enterid*) ;
procedure searchsection(fcp: ctp; var fcp1: ctp);
(*to find record fields and forward declared procedure id's
--> procedure proceduredeclaration
--> procedure selector*)
label 1;
begin
while fcp <> nil do
if strequvf(fcp^.name, id) then goto 1
else if strltnvf(fcp^.name, id) then fcp := fcp^.rlink
else fcp := fcp^.llink;
1: if fcp <> nil then
if fcp^.klass = alias then fcp := fcp^.actid;
fcp1 := fcp
end (*searchsection*) ;
procedure schsecidnenm(lcp: ctp; fidcls: setofids; var fcp: ctp;
var mm: boolean);
var lcp1: ctp;
function inclass(lcp: ctp): ctp;
var fcp: ctp;
begin fcp := nil;
if lcp^.klass in [proc,func] then begin
lcp := lcp^.grppar;
while lcp <> nil do begin
if lcp^.klass in fidcls then fcp := lcp;
lcp := lcp^.grpnxt
end
end else if lcp^.klass in fidcls then fcp := lcp;
inclass := fcp
end;
begin
mm := false; fcp := nil;
while lcp <> nil do begin
if strequvf(lcp^.name, id) then begin
lcp1 := lcp; if lcp1^.klass = alias then lcp1 := lcp1^.actid;
lcp1 := inclass(lcp1);
if lcp1 <> nil then begin fcp := lcp1; lcp := nil end
else begin mm := true; lcp := lcp^.rlink end
end else
if strltnvf(lcp^.name, id) then lcp := lcp^.rlink
else lcp := lcp^.llink
end
end (*searchidnenm*) ;
procedure searchidnenm(fidcls: setofids; var fcp: ctp; var mm: boolean);
label 1;
var disxl: disprange;
begin
mm := false; disx := 0;
for disxl := top downto 0 do
begin
schsecidnenm(display[disxl].fname, fidcls, fcp, mm);
if fcp <> nil then begin disx := disxl; goto 1 end
end;
1:;
end (*searchidnenm*) ;
procedure searchidne(fidcls: setofids; var fcp: ctp);
var mm: boolean;
begin
searchidnenm(fidcls, fcp, mm);
if mm then error(103)
end (*searchidne*) ;
procedure schsecidne(lcp: ctp; fidcls: setofids; var fcp: ctp);
var mm: boolean;
begin
schsecidnenm(lcp, fidcls, fcp, mm);
if mm then error(103)
end (*searchidne*) ;
procedure searchid(fidcls: setofids; var fcp: ctp);
var lcp, lcp1: ctp; pn, fpn: disprange; pdf: boolean;
begin
pdf := false;
searchidne(fidcls, lcp); { perform no error search }
if lcp = nil then begin
{ search module leader in the pile }
if ptop > 0 then for pn := ptop-1 downto 0 do
if strequvf(pile[pn].modnam, id) then begin fpn := pn; pdf := true end;
if pdf then begin { module name was found }
insymbol; if sy <> period then error(21) else insymbol;
if sy <> ident then error(2)
else schsecidne(pile[fpn].fname,fidcls,lcp); { search qualifed name }
if lcp = nil then begin error(268); pdf := false end { not found }
end
end;
if lcp <> nil then begin { found }
lcp^.refer := true;
if (disx <> top) and (display[top].define) and not pdf then begin
{ downlevel, create an alias and link to bottom }
new(lcp1, alias); ininam(lcp1); lcp1^.klass := alias;
lcp1^.name := lcp^.name; lcp1^.actid := lcp;
enterid(lcp1)
end
end else begin (*search not successful
--> procedure simpletype*)
error(104);
(*to avoid returning nil, reference an entry
for an undeclared id of appropriate class
--> procedure enterundecl*)
if types in fidcls then lcp := utypptr
else
if (vars in fidcls) or (fixedt in fidcls) then lcp := uvarptr
else
if field in fidcls then lcp := ufldptr
else
if konst in fidcls then lcp := ucstptr
else
if proc in fidcls then lcp := uprcptr
else lcp := ufctptr
end;
fcp := lcp
end (*searchid*) ;
procedure getbounds(fsp: stp; var fmin,fmax: integer);
(*get internal bounds of subrange or scalar type*)
(*assume fsp<>intptr and fsp<>realptr*)
begin
fmin := 0; fmax := 0;
if fsp <> nil then
with fsp^ do
if form = subrange then
begin fmin := min.ival; fmax := max.ival end
else
if fsp = charptr then
begin fmin := ordminchar; fmax := ordmaxchar
end
else
if fsp = intptr then
begin fmin := -pmmaxint; fmax := pmmaxint
end
else
if fconst <> nil then
fmax := fconst^.values.ival
end (*getbounds*) ;
{ get span of type }
function span(fsp: stp): integer;
var fmin, fmax: integer;
begin
getbounds(fsp, fmin, fmax); span := fmax-fmin+1
end;
{ get span of array index }
function spana(fsp: stp): integer;
begin
if fsp <> nil then begin
if fsp^.form <> arrays then error(512);
{ if the index type is nil, assume string and take the array size as the
span }
if fsp^.inxtype = nil then spana := fsp^.size
else spana := span(fsp^.inxtype)
end
end;
function isbyte(fsp: stp): boolean;
{ check structure is byte }
var fmin, fmax: integer;
begin
getbounds(fsp, fmin, fmax);
isbyte := (fmin >= 0) and (fmax <= 255)
end;
function basetype(fsp: stp): stp;
{ remove any subrange types }
function issub(fsp: stp): boolean;
begin
if fsp <> nil then issub := fsp^.form = subrange
else issub := false
end;
begin
if fsp <> nil then
while issub(fsp) do
fsp := fsp^.rangetype;
basetype := fsp
end;
{ alignment for general memory placement }
function alignquot(fsp: stp): integer;
begin
alignquot := 1;
if fsp <> nil then
with fsp^ do
case form of
scalar: if fsp=intptr then alignquot := intal
else if fsp=boolptr then alignquot := boolal
else if scalkind=declared then alignquot := intal
else if fsp=charptr then alignquot := charal
else if fsp=realptr then alignquot := realal
else (*parmptr*) alignquot := parmal;
subrange: alignquot := alignquot(rangetype);
pointer: alignquot := adral;
power: alignquot := setal;
files: alignquot := fileal;
arrays: alignquot := alignquot(aeltype);
arrayc: alignquot := alignquot(abstype);
records: alignquot := recal;
exceptf: alignquot := exceptal;
variant,tagfld: error(501)
end
end (*alignquot*);
procedure alignu(fsp: stp; var flc: addrrange);
var k,l: integer;
begin
k := alignquot(fsp);
l := flc-1;
flc := l + k - (k+l) mod k
end (*align*);
procedure alignd(fsp: stp; var flc: stkoff);
var k,l: integer;
begin
k := alignquot(fsp);
if (flc mod k) <> 0 then begin
l := flc+1;
flc := l - k + (k-l) mod k
end
end (*align*);
{ align for stack }
function aligns(flc: addrrange): addrrange;
var l: integer;
begin
if (flc mod stackal) <> 0 then begin
l := flc+1;
flc := l - stackal + (stackal-l) mod stackal
end;
aligns := flc
end (*aligns*);
procedure wrtctp(ip: ctp);
begin
if ip = nil then write('<nil>':intdig) else write(ip^.snm:intdig)
end;
procedure wrtstp(sp: stp);
begin
if sp = nil then write('<nil>':intdig) else write(sp^.snm:intdig)
end;
procedure prtstp(sp: stp);
begin
if sp = nil then write('<nil>':intdig)
else with sp^ do begin
write(sp^.snm:intdig);
write(' ', size:intdig, ' ');
case form of
scalar: begin write('scalar':intdig, ' ');
if scalkind = standard then write('standard':intdig)
else begin write('declared':intdig,' '); wrtctp(fconst) end
end;
subrange: begin
write('subrange':intdig,' '); wrtstp(rangetype); write(' ');
if rangetype <> realptr then
write(min.ival:intdig, ' ', max.ival:intdig)
else
if (min.valp <> nil) and (max.valp <> nil) then begin
write(' '); write(min.valp^.rval:9);
write(' '); write(max.valp^.rval:9)
end
end;
pointer: begin write('pointer':intdig,' '); wrtstp(eltype) end;
power: begin write('set':intdig,' '); wrtstp(elset); write(' ');
write(matchpack:intdig) end;
arrays: begin
write('array':intdig,' '); wrtstp(inxtype); write(' ');
wrtstp(aeltype); end;
arrayc: begin write('array':intdig,' '); wrtstp(abstype) end;
records: begin
write('record':intdig,' '); wrtctp(fstfld); write(' ');
wrtstp(recvar); write(' '); wrtstp(recyc)
end;
files: begin write('file':intdig,' '); wrtstp(filtype) end;
tagfld: begin write('tagfld':intdig,' '); wrtctp(tagfieldp);
write(' '); wrtstp(fstvar)
end;
variant: begin write('variant':intdig,' '); wrtstp(nxtvar);
write(' '); wrtstp(subvar); write(' '); wrtstp(caslst);
write(' '); wrtctp(varfld);
write(' ',varval.ival:intdig, ' ', varln:intdig)
end;
exceptf: begin write('except':intdig) end
end (*case*)
end
end;
procedure prtctp(cp: ctp);
begin
if cp = nil then write('<nil>':intdig)
else with cp^ do begin
write(cp^.snm:intdig); write(' '); writev(output, name, intdig);
write(' '); wrtctp(llink); write(' '); wrtctp(rlink); write(' ');
wrtstp(idtype); write(' ');
case klass of
types: write('type':intdig);
konst: begin write('constant':intdig,' '); wrtctp(next); write(' ');
if idtype <> nil then
if idtype = realptr then
begin
if values.valp <> nil then write(values.valp^.rval:9)
end
else
if idtype^.form = arrays then (*stringconst*)
begin
if values.valp <> nil then
begin
with values.valp^ do writev(output, sval, slgth)
end
end
else write(values.ival:intdig)
end;
vars: begin write('variable':intdig, ' ');
if vkind = actual then write('actual':intdig)
else write('formal':intdig);
write(' '); wrtctp(next);
write(' ', vlev:intdig,' ',vaddr:intdig, ' ');
if threat then write('threat':intdig) else write(' ':intdig);
write(' ', forcnt:intdig, ' ');
case part of
ptval: write('value':intdig, ' ');
ptvar: write('var':intdig, ' ');
ptview: write('view':intdig, ' ');
ptout:write('out':intdig, ' ');
end;
if hdr then write('header':intdig, ' ') else write(' ':intdig, ' ');
if vext then write('external':intdig, ' ') else write(' ':intdig, ' ');
if vext then write(vmod^.fn:intdig, ' ') else write(' ':intdig, ' ');
write(inilab:intdig, ' '); wrtctp(ininxt);
write(' ', dblptr:intdig);
end;
fixedt: begin write('fixed':intdig, ' ', floc:intdig, ' ');
if fext then write('external':intdig) else write(' ':intdig);
if fext then write(fmod^.fn:intdig) else write(' ':intdig)
end;
field: begin write('field':intdig,' '); wrtctp(next); write(' ');
write(fldaddr:intdig,' '); wrtstp(varnt); write(' ');
wrtctp(varlb); write(' ');
if tagfield then write('tagfield':intdig) else write(' ':intdig);
write(' ', taglvl:intdig, ' ',varsaddr:intdig, ' ', varssize:intdig);
write(' ', vartl:intdig)
end;
proc,
func: begin
if klass = proc then write('procedure':intdig, ' ')
else write('function':intdig, ' ');
write(pfaddr:intdig, ' '); wrtctp(pflist); write(' ');
if asgn then write('assigned':intdig, ' ') else write(' ':intdig, ' ');
if pext then write('external':intdig, ' ') else write(' ':intdig, ' ');
if pext then write(pmod^.fn:intdig) else write(' ':intdig); write(' ');
case pfattr of
fpanone: write(' ':intdig);
fpaoverload: write('overload':intdig);
fpastatic: write('static':intdig);
fpavirtual: write('virtual':intdig);
fpaoverride: write('override': intdig);
end;
write(' ', pfvaddr:intdig, ' '); wrtctp(pfvid); write(' '); wrtctp(grppar);
write(' '); wrtctp(grpnxt); write(' ');
if pfdeckind = standard then
write('standard':intdig, ' ', key:intdig)
else
begin write('declared':intdig,' '); wrtctp(pflist); write(' ');
write(pflev:intdig,' ',pfname:intdig, ' ');
if pfkind = actual then
begin write('actual':intdig, ' ');
if forwdecl then write('forward':intdig, ' ')
else write('not forward':intdig, ' ');
if sysrot then write('system routine':intdig)
else write('not system routine':intdig);
if extern then write('external':intdig)
else write('not external':intdig)
end
else write('formal':intdig)
end
end;
alias: begin write('alias':intdig, ' '); wrtctp(actid); end;
end (*case*);
end
end;
procedure printtables(fb: boolean);
(*print data structure and name table*)
var i, lim: disprange;
procedure marker;
(*mark data structure entries to avoid multiple printout*)
var i: integer;
procedure markctp(fp: ctp); forward;
procedure markstp(fp: stp);
(*mark data structures, prevent cycles*)
begin
if fp <> nil then
with fp^ do
begin marked := true;
case form of
scalar: ;
subrange: markstp(rangetype);
pointer: (*don't mark eltype: cycle possible; will be marked
anyway, if fp = true*) ;
power: markstp(elset) ;
arrays: begin markstp(aeltype); markstp(inxtype) end;
arrayc: markstp(abstype);
records: begin markctp(fstfld); markstp(recvar) end;
files: markstp(filtype);
tagfld: markstp(fstvar);
variant: begin markstp(nxtvar); markstp(subvar) end;
exceptf: ;
end (*case*)
end (*with*)
end (*markstp*);
procedure markctp{(fp: ctp)};
begin
if fp <> nil then
with fp^ do
begin markctp(llink); markctp(rlink);
markstp(idtype)
end
end (*markctp*);
begin (*marker*)
for i := top downto lim do
markctp(display[i].fname)
end (*marker*);
procedure followctp(fp: ctp); forward;
procedure followstp(fp: stp);
begin
if fp <> nil then
with fp^ do
if marked then
begin marked := false; write('S: '); prtstp(fp); writeln;
case form of
scalar: ;
subrange: followstp(rangetype);
pointer: ;
power: followstp(elset);
arrays: begin followstp(aeltype); followstp(inxtype) end;
arrayc: followstp(abstype);
records: begin followctp(fstfld); followstp(recvar) end;
files: followstp(filtype);
tagfld: followstp(fstvar);
variant: begin followstp(nxtvar); followstp(subvar) end;
exceptf: ;
end (*case*)
end (*if marked*)
end (*followstp*);
procedure followctp{(fp: ctp)};
begin
if fp <> nil then
with fp^ do
begin write('C: '); prtctp(fp); writeln;
followctp(llink); followctp(rlink);
followstp(idtype)
end (*with*)
end (*followctp*);
begin (*printtables*)
writeln(output); writeln(output); writeln(output);
if fb then lim := 0
else begin lim := top; write(' local') end;
writeln(' tables:', top:1, '-', lim:1, ':'); writeln(output);
writeln('C: ', 'Entry #':intdig, ' ', 'Id':intdig, ' ', 'llink':intdig, ' ',
'rlink':intdig, ' ', 'Typ':intdig, ' ', 'Class':intdig);
writeln('S: ', 'Entry #':intdig, ' ', 'Size':intdig, ' ', 'Form ':intdig);
write('===============================================================');
writeln('==========================');
marker;
for i := top downto lim do
begin writeln('Level: ', i:1); followctp(display[i].fname) end;
writeln(output);
if not eol then write(' ':chcnt+16)
end (*printtables*);
procedure chkrefs(p: ctp; var w: boolean);
begin
if chkref then begin
if p <> nil then begin
chkrefs(p^.llink, w); { check left }
chkrefs(p^.rlink, w); { check right }
if not p^.refer and (p^.klass <> alias) and not incact then begin
if not w then writeln; writev(output, p^.name, 10);
writeln(' unreferenced'); w := true
end
end
end
end;
function chkext(fcp: ctp): boolean;
begin chkext := false;
if fcp <> nil then begin
if fcp^.klass = vars then chkext := fcp^.vext
else if fcp^.klass = fixedt then chkext := fcp^.fext
else if (fcp^.klass = proc) or (fcp^.klass = func) then
chkext := fcp^.pext
end
end;
function chkfix(fcp: ctp): boolean;
begin chkfix := false;
if fcp <> nil then chkfix := fcp^.klass = fixedt
end;
{ id contains a procedure in overload list }
function hasovlproc(fcp: ctp): boolean;
begin hasovlproc := false;
if fcp <> nil then
if fcp^.klass in [proc, func] then begin
fcp := fcp^.grppar;
while fcp <> nil do begin
if fcp^.klass = proc then hasovlproc := true;
fcp := fcp^.grpnxt
end
end
end;
{ id contains a function in overload list }
function hasovlfunc(fcp: ctp): boolean;
begin hasovlfunc := false;
if fcp <> nil then
if fcp^.klass in [proc, func] then begin
fcp := fcp^.grppar;
while fcp <> nil do begin
if fcp^.klass = func then hasovlfunc := true;
fcp := fcp^.grpnxt
end
end
end;
{ return overload function from list }
function ovlfunc(fcp: ctp): ctp;
var rcp: ctp;
begin rcp := nil;
if fcp <> nil then
if fcp^.klass in [proc, func] then begin
fcp := fcp^.grppar;
while fcp <> nil do begin
if fcp^.klass = func then rcp := fcp;
fcp := fcp^.grpnxt
end
end;
ovlfunc := rcp
end;
{ return override procedure/function from list }
function ovrpf(fcp: ctp): ctp;
var rcp: ctp;
begin rcp := nil;
if fcp <> nil then
if fcp^.klass in [proc, func] then begin
fcp := fcp^.grppar;
while fcp <> nil do begin
if fcp^.pfattr = fpaoverride then rcp := fcp;
fcp := fcp^.grpnxt
end
end;
ovrpf := rcp
end;
procedure genlabel(var nxtlab: integer);
begin intlabel := intlabel + 1;
nxtlab := intlabel
end (*genlabel*);
{ write shorthand type }
procedure wrttyp(var f: text; tp: stp);
const maxtrk = 4000;
var typtrk: array [1..maxtrk] of stp; cti: integer; err: boolean;
procedure wrttypsub(tp: stp);
var x, y, fi: integer;
procedure nxtcti;
begin
cti := cti+1; if cti <= maxtrk then typtrk[cti] := nil
end;
procedure nxtctis(i: integer);
var x: integer;
begin
for x := 1 to i do nxtcti
end;
procedure wrtchr(c: char);
begin
write(f, c); nxtcti
end;
procedure wrtint(i: integer);
var p, d: integer;
begin
p := 10; d := 1;
while (i >= p) and (p < maxpow10) do begin p := p*10; d := d+1 end;
write(f, i:1);
nxtctis(d)
end;
procedure wrtrfd(fld: ctp);
begin
while fld <> nil do begin
with fld^ do begin
writev(f, name, lenpv(name)); nxtctis(lenpv(name));
wrtchr(':');
if klass = field then wrtint(fldaddr) else wrtchr('?');
wrtchr(':'); wrttypsub(idtype);
end;
fld := fld^.next;
if fld <> nil then wrtchr(',')
end
end;
procedure wrtvar(sp: stp);
begin
while sp <> nil do with sp^ do
if form = variant then begin
wrtint(varval.ival); wrtchr('('); wrtrfd(varfld); wrtchr(')');
sp := nxtvar
end else sp := nil
end;
{ enums are backwards, so print thus }
procedure wrtenm(ep: ctp; i: integer);
begin
if ep <> nil then begin
wrtenm(ep^.next, i+1);
writev(f, ep^.name, lenpv(ep^.name)); nxtctis(lenpv(ep^.name));
if i > 0 then wrtchr(',')
end
end;
begin { wrttypsub }
if cti > maxtrk then begin
if not err then error(227);
err := true
end else typtrk[cti] := tp; { track this type entry }
if tp <> nil then with tp^ do case form of
scalar: begin
if tp = intptr then wrtchr('i')
else if tp = boolptr then wrtchr('b')
else if tp = charptr then wrtchr('c')
else if tp = realptr then wrtchr('n')
else if scalkind = declared then
begin wrtchr('x'); wrtchr('('); wrtenm(fconst, 0);
wrtchr(')') end
else wrtchr('?')
end;
subrange: begin
wrtchr('x'); wrtchr('('); wrtint(min.ival); wrtchr(',');
wrtint(max.ival); wrtchr(')');
wrttypsub(rangetype)
end;
pointer: begin
wrtchr('p'); fi := 0; y := cti;
if y > maxtrk then y := maxtrk;
if eltype <> nil then
for x := y downto 1 do if typtrk[x] = eltype then fi := x;
{ if there is a cycle, output type digest position, otherwise
the actual type }
if fi > 0 then wrtint(fi) else wrttypsub(eltype)
end;
power: begin wrtchr('s'); wrttypsub(elset) end;
arrays: begin wrtchr('a'); wrttypsub(inxtype); wrttypsub(aeltype) end;
arrayc: begin wrtchr('v'); wrttypsub(abstype) end;
records: begin wrtchr('r'); wrtchr('('); wrtrfd(fstfld);
if recvar <> nil then if recvar^.form = tagfld then
begin wrtchr(','); wrtrfd(recvar^.tagfieldp);
wrtchr('('); wrtvar(recvar^.fstvar);
wrtchr(')') end;
wrtchr(')') end;
files: begin wrtchr('f'); wrttypsub(filtype) end;
variant: wrtchr('?');
exceptf: wrtchr('e')
end else wrtchr('?')
end;
begin { wrttyp }
cti := 1; { set 1st position in tracking }
err := false; { set no error }
wrttypsub(tp) { issue type }
end;
procedure prtlabel(labname: integer);
begin
if prcode then begin
write(prr, 'l '); writevp(prr, nammod); write(prr, '.', labname:1)
end
end;
procedure prtflabel(fcp: ctp);
begin
if prcode then begin
write(prr, 'l ');
if fcp^.klass = vars then writevp(prr, fcp^.vmod^.mn)
else if fcp^.klass = fixedt then writevp(prr, fcp^.fmod^.mn)
else writevp(prr, fcp^.pmod^.mn);
write(prr, '.');
writevp(prr, fcp^.name)
end
end;
procedure prtpartyp(fcp: ctp);
var plst: ctp;
begin
plst := fcp^.pflist;
while plst <> nil do begin
if plst^.klass in [proc, func] then begin
write(prr, 'q('); prtpartyp(plst); write(prr, ')');
if plst^.klass = func then begin
write(prr, ':'); wrttyp(prr, plst^.idtype)
end
end else wrttyp(prr, plst^.idtype);
if plst^.next <> nil then write(prr, '_');
plst := plst^.next
end
end;
procedure putlabel(labname: integer);
begin
if prcode then begin prtlabel(labname); writeln(prr) end
end (*putlabel*);
procedure searchlabel(var llp: lbp; level: disprange; isid: boolean);
var fllp: lbp; { found label entry }
lv: integer;
begin lv := -1;
if not isid then if val.intval then lv := val.ival;
fllp := nil; { set no label found }
llp := display[level].flabel; { index top of label list }
while llp <> nil do begin { traverse }
if isid and (llp^.labid <> nil) then begin { id type label }
if strequvf(llp^.labid, id) then begin
fllp := llp; { set entry found }
llp := nil { stop }
end else llp := llp^.nextlab { next in list }
end else if not isid and (llp^.labval = lv) then begin { found }
fllp := llp; { set entry found }
llp := nil { stop }
end else llp := llp^.nextlab { next in list }
end;
llp := fllp { return found entry or nil }
end;
procedure newlabel(var llp: lbp; isid: boolean);
var lbname: integer;
begin
with display[top] do
begin getlab(llp);
with llp^ do
begin labid := nil; labval := 0;
if isid then strassvf(labid, id) { id type label }
else labval := val.ival; { numeric type label }
if labval > 9999 then error(261);
genlabel(lbname); defined := false; nextlab := flabel;
labname := lbname; vlevel := level; slevel := 0;
ipcref := false; minlvl := pmmaxint; bact := false;
refer := false
end;
flabel := llp
end
end;
procedure prtlabels;
var llp: lbp; { found label entry }
begin
writeln;
writeln('Labels: ');
writeln;
llp := display[level].flabel; { index top of label list }
while llp <> nil do with llp^ do begin { traverse }
writeln('label: ', labval:1, ' defined: ', defined,
' internal: ', labname:1, ' vlevel: ', vlevel:1,
' slevel: ', slevel:1, ' ipcref: ', ipcref:1,
' minlvl: ', minlvl:1);
writeln(' bact: ', bact);
llp := llp^.nextlab { next in list }
end
end;
procedure mesl(i: integer);
begin topnew := topnew + i;
if topnew < topmin then topmin := topnew;
if toterr = 0 then
if (topnew > 0) and prcode then error(500) { stack should never go positive }
end;
procedure mes(i: integer);
begin mesl(cdx[i]) end;
procedure mest(i: integer; fsp: stp);
function mestn(fsp: stp): integer;
var ss: integer;
begin ss := 1;
if fsp<>nil then
with fsp^ do
case form of
scalar: if fsp=intptr then ss := 1
else
if fsp=boolptr then ss := 3
else
if fsp=charptr then ss := 4
else
if scalkind = declared then ss := 1
else ss := 2;
subrange: ss := mestn(rangetype);
pointer,
files,
exceptf: ss := 5;
power: ss := 6;
records,arrays,arrayc: ss := 7;
tagfld,variant: error(501)
end;
mestn := ss
end;
begin (*mest*)
if (cdx[i] < 1) or (cdx[i] > 6) then error(502);
mesl(cdxs[cdx[i]][mestn(fsp)]);
end (*mest*);
procedure gen0(fop: oprange);
begin
if prcode then writeln(prr,mn[fop]:11);
ic := ic + 1; mes(fop)
end (*gen0*) ;
procedure gen1s(fop: oprange; fp2: integer; symptr: ctp);
var k, j: integer; p: strvsp;
begin
if prcode then
begin write(prr,mn[fop]:11);
if fop = 30 then
begin writeln(prr,' ':5,sna[fp2]:4);
mesl(pdx[fp2]);
end
else
begin
if fop = 38 then
begin with cstptr[fp2]^ do begin p := sval; j := 1;
write(prr,' ':5,slgth:1,' ''');
for k := 1 to lenpv(p) do begin
if p^.str[j] = '''' then write(prr, '''''')
else write(prr,p^.str[j]:1);
j := j+1; if j > varsqt then begin
p := p^.next; j := 1
end
end
end;
writeln(prr,'''')
end
else if fop = 42 then writeln(prr,chr(fp2))
else if fop = 67 then writeln(prr,' ':5,fp2:1)
else if fop = 105 then begin write(prr,' ':5); putlabel(fp2) end
else if chkext(symptr) then
begin write(prr,' ':5); prtflabel(symptr); writeln(prr) end
else if chkfix(symptr) then
begin write(prr,' ':5); prtlabel(symptr^.floc); writeln(prr) end
else writeln(prr,' ':5,fp2:1);
if fop = 42 then mes(0)
else if fop = 71 then mesl(fp2)
else mes(fop)
end
end;
ic := ic + 1
end (*gen1s*) ;
procedure gen1(fop: oprange; fp2: integer);
begin
gen1s(fop, fp2, nil)
end;
procedure gen2(fop: oprange; fp1,fp2: integer);
var k : integer;
begin
if prcode then
begin write(prr,mn[fop]:11);
case fop of
42: begin
writeln(prr,chr(fp1),' ':4,fp2:1);
mes(0)
end;
45,50,54,56,74,62,63,81,82,96,97,102,104,109,112,115,116,117:
begin
writeln(prr,' ':5,fp1:1,' ',fp2:1);
if fop = 116 then mesl(-fp2)
else if fop = 117 then mesl(fp2-fp1)
else mes(fop)
end;
47,48,49,52,53,55:
begin write(prr,chr(fp1));
if chr(fp1) = 'm' then write(prr,' ':4,fp2:1);
writeln(prr);
case chr(fp1) of
'i': mesl(cdxs[cdx[fop]][1]);
'r': mesl(cdxs[cdx[fop]][2]);
'b': mesl(cdxs[cdx[fop]][3]);
'c': mesl(cdxs[cdx[fop]][4]);
'a': mesl(cdxs[cdx[fop]][5]);
's': mesl(cdxs[cdx[fop]][6]);
'm': mesl(cdxs[cdx[fop]][7]);
'v': mesl(cdxs[cdx[fop]][8]);
end
end;
51:
begin
case fp1 of
1: begin writeln(prr,'i',' ':4,fp2:1);
mesl(cdxs[cdx[fop]][1])
end;
2: begin write(prr,'r',' ':4);
with cstptr[fp2]^ do write(prr,rval:23);
writeln(prr);
mesl(cdxs[cdx[fop]][2]);
end;
3: begin writeln(prr,'b',' ':4,fp2:1);
mesl(cdxs[cdx[fop]][3])
end;
4: begin writeln(prr,'n');
mesl(-ptrsize)
end;
6: begin
if chartp[chr(fp2)] = illegal then
{ output illegal characters as numbers }
writeln(prr,'c',' ':4,fp2:1)
else
writeln(prr,'c',' ':4, '''',chr(fp2),'''');
mesl(cdxs[cdx[fop]][4])
end;
5: begin write(prr,'s',' ':4, '(');
with cstptr[fp2]^ do
for k := setlow to sethigh do
if k in pval then write(prr,k:4);
writeln(prr,')');
mesl(cdxs[cdx[fop]][6])
end
end
end
end
end;
ic := ic + 1
end (*gen2*) ;
procedure gentypindicator(fsp: stp);
begin
if (fsp <> nil) and prcode then
with fsp^ do
case form of
scalar: if fsp=intptr then write(prr,'i')
else
if fsp=boolptr then write(prr,'b')
else
if fsp=charptr then write(prr,'c')
else
if scalkind = declared then begin
if fsp^.size = 1 then write(prr, 'x')
else write(prr,'i')
end else write(prr,'r');
subrange: if fsp^.size = 1 then write(prr, 'x')
else gentypindicator(rangetype);
pointer,
files,
exceptf: write(prr,'a');
power: write(prr,'s');
records,arrays,arrayc: write(prr,'m');
tagfld,variant: error(503)
end
end (*typindicator*);
procedure gen0t(fop: oprange; fsp: stp);
begin
if prcode then
begin
write(prr,mn[fop]:11);
gentypindicator(fsp);
writeln(prr);
end;
ic := ic + 1; mest(fop, fsp)
end (*gen0t*);
procedure gen1ts(fop: oprange; fp2: integer; fsp: stp; symptr: ctp);
begin
if prcode then
begin
write(prr,mn[fop]:11);
gentypindicator(fsp);
write(prr, ' ':4);
if chkext(symptr) then prtflabel(symptr)
else if chkfix(symptr) then prtlabel(symptr^.floc)
else write(prr,fp2:1);
writeln(prr)
end;
ic := ic + 1; mest(fop, fsp)
end (*gen1ts*);
procedure gen1t(fop: oprange; fp2: integer; fsp: stp);
begin
gen1ts(fop, fp2, fsp, nil)
end;
procedure gen2t(fop: oprange; fp1,fp2: integer; fsp: stp);
begin
if prcode then
begin
write(prr,mn[fop]:11);
gentypindicator(fsp);
writeln(prr,' ':4, fp1:1,' ',fp2:1);
end;
ic := ic + 1; mest(fop, fsp)
end (*gen2t*);
procedure genujpxjpcal(fop: oprange; fp2: integer);
begin
if prcode then
begin write(prr,mn[fop]:11, ' ':5); prtlabel(fp2); writeln(prr) end;
ic := ic + 1; mes(fop)
end (*genujpxjpcal*);
procedure gencjp(fop: oprange; fp1,fp2,fp3: integer);
begin
if prcode then
begin
write(prr,mn[fop]:11, ' ':5, fp1:3+5*ord(abs(fp1)>99),' ',fp2:11,
' '); prtlabel(fp3); writeln(prr)
end;
ic := ic + 1; mes(fop)
end (*gencjp*);
procedure genipj(fop: oprange; fp1, fp2: integer);
begin
if prcode then
begin write(prr,mn[fop]:11,' ':5,fp1:1,' '); prtlabel(fp2); writeln(prr) end;
ic := ic + 1; mes(fop)
end (*genipj*);
procedure gencupcuf(fop: oprange; fp1,fp2: integer; fcp: ctp);
begin
if prcode then
begin
write(prr,mn[fop]:11, ' ':5);
if chkext(fcp) then begin
prtflabel(fcp);
write(prr, '@'); { this keeps the user from aliasing it }
if fcp^.klass = proc then write(prr, 'p') else write(prr, 'f');
if fcp^.pflist <> nil then begin
write(prr, '_');
prtpartyp(fcp)
end
end else prtlabel(fp2);
writeln(prr);
mesl(fp1)
end;
ic := ic + 1
end;
procedure gencuv(fp1,fp2: integer; fcp: ctp);
begin
if prcode then
begin
write(prr,mn[91(*cuv*)]:11,' ':5);
if chkext(fcp) then prtflabel(fcp) else writeln(prr,fp2:12);
writeln(prr);
mes(91)
end;
ic := ic + 1
end;
procedure genlpa(fp1,fp2: integer);
begin
if prcode then
begin
write(prr,mn[68(*lpa*)]:11,' ':5, fp2:4, ' '); prtlabel(fp1); writeln(prr);
end;
ic := ic + 1; mes(68)
end (*genlpa*);
procedure gensuv(fp1, fp2: integer; sym: ctp);
begin
if prcode then begin
write(prr,mn[92(*suv*)]:11, ' ':5); prtlabel(fp1);
if chkext(sym) then
begin write(prr, ' '); prtflabel(sym); writeln(prr) end
else writeln(prr, ' ', fp2:1)
end;
ic := ic + 1; mes(92)
end;
procedure genctaivtcvb(fop: oprange; fp1,fp2,fp3: integer; fsp: stp);
begin if fp3 < 0 then error(511);
if prcode then
begin write(prr,mn[fop]:11);
if fop <> 81(*cta*) then gentypindicator(fsp);
write(prr,' ':4,fp1:1,' ',fp2:1,' ');
mes(fop); putlabel(fp3)
end;
ic := ic + 1
end (*genctaivtcvb*) ;
procedure gensfr(lb: integer);
begin
if prcode then begin
write(prr,mn[121(*sfr*)]:11, ' ':5); prtlabel(lb); writeln(prr);
end
end;
procedure genmst(lev: levrange; fp1,fp2: integer);
begin
if prcode then begin
write(prr,mn[41(*mst*)]:11, ' ':5, lev:1, ' '); prtlabel(fp1);
write(prr, ' '); prtlabel(fp2); writeln(prr)
end
end;
procedure gensca(c: char);
begin
if prcode then begin
write(prr,mn[(*lca*)38]:11,1:6,' ''');
if c = '''' then write(prr,'''') else write(prr,c);
writeln(prr,'''');
mes(38)
end
end;
function comptypes(fsp1,fsp2: stp) : boolean; forward;
{ check integer or subrange of }
function intt(fsp: stp): boolean;
var t: stp;
begin intt := false;
if fsp <> nil then begin
t := basetype(fsp);
if t = intptr then intt := true
end
end;
{ check real }
function realt(fsp: stp): boolean;
begin realt := false;
if fsp <> nil then
if fsp = realptr then realt := true
end;
{ the type test for character includes very broad definitions of char,
including packed character arrays of 1 length, and even packed character
array containers, because they could be length 1 }
function chart(fsp: stp): boolean;
var t: stp; fmin, fmax: integer;
begin chart := false;
if fsp <> nil then begin
t := basetype(fsp);
if t = charptr then chart := true
else if (t^.form = arrays) and t^.packing then begin
if (t^.inxtype = nil) and (t^.size = 1) then chart := true
else if chart(t^.aeltype) and intt(t^.inxtype) then begin
getbounds(t^.inxtype,fmin,fmax);
if (fmin = 1) and (fmax = 1) then chart := true
end
end else if (t^.form = arrayc) and t^.packing then begin
if chart(t^.abstype) then chart := true
end
end
end;
{ check boolean }
function bolt(fsp: stp): boolean;
var t: stp;
begin bolt := false;
if fsp <> nil then begin
t := basetype(fsp);
if t = boolptr then bolt := true
end
end;
function stringt(fsp: stp) : boolean;
var fmin, fmax: integer;
begin stringt := false;
if fsp <> nil then
if (fsp^.form = arrays) or (fsp^.form = arrayc) then
if fsp^.packing then begin
if fsp^.form = arrays then begin
{ if the index is nil, either the array is a string constant or the
index type was in error. Either way, we call it a string }
if fsp^.inxtype = nil then stringt := true
else begin
{ common string must pass test of 1..N where N>1 }
getbounds(fsp^.inxtype,fmin,fmax);
stringt := (fsp^.aeltype = charptr) and (fmin = 1) and (fmax > 1)
end
end else stringt := fsp^.abstype = charptr
end
end (*stringt*);
{ check structure is, or contains, a file }
function filecomponent(fsp: stp): boolean;
var f: boolean;
{ tour identifier tree }
function filecomponentre(lcp: ctp): boolean;
var f: boolean;
begin
f := false; { set not file by default }
if lcp <> nil then with lcp^ do begin
if filecomponent(idtype) then f := true;
if filecomponentre(llink) then f := true;
if filecomponentre(rlink) then f := true
end;
filecomponentre := f
end;
begin
f := false; { set not a file by default }
if fsp <> nil then with fsp^ do case form of
scalar: ;
subrange: ;
pointer: ;
power: ;
arrays: if filecomponent(aeltype) then f := true;
arrayc: if filecomponent(abstype) then f := true;
records: if filecomponentre(fstfld) then f := true;
files: f := true;
tagfld: ;
variant: ;
exceptf: ;
end;
filecomponent := f
end;
{ check array type, fixed or container }
function arrayt(fsp: stp): boolean;
begin
if fsp = nil then arrayt := false
else arrayt := (fsp^.form = arrays) or (fsp^.form = arrayc);
end;
{ check set type }
function sett(fsp: stp): boolean;
begin
if fsp = nil then sett := false
else sett := fsp^.form = power
end;
{ check pointer type }
function ptrt(fsp: stp): boolean;
begin
if fsp = nil then ptrt := false
else ptrt := fsp^.form = pointer
end;
{ check simple type }
function simt(fsp: stp): boolean;
begin
if fsp = nil then simt := false
else simt := (fsp^.form = scalar) or (fsp^.form = subrange)
end;
{ check ordinal type }
function ordt(fsp: stp): boolean;
begin
if fsp = nil then ordt := false
else ordt := ((fsp^.form = scalar) or (fsp^.form = subrange)) and
not realt(fsp)
end;
{ check file type }
function filet(fsp: stp): boolean;
begin
if fsp = nil then filet := false
else filet := fsp^.form = files
end;
function comptypes{(fsp1,fsp2: stp) : boolean};
(*decide whether structures pointed at by fsp1 and fsp2 are compatible*)
var ty1, ty2: stp;
begin
comptypes := false; { set default is false }
{ remove any subranges }
fsp1 := basetype(fsp1);
fsp2 := basetype(fsp2);
{ Check equal. Aliases of the same type will also be equal. }
if fsp1 = fsp2 then comptypes := true
else
if (fsp1 <> nil) and (fsp2 <> nil) then
{ if the structure forms are the same, or they are both array types }
if (fsp1^.form = fsp2^.form) or (arrayt(fsp1) and arrayt(fsp2)) then
case fsp1^.form of
scalar: ;
{ Subranges are compatible if either type is a subrange of the
other, or if the base type is the same. }
subrange: ; { done above }
{ Sets are compatible if they have the same base types and packed/
unpacked status, or one of them is the empty set. The empty set
is indicated by a nil base type, which is identical to a base
type in error. Either way, we treat them as compatible.
Set types created for set constants have a flag that disables
packing matches. This is because set constants can be packed or
unpacked by context. }
power: comptypes := (comptypes(fsp1^.elset, fsp2^.elset) and
((fsp1^.packing = fsp2^.packing) or
not fsp1^.matchpack or
not fsp2^.matchpack)) or
(fsp1^.elset = nil) or (fsp2^.elset = nil);
{ Arrays are compatible if they are string types and equal in size,
or are one or both containers, equally packed, and with equal
base types }
arrays,
arrayc: begin
if ((fsp1^.form = arrayc) or (fsp2^.form = arrayc)) and
(fsp1^.packing = fsp2^.packing) then begin
{ one or both are containers and have same packing status }
if fsp1^.form = arrays then ty1 := fsp1^.aeltype
else ty1 := fsp1^.abstype;
if fsp2^.form = arrays then ty2 := fsp2^.aeltype
else ty2 := fsp2^.abstype;
{ compatible if bases are compatible }
comptypes := comptypes(ty1, ty2)
end else
{ note containers have no size to compare, but will test as
compatible arrays before this string test is applied }
comptypes := stringt(fsp1) and stringt(fsp2) and
(fsp1^.size = fsp2^.size );
end;
{ Pointers, must either be the same type or aliases of the same
type, or one must be nil. The nil pointer is indicated by a nil
base type, which is identical to a base type in error. Either
way, we treat them as compatible. }
pointer: comptypes := (fsp1^.eltype = nil) or (fsp2^.eltype = nil);
{ records and files must either be the same type or aliases of the
same type }
records: ;
files:
end (*case*)
else (*fsp1^.form <> fsp2^.form*)
{ subranges of a base type match the base type }
if fsp1^.form = subrange then
comptypes := fsp1^.rangetype = fsp2
else
if fsp2^.form = subrange then
comptypes := fsp1 = fsp2^.rangetype
else comptypes := false
else comptypes := true { one of the types is in error }
end (*comptypes*) ;
function cmpparlst(pla, plb: ctp): boolean; forward;
{ compare two parameters }
function cmppar(pa, pb: ctp): boolean;
begin cmppar := false;
if (pa <> nil) and (pb <> nil) then
if (pa^.klass in [proc,func]) or (pb^.klass in [proc,func]) then begin
if cmpparlst(pa^.pflist, pb^.pflist)
then cmppar := comptypes(pa^.idtype,pb^.idtype)
end else cmppar := comptypes(pa^.idtype,pb^.idtype)
end;
{ compare parameter lists }
function cmpparlst{(pla, plb: ctp): boolean};
begin cmpparlst := true;
while (pla <> nil) and (plb <> nil) do begin
if not cmppar(pla,plb) then cmpparlst := false;
pla := pla^.next; plb := plb^.next
end;
if (pla <> nil) or (plb <> nil) then cmpparlst := false
end;
procedure skip(fsys: setofsys);
(*skip input string until relevant symbol found*)
begin
if not eofinp then
begin while not(sy in fsys) and (not eofinp) do insymbol;
if not (sy in fsys) then insymbol
end
end (*skip*) ;
{ output fixed array template }
procedure arrtmp(sp: stp);
var tp: stp; lc: integer; l, h: integer;
begin
if prcode and (sp <> nil) then begin
{ check fixed array type }
if sp^.form = arrays then begin
{ count levels }
lc := 0;
tp := sp; while tp <> nil do
if tp^.form = arrays then begin lc := lc+1; tp := tp^.aeltype end
else tp := nil;
write(prr, 't',' ':7);
genlabel(sp^.tmpl); prtlabel(sp^.tmpl);
write(prr, ' ', lc:1);
while sp <> nil do
if sp^.form = arrays then begin getbounds(sp^.inxtype, l, h);
write(prr, ' ', h-l+1:1); lc := lc+1; sp := sp^.aeltype
end else sp := nil;
writeln(prr)
end
end
end;
procedure constexpr(fsys: setofsys; var fsp: stp; var fvalu: valu); forward;
procedure constfactor(fsys: setofsys; var fsp: stp; var fvalu: valu);
var lsp: stp; lcp: ctp; lvp: csp; test: boolean; lv: valu; i: integer;
begin lsp := nil; fvalu.intval := true; fvalu.ival := 0;
if not(sy in constbegsys) then
begin error(50); skip(fsys+constbegsys) end;
if sy in constbegsys then
begin
if sy = lparent then begin chkstd;
insymbol; constexpr(fsys+[rparent], fsp, fvalu);
if sy = rparent then insymbol else error(4);
lsp := fsp
end else if sy = notsy then begin chkstd;
insymbol; constfactor(fsys+[rparent], fsp, fvalu);
if (fsp <> intptr) and (fsp <> boolptr) then error(134)
else if fvalu.ival < 0 then error(213)
else fvalu.ival := bnot(fvalu.ival);
{ not boolean does not quite work here }
if fsp = boolptr then fvalu.ival := band(fvalu.ival, 1);
lsp := fsp
end else if sy = stringconst then
begin
{ note: this is a bit redundant since insymbol does this
conversion }
if lgth = 1 then lsp := charptr
else
begin
new(lsp,arrays); pshstc(lsp);
with lsp^ do
begin form := arrays; aeltype := charptr; inxtype := nil;
tmpl := -1; size := lgth*charsize; packing := true
end;
arrtmp(lsp) { output fixed template }
end;
fvalu := val; insymbol
end
else if sy = lbrack then begin
{ set }
insymbol;
new(lvp,pset); pshcst(lvp); lvp^.cclass := pset; lvp^.pval := [];
if sy <> rbrack then repeat
constexpr(fsys+[rbrack,comma,range], fsp, fvalu);
if not fvalu.intval then error(134);
if sy = range then begin
insymbol; lv := fvalu;
constexpr(fsys+[rbrack,comma], fsp, fvalu);
if not fvalu.intval then error(134);
if (lv.ival < setlow) or (lv.ival > sethigh) or
(fvalu.ival < setlow) or (fvalu.ival > sethigh) then error(291)
else for i := lv.ival to fvalu.ival do lvp^.pval := lvp^.pval+[i]
end else begin
if (fvalu.ival < setlow) or (fvalu.ival > sethigh) then error(291)
else lvp^.pval := lvp^.pval+[fvalu.ival]
end;
test := sy <> comma;
if not test then insymbol
until test;
if sy = rbrack then insymbol else error(12);
fvalu.intval := false; fvalu.valp := lvp;
new(lsp,power); pshstc(lsp);
with lsp^ do
begin form:=power; elset:=nil; size:=setsize; packing := false;
matchpack := false end;
end else
begin
if sy = ident then
begin searchid([konst],lcp);
with lcp^ do
begin lsp := idtype; fvalu := values end;
insymbol;
end
else
if sy = intconst then
begin lsp := intptr; fvalu := val; insymbol end
else
if sy = realconst then
begin lsp := realptr; fvalu := val; insymbol end
else
begin error(106); skip(fsys) end
end;
if not (sy in fsys) then
begin error(6); skip(fsys) end
end;
fsp := lsp
end (*constfactor*) ;
procedure constterm(fsys: setofsys; var fsp: stp; var fvalu: valu);
var lvp: csp; lv: valu; lop: operatort; lsp: stp;
begin
constfactor(fsys+[mulop], fsp, fvalu);
while (sy = mulop) and (op in [mul,rdiv,idiv,imod,andop]) do begin
chkstd; lv := fvalu; lsp := fsp; lop := op; insymbol;
constfactor(fsys+[mulop], fsp, fvalu);
lvp := nil;
if ((lop in [mul,minus]) and ((lsp = realptr) or (fsp = realptr))) or
(lop = rdiv) then
begin new(lvp,reel); pshcst(lvp); lvp^.cclass := reel end;
case lop of { operator }
{ * } mul: if (lsp = intptr) and (fsp = intptr) then begin
if (lv.ival <> 0) and (fvalu.ival <> 0) then
if abs(lv.ival) > pmmaxint div abs(fvalu.ival) then
begin error(306); fvalu.ival := 0 end
else fvalu.ival := lv.ival*fvalu.ival
end else if (lsp = realptr) and (fsp = realptr) then
lvp^.rval := lv.valp^.rval*fvalu.valp^.rval
else if (lsp = realptr) and (fsp = intptr) then
lvp^.rval := lv.valp^.rval*fvalu.ival
else if (lsp = intptr) and (fsp = realptr) then
lvp^.rval := lv.ival*fvalu.valp^.rval
else error(134);
{ / } rdiv: if (lsp = intptr) and (fsp = intptr) then
lvp^.rval := lv.ival/fvalu.ival
else if (lsp = realptr) and (fsp = realptr) then
lvp^.rval := lv.valp^.rval/fvalu.valp^.rval
else if (lsp = realptr) and (fsp = intptr) then
lvp^.rval := lv.valp^.rval/fvalu.ival
else if (lsp = intptr) and (fsp = realptr) then
lvp^.rval := lv.ival/fvalu.valp^.rval
else error(134);
{ div } idiv: if (lsp = intptr) and (fsp = intptr) then
fvalu.ival := lv.ival div fvalu.ival
else error(134);
{ mod } imod: if (lsp = intptr) and (fsp = intptr) then
fvalu.ival := lv.ival mod fvalu.ival
else error(134);
{ and } andop: if ((lsp = intptr) and (fsp = intptr)) or
((lsp = boolptr) and (fsp = boolptr)) then
if (lv.ival < 0) or (fvalu.ival < 0) then error(213)
else fvalu.ival := band(lv.ival, fvalu.ival)
else error(134);
end;
if lvp <> nil then fvalu.valp := lvp; { place result }
{ mixed types or / = real }
if (lsp = realptr) or (lop = rdiv) then fsp := realptr
end
end (*constterm*) ;
procedure constexpr{(fsys: setofsys; var fsp: stp; var fvalu: valu)};
var sign: (none,pos,neg); lvp,svp: csp; lv: valu; lop: operatort; lsp: stp;
begin sign := none; svp := nil;
if (sy = addop) and (op in [plus,minus]) then
begin if op = plus then sign := pos else sign := neg;
insymbol
end;
constterm(fsys+[addop], fsp, fvalu);
if sign > none then begin { apply sign to number }
if (fsp <> intptr) and (fsp <> realptr) then error(106);
if sign = neg then { must flip sign }
if fsp = intptr then fvalu.ival := -fvalu.ival
else if fsp = realptr then begin new(lvp,reel); pshcst(lvp);
lvp^.cclass := reel; lvp^.rval := -fvalu.valp^.rval;
fvalu.valp := lvp; svp := lvp;
end else begin fvalu.intval := true; fvalu.ival := 0 end
end;
while (sy = addop) and (op in [plus,minus,orop,xorop]) do begin
chkstd; lv := fvalu; lsp := fsp; lop := op; insymbol;
constterm(fsys+[addop], fsp, fvalu);
lvp := nil;
if (lop in [plus,minus]) and ((lsp = realptr) or (fsp = realptr)) then
begin new(lvp,reel); pshcst(lvp); lvp^.cclass := reel end;
case lop of { operator }
{ + } plus: if (lsp = intptr) and (fsp = intptr) then begin
if (lv.ival<0) = (fvalu.ival<0) then
if pmmaxint-abs(lv.ival) < abs(fvalu.ival) then
begin error(306); fvalu.ival := 0 end
else fvalu.ival := lv.ival+fvalu.ival
end else if (lsp = realptr) and (fsp = realptr) then
lvp^.rval := lv.valp^.rval+fvalu.valp^.rval
else if (lsp = realptr) and (fsp = intptr) then
lvp^.rval := lv.valp^.rval+fvalu.ival
else if (lsp = intptr) and (fsp = realptr) then
lvp^.rval := lv.ival+fvalu.valp^.rval
else error(134);
{ - } minus: if (lsp = intptr) and (fsp = intptr) then begin
if (lv.ival<0) <> (fvalu.ival>0) then
if pmmaxint-abs(lv.ival) < abs(fvalu.ival) then
begin error(306); fvalu.ival := 0 end
else fvalu.ival := lv.ival-fvalu.ival
end else if (lsp = realptr) and (fsp = realptr) then
lvp^.rval := lv.valp^.rval-fvalu.valp^.rval
else if (lsp = realptr) and (fsp = intptr) then
lvp^.rval := lv.valp^.rval-fvalu.ival
else if (lsp = intptr) and (fsp = realptr) then
lvp^.rval := lv.ival-fvalu.valp^.rval
else error(134);
{ or } orop: if ((lsp = intptr) and (fsp = intptr)) or
((lsp = boolptr) and (fsp = boolptr)) then
if (lv.ival < 0) or (fvalu.ival < 0) then error(213)
else fvalu.ival := bor(lv.ival, fvalu.ival)
else error(134);
{ xor } xorop: if ((lsp = intptr) and (fsp = intptr)) or
((lsp = boolptr) and (fsp = boolptr)) then
if (lv.ival < 0) or (fvalu.ival < 0) then error(213)
else fvalu.ival := bxor(lv.ival, fvalu.ival)
else error(134)
end;
{ if left negated, recycle it just once }
if svp <> nil then begin putcst(svp); svp := nil end;
if lvp <> nil then fvalu.valp := lvp; { place result }
if lsp = realptr then fsp := realptr { mixed types = real }
end
end (*constexpr*) ;
procedure checkbnds(fsp: stp);
var lmin,lmax: integer;
fsp2: stp;
begin
if fsp <> nil then begin
{ if set use the base type for the check }
fsp2 := fsp;
if fsp^.form = power then fsp := fsp^.elset;
if fsp <> nil then
if fsp <> intptr then
if fsp <> realptr then
if fsp^.form <= subrange then
begin
getbounds(fsp,lmin,lmax);
gen2t(45(*chk*),lmin,lmax,fsp2)
end
end
end (*checkbnds*);
{ find number of containers }
function containers(lsp: stp): integer;
var cc: integer;
begin cc := 0;
while lsp <> nil do
if lsp^.form = arrayc then begin lsp := lsp^.abstype; cc := cc+1 end
else lsp := nil;
containers := cc
end;
{ find base size of container or array series }
function containerbase(lsp: stp): integer;
var bp: stp;
begin bp := nil;
while lsp <> nil do
if lsp^.form = arrayc then lsp := lsp^.abstype
else if lsp^.form = arrays then lsp := lsp^.aeltype
else begin bp := lsp; lsp := nil end;
if bp = nil then containerbase := 0
else containerbase := bp^.size
end;
procedure load;
begin
with gattr do
if typtr <> nil then
begin
case kind of
cst: if (typtr^.form <= subrange) and (typtr <> realptr) then
if typtr = boolptr then gen2(51(*ldc*),3,cval.ival)
else
if typtr=charptr then
gen2(51(*ldc*),6,cval.ival)
else gen2(51(*ldc*),1,cval.ival)
else
if typtr = nilptr then gen2(51(*ldc*),4,0)
else
if cstptrix >= cstoccmax then error(254)
else
begin cstptrix := cstptrix + 1;
cstptr[cstptrix] := cval.valp;
if typtr = realptr then
gen2(51(*ldc*),2,cstptrix)
else
gen2(51(*ldc*),5,cstptrix)
end;
varbl: case access of
drct: if vlevel<=1 then begin
if (chkext(symptr) or chkfix(symptr)) and
(dplmt <> 0) then begin
{ labeled base with offset, need to change
to address load with offset }
if chkfix(symptr) then
gen1s(114(*lto*),dplmt,symptr)
else gen1s(37(*lao*),dplmt,symptr);
gen1t(35(*ind*),dplmt,typtr);
end else begin
if chkfix(symptr) then
gen1ts(8(*ltc*),dplmt,typtr,symptr)
else gen1ts(39(*ldo*),dplmt,typtr,symptr)
end
end else
gen2t(54(*lod*),level-(level-vlevel),dplmt,
typtr);
indrct: gen1t(35(*ind*),idplmt,typtr);
inxd: error(400)
end;
expr:
end;
kind := expr;
{ operand is loaded, and subranges are now normalized to their
base type }
typtr := basetype(typtr);
symptr := nil { break variable association }
end
end (*load*) ;
procedure loadaddress;
begin
with gattr do
if typtr <> nil then
begin
case kind of
cst: if stringt(typtr) then
if cstptrix >= cstoccmax then error(254)
else
begin cstptrix := cstptrix + 1;
cstptr[cstptrix] := cval.valp;
gen1(38(*lca*),cstptrix)
end
else error(403);
varbl: case access of
drct: if vlevel <= 1 then begin
if chkfix(symptr) then
gen1s(114(*lto*),dplmt,symptr)
else gen1s(37(*lao*),dplmt,symptr);
{ if there is an offset left in the address,
apply it now }
if (chkext(symptr) or chkfix(symptr)) and
(dplmt <> 0) then
gen1t(34(*inc*),idplmt,nilptr);
end else gen2(50(*lda*),level-(level-vlevel),dplmt);
indrct: if idplmt <> 0 then
gen1t(34(*inc*),idplmt,nilptr);
inxd: error(404)
end;
expr: gen1(118(*lsa*),0)
end;
if typtr^.form = arrayc then if pickup then begin
{ it's a container, load a complex pointer based on that }
if dblptr then gen0(111(*ldp*)) else begin
gen0(98(*lcp*));
{ if level is at bottom, simplify the template }
if containers(typtr) = 1 then gen0(108(*spc*))
end
end;
kind := varbl; access := indrct; idplmt := 0; packing := false;
symptr := nil { break variable association }
end
end (*loadaddress*) ;
procedure store(var fattr: attr);
var lsize: addrrange;
begin
with fattr do
if typtr <> nil then
case access of
drct: if vlevel <= 1 then gen1ts(43(*sro*),dplmt,typtr,symptr)
else gen2t(56(*str*),level-(level-vlevel),dplmt,typtr);
indrct: if idplmt <> 0 then error(401)
else if typtr^.form in [records,arrays] then begin
lsize := typtr^.size;
alignu(parmptr,lsize);
gen2t(26(*sto*),typtr^.size, lsize,typtr);
mesl(adrsize+lsize)
end else
gen0t(26(*sto*),typtr);
inxd: error(402)
end
end (*store*) ;
{ rationalize binary container operator }
procedure containerop(var lattr: attr);
var cc: integer; len:addrrange;
begin
{ check one or both operands is container }
if (lattr.typtr^.form = arrayc) or
(gattr.typtr^.form = arrayc) then begin
{ one or both are containers, find the index level }
if lattr.typtr^.form = arrayc then
cc := containers(lattr.typtr)
else
cc := containers(gattr.typtr);
if gattr.kind = expr then begin
{ have to pull pointer over stack bubble }
len := gattr.typtr^.size;
alignu(parmptr,len);
gen1(118(*lsa*),len);
gen0(111(*ldp*));
gen1(118(*lsa*),ptrsize*2)
end;
if gattr.typtr^.form = arrays then begin
{ right is fixed }
if cc = 1 then begin
{ load simple template }
gen2(51(*ldc*),1,spana(gattr.typtr));
gen1(72(*swp*),stackelsize)
end else
{ load complex fixed template }
gen1(105(*lft*),gattr.typtr^.tmpl)
end else if lattr.typtr^.form = arrays then begin
{ left is fixed }
if cc = 1 then
{ load simple template }
gen2(51(*ldc*),1,spana(lattr.typtr))
{ load complex fixed template }
else gen1(105(*lft*),lattr.typtr^.tmpl);
gen1(72(*swp*),ptrsize*3) { swap under right side and fix addr }
end;
{ compare templates }
if cc = 1 then gen0(99(*cps*)) { simple compare }
else gen1(100(*cpc*),cc); { complex compare }
end
end;
function parnum(fcp: ctp): integer;
var pn: integer;
begin
pn := 0; fcp := fcp^.pflist;
while fcp <> nil do begin pn := pn+1; fcp := fcp^.next end;
parnum := pn
end;
function partype(fcp: ctp; pn: integer): stp;
begin fcp := fcp^.pflist;
while (pn > 1) and (fcp <> nil) do begin fcp := fcp^.next; pn := pn-1 end;
if fcp = nil then partype := nil else partype := fcp^.idtype
end;
{ compare parameter type to actual type }
function cmptyp(pt, at: stp): boolean;
begin cmptyp := false;
if comptypes(pt, at) then cmptyp := true
else if realt(pt) and intt(at) then cmptyp := true
end;
function ischrcst(var at: attr): boolean;
begin
ischrcst := (at.typtr = charptr) and (at.kind = cst)
end;
{ find matching uary operator overload }
procedure fndopr1(opr: operatort; var fcp: ctp);
var dt: disprange; fcp2: ctp;
begin fcp := nil;
if not iso7185 then begin
dt := top; { search top down }
repeat
while (dt > 0) and (display[dt].oprprc[opr] = nil) do dt := dt-1;
fcp2 := display[dt].oprprc[opr];
fcp := nil; { set not found }
while fcp2 <> nil do begin
if parnum(fcp2) = 1 then
if cmptyp(partype(fcp2, 1), gattr.typtr) then fcp := fcp2;
fcp2 := fcp2^.grpnxt
end;
if dt > 0 then dt := dt-1
until (fcp <> nil) or (dt = 0)
end
end;
{ find matching binary operator overload }
procedure fndopr2(opr: operatort; var lattr: attr; var fcp: ctp);
var dt: disprange; fcp2: ctp;
begin fcp := nil;
if not iso7185 then begin
dt := top; { search top down }
repeat
while (dt > 0) and (display[dt].oprprc[opr] = nil) do dt := dt-1;
fcp2 := display[dt].oprprc[opr];
fcp := nil; { set not found }
while fcp2 <> nil do begin
if parnum(fcp2) = 2 then
if cmptyp(partype(fcp2, 1), lattr.typtr) then
if cmptyp(partype(fcp2, 2), gattr.typtr) then fcp := fcp2;
fcp2 := fcp2^.grpnxt
end;
if dt > 0 then dt := dt-1
until (fcp <> nil) or (dt = 0)
end
end;
procedure expression(fsys: setofsys; threaten: boolean); forward;
procedure callop1(fcp: ctp); forward;
procedure callop2(fcp: ctp; var lattr: attr); forward;
{ check any overloads exist for given operator }
function isopr(opt: operatort): boolean;
var dt: disprange;
begin isopr := false;
dt := top;
while (dt > 0) and (display[dt].oprprc[opt] = nil) do dt := dt-1;
isopr := display[dt].oprprc[opt] <> nil
end;
function taggedrec(fsp: stp): boolean;
var b: boolean;
begin b := false;
if fsp <> nil then
if fsp^.form = tagfld then b := true
else if fsp^.form = records then
if fsp^.recvar <> nil then
b := fsp^.recvar^.form = tagfld;
taggedrec := b
end;
procedure selector(fsys: setofsys; fcp: ctp; skp: boolean);
var lattr: attr; lcp: ctp; lsize: addrrange; lmin,lmax: integer;
id: stp; lastptr: boolean; cc: integer; ct: boolean;
function schblk(fcp: ctp): boolean;
var i: disprange; f: boolean;
begin
f := false;
for i := level downto 2 do if display[i].bname = fcp then f := true;
schblk := f
end;
procedure checkvrnt(lcp: ctp);
var vp: stp; vl: ctp; gattrs: attr;
begin
if chkvar then begin
if lcp^.klass = field then begin
vp := lcp^.varnt; vl := lcp^.varlb;
if (vp <> nil) and (vl <> nil) then
if (vl^.name <> nil) or chkudtf then begin { is a variant }
if chkudtf and (vl^.name = nil) and (vp <> nil) then begin
{ tagfield is unnamed and checking is on, force tagfield
assignment }
gattrs := gattr;
with gattr, vl^ do begin
typtr := idtype;
case access of
drct: dplmt := dplmt + fldaddr;
indrct: begin
idplmt := idplmt + fldaddr;
gen0t(76(*dup*),nilptr)
end;
inxd: error(406)
end;
loadaddress;
gen2(51(*ldc*),1,vp^.varval.ival);
if chkvbk then
genctaivtcvb(95(*cvb*),vl^.varsaddr-fldaddr,vl^.varssize,
vl^.vartl,vl^.idtype);
if debug then
genctaivtcvb(82(*ivt*),vl^.varsaddr-fldaddr,vl^.varssize,
vl^.vartl,vl^.idtype);
gen0t(26(*sto*),basetype(idtype));
end;
gattr := gattrs
end;
gattrs := gattr;
with gattr, vl^ do begin
typtr := idtype;
case access of
drct: dplmt := dplmt + fldaddr;
indrct: begin
idplmt := idplmt + fldaddr;
gen0t(76(*dup*),nilptr)
end;
inxd: error(406)
end;
load;
gen0(78(*cks*));
while vp <> nil do begin
gen1t(75(*ckv*),vp^.varval.ival, basetype(idtype));
vp := vp^.caslst
end;
gen0(77(*cke*));
end;
gattr := gattrs
end
end
end
end;
begin { selector }
lastptr := false; { set last index op not ptr }
with fcp^, gattr do
begin symptr := nil; typtr := idtype; spv := false; kind := varbl;
packing := false; packcom := false; tagfield := false; ptrref := false;
vartl := -1; pickup := true; dblptr := false;
case klass of
vars: begin symptr := fcp;
if typtr <> nil then
begin packing := typtr^.packing; dblptr := fcp^.dblptr end;
if vkind = actual then
begin access := drct; vlevel := vlev;
dplmt := vaddr
end
else
begin
{ if container, just load the address of it, the complex
pointer is loaded when the address is loaded }
ct := false; if typtr <> nil then ct := typtr^.form = arrayc;
if ct then gen2(50(*lda*),level-(level-vlev),vaddr)
else gen2t(54(*lod*),level-(level-vlev),vaddr,nilptr);
access := indrct; idplmt := 0
end;
end;
fixedt: begin symptr := fcp;
if typtr <> nil then packing := typtr^.packing;
access := drct; vlevel := 0; dplmt := 0
end;
field:
with display[disx] do begin
gattr.packcom := display[disx].packing;
if typtr <> nil then
gattr.packing := display[disx].packing or typtr^.packing;
gattr.ptrref := display[disx].ptrref;
gattr.tagfield := fcp^.tagfield;
gattr.taglvl := fcp^.taglvl;
gattr.varnt := fcp^.varnt;
if gattr.tagfield then
gattr.vartagoff := fcp^.varsaddr-fldaddr;
gattr.varssize := fcp^.varssize;
gattr.vartl := fcp^.vartl;
if occur = crec then
begin access := drct; vlevel := clev;
dplmt := cdspl + fldaddr
end
else if occur = vrec then
begin
{ override to local for with statement }
gen2t(54(*lod*),level,vdspl,nilptr);
access := indrct; idplmt := fldaddr
end
else
begin
if level = 1 then gen1t(39(*ldo*),vdspl,nilptr)
else gen2t(54(*lod*),level,vdspl,nilptr);
access := indrct; idplmt := fldaddr
end
end;
func:
if pfdeckind = standard then
begin error(150); typtr := nil end
else
begin
if pfkind = formal then error(151)
else
if not schblk(fcp) then error(192);
begin access := drct; vlevel := pflev + 1;
{ determine size of FR. This is a bit of a hack
against the fact that int/ptr results fit in
the upper half of the FR. }
id := basetype(fcp^.idtype);
lsize := parmsize; if id <> nil then lsize := id^.size;
dplmt := marksize+ptrsize+adrsize+locpar { addr of fr }
end
end;
proc: { nothing, its an error case }
end (*case*)
end (*with*);
if not (sy in selectsys + fsys) and not skp then
begin error(59); skip(selectsys + fsys) end;
while sy in selectsys do
begin
(*[*) if sy = lbrack then
begin gattr.ptrref := false;
repeat lattr := gattr;
with lattr do
if typtr <> nil then begin
if not arrayt(typtr) then begin error(138); typtr := nil end
end;
loadaddress;
insymbol; expression(fsys + [comma,rbrack], false);
load;
if gattr.typtr <> nil then
if gattr.typtr^.form<>scalar then error(113)
else if not comptypes(gattr.typtr,intptr) then
gen0t(58(*ord*),gattr.typtr);
if lattr.typtr <> nil then
with lattr.typtr^ do
begin
if form = arrayc then begin
{ note containers merge index and bounds check }
if gattr.typtr <> intptr then error(139)
end else if comptypes(inxtype,gattr.typtr) then
begin
if inxtype <> nil then
begin getbounds(inxtype,lmin,lmax);
if debug then
gen2t(45(*chk*),lmin,lmax,intptr);
if lmin>0 then gen1t(31(*dec*),lmin,intptr)
else if lmin<0 then
gen1t(34(*inc*),-lmin,intptr);
(*or simply gen1(31,lmin)*)
end
end
else error(139);
with gattr do
begin
if lattr.typtr^.form = arrays then typtr := aeltype
else typtr := abstype;
kind := varbl;
access := indrct; idplmt := 0; packing := false;
packcom := false; tagfield := false; ptrref := false;
vartl := -1; pickup := false; dblptr := false;
end;
if gattr.typtr <> nil then
begin
gattr.packcom := lattr.packing;
gattr.packing :=
lattr.packing or gattr.typtr^.packing;
lsize := gattr.typtr^.size; { get base size }
cc := containers(lattr.typtr);
if lattr.typtr^.form = arrays then gen1(36(*ixa*),lsize)
else if cc = 1 then
gen1(103(*cxs*),lsize) { simple container index }
else begin { complex container index }
gen2(104(*cxc*),cc,containerbase(gattr.typtr));
{ if level is at bottom, simplify the template }
if cc = 2 then gen0(108(*spc*))
end
end
end
else gattr.typtr := nil
until sy <> comma;
if sy = rbrack then insymbol else error(12);
lastptr := false { set not pointer op }
end (*if sy = lbrack*)
else
(*.*) if sy = period then
begin
with gattr do
begin
if typtr <> nil then begin
if typtr^.form <> records then
begin error(140); typtr := nil end
end;
insymbol;
if sy = ident then
begin
if typtr <> nil then
begin searchsection(typtr^.fstfld,lcp);
if lcp = nil then
begin error(152); typtr := nil end
else
with lcp^ do
begin checkvrnt(lcp);
typtr := idtype;
gattr.packcom := gattr.packing;
if typtr <> nil then
gattr.packing :=
gattr.packing or typtr^.packing;
gattr.tagfield := lcp^.tagfield;
gattr.taglvl := lcp^.taglvl;
gattr.varnt := lcp^.varnt;
if gattr.tagfield then
gattr.vartagoff := lcp^.varsaddr-fldaddr;
gattr.varssize := lcp^.varssize;
{ only set ptr offset ref if last was ptr }
gattr.ptrref := lastptr;
gattr.vartl := lcp^.vartl;
gattr.pickup := false;
gattr.dblptr := false;
case access of
drct: dplmt := dplmt + fldaddr;
indrct: idplmt := idplmt + fldaddr;
inxd: error(407)
end
end
end;
insymbol
end (*sy = ident*)
else error(2)
end; (*with gattr*)
lastptr := false { set last not ptr op }
end (*if sy = period*)
else
(*^*) begin
if gattr.typtr <> nil then
with gattr,typtr^ do
if form = pointer then
begin load;
if eltype <> nil then
if eltype^.form = arrayc then begin
{ it's a container, load a complex pointer based on
that }
gen0t(76(*dup*),nilptr); { copy that }
{ index data }
gen1t(34(*inc*),containers(eltype)*intsize,nilptr);
{ if level is at bottom, simplify the template }
if containers(eltype) = 1 then gen0(108(*spc*))
end;
typtr := eltype;
if debug then begin
if taggedrec(eltype) then
gen2t(80(*ckl*),1,maxaddr,nilptr)
else gen2t(45(*chk*),1,maxaddr,nilptr);
end;
with gattr do
begin kind := varbl; access := indrct; idplmt := 0;
packing := false; packcom := false;
tagfield := false; ptrref := true; vartl := -1;
pickup := false; dblptr := false;
end
end
else
if form = files then begin loadaddress;
{ generate buffer validate for file }
if typtr = textptr then
gen1(30(*csp*), 46(*fbv*))
else begin
gen2(51(*ldc*),1,filtype^.size);
gen1(30(*csp*),47(*fvb*))
end;
{ index buffer }
gen1t(34(*inc*),fileidsize,gattr.typtr);
typtr := filtype;
end else error(141);
insymbol;
lastptr := true { set last was ptr op }
end;
if not (sy in fsys + selectsys) then
begin error(6); skip(fsys + selectsys) end
end (*while*)
end (*selector*) ;
procedure fixpar(fsp,asp: stp);
var cc: integer;
begin
if fsp <> nil then begin
if (asp^.form = arrays) and (fsp^.form = arrayc) then begin
{ fixed into container }
cc := containers(fsp);
if cc = 1 then begin
{ load simple template }
gen2(51(*ldc*),1,spana(asp));
gen1(72(*swp*),stackelsize)
end else
{ load complex fixed template }
gen1(105(*lft*),asp^.tmpl)
end else if (asp^.form = arrayc) and
(fsp^.form = arrays) then begin
{ container into fixed, load template for fixed side }
cc := containers(asp);
if cc = 1 then begin
{ load simple template }
gen2(51(*ldc*),1,span(fsp));
gen2(51(*ldc*),4,0) { load dummy address }
end else begin
{ load complex fixed template }
gen2(51(*ldc*),4,0); { load dummy address }
gen1(105(*lft*),fsp^.tmpl);
end;
{ compare templates }
if cc = 1 then gen0(99(*cps*)) { simple compare }
else gen1(100(*cpc*),cc); { complex compare }
{ discard the templates }
gen1(71(*dmp*),ptrsize*2);
gen1(72(*swp*),ptrsize);
gen1(71(*dmp*),ptrsize)
end
end
end;
procedure call(fsys: setofsys; fcp: ctp; inherit: boolean; isfunc: boolean);
var lkey: keyrng;
procedure variable(fsys: setofsys; threaten: boolean);
var lcp: ctp;
begin
if sy = ident then
begin searchid([vars,fixedt,field],lcp); insymbol end
else begin error(2); lcp := uvarptr end;
if threaten and (lcp^.klass = vars) then with lcp^ do begin
if vlev < level then threat := true;
if forcnt > 0 then error(195);
if part = ptview then error(290)
end;
selector(fsys,lcp, false);
if gattr.kind = expr then error(287)
end (*variable*) ;
procedure chkhdr;
var lcp: ctp; dummy: boolean;
begin
if sy = ident then begin { test for file }
searchidnenm([vars],lcp,dummy);
if (lcp = inputptr) and not inputptr^.hdr then error(175)
else if (lcp = outputptr) and not outputptr^.hdr then error(176)
else if (lcp = prdptr) and not prdptr^.hdr then error(217)
else if (lcp = prrptr) and not prrptr^.hdr then error(218)
else if (lcp = errorptr) and not errorptr^.hdr then error(219)
else if (lcp = listptr) and not listptr^.hdr then error(220)
else if (lcp = commandptr) and not commandptr^.hdr then error(221)
end
end;
procedure getputresetrewriteprocedure;
begin chkhdr; variable(fsys + [rparent], false); loadaddress;
if gattr.typtr <> nil then
if gattr.typtr^.form <> files then error(116);
if lkey <= 2 then begin
if gattr.typtr = textptr then gen1(30(*csp*),lkey(*get,put*))
else begin
if gattr.typtr <> nil then
gen2(51(*ldc*),1,gattr.typtr^.filtype^.size);
if lkey = 1 then gen1(30(*csp*),38(*gbf*))
else gen1(30(*csp*),39(*pbf*))
end
end else
if gattr.typtr = textptr then begin
if lkey = 3 then gen1(30(*csp*),25(*reset*))
else gen1(30(*csp*),26(*rewrite*))
end else begin
if lkey = 3 then gen1(30(*csp*),36(*reset*))
else gen1(30(*csp*),37(*rewrite*))
end
end (*getputresetrewrite*) ;
procedure pageprocedure;
var llev:levrange;
begin
llev := 1;
if sy = lparent then
begin insymbol; chkhdr;
variable(fsys + [rparent], false); loadaddress;
if gattr.typtr <> nil then
if gattr.typtr <> textptr then error(116);
if sy = rparent then insymbol else error(4)
end else begin
if not outputptr^.hdr then error(176);
gen1(37(*lao*),outputptr^.vaddr);
end;
gen1(30(*csp*),24(*page*))
end (*page*) ;
procedure readprocedure;
var lsp : stp;
txt: boolean; { is a text file }
deffil: boolean; { default file was loaded }
test: boolean;
lmin,lmax: integer;
len:addrrange;
fld, spad: boolean;
cp: boolean;
begin
txt := true; deffil := true; cp := false;
if sy = lparent then
begin insymbol; chkhdr;
variable(fsys + [comma,colon,rparent], true);
if gattr.typtr <> nil then cp := gattr.typtr^.form = arrayc;
lsp := gattr.typtr; test := false;
if lsp <> nil then
if lsp^.form = files then
with gattr, lsp^ do
begin
txt := lsp = textptr;
if not txt and (lkey = 11) then error(116);
loadaddress; deffil := false;
if sy = rparent then
begin if lkey = 5 then error(116);
test := true
end
else
if sy <> comma then
begin error(116);
skip(fsys + [comma,colon,rparent])
end;
if sy = comma then
begin insymbol;
variable(fsys + [comma,colon,rparent], true);
if gattr.typtr <> nil then
cp := gattr.typtr^.form = arrayc
end
else test := true
end
else if not inputptr^.hdr then error(175);
if not test then
repeat loadaddress;
if deffil then begin
{ file was not loaded, we load and swap so that it ends up
on the bottom.}
gen1(37(*lao*),inputptr^.vaddr);
{ note 2nd is always pointer }
if cp then gen1(72(*swp*),ptrsize+intsize)
else gen1(72(*swp*),ptrsize);
deffil := false
end;
if txt then begin lsp := gattr.typtr;
fld := false; spad := false;
if sy = colon then begin { field }
chkstd; insymbol;
if (sy = mulop) and (op = mul) then begin
spad := true; insymbol;
if not stringt(lsp) then error(215);
end else begin
expression(fsys + [comma,rparent], false);
if gattr.typtr <> nil then
if basetype(gattr.typtr) <> intptr then error(116);
load; fld := true
end
end;
if lsp <> nil then
if (lsp^.form <= subrange) or
(stringt(lsp) and not iso7185) then
if comptypes(intptr,lsp) then begin
if debug then begin
getbounds(lsp, lmin, lmax);
gen1t(51(*ldc*),lmin,basetype(lsp));
gen1t(51(*ldc*),lmax,basetype(lsp));
if fld then gen1(30(*csp*),74(*ribf*))
else gen1(30(*csp*),40(*rib*))
end else if fld then gen1(30(*csp*),75(*rdif*))
else gen1(30(*csp*),3(*rdi*))
end else
if comptypes(realptr,lsp) then
if fld then gen1(30(*csp*),76(*rdrf*))
else gen1(30(*csp*),4(*rdr*))
else
if comptypes(charptr,lsp) then begin
if debug then begin
getbounds(lsp, lmin, lmax);
gen2(51(*ldc*),6,lmin);
gen2(51(*ldc*),6,lmax);
if fld then gen1(30(*csp*),77(*rcbf*))
else gen1(30(*csp*),41(*rcb*))
end else if fld then gen1(30(*csp*),78(*rdcf*))
else gen1(30(*csp*),5(*rdc*))
end else if stringt(lsp) then begin
len := lsp^.size div charmax;
if not cp then gen2(51(*ldc*),1,len)
else gen1(72(*swp*),intsize);
if fld then gen1(30(*csp*),79(*rdsf*))
else if spad then gen1(30(*csp*),80(*rdsp*))
else gen1(30(*csp*),73(*rds*))
end else error(153)
else error(116);
end else begin { binary file }
if not comptypes(gattr.typtr,lsp^.filtype) then error(129);
gen2(51(*ldc*),1,lsp^.filtype^.size);
gen1(30(*csp*),35(*rbf*))
end;
test := sy <> comma;
if not test then
begin insymbol; variable(fsys + [comma,colon,rparent], true);
if gattr.typtr <> nil then cp := gattr.typtr^.form = arrayc
end
until test;
if sy = rparent then insymbol else error(4)
end
else begin
if not inputptr^.hdr then error(175);
if lkey = 5 then error(116);
gen1(37(*lao*),inputptr^.vaddr);
end;
if lkey = 11 then gen1(30(*csp*),21(*rln*));
{ remove the file pointer from stack }
gen1(71(*dmp*),ptrsize);
end (*read*) ;
procedure writeprocedure;
var lsp,lsp1: stp; default, default1: boolean; llkey: 1..15;
len:addrrange; strspc: addrrange;
txt: boolean; { is a text file }
byt: boolean; { is a byte file }
deffil: boolean; { default file was loaded }
test: boolean;
r: integer; { radix of print }
spad: boolean; { write space padded string }
ledz: boolean; { use leading zeros }
cpx: boolean; { is complex pointer }
onstk: boolean; { expression result on stack }
begin llkey := lkey; txt := true; deffil := true; byt := false;
if sy = lparent then
begin insymbol; chkhdr;
expression(fsys + [comma,colon,rparent,hexsy,octsy,binsy], false);
onstk := gattr.kind = expr;
lsp := gattr.typtr; test := false;
if lsp <> nil then
if lsp^.form = files then
with gattr, lsp^ do
begin lsp1 := lsp;
txt := lsp = textptr;
if not txt then begin
if lkey = 12 then error(116);
byt := isbyte(lsp^.filtype)
end;
loadaddress; deffil := false;
if sy = rparent then
begin if llkey = 6 then error(116);
test := true
end
else
if sy <> comma then
begin error(116); skip(fsys+[comma,rparent]) end;
if sy = comma then
begin insymbol;
expression(fsys+[comma,colon,rparent,hexsy,octsy,binsy],
false);
onstk := gattr.kind = expr
end
else test := true
end
else if not outputptr^.hdr then error(176);
if not test then
repeat
lsp := gattr.typtr;
if lsp <> nil then
if lsp^.form <= subrange then load else loadaddress;
lsp := basetype(lsp); { remove any subrange }
if deffil then begin
{ file was not loaded, we load and swap so that it ends up
on the bottom.}
gen1(37(*lao*),outputptr^.vaddr);
if lsp <> nil then begin
if lsp^.form <= subrange then begin
if lsp^.size < stackelsize then
{ size of 2nd is minimum stack }
gen1(72(*swp*),stackelsize)
else
gen1(72(*swp*),lsp^.size) { size of 2nd is operand }
end else
{ 2nd is pointer, either simple or complex }
if lsp^.form = arrayc then gen1(72(*swp*),ptrsize*2)
else gen1(72(*swp*),ptrsize);
end;
deffil := false
end;
if txt then begin
{ check radix markers }
r := 10;
if sy = hexsy then begin r := 16; insymbol end
else if sy = octsy then begin r := 8; insymbol end
else if sy = binsy then begin r := 2; insymbol end;
if (r <> 10) and (lsp <> intptr) then error(214);
spad := false; { set no padded string }
ledz := false; { set no leading zero }
{ if string and not container, convert to complex }
if lsp <> nil then
if stringt(lsp) and not (lsp^.form = arrayc) then begin
len := lsp^.size div charmax;
gen2(51(*ldc*),1,len); { load len }
gen1(72(*swp*),stackelsize) { swap ptr and len }
end;
if sy = colon then
begin insymbol;
if (sy = mulop) and (op = mul) then begin
spad := true; insymbol;
if not stringt(lsp) then error(215)
end else begin
if sy = numsy then
begin chkstd; ledz := true; insymbol end;
expression(fsys + [comma,colon,rparent], false);
if gattr.typtr <> nil then
if basetype(gattr.typtr) <> intptr then error(116);
load;
end;
default := false
end
else default := true;
if sy = colon then
begin insymbol;
expression(fsys + [comma,rparent], false);
if gattr.typtr <> nil then
if basetype(gattr.typtr) <> intptr then error(116);
if lsp <> realptr then error(124);
load; default1 := false
end else default1 := true;
if lsp = intptr then
begin if default then gen2(51(*ldc*),1,intdeff);
if ledz then begin { leading zeros }
if r = 10 then gen1(30(*csp*),69(*wiz*))
else if r = 16 then gen1(30(*csp*),70(*wizh*))
else if r = 8 then gen1(30(*csp*),71(*wizo*))
else if r = 2 then gen1(30(*csp*),72(*wizb*))
end else begin
if r = 10 then gen1(30(*csp*),6(*wri*))
else if r = 16 then gen1(30(*csp*),65(*wrih*))
else if r = 8 then gen1(30(*csp*),66(*wrio*))
else if r = 2 then gen1(30(*csp*),67(*wrib*))
end
end
else
if lsp = realptr then
begin
if default1 then begin
if default then gen2(51(*ldc*),1,reldeff);
gen1(30(*csp*),8(*wrr*))
end else begin
if default then gen2(51(*ldc*),1,reldeff);
gen1(30(*csp*),28(*wrf*))
end
end
else
if lsp = charptr then
begin if default then gen2(51(*ldc*),1,chrdeff);
gen1(30(*csp*),9(*wrc*))
end
else
if lsp = boolptr then
begin if default then gen2(51(*ldc*),1,boldeff);
gen1(30(*csp*),27(*wrb*))
end
else
if lsp <> nil then
begin
if lsp^.form = scalar then error(236)
else
if stringt(lsp) then begin
if onstk then begin
strspc := lsp^.size;
alignu(parmptr,strspc);
gen1(118(*lsa*),strspc+ptrsize+intsize);
gen1t(35(*ind*),0,nilptr);
gen1(72(*swp*),stackelsize*2)
end;
if lsp = nil then cpx := false
else cpx := lsp^.form = arrayc;
if cpx then begin { complex }
if default then begin
{ no field, need to duplicate len to make the
field }
gen1(72(*swp*),stackelsize); { swap ptr and len }
gen0t(76(*dup*),nilptr); { make copy len }
gen1(72(*swp*),stackelsize*2); { back in order }
end
end else begin { standard array }
len := lsp^.size div charmax;
if default then gen2(51(*ldc*),1,len)
end;
if spad then gen1(30(*csp*),68(*wrsp*))
else gen1(30(*csp*),10(*wrs*));
if onstk then gen1(71(*dmp*),strspc+ptrsize)
end else error(116)
end
end else begin { binary file }
if not comptypes(lsp1^.filtype,lsp) then error(129);
if lsp <> nil then
if (lsp = intptr) and not byt then gen1(30(*csp*),31(*wbi*))
else
if lsp = realptr then gen1(30(*csp*),32(*wbr*))
else
if lsp = charptr then gen1(30(*csp*),33(*wbc*))
else
if lsp = boolptr then gen1(30(*csp*),34(*wbb*))
else
if lsp^.form <= subrange then begin
if byt then gen1(30(*csp*),48(*wbx*))
else gen1(30(*csp*),31(*wbi*))
end else begin
gen2(51(*ldc*),1,lsp1^.filtype^.size);
gen1(30(*csp*),30(*wbf*))
end
end;
test := sy <> comma;
if not test then
begin insymbol;
expression(fsys + [comma,colon,rparent,hexsy,octsy,binsy],
false);
onstk := gattr.kind = expr
end
until test;
if sy = rparent then insymbol else error(4)
end else begin
if not outputptr^.hdr then error(176);
if lkey = 6 then error(116);
gen1(37(*lao*),outputptr^.vaddr);
end;
if llkey = 12 then (*writeln*)
gen1(30(*csp*),22(*wln*));
{ remove the file pointer from stack }
gen1(71(*dmp*),ptrsize)
end (*write*) ;
procedure packprocedure;
var lsp,lsp1: stp; lb, bs: integer; lattr: attr;
begin variable(fsys + [comma,rparent], false); loadaddress;
lsp := nil; lsp1 := nil; lb := 1; bs := 1;
lattr := gattr;
if gattr.typtr <> nil then
with gattr.typtr^ do
if form = arrays then
begin lsp := inxtype; lsp1 := aeltype;
if (inxtype = charptr) or (inxtype = boolptr) then lb := 0
else if inxtype^.form = subrange then lb := inxtype^.min.ival;
bs := aeltype^.size
end
else error(116);
if sy = comma then insymbol else error(20);
expression(fsys + [comma,rparent], false); load;
if gattr.typtr <> nil then
if gattr.typtr^.form <> scalar then error(116)
else
if not comptypes(lsp,gattr.typtr) then error(116);
gen2(51(*ldc*),1,lb);
gen0(21(*sbi*));
gen2(51(*ldc*),1,bs);
gen0(15(*mpi*));
if sy = comma then insymbol else error(20);
variable(fsys + [rparent], false); loadaddress;
if gattr.typtr <> nil then
with gattr.typtr^ do
if form = arrays then
begin
if not comptypes(aeltype,lsp1) then error(116)
end
else error(116);
if (gattr.typtr <> nil) and (lattr.typtr <> nil) then
gen2(62(*pck*),gattr.typtr^.size,lattr.typtr^.size)
end (*pack*) ;
procedure unpackprocedure;
var lsp,lsp1: stp; lattr,lattr1: attr; lb, bs: integer;
begin variable(fsys + [comma,rparent], false); loadaddress;
lattr := gattr;
lsp := nil; lsp1 := nil; lb := 1; bs := 1;
if gattr.typtr <> nil then
with gattr.typtr^ do
if form = arrays then lsp1 := aeltype
else error(116);
if sy = comma then insymbol else error(20);
variable(fsys + [comma,rparent], false); loadaddress;
lattr1 := gattr;
if gattr.typtr <> nil then
with gattr.typtr^ do
if form = arrays then
begin
if not comptypes(aeltype,lsp1) then error(116);
if (inxtype = charptr) or (inxtype = boolptr) then lb := 0
else if inxtype^.form = subrange then lb := inxtype^.min.ival;
bs := aeltype^.size;
lsp := inxtype;
end
else error(116);
if sy = comma then insymbol else error(20);
expression(fsys + [rparent], false); load;
if gattr.typtr <> nil then
if gattr.typtr^.form <> scalar then error(116)
else
if not comptypes(lsp,gattr.typtr) then error(116);
gen2(51(*ldc*),1,lb);
gen0(21(*sbi*));
gen2(51(*ldc*),1,bs);
gen0(15(*mpi*));
if (lattr.typtr <> nil) and (lattr1.typtr <> nil) then
gen2(63(*upk*),lattr.typtr^.size,lattr1.typtr^.size)
end (*unpack*) ;
procedure newdisposeprocedure(disp: boolean);
label 1;
var lsp,lsp1,lsp2,lsp3: stp; varts: integer;
lsize: addrrange; lval: valu; tagc: integer; tagrec: boolean;
ct: boolean; cc,pc: integer;
begin
if disp then begin
expression(fsys + [comma, rparent], false);
load
end else begin
variable(fsys + [comma,rparent], false);
loadaddress
end;
ct := false;
if gattr.typtr <> nil then
if gattr.typtr^.form = pointer then
if gattr.typtr^.eltype <> nil then
ct := gattr.typtr^.eltype^.form = arrayc;
if ct then begin { container array }
if disp then gen0(113(*vdd*))
else begin lsp := gattr.typtr^.eltype;
cc := containers(lsp); { find no. containers }
pc := 0;
while sy = comma do begin insymbol;
expression(fsys+[comma,rparent], false); load;
if gattr.typtr <> nil then
if basetype(gattr.typtr) <> intptr then error(243);
pc := pc+1;
gen1(72(*swp*),ptrsize) { keep the var address on top }
end;
if pc <> cc then error(269);
{ issue vector init dynamic instruction }
gen2(112(*vin*),pc,containerbase(lsp));
{ remove initializers, var addr }
mesl(pc*intsize+adrsize)
end
end else begin
lsp := nil; varts := 0; lsize := 0; tagc := 0; tagrec := false;
if gattr.typtr <> nil then
with gattr.typtr^ do
if form = pointer then
begin
if eltype <> nil then
begin lsize := eltype^.size;
if eltype^.form = records then lsp := eltype^.recvar
end
end
else error(116);
tagrec := taggedrec(lsp);
while sy = comma do
begin insymbol;constexpr(fsys + [comma,rparent],lsp1,lval);
if not lval.intval then
begin lval.intval := true; lval.ival := 1 end;
varts := varts + 1; lsp2 := lsp1;
(*check to insert here: is constant in tagfieldtype range*)
if lsp = nil then error(158)
else
if lsp^.form <> tagfld then error(162)
else
if lsp^.tagfieldp <> nil then
if stringt(lsp1) or (lsp1 = realptr) then error(159)
else
if comptypes(lsp^.tagfieldp^.idtype,lsp1) then
begin
lsp3 := lsp; lsp1 := lsp^.fstvar;
while lsp1 <> nil do
with lsp1^ do
if varval.ival = lval.ival then
begin lsize := size; lsp := subvar;
if debug then begin
if lsp3^.vart = nil then error(510);
if lsp2=charptr then
gen2(51(*ldc*),6,lsp3^.vart^[varval.ival])
else
gen2(51(*ldc*),1,lsp3^.vart^[varval.ival])
end;
tagc := tagc+1;
goto 1
end
else lsp1 := nxtvar;
lsize := lsp^.size; lsp := nil;
end
else error(116);
1: end (*while*) ;
if debug and tagrec then gen2(51(*ldc*),1,tagc);
gen2(51(*ldc*),1,lsize);
if debug and tagrec then begin
if lkey = 9 then gen1(30(*csp*),42(*nwl*))
else gen1(30(*csp*),43(*dsl*));
mesl(tagc*intsize)
end else begin
if lkey = 9 then gen1(30(*csp*),12(*new*))
else gen1(30(*csp*),29(*dsp*))
end
end
end (*newdisposeprocedure*) ;
procedure absfunction;
begin
if gattr.typtr <> nil then
if gattr.typtr = intptr then gen0(0(*abi*))
else
if gattr.typtr = realptr then gen0(1(*abr*))
else begin error(125); gattr.typtr := intptr end
end (*abs*) ;
procedure sqrfunction;
begin
if gattr.typtr <> nil then
if gattr.typtr = intptr then gen0(24(*sqi*))
else
if gattr.typtr = realptr then gen0(25(*sqr*))
else begin error(125); gattr.typtr := intptr end
end (*sqr*) ;
procedure truncfunction;
begin
if gattr.typtr <> nil then
if gattr.typtr <> realptr then error(125);
gen0(27(*trc*));
gattr.typtr := intptr
end (*trunc*) ;
procedure roundfunction;
begin
if gattr.typtr <> nil then
if gattr.typtr <> realptr then error(125);
gen0(61(*rnd*));
gattr.typtr := intptr
end (*round*) ;
procedure oddfunction;
begin
if gattr.typtr <> nil then
if gattr.typtr <> intptr then error(125);
gen0(20(*odd*));
gattr.typtr := boolptr
end (*odd*) ;
procedure ordfunction;
begin
if gattr.typtr <> nil then
if gattr.typtr^.form >= power then error(125);
gen0t(58(*ord*),gattr.typtr);
gattr.typtr := intptr
end (*ord*) ;
procedure chrfunction;
begin
if gattr.typtr <> nil then
if gattr.typtr <> intptr then error(125);
gen0(59(*chr*));
gattr.typtr := charptr
end (*chr*) ;
procedure predsuccfunction;
begin
if gattr.typtr <> nil then
if gattr.typtr^.form <> scalar then error(125);
if lkey = 7 then gen1t(31(*dec*),1,gattr.typtr)
else gen1t(34(*inc*),1,gattr.typtr)
end (*predsucc*) ;
procedure eofeolnfunction;
begin
if sy = lparent then
begin insymbol; variable(fsys + [rparent], false);
if sy = rparent then insymbol else error(4);
loadaddress
end
else begin
if not inputptr^.hdr then error(175);
gen1(37(*lao*),inputptr^.vaddr);
gattr.typtr := textptr
end;
if gattr.typtr <> nil then
if gattr.typtr^.form <> files then error(125)
else if (lkey = 10) and (gattr.typtr <> textptr) then error(116);
if lkey = 9 then begin
if gattr.typtr = textptr then gen1(30(*csp*),44(*eof*))
else gen1(30(*csp*),45(*efb*))
end else gen1(30(*csp*),14(*eln*));
gattr.typtr := boolptr
end (*eof*) ;
procedure assignprocedure;
var len: addrrange; lattr: attr;
begin chkstd; chkhdr;
variable(fsys+[comma,rparent], false); loadaddress;
if gattr.typtr <> nil then
if gattr.typtr^.form <> files then error(125);
if sy = comma then insymbol else error(20);
lattr := gattr;
expression(fsys + [rparent], false); loadaddress;
if not stringt(gattr.typtr) then error(208);
if gattr.typtr <> nil then begin
len := gattr.typtr^.size div charmax;
gen2(51(*ldc*),1,len);
if lattr.typtr = textptr then { text }
gen1(30(*csp*),49(*asst*))
else { binary }
gen1(30(*csp*),59(*assb*))
end
end;
procedure closeupdateappendprocedure;
begin chkstd; chkhdr;
variable(fsys+[rparent], false); loadaddress;
if gattr.typtr <> nil then
if gattr.typtr^.form <> files then error(125);
if lkey = 20 then begin
if gattr.typtr = textptr then { text }
gen1(30(*csp*),50(*clst*))
else { binary }
gen1(30(*csp*),60(*clst*))
end else if lkey = 24 then begin
if gattr.typtr = textptr then error(262);
gen1(30(*csp*),52(*upd*))
end else begin
if gattr.typtr = textptr then { text }
gen1(30(*csp*),53(*appt*))
else { binary }
gen1(30(*csp*),61(*appb*))
end
end;
procedure positionprocedure;
begin chkstd; chkhdr;
variable(fsys+[comma,rparent], false); loadaddress;
if gattr.typtr <> nil then begin
if gattr.typtr^.form <> files then error(125);
if gattr.typtr = textptr then error(262);
end;
if sy = comma then insymbol else error(20);
expression(fsys + [rparent], false); load;
if gattr.typtr <> nil then
if gattr.typtr <> intptr then error(125);
gen1(30(*csp*),51(*pos*));
end;
procedure deleteprocedure;
var len: addrrange;
begin chkstd;
expression(fsys + [rparent], false); loadaddress;
if not stringt(gattr.typtr) then error(208);
if gattr.typtr <> nil then begin
len := gattr.typtr^.size div charmax;
gen2(51(*ldc*),1,len);
gen1(30(*csp*),54(*del*));
end
end;
procedure changeprocedure;
var len: addrrange;
begin chkstd;
expression(fsys + [comma,rparent], false); loadaddress;
if not stringt(gattr.typtr) then error(208);
if gattr.typtr <> nil then begin
len := gattr.typtr^.size div charmax;
gen2(51(*ldc*),1,len)
end;
if sy = comma then insymbol else error(20);
expression(fsys + [rparent], false); loadaddress;
if not stringt(gattr.typtr) then error(208);
if gattr.typtr <> nil then begin
len := gattr.typtr^.size div charmax;
gen2(51(*ldc*),1,len)
end;
gen1(30(*csp*),55(*del*));
end;
procedure lengthlocationfunction;
begin chkstd; chkhdr;
if sy = lparent then insymbol else error(9);
variable(fsys+[rparent], false); loadaddress;
if gattr.typtr <> nil then begin
if gattr.typtr^.form <> files then error(125);
if gattr.typtr = textptr then error(262);
end;
if lkey = 21 then gen1(30(*csp*),56(*len*))
else gen1(30(*csp*),57(*loc*));
if sy = rparent then insymbol else error(4);
gattr.typtr := intptr
end;
procedure existsfunction;
var len: addrrange;
begin chkstd;
if sy = lparent then insymbol else error(9);
expression(fsys + [rparent], false); loadaddress;
if not stringt(gattr.typtr) then error(208);
if gattr.typtr <> nil then begin
len := gattr.typtr^.size div charmax;
gen2(51(*ldc*),1,len)
end;
gen1(30(*csp*),58(*exs*));
if sy = rparent then insymbol else error(4);
gattr.typtr := boolptr
end;
procedure haltprocedure;
begin chkstd;
gen1(30(*csp*),62(*hlt*))
end;
procedure assertprocedure;
var len: addrrange;
begin chkstd;
expression(fsys+[comma,rparent], false); load;
if gattr.typtr <> nil then
if gattr.typtr <> boolptr then error(135);
if sy = comma then begin insymbol;
expression(fsys + [rparent], false); loadaddress;
if not stringt(gattr.typtr) then error(208);
if gattr.typtr <> nil then begin
len := gattr.typtr^.size div charmax;
gen2(51(*ldc*),1,len);
gen1(30(*csp*),64(*asts*))
end
end else
gen1(30(*csp*),63(*ast*))
end;
procedure throwprocedure;
begin chkstd;
variable(fsys+[rparent], false); loadaddress;
if gattr.typtr <> nil then begin
if gattr.typtr^.form <> exceptf then error(226);
end;
gen1(30(*csp*),85(*thw*))
end;
procedure maxfunction;
var lattr: attr;
begin chkstd;
if sy = lparent then insymbol else error(9);
variable(fsys+[rparent,comma], false); loadaddress;
if gattr.typtr <> nil then
if gattr.typtr^.form <> arrayc then error(273);
lattr := gattr;
if sy = comma then begin insymbol;
expression(fsys + [rparent], false); load;
if gattr.typtr <> nil then if gattr.typtr <> intptr then error(125)
end else gen2(51(*ldc*),1,1); { default level 1 }
gen1(106(*max*),containers(lattr.typtr));
if sy = rparent then insymbol else error(4);
gattr.typtr := intptr
end;
{ assign buffer to id and copy top of stack to it, replacing with address }
procedure cpy2adr(id: ctp; var at: attr);
var lsize: addrrange;
begin
lsize := at.typtr^.size;
alignu(parmptr,lsize);
getcbb(id^.cbb,id,at.typtr^.size); { get a buffer }
gen1(37(*lao*),id^.cbb^.addr); { load address }
{ store to that }
gen2(115(*ctb*),at.typtr^.size,lsize);
mesl(lsize)
end;
procedure callnonstandard(fcp: ctp; inherit: boolean);
var nxt,lcp: ctp; lsp: stp; lkind: idkind; lb: boolean;
locpar, llc, soff: addrrange; varp: boolean; lsize: addrrange;
frlab: integer; prcnt: integer; fcps: ctp; ovrl: boolean;
test: boolean; match: boolean; e: boolean; mm: boolean;
{ This overload does not match, sequence to the next, same parameter.
Set sets fcp -> new proc/func, nxt -> next parameter in new list. }
procedure nxtprc;
var pc: integer; fcpn, fcpf: ctp;
{ compare parameter lists until current }
function cmplst(pl1, pl2: ctp): boolean;
var pc: integer; pll1, pll2: ctp;
begin cmplst := false; pc := 1;
pll1 := nil; pll2 := nil;
while (pc < prcnt) and cmppar(pl1, pl2) do begin
pll1 := pl1; pll2 := pl2;
if pl1 <> nil then pl1 := pl1^.next;
if pl2 <> nil then pl2 := pl2^.next;
pc := pc+1
end;
{ compare last entry }
if (pll1 <> nil) and (pll2 <> nil) then cmplst := cmppar(pll1, pll2)
else cmplst := (pll1 = nil) and (pll2 = nil) { reached end of both lists }
end;
begin pc := 1;
fcpn := fcp^.grpnxt; { go next proc/func, which may not exist }
fcpf := nil; { set none found }
while fcpn <> nil do begin { search next for match }
if (isfunc and (fcpn^.klass = func)) or (not isfunc and (fcpn^.klass = proc)) then
if cmplst(fcp^.pflist, fcpn^.pflist) then
begin fcpf := fcpn; fcpn := nil end
else fcpn := fcpn^.grpnxt { next group proc/func }
else fcpn := fcpn^.grpnxt
end;
fcp := fcpf; { set found/not found }
if fcp <> nil then begin { recover parameter position in new list }
nxt := fcp^.pflist;
while (pc < prcnt) do begin if nxt <> nil then nxt := nxt^.next; pc := pc+1 end
end
end;
begin { callnonstandard }
soff := abs(topnew); { save stack net offset }
fcps := fcp; fcp := fcp^.grppar; locpar := 0; genlabel(frlab);
while ((isfunc and (fcp^.klass <> func)) or
(not isfunc and (fcp^.klass <> proc))) and (fcp^.grpnxt <> nil) do
fcp := fcp^.grpnxt;
if isfunc and (fcp^.klass <> func) then error(292)
else if not isfunc and (fcp^.klass <> proc) then error(293);
prcnt := 1; ovrl := fcp^.grpnxt <> nil;
with fcp^ do
begin nxt := pflist; lkind := pfkind;
{ I don't know why these are dups, guess is a badly formed far call }
if pfkind = actual then begin { it's a system call }
if not sysrot then gensfr(frlab)
end else gensfr(frlab) { its an indirect }
end;
if sy = lparent then
begin llc := lc; insymbol;
repeat lb := false; (*decide whether proc/func must be passed*)
if nxt = nil then begin
{ out of parameters, try to find another overload }
nxtprc;
if nxt = nil then begin
{ dispatch error according to overload status }
if ovrl then error(275) else error(126);
fcp := fcps
end
end;
e := false;
if (sy = ident) and (fcp^.grpnxt <> nil) then begin
{ next is id, and proc/func is overload, try proc/func parameter }
match := false;
searchidnenm([proc,func],lcp,mm);
if lcp <> nil then if lcp^.klass in [proc,func] then begin
{ Search matching overload. For proc/func parameters, we allow
all features of the target to match, including function
result. }
repeat
if nxt^.klass = proc then begin
if cmpparlst(nxt^.pflist, lcp^.pflist) then match := true
end else if nxt^.klass = func then begin
if cmpparlst(nxt^.pflist, lcp^.pflist) then
if comptypes(lcp^.idtype,nxt^.idtype) then match := true
end;
if not match then nxtprc { no match get next overload }
until match or (fcp = nil);
if fcp = nil then begin error(277); e := true; fcp := fcps end
end
end;
{ match same thing for all procs/funcs }
if nxt <> nil then lb := nxt^.klass in [proc,func];
if lb then (*pass function or procedure*)
begin
if sy <> ident then
begin error(2); skip(fsys + [comma,rparent]) end
else if nxt <> nil then
begin
if nxt^.klass = proc then searchid([proc],lcp)
else
begin searchid([func],lcp);
{ compare result types }
if not comptypes(lcp^.idtype,nxt^.idtype) then
if not e then error(128)
end;
{ compare parameter lists }
if (nxt^.klass in [proc,func]) and
(lcp^.klass in [proc,func]) then
if not cmpparlst(nxt^.pflist, lcp^.pflist) then
if not e then error(189);
if lcp^.pfkind = actual then
genlpa(lcp^.pfname,level-(level-lcp^.pflev))
else gen2(74(*lip*),level-(level-lcp^.pflev),lcp^.pfaddr);
locpar := locpar+ptrsize*2;
insymbol;
if not (sy in fsys + [comma,rparent]) then
begin error(6); skip(fsys + [comma,rparent]) end
end
end (*if lb*)
else
begin varp := false;
if nxt <> nil then varp := nxt^.vkind = formal;
expression(fsys + [comma,rparent], varp);
{ find the appropriate overload }
match := false;
repeat
if (nxt <> nil) and (gattr.typtr <> nil) then
if nxt^.idtype <> nil then begin
if comptypes(nxt^.idtype, gattr.typtr) or
{ special rule: const char matches container }
((nxt^.idtype^.form = arrayc) and
chart(gattr.typtr) and (gattr.kind = cst)) then
match := true
else if comptypes(realptr,nxt^.idtype) and
(gattr.typtr = intptr) then match := true
end;
if not match then nxtprc { no match get next overload }
until match or (fcp = nil);
if fcp = nil then begin error(277); e := true; fcp := fcps end;
{ override variable status for view parameter }
if nxt <> nil then varp := (nxt^.vkind = formal) and not (nxt^.part = ptview);
if varp and (gattr.kind <> varbl) then error(278);
if gattr.typtr <> nil then
begin
if nxt <> nil then
begin lsp := nxt^.idtype;
if lsp <> nil then
begin
if (nxt^.vkind = actual) or (nxt^.part = ptview) then begin
if not comptypes(lsp,gattr.typtr) and not
{ special rule: const char matches container }
((nxt^.idtype^.form = arrayc) and
chart(gattr.typtr) and (gattr.kind = cst)) and not
(comptypes(realptr,lsp) and
(gattr.typtr = intptr)) then
if not e then error(142);
if lsp^.form <= power then
begin load;
if debug then checkbnds(lsp);
if comptypes(realptr,lsp)
and (gattr.typtr = intptr) then
begin gen0(10(*flt*));
gattr.typtr := realptr
end;
locpar := locpar+lsp^.size;
alignu(parmptr,locpar);
end
else if stringt(lsp) and ischrcst(gattr) then
begin { is char to string }
gen2(51(*ldc*),1,1);
gensca(chr(gattr.cval.ival));
locpar := locpar+ptrsize*2;
alignu(parmptr,locpar)
end else begin
if gattr.kind = expr then cpy2adr(nxt,gattr)
else loadaddress;
fixpar(lsp,gattr.typtr);
if lsp^.form = arrayc then
locpar := locpar+ptrsize*2
else locpar := locpar+ptrsize;
alignu(parmptr,locpar)
end
end else begin
if gattr.kind = varbl then
begin if gattr.packcom then error(197);
if gattr.tagfield then error(198);
if gattr.kind = expr then cpy2adr(nxt,gattr)
else loadaddress;
fixpar(lsp,gattr.typtr);
if lsp^.form = arrayc then
locpar := locpar+ptrsize*2
else locpar := locpar+ptrsize;
alignu(parmptr,locpar);
end
else error(154);
if (lsp^.form = arrayc) and not iso7185 then begin
if not comptypes(lsp, gattr.typtr)
and not e then error(289)
end else if lsp <> gattr.typtr then
if not e then error(199)
end
end
end
end
end;
if nxt <> nil then begin nxt := nxt^.next; prcnt := prcnt+1 end;
test := sy <> comma;
if sy = comma then insymbol;
until test;
lc := llc;
if sy = rparent then insymbol else error(4)
end (*if lparent*);
{ not out of proto parameters, sequence until we are or there are no
candidate overloads }
while (nxt <> nil) and (fcp <> nil) do nxtprc;
if fcp = nil then fcp := fcps;
{ find function result size }
lsize := 0;
if (fcp^.klass = func) and (fcp^.idtype <> nil) then begin
lsize := fcp^.idtype^.size;
alignu(parmptr,lsize);
end;
if prcode then begin prtlabel(frlab); writeln(prr,'=',lsize:1) end;
if lkind = actual then
begin if nxt <> nil then if ovrl then error(275) else error(126);
with fcp^ do
begin
if sysrot then gen1(30(*csp*),pfname)
else begin
if (pfattr = fpavirtual) or (pfattr = fpaoverride) then begin
if inherit then begin
fcp := ovrpf(fcp); if fcp = nil then error(516);
if fcp^.pfattr <> fpaoverride then error(507);
{ inherited calls will never be far }
gencuv(locpar,fcp^.pfvaddr,nil)
end else begin
lcp := fcp^.grppar;
if lcp^.pfvid <> nil then
gencuv(locpar,lcp^.pfvid^.vaddr,lcp^.pfvid)
end
end else begin
if inherit then error(234);
if fcp^.klass = func then
gencupcuf(122(*cuf*),locpar,pfname,fcp)
else
gencupcuf(46(*cup*),locpar,pfname,fcp)
end;
mesl(-lsize)
end
end
end
else begin { call procedure or function parameter }
gen2(50(*lda*),level-(level-fcp^.pflev),fcp^.pfaddr);
if fcp^.klass = func then gen0(123(*cif*))
else gen0(67(*cip*));
gen1(32(*rip*),lcs+lsize+soff);
mesl(locpar); { remove stack parameters }
mesl(-lsize)
end;
gattr.typtr := fcp^.idtype;
{ clean any copyback buffers out of list }
nxt := fcp^.pflist;
while nxt <> nil do
begin putcbb(nxt^.cbb); nxt^.cbb := nil; nxt := nxt^.next end
end (*callnonstandard*) ;
begin (*call*)
if fcp^.pfdeckind = standard then
begin lkey := fcp^.key; if inherit then error(233);
if fcp^.klass = proc then
begin
if not(lkey in [5,6,11,12,17,29]) then
if sy = lparent then insymbol else error(9);
case lkey of
1,2,
3,4: getputresetrewriteprocedure;
17: pageprocedure;
5,11: readprocedure;
6,12: writeprocedure;
7: packprocedure;
8: unpackprocedure;
9,18: newdisposeprocedure(lkey = 18);
19: assignprocedure;
20, 24,
25: closeupdateappendprocedure;
23: positionprocedure;
27: deleteprocedure;
28: changeprocedure;
29: haltprocedure;
30: assertprocedure;
31: throwprocedure;
10,13: error(508)
end;
if not(lkey in [5,6,11,12,17,29]) then
if sy = rparent then insymbol else error(4)
end
else
begin
if (lkey <= 8) or (lkey = 16) then
begin
if sy = lparent then insymbol else error(9);
expression(fsys+[rparent], false); load
end;
case lkey of
1: absfunction;
2: sqrfunction;
3: truncfunction;
16: roundfunction;
4: oddfunction;
5: ordfunction;
6: chrfunction;
7,8: predsuccfunction;
9,10: eofeolnfunction;
21,22: lengthlocationfunction;
26: existsfunction;
32: maxfunction;
end;
if (lkey <= 8) or (lkey = 16) then
if sy = rparent then insymbol else error(4)
end;
end (*standard procedures and functions*)
else begin callnonstandard(fcp,inherit); markline end
end (*call*) ;
function psize(sp: stp): addrrange;
var ps: addrrange;
begin ps := 0;
if sp <> nil then begin
if sp^.form = arrayc then ps := ptrsize*2
else if sp^.form <= power then ps := sp^.size
else ps := ptrsize;
alignu(parmptr, ps)
end;
psize := ps
end;
{ call operator type with 1 parameter }
procedure callop1{(fcp: ctp)};
var frlab: integer; lsize: addrrange; locpar, locpars: addrrange;
sp: stp;
begin
sp := partype(fcp, 1);
genlabel(frlab); gensfr(frlab);
{ find uncoerced parameters size }
locpars := psize(gattr.typtr);
{ find final parameters size }
locpar := psize(sp);
{ find function result size }
lsize := fcp^.idtype^.size;
alignu(parmptr,lsize);
{ generate a stack hoist of parameters. Basically the common math on stack
not formatted the same way as function calls, so we hoist the parameters
over the mark, call and then drop the function result downwards. }
if gattr.typtr <> nil then
if (gattr.kind = expr) and (gattr.typtr^.form > power) then
gen1(118(*lsa*),lsize)
else gen2(116(*cpp*),lsize,locpars);
{ do coercions }
if realt(sp) and intt(gattr.typtr) then
begin gen0(10(*flt*)); gattr.typtr := realptr end;
fixpar(sp,gattr.typtr);
if prcode then begin prtlabel(frlab); writeln(prr,'=',lsize:1) end;
gencupcuf(122(*cuf*),locpar,fcp^.pfname,fcp);
gen2(117(*cpr*),lsize,locpars);
gattr.typtr := fcp^.idtype
end;
{ call operator type with 2 parameters }
procedure callop2{(fcp: ctp; var lattr: attr)};
var frlab: integer; lsize: addrrange;
locpar, locpars, lpl, lpr, lpls, lprs: addrrange;
lsp, rsp: stp;
{ check actual type can be coerced into formal }
function fungible(fsp,asp: stp): boolean;
begin fungible := false;
if (fsp <> nil) and (asp <> nil) then begin
if realt(fsp) and intt(asp) then fungible := true
else if ((fsp^.form = arrayc) and (asp^.form = arrays)) or
((fsp^.form = arrays) and (asp^.form = arrayc)) then
fungible := true
end
end;
begin
lsp := partype(fcp, 1); rsp := partype(fcp, 2);
genlabel(frlab); gensfr(frlab);
{ find uncoerced parameters size }
lpls := psize(lattr.typtr); lprs := psize(gattr.typtr);
locpars := lpls+lprs;
{ find final parameters size }
lpl := psize(lsp); lpr := psize(rsp); locpar := lpl+lpr;
{ find function result size }
lsize := 0;
if fcp^.klass = func then begin
lsize := fcp^.idtype^.size;
alignu(parmptr,lsize)
end;
{ generate a stack hoist of parameters. Basically the common math on stack
not formatted the same way as function calls, so we hoist the parameters
over the mark, call and then drop the function result downwards. }
if fungible(lsp, lattr.typtr) or (lattr.kind = expr) or
fungible(rsp, gattr.typtr) or (gattr.kind = expr) then begin
{ bring the parameters up and convert them one by one }
if lattr.typtr <> nil then
if (lattr.kind = expr) and (lattr.typtr^.form > power) then
gen1(118(*lsa*),lsize+lprs)
else gen2(116(*cpp*),lsize+lprs,lpls);
{ do coercions }
if realt(lsp) and intt(lattr.typtr) then
begin gen0(10(*flt*)); lattr.typtr := realptr end;
fixpar(lsp,lattr.typtr);
if gattr.typtr <> nil then
if (gattr.kind = expr) and (gattr.typtr^.form > power) then
gen1(118(*lsa*),lsize+lpl)
else gen2(116(*cpp*),lsize+lpl,lprs);
{ do coercions }
if realt(rsp) and intt(gattr.typtr) then
begin gen0(10(*flt*)); gattr.typtr := realptr end;
fixpar(rsp,gattr.typtr);
end else gen2(116(*cpp*),lsize,locpar); { get both params }
if prcode then begin prtlabel(frlab); writeln(prr,'=',lsize:1) end;
gencupcuf(122(*cuf*),locpar,fcp^.pfname,fcp);
gen2(117(*cpr*),lsize,locpars);
gattr.typtr := fcp^.idtype
end;
procedure expression{(fsys: setofsys; threaten: boolean)};
var lattr: attr; lop: operatort; typind: char; lsize, lsizspc: addrrange;
fcp: ctp; onstkl, onstkr, lschrcst, rschrcst, revcmp: boolean;
procedure simpleexpression(fsys: setofsys; threaten: boolean);
var lattr: attr; lop: operatort; fsy: symbol; fop: operatort; fcp: ctp;
procedure term(fsys: setofsys; threaten: boolean);
var lattr: attr; lop: operatort; fcp: ctp;
procedure factor(fsys: setofsys; threaten: boolean);
var lcp,fcp: ctp; lvp: csp; varpart: boolean; inherit: boolean;
cstpart: setty; lsp: stp; tattr, rattr: attr; test: boolean;
begin
if not (sy in facbegsys) then
begin error(58); skip(fsys + facbegsys);
gattr.typtr := nil
end;
while sy in facbegsys do
begin inherit := false;
if sy = inheritedsy then begin insymbol; inherit := true;
if not (sy in facbegsys) then
begin error(58); skip(fsys + facbegsys);
gattr.typtr := nil end;
if sy <> ident then error(233);
end;
if sy in facbegsys then case sy of
(*id*) ident:
begin searchid([types,konst,vars,fixedt,field,func,proc],lcp);
insymbol;
if hasovlfunc(lcp) or hasovlproc(lcp) then
begin call(fsys,lcp, inherit, true);
with gattr do
begin kind := expr;
if typtr <> nil then
if typtr^.form=subrange then
typtr := typtr^.rangetype
end
end
else begin if inherit then error(233);
if lcp^.klass = konst then
with gattr, lcp^ do
begin typtr := idtype; kind := cst;
cval := values
end
else
if lcp^.klass = types then begin
{ type convert/restrict }
chkstd;
if lcp^.idtype <> nil then
if (lcp^.idtype^.form <> scalar) and
(lcp^.idtype^.form <> subrange) then
error(223);
{ if simple underfined error and no () trailer,
then assume it is just an undefined id }
if (lcp <> utypptr) or (sy = lparent) then begin
if sy <> lparent then error(9);
insymbol; expression(fsys + [rparent], false);
load;
if sy = rparent then insymbol else error(4);
if gattr.typtr <> nil then
if (gattr.typtr^.form <> scalar) and
(gattr.typtr^.form <> subrange) then
error(224);
{ bounds check to target type }
checkbnds(lcp^.idtype);
gattr.typtr := lcp^.idtype { retype }
end
end else
begin selector(fsys,lcp,false);
if threaten and (lcp^.klass = vars) then with lcp^ do begin
if vlev < level then threat := true;
if forcnt > 0 then error(195);
if part = ptview then error(290)
end;
if gattr.typtr<>nil then(*elim.subr.types to*)
with gattr,typtr^ do(*simplify later tests*)
end
end
end;
(*cst*) intconst:
begin
with gattr do
begin typtr := intptr; kind := cst;
cval := val
end;
insymbol
end;
realconst:
begin
with gattr do
begin typtr := realptr; kind := cst;
cval := val
end;
insymbol
end;
stringconst:
begin
with gattr do
begin
if lgth = 1 then typtr := charptr
else
begin new(lsp,arrays); pshstc(lsp);
with lsp^ do
begin form:=arrays; aeltype := charptr;
packing := true; inxtype := nil; tmpl := -1;
size := lgth*charsize
end;
arrtmp(lsp); { output fixed template }
typtr := lsp
end;
kind := cst; cval := val
end;
insymbol
end;
(* ( *) lparent:
begin insymbol; expression(fsys + [rparent], false);
if sy = rparent then insymbol else error(4)
end;
(*not*) notsy:
begin insymbol; factor(fsys, false);
if gattr.kind <> expr then
if gattr.typtr <> nil then
if gattr.typtr^.form <= power then load else loadaddress;
fndopr1(notop, fcp);
if fcp <> nil then callop1(fcp) else begin
if (gattr.typtr = boolptr) or
((gattr.typtr = intptr) and not iso7185) then
gen0t(19(*not*),gattr.typtr)
else begin error(135); gattr.typtr := nil end
end
end;
(*[*) lbrack:
begin insymbol; cstpart := [ ]; varpart := false;
new(lsp,power); pshstc(lsp);
with lsp^ do
begin form:=power; elset:=nil;size:=setsize;
packing := false; matchpack := false end;
if sy = rbrack then
begin
with gattr do
begin typtr := lsp; kind := cst end;
insymbol
end
else
begin
repeat
expression(fsys + [comma,range,rbrack], false);
rattr.typtr := nil;
if sy = range then begin insymbol;
{ if the left side is not constant, load it
and coerce it to integer now }
if gattr.kind <> cst then begin
load;
if not comptypes(gattr.typtr,intptr)
then gen0t(58(*ord*),gattr.typtr);
end;
tattr := gattr;
expression(fsys + [comma,rbrack], false);
rattr := gattr; gattr := tattr;
end;
if gattr.typtr <> nil then
if (gattr.typtr^.form <> scalar) and
(gattr.typtr^.form <> subrange) then
begin error(136); gattr.typtr := nil end
else if comptypes(gattr.typtr,realptr) then
begin error(109); gattr.typtr := nil end
else
if comptypes(lsp^.elset,gattr.typtr) then
begin
if rattr.typtr <> nil then begin { x..y form }
if (rattr.typtr^.form <> scalar) and
(rattr.typtr^.form <> subrange) then
begin error(136); rattr.typtr := nil end
else if comptypes(rattr.typtr,realptr) then
begin error(109); rattr.typtr := nil end
else
if comptypes(lsp^.elset,rattr.typtr) then
begin
if (gattr.kind = cst) and
(rattr.kind = cst) then
if (rattr.cval.ival < setlow) or
(rattr.cval.ival > sethigh) or
(gattr.cval.ival < setlow) or
(gattr.cval.ival > sethigh) then
error(304)
else
cstpart := cstpart+
[gattr.cval.ival..rattr.cval.ival]
else
begin
if gattr.kind = cst then begin
load;
if not comptypes(gattr.typtr,intptr)
then gen0t(58(*ord*),gattr.typtr)
end;
tattr := gattr; gattr := rattr;
load;
gattr := tattr;
if not comptypes(rattr.typtr,intptr)
then gen0t(58(*ord*),rattr.typtr);
gen0(64(*rgs*));
if varpart then gen0(28(*uni*))
else varpart := true
end
end
else error(137)
end else begin
if gattr.kind = cst then
if (gattr.cval.ival < setlow) or
(gattr.cval.ival > sethigh) then
error(304)
else
cstpart := cstpart+[gattr.cval.ival]
else
begin load;
if not comptypes(gattr.typtr,intptr)
then gen0t(58(*ord*),gattr.typtr);
gen0(23(*sgs*));
if varpart then gen0(28(*uni*))
else varpart := true
end
end;
lsp^.elset := gattr.typtr;
gattr.typtr := lsp
end
else begin error(137); gattr.typtr := nil end;
test := sy <> comma;
if not test then insymbol
until test;
if sy = rbrack then insymbol else error(12)
end;
if varpart then
begin
if cstpart <> [ ] then
begin new(lvp,pset); pshcst(lvp);
lvp^.pval := cstpart;
lvp^.cclass := pset;
if cstptrix = cstoccmax then error(254)
else
begin cstptrix := cstptrix + 1;
cstptr[cstptrix] := lvp;
gen2(51(*ldc*),5,cstptrix);
gen0(28(*uni*)); gattr.kind := expr
end
end
end
else
begin new(lvp,pset); pshcst(lvp);
lvp^.cclass := pset;
lvp^.pval := cstpart;
gattr.cval.intval := false;
gattr.cval.valp := lvp
end
end;
(*nil*) nilsy: with gattr do
begin typtr := nilptr; kind := cst;
cval.intval := true;
cval.ival := nilval;
insymbol
end
end (*case*) ;
if not (sy in fsys) then
begin error(6); skip(fsys + facbegsys) end
end (*while*)
end (*factor*) ;
begin (*term*)
factor(fsys + [mulop], threaten);
while sy = mulop do
begin
if gattr.kind <> expr then
if gattr.typtr <> nil then
if gattr.typtr^.form <= power then load else loadaddress;
lattr := gattr; lop := op;
insymbol; factor(fsys + [mulop], threaten);
if gattr.kind <> expr then
if gattr.typtr <> nil then
if gattr.typtr^.form <= power then load else loadaddress;
if (lattr.typtr <> nil) and (gattr.typtr <> nil) then
case lop of
(***) mul: begin fndopr2(lop, lattr, fcp);
if fcp <> nil then callop2(fcp, lattr) else begin
if (lattr.typtr=intptr) and (gattr.typtr=intptr)
then gen0(15(*mpi*))
else
begin
{ convert either integer to real }
if lattr.typtr = intptr then
begin gen0(9(*flo*));
lattr.typtr := realptr
end
else
if gattr.typtr = intptr then
begin gen0(10(*flt*));
gattr.typtr := realptr
end;
if (lattr.typtr = realptr) and
(gattr.typtr=realptr) then gen0(16(*mpr*))
else if (lattr.typtr^.form=power) and
comptypes(lattr.typtr,gattr.typtr) then
gen0(12(*int*))
else begin error(134); gattr.typtr:=nil end
end
end
end;
(* / *) rdiv: begin fndopr2(lop, lattr, fcp);
if fcp <> nil then callop2(fcp, lattr) else begin
{ convert either integer to real }
if gattr.typtr = intptr then
begin gen0(10(*flt*)); gattr.typtr := realptr end;
if lattr.typtr = intptr then
begin gen0(9(*flo*)); lattr.typtr := realptr end;
if (lattr.typtr = realptr) and
(gattr.typtr=realptr) then gen0(7(*dvr*))
else begin error(134); gattr.typtr := nil end
end
end;
(*div*) idiv: begin fndopr2(lop, lattr, fcp);
if fcp <> nil then callop2(fcp, lattr) else begin
if (lattr.typtr = intptr) and (gattr.typtr = intptr) then
gen0(6(*dvi*))
else begin error(134); gattr.typtr := nil end
end
end;
(*mod*) imod: begin fndopr2(lop, lattr, fcp);
if fcp <> nil then callop2(fcp, lattr) else begin
if (lattr.typtr = intptr) and (gattr.typtr = intptr) then
gen0(14(*mod*))
else begin error(134); gattr.typtr := nil end
end
end;
(*and*) andop: begin fndopr2(lop, lattr, fcp);
if fcp <> nil then callop2(fcp, lattr) else begin
if ((lattr.typtr = boolptr) and (gattr.typtr = boolptr)) or
((lattr.typtr=intptr) and (gattr.typtr=intptr) and
not iso7185) then gen0(4(*and*))
else begin error(134); gattr.typtr := nil end
end
end
end (*case*)
else gattr.typtr := nil
end (*while*)
end (*term*) ;
begin (*simpleexpression*)
fsy := sy; fop := op;
if (sy = addop) and (op in [plus,minus]) then insymbol;
term(fsys + [addop], threaten);
if (fsy = addop) and (fop in [plus, minus]) then begin
if gattr.kind <> expr then
if gattr.typtr <> nil then
if gattr.typtr^.form <= power then load else loadaddress;
fndopr1(fop, fcp);
if fcp <> nil then callop1(fcp) else begin
if fop = minus then begin
if gattr.typtr = intptr then gen0(17(*ngi*))
else
if gattr.typtr = realptr then gen0(18(*ngr*))
else begin error(134); gattr.typtr := nil end
end else begin
if (gattr.typtr <> intptr) and
(gattr.typtr <> realptr) then
begin error(134); gattr.typtr := nil end
end
end
end;
while sy = addop do
begin
if gattr.kind <> expr then
if gattr.typtr <> nil then
if gattr.typtr^.form <= power then load else loadaddress;
lattr := gattr; lop := op;
insymbol; term(fsys + [addop], threaten);
if gattr.kind <> expr then
if gattr.typtr <> nil then
if gattr.typtr^.form <= power then load else loadaddress;
if (lattr.typtr <> nil) and (gattr.typtr <> nil) then
case lop of
(*+,-*) plus,minus: begin fndopr2(lop, lattr, fcp);
if fcp <> nil then callop2(fcp, lattr) else begin
if (lattr.typtr = intptr) and (gattr.typtr = intptr) then begin
if lop = plus then gen0(2(*adi*)) else gen0(21(*sbi*))
end else begin
{ convert either integer to real }
if lattr.typtr = intptr then
begin gen0(9(*flo*));
lattr.typtr := realptr
end
else
if gattr.typtr = intptr then
begin gen0(10(*flt*));
gattr.typtr := realptr
end;
if (lattr.typtr = realptr) and
(gattr.typtr = realptr) then begin
if lop = plus then gen0(3(*adr*)) else gen0(22(*sbr*))
end else if (lattr.typtr^.form=power) and
comptypes(lattr.typtr,gattr.typtr) then begin
if lop = plus then gen0(28(*uni*)) else gen0(5(*dif*))
end else begin error(134); gattr.typtr:=nil end
end
end
end;
(*or,xor*) orop, xorop: begin fndopr2(lop, lattr, fcp);
if fcp <> nil then callop2(fcp, lattr) else begin
if ((lattr.typtr=boolptr) and (gattr.typtr=boolptr)) or
((lattr.typtr=intptr) and (gattr.typtr=intptr) and
not iso7185) then begin
if lop = orop then gen0(13(*ior*)) else gen0(83(*ixor*))
end else begin error(134); gattr.typtr := nil end
end
end
end (*case*)
else gattr.typtr := nil
end (*while*)
end (*simpleexpression*) ;
begin (*expression*)
revcmp := false;
simpleexpression(fsys + [relop], threaten);
onstkl := gattr.kind = expr; lschrcst := ischrcst(gattr);
if sy = relop then begin
if gattr.typtr <> nil then
if gattr.typtr^.form <= power then load
else loadaddress;
lattr := gattr; lop := op;
if (lop = inop) and (gattr.typtr <> nil) then
if not comptypes(gattr.typtr,intptr) and
(gattr.typtr^.form <= subrange) then
gen0t(58(*ord*),gattr.typtr);
insymbol; simpleexpression(fsys, threaten);
onstkr := gattr.kind = expr; rschrcst := ischrcst(gattr);
if gattr.typtr <> nil then
if gattr.typtr^.form <= power then load
else loadaddress;
if (lattr.typtr <> nil) and (gattr.typtr <> nil) then begin
fndopr2(lop, lattr, fcp);
if fcp <> nil then callop2(fcp, lattr) else begin
if lop = inop then
if gattr.typtr^.form = power then
if comptypes(lattr.typtr,gattr.typtr^.elset) then
gen0(11(*inn*))
else begin error(129); gattr.typtr := nil end
else begin error(130); gattr.typtr := nil end
else
begin
{ convert either integer to real }
if lattr.typtr <> gattr.typtr then
if lattr.typtr = intptr then
begin gen0(9(*flo*));
lattr.typtr := realptr
end
else
if gattr.typtr = intptr then
begin gen0(10(*flt*));
gattr.typtr := realptr
end;
if comptypes(lattr.typtr,gattr.typtr) or
(lschrcst and (gattr.typtr^.form = arrayc)) or
((lattr.typtr^.form = arrayc) and rschrcst) then
begin lsize := lattr.typtr^.size;
typind := ' ';
case lattr.typtr^.form of
scalar:
if lschrcst and (gattr.typtr^.form = arrayc) then
begin
{ load char ptr under }
gen2(51(*ldc*),1,1);
gensca(chr(gattr.cval.ival));
typind := 'v';
revcmp := true
end
else if lattr.typtr = realptr then typind := 'r'
else
if lattr.typtr = boolptr then typind := 'b'
else
if lattr.typtr = charptr then typind := 'c'
else typind := 'i';
pointer:
begin
if lop in [ltop,leop,gtop,geop] then error(131);
typind := 'a'
end;
power:
begin if lop in [ltop,gtop] then error(132);
typind := 's'
end;
arrays, arrayc:
begin
if not stringt(lattr.typtr) then error(134);
if rschrcst and (lattr.typtr^.form = arrayc) then begin
gen1(71(*dmp*),intsize); { discard char }
{ rationalize character }
gen2(51(*ldc*),1,1);
gensca(chr(gattr.cval.ival));
typind := 'v'
end else begin
lsizspc := lsize; alignu(parmptr,lsizspc);
if (lattr.typtr^.form = arrayc) or
(gattr.typtr^.form = arrayc) then typind := 'v'
else typind := 'm';
containerop(lattr); { rationalize binary container }
if onstkr then begin { pull left up }
gen1(118(*lsa*),ptrsize+lsizspc);
gen1t(35(*ind*),0,nilptr);
gen1(72(*swp*),stackelsize)
end
end
end;
records:
begin
error(134);
typind := 'm'
end;
files:
begin error(133); typind := 'f' end
end;
if typind <> ' ' then if revcmp then begin
case lop of
{ reverse flipped operands }
ltop: gen2(49(*grt*),ord(typind),lsize);
leop: gen2(48(*geq*),ord(typind),lsize);
gtop: gen2(53(*les*),ord(typind),lsize);
geop: gen2(52(*leq*),ord(typind),lsize);
neop: gen2(55(*neq*),ord(typind),lsize);
eqop: gen2(47(*equ*),ord(typind),lsize)
end;
gen1(72(*swp*),intsize); { swap for previous const }
gen1(71(*dmp*),ptrsize) { dump it }
end else case lop of
ltop: gen2(53(*les*),ord(typind),lsize);
leop: gen2(52(*leq*),ord(typind),lsize);
gtop: gen2(49(*grt*),ord(typind),lsize);
geop: gen2(48(*geq*),ord(typind),lsize);
neop: gen2(55(*neq*),ord(typind),lsize);
eqop: gen2(47(*equ*),ord(typind),lsize)
end;
if lattr.typtr^.form = arrays then begin
alignu(parmptr,lsize);
if onstkl and onstkr then
begin gen1(72(*swp*),lsizspc*2); gen1(71(*dmp*),lsizspc*2)
end
else if onstkr then
begin gen1(72(*swp*),lsizspc+ptrsize);
gen1(71(*dmp*),lsizspc+ptrsize) end
else if onstkl then
begin gen1(72(*swp*),lsizspc); gen1(71(*dmp*),lsizspc) end
end
end
else error(129)
end;
gattr.typtr := boolptr; gattr.kind := expr
end
end
end (*sy = relop*)
end (*expression*) ;
procedure body(fsys: setofsys; fprocp: ctp); forward;
procedure declare(fsys: setofsys);
var lsy: symbol;
{ resolve all pointer references in the forward list }
procedure resolvep;
var ids: idstr; lcp1, lcp2: ctp; mm, fe: boolean;
begin
ids := id;
fe := true;
while fwptr <> nil do begin
lcp1 := fwptr;
fwptr := lcp1^.next;
strassfv(id, lcp1^.name);
searchidnenm([types], lcp2, mm);
if lcp2 <> nil then begin
lcp1^.idtype^.eltype := lcp2^.idtype;
lcp2^.refer := true;
end else begin
if fe then begin error(117); writeln(output) end;
write('*** undefined type-id forward reference: ');
writev(output, lcp1^.name, prtlln); writeln;
fe := false
end;
putnam(lcp1)
end;
id := ids
end;
procedure typ(fsys: setofsys; var fsp: stp; var fsize: addrrange);
var lsp,lsp1,lsp2: stp; oldtop: disprange; lcp: ctp;
lsize,displ: addrrange; lmin,lmax, span: integer;
test: boolean; ispacked: boolean; lvalu: valu;
procedure simpletype(fsys:setofsys; var fsp:stp; var fsize:addrrange);
var lsp,lsp1: stp; lcp,lcp1: ctp; ttop: disprange;
lcnt: integer; lvalu: valu; t: integer;
begin fsize := 1;
if not (sy in simptypebegsys) then
begin error(1); skip(fsys + simptypebegsys) end;
if sy in simptypebegsys then
begin
if sy = lparent then
begin ttop := top; (*decl. consts local to innermost block*)
while display[top].occur <> blck do top := top - 1;
new(lsp,scalar,declared); pshstc(lsp);
with lsp^ do
begin form := scalar; size := intsize; scalkind := declared;
packing := false
end;
lcp1 := nil; lcnt := 0;
repeat insymbol;
if sy = ident then
begin new(lcp,konst); ininam(lcp);
with lcp^ do
begin klass := konst; strassvf(name, id); idtype := lsp;
next := lcp1; values.intval := true;
values.ival := lcnt;
end;
enterid(lcp);
lcnt := lcnt + 1;
lcp1 := lcp; insymbol
end
else error(2);
if not (sy in fsys + [comma,rparent]) then
begin error(6); skip(fsys + [comma,rparent]) end
until sy <> comma;
lsp^.fconst := lcp1; top := ttop;
if sy = rparent then insymbol else error(4);
{ resize for byte if needed }
if isbyte(lsp) then lsp^.size := 1;
fsize := lsp^.size
end
else
begin
if sy = ident then
begin searchid([types,konst],lcp);
insymbol;
if lcp^.klass = konst then
begin new(lsp,subrange); pshstc(lsp);
with lsp^, lcp^ do
begin form := subrange; rangetype := idtype;
if stringt(rangetype) then
begin error(148); rangetype := nil end;
if rangetype = realptr then
begin error(109); rangetype := nil end;
if not values.intval then
begin min.intval := true; min.ival := 1 end
else min := values;
size := intsize; packing := false
end;
if sy = range then insymbol else error(30);
constexpr(fsys,lsp1,lvalu);
if not lvalu.intval then
begin lsp^.max.intval := true; lsp^.max.ival := 1 end
else lsp^.max := lvalu;
if lsp^.rangetype <> lsp1 then error(107);
if isbyte(lsp) then lsp^.size := 1
end
else
begin lsp := lcp^.idtype;
if lsp <> nil then fsize := lsp^.size
end
end (*sy = ident*)
else
begin new(lsp,subrange); pshstc(lsp);
lsp^.form := subrange; lsp^.packing := false;
constexpr(fsys + [range],lsp1,lvalu);
if stringt(lsp1) then
begin error(148); lsp1 := nil end;
if lsp1 = realptr then begin error(109); lsp1 := nil end;
with lsp^ do begin
rangetype:=lsp1;
if lvalu.intval then min:=lvalu else
begin min.intval := true; min.ival := 1 end;
size:=intsize
end;
if sy = range then insymbol else error(30);
constexpr(fsys,lsp1,lvalu);
if lvalu.intval then lsp^.max := lvalu
else begin lsp^.max.intval := true; lsp^.max.ival := 1 end;
if lsp^.rangetype <> lsp1 then error(107);
if isbyte(lsp) then lsp^.size := 1;
fsize := lsp^.size
end;
if lsp <> nil then
with lsp^ do
if form = subrange then begin
if rangetype <> nil then
if rangetype = realptr then
begin error(109); rangetype := intptr end;
if min.ival > max.ival then
begin error(102);
{ swap to fix and suppress further errors }
t := min.ival; min.ival := max.ival; max.ival := t
end
end
end;
fsp := lsp;
if not (sy in fsys) then
begin error(6); skip(fsys) end
end
else fsp := nil
end (*simpletype*) ;
procedure fieldlist(fsys: setofsys; var frecvar: stp; vartyp: stp;
varlab: ctp; lvl: integer; var fstlab: ctp);
var lcp,lcp1,lcp2,nxt,nxt1: ctp; lsp,lsp1,lsp2,lsp3,lsp4: stp;
minsize,maxsize,lsize: addrrange; lvalu,rvalu: valu;
test: boolean; mm: boolean; varlnm, varcn, varcmx: varinx;
varcof: boolean; tagp,tagl: ttp; mint, maxt: integer; ferr: boolean;
procedure ordertag(var tp: ttp);
var lp, p, p2, p3: ttp;
begin
if tp <> nil then begin
lp := tp; tp := tp^.next; lp^.next := nil;
while tp <> nil do begin
p := tp; tp := tp^.next; p^.next := nil; p2 := lp; p3 := nil;
while (p^.ival > p2^.ival) and (p2^.next <> nil) do
begin p3 := p2; p2 := p2^.next end;
if p^.ival > p2^.ival then p2^.next := p
else if p3 = nil then begin p^.next := lp; lp := p end
else begin p^.next := p3^.next; p3^.next := p end
end
end;
tp := lp
end;
begin nxt1 := nil; lsp := nil; fstlab := nil;
if not (sy in (fsys+[ident,casesy])) then
begin error(19); skip(fsys + [ident,casesy]) end;
while sy = ident do
begin nxt := nxt1;
repeat
if sy = ident then
begin new(lcp,field); ininam(lcp);
if fstlab = nil then fstlab := lcp;
with lcp^ do
begin klass := field; strassvf(name, id); idtype := nil;
next := nxt; fldaddr := 0; varnt := vartyp;
varlb := varlab; tagfield := false; taglvl := lvl;
varsaddr := 0; varssize := 0; vartl := -1
end;
nxt := lcp;
enterid(lcp);
insymbol
end
else error(2);
if not (sy in [comma,colon]) then
begin error(6); skip(fsys + [comma,colon,semicolon,casesy])
end;
test := sy <> comma;
if not test then insymbol
until test;
if sy = colon then insymbol else error(5);
typ(fsys + [casesy,semicolon],lsp,lsize);
if lsp <> nil then
if lsp^.form = arrayc then error(272);
while nxt <> nxt1 do
with nxt^ do
begin alignu(lsp,displ);
idtype := lsp; fldaddr := displ;
nxt := next; displ := displ + lsize
end;
nxt1 := lcp;
while sy = semicolon do
begin insymbol;
if not (sy in fsys + [ident,casesy,semicolon]) then
begin error(19); skip(fsys + [ident,casesy]) end
end
end (*while*);
nxt := nil;
while nxt1 <> nil do
with nxt1^ do
begin lcp := next; next := nxt; nxt := nxt1; nxt1 := lcp end;
if sy = casesy then
begin new(lsp,tagfld); pshstc(lsp);
with lsp^ do
begin form := tagfld; tagfieldp := nil; fstvar := nil;
packing := false; new(vart);
for varcn := 0 to varmax do vart^[varcn] := 0
end;
varlnm := 1; varcof := false; varcmx := 0;
frecvar := lsp;
insymbol;
if sy = ident then
begin
{ find possible type first }
searchidnenm([types],lcp1,mm);
{ now set up as field id }
new(lcp,field); ininam(lcp);
with lcp^ do
begin klass:=field; strassvf(name, id); idtype := nil;
next := nil; fldaddr := displ; varnt := vartyp;
varlb := varlab; tagfield := true; taglvl := lvl;
varsaddr := 0; varssize := 0; vartl := -1
end;
lsp^.tagfieldp := lcp;
insymbol;
if sy = colon then begin
enterid(lcp); insymbol;
if sy = ident then begin searchid([types],lcp1); insymbol end
else begin error(2); skip(fsys + [ofsy,lparent]); lcp1 := nil end
end else begin
if lcp1 = nil then begin error(104); lcp1 := usclrptr end;
{ If type only (undiscriminated variant), kill the id. }
if mm then error(103);
putstrs(lcp^.name); { release name string }
lcp^.name := nil { set no tagfield }
end;
if lcp1 <> nil then begin
lsp1 := lcp1^.idtype;
if lsp1 <> nil then
begin alignu(lsp1,displ);
lcp^.fldaddr := displ;
{ only allocate field if named or if undiscriminated
tagfield checks are on }
if (lcp^.name <> nil) or chkudtf then
displ := displ+lsp1^.size;
if (lsp1^.form <= subrange) or stringt(lsp1) then
begin if comptypes(realptr,lsp1) then error(159)
else if stringt(lsp1) then error(159);
lcp^.idtype := lsp1
end
else error(110);
end
end
end
else begin error(2); skip(fsys + [ofsy,lparent]) end;
lsp^.size := displ;
if sy = ofsy then insymbol else error(8);
lsp1 := nil; minsize := displ; maxsize := displ;
tagl := nil;
mint := -maxint; maxt := maxint;
if lsp^.tagfieldp <> nil then
if lsp^.tagfieldp^.idtype <> nil then begin
getbounds(lsp^.tagfieldp^.idtype, mint, maxt);
if maxt-mint+1 > varmax then error(239)
end;
repeat lsp2 := nil;
if not (sy in fsys + [semicolon]) then
begin
repeat constexpr(fsys + [comma,colon,lparent,range],lsp3,lvalu);
rvalu := lvalu; lsp4 := lsp3; if sy = range then begin chkstd;
insymbol; constexpr(fsys + [comma,colon,lparent],lsp4,rvalu)
end;
if lsp^.tagfieldp <> nil then begin
if not comptypes(lsp^.tagfieldp^.idtype,lsp3)then error(111);
if not comptypes(lsp^.tagfieldp^.idtype,lsp4)then error(111);
end;
{ fix up for error processing }
if not lvalu.intval then
begin lvalu.intval := true; lvalu.ival := 1 end;
if not rvalu.intval then
begin rvalu.intval := true; rvalu.ival := 1 end;
if lvalu.ival > rvalu.ival then error(225);
repeat { case range }
gettag(tagp); tagp^.ival := lvalu.ival; tagp^.next := tagl;
tagl := tagp;
new(lsp3,variant); pshstc(lsp3);
with lsp3^ do
begin form := variant; varln := varlnm;
nxtvar := lsp1; subvar := lsp2; varval := lvalu;
caslst := lsp2; packing := false
end;
if (lvalu.ival >= 0) and (lvalu.ival <= varmax) then
lsp^.vart^[lvalu.ival] := varlnm; { set case to logical }
lsp4 := lsp1;
while lsp4 <> nil do
with lsp4^ do
begin
if varval.ival = lvalu.ival then error(178);
lsp4 := nxtvar
end;
lsp1 := lsp3; lsp2 := lsp3;
lvalu.ival := lvalu.ival+1 { next range value }
until lvalu.ival > rvalu.ival; { range is complete }
if lvalu.ival-1 > varcmx then varcmx := lvalu.ival-1;
if lvalu.ival > varmax then
{ errors supressed for multiple overflows in list }
begin if not varcof then error(239); varcof := true end;
test := sy <> comma;
if not test then insymbol
until test;
if sy = colon then insymbol else error(5);
if sy = lparent then insymbol else error(9);
alignu(nilptr, displ); { max align all variants }
if lcp <> nil then lcp^.varsaddr := displ;
fieldlist(fsys + [rparent,semicolon],lsp2,lsp3,lcp, lvl+1,lcp2);
if displ > maxsize then maxsize := displ;
if lcp <> nil then lcp^.varssize := maxsize-lcp^.varsaddr;
while lsp3 <> nil do
begin lsp4 := lsp3^.subvar; lsp3^.subvar := lsp2;
lsp3^.varfld := lcp2;
lsp3^.size := displ;
lsp3 := lsp4
end;
if sy = rparent then
begin insymbol;
if not (sy in fsys + [semicolon]) then
begin error(6); skip(fsys + [semicolon]) end
end
else error(4);
end;
varlnm := varlnm+1;
test := sy <> semicolon;
if not test then
begin displ := minsize;
insymbol
end
until test;
displ := maxsize;
lsp^.fstvar := lsp1;
lsp^.varts := 0;
if lcp <> nil then begin
if varcmx >= 0 then lsp^.varts := varcmx+1;
{ output LVN table }
if prcode then begin
write(prr, 'v',' ':7);
genlabel(lcp^.vartl); prtlabel(lcp^.vartl);
write(prr, ' ', lsp^.varts:1);
for varcn := 0 to lsp^.varts-1 do
write(prr, ' ', lsp^.vart^[varcn]:1);
writeln(prr)
end
end;
if lsp^.tagfieldp <> nil then begin
ordertag(tagl);
tagp := tagl; ferr := false;
while (tagp <> nil) and (mint <= maxt) and not ferr do begin
if tagp^.ival <> mint then begin error(200); ferr := true end
else begin mint := mint+1; tagp := tagp^.next end
end;
if (mint <= maxt) and not ferr then error(200)
end;
while tagl <> nil do
begin tagp := tagl; tagl := tagl^.next; puttag(tagp) end
end
else frecvar := nil
end (*fieldlist*) ;
begin (*typ*)
lsp := nil;
if not (sy in typebegsys) then
begin error(10); skip(fsys + typebegsys) end;
if sy in typebegsys then
begin
if sy in simptypebegsys then simpletype(fsys,fsp,fsize)
else
(*^*) if sy = arrow then
begin new(lsp,pointer); pshstc(lsp); fsp := lsp;
with lsp^ do
begin form:=pointer; eltype := nil; size := ptrsize;
packing := false end;
insymbol;
if sy = ident then
begin { forward reference everything }
new(lcp,types); ininam(lcp);
with lcp^ do
begin klass := types; strassvf(name,id); idtype := lsp;
next := fwptr;
end;
fwptr := lcp;
insymbol;
end
else error(2);
end
else
begin
ispacked := false; { set not packed by default }
if sy = packedsy then
begin insymbol; ispacked := true; { packed }
if not (sy in typedels) then
begin
error(10); skip(fsys + typedels)
end
end;
(*array*) if sy = arraysy then
begin insymbol;
if (sy <> lbrack) and iso7185 then error(11);
if (sy = ofsy) and not iso7185 then begin
lsp1 := nil;
{ process container array }
new(lsp,arrayc); pshstc(lsp);
with lsp^ do
begin form:=arrayc; abstype := lsp1;
packing := ispacked end;
lsp1 := lsp
end else if (sy <> lbrack) and not iso7185 then begin
{ process Pascaline array }
lsp1 := nil;
repeat new(lsp,arrays); pshstc(lsp);
with lsp^ do
begin form:=arrays; aeltype := lsp1; inxtype := nil;
tmpl := -1; packing := ispacked end;
lsp1 := lsp;
constexpr(fsys+[comma,ofsy],lsp2,lvalu);
if lsp2 <> nil then if lsp2 <> intptr then error(15);
if not lvalu.intval then
begin lvalu.intval := true; lvalu.ival := 1 end;
if lvalu.ival <= 0 then
begin error(238); lvalu.ival := 1 end;
lsp1^.size := lsize;
{ build subrange type based on 1..n }
new(lsp2,subrange); pshstc(lsp2);
with lsp2^ do
begin form := subrange; rangetype := intptr;
min.ival := 1; max := lvalu end;
lsp^.inxtype := lsp2;
test := sy <> comma;
if not test then insymbol
until test
end else begin if sy = lbrack then insymbol;
{ process ISO 7185 array }
lsp1 := nil;
repeat new(lsp,arrays); pshstc(lsp);
with lsp^ do
begin form:=arrays; aeltype := lsp1; inxtype := nil;
tmpl := -1; packing := ispacked end;
lsp1 := lsp;
simpletype(fsys + [comma,rbrack,ofsy],lsp2,lsize);
lsp1^.size := lsize;
if lsp2 <> nil then
if lsp2^.form <= subrange then
begin
if lsp2 = realptr then
begin error(109); lsp2 := nil end
else
if lsp2 = intptr then
begin error(149); lsp2 := nil end;
lsp^.inxtype := lsp2
end
else begin error(113); lsp2 := nil end;
test := sy <> comma;
if not test then insymbol
until test;
if sy = rbrack then insymbol else error(12)
end;
if sy = ofsy then insymbol else error(8);
typ(fsys,lsp,lsize);
repeat
with lsp1^ do begin
if lsp1^.form = arrays then begin
if lsp <> nil then
if lsp^.form = arrayc then error(272);
lsp2 := aeltype; aeltype := lsp;
if inxtype <> nil then begin
getbounds(inxtype,lmin,lmax);
span := lmax-lmin+1;
if span < 1 then error(509);
if lsize > pmmaxint div span then
begin error(237); lsize := 1 end
else lsize := lsize*span;
size := lsize
end;
arrtmp(lsp1) { output fixed template }
end else
{ note containers are only one deep, and have no size }
begin lsp2 := abstype; abstype := lsp; size := 0 end
end;
lsp := lsp1; lsp1 := lsp2
until lsp1 = nil
end
else
(*record*) if sy = recordsy then
begin insymbol;
oldtop := top;
if top < displimit then
begin top := top + 1; inidsp(display[top]);
display[top].occur := rec
end
else error(250);
displ := 0;
fieldlist(fsys-[semicolon]+[endsy],lsp1,nil,nil,1,lcp);
new(lsp,records);
with lsp^ do
begin form := records; fstfld := display[top].fname;
display[top].fname := nil;
recvar := lsp1; size := displ;
packing := ispacked;
recyc := display[top].fstruct;
display[top].fstruct := nil
end;
putdsps(oldtop); top := oldtop;
{ register the record late because of the purge above }
pshstc(lsp);
if sy = endsy then insymbol else error(13)
end
else
(*set*) if sy = setsy then
begin insymbol;
if sy = ofsy then insymbol else error(8);
simpletype(fsys,lsp1,lsize);
if lsp1 <> nil then
if lsp1^.form > subrange then
begin error(115); lsp1 := nil end
else
if lsp1 = realptr then
begin error(114); lsp1 := nil end
else if lsp1 = intptr then
begin error(169); lsp1 := nil end
else
begin getbounds(lsp1,lmin,lmax);
if (lmin < setlow) or (lmax > sethigh)
then error(169);
end;
new(lsp,power); pshstc(lsp);
with lsp^ do
begin form:=power; elset:=lsp1; size:=setsize;
packing := ispacked; matchpack := true end;
end
else
(*file*) if sy = filesy then
begin insymbol;
if sy = ofsy then insymbol else error(8);
typ(fsys,lsp1,lsize);
if filecomponent(lsp1) then error(190);
new(lsp,files); pshstc(lsp);
with lsp^ do
begin form := files; filtype := lsp1;
size := filesize+lsize; packing := ispacked
end
end
else fsp := nil;
fsp := lsp
end;
if not (sy in fsys) then
begin error(6); skip(fsys) end
end
else fsp := nil;
if fsp = nil then fsize := 1 else fsize := fsp^.size
end (*typ*) ;
procedure labeldeclaration;
var llp: lbp;
test: boolean;
begin
repeat
if (sy = intconst) or (sy = ident) then begin
if sy = ident then chkstd;
searchlabel(llp, top, sy = ident); { search preexisting label }
if llp <> nil then error(166) { multideclared label }
else newlabel(llp, sy = ident);
insymbol
end else if iso7185 then error(15) else error(22);
if not ( sy in fsys + [comma, semicolon] ) then
begin error(6); skip(fsys+[comma,semicolon]) end;
test := sy <> comma;
if not test then insymbol
until test;
if sy = semicolon then insymbol else error(14)
end (* labeldeclaration *) ;
procedure constdeclaration;
var lcp: ctp; lsp: stp; lvalu: valu;
begin
if sy <> ident then
begin error(2); skip(fsys + [ident]) end;
while sy = ident do
begin new(lcp,konst); ininam(lcp);
with lcp^ do
begin klass:=konst; strassvf(name, id); idtype := nil; next := nil;
refer := false
end;
insymbol;
if (sy = relop) and (op = eqop) then insymbol else error(16);
constexpr(fsys + [semicolon],lsp,lvalu);
enterid(lcp);
lcp^.idtype := lsp; lcp^.values := lvalu;
if sy = semicolon then
begin insymbol;
if not (sy in fsys + [ident]) then
begin error(6); skip(fsys + [ident]) end
end
else error(14)
end
end (*constdeclaration*) ;
procedure typedeclaration;
var lcp: ctp; lsp: stp; lsize: addrrange;
begin
if sy <> ident then
begin error(2); skip(fsys + [ident]) end;
while sy = ident do
begin new(lcp,types); ininam(lcp);
with lcp^ do
begin klass := types; strassvf(name, id); idtype := nil;
refer := false
end;
insymbol;
if (sy = relop) and (op = eqop) then insymbol else error(16);
typ(fsys + [semicolon],lsp,lsize);
enterid(lcp);
lcp^.idtype := lsp;
if sy = semicolon then
begin insymbol;
if not (sy in fsys + [ident]) then
begin error(6); skip(fsys + [ident]) end
end
else error(14)
end;
resolvep
end (*typedeclaration*) ;
procedure wrtsym(lcp: ctp; typ: char);
begin
if prcode then begin
with lcp^ do begin
write(prr, 's',' ':7);
writev(prr, name, lenpv(name)); write(prr, ' ', typ);
write(prr, ' ', vaddr:1, ' ');
if klass in [proc, func] then begin
write(prr, 'q('); prtpartyp(lcp); write(prr, ')');
if klass = func then begin
write(prr, ':'); wrttyp(prr, idtype)
end
end else wrttyp(prr, idtype);
writeln(prr)
end
end
end;
procedure vardeclaration;
var lcp,nxt: ctp; lsp: stp; lsize: addrrange;
test: boolean; maxpar, curpar: integer; cc: integer;
begin nxt := nil;
repeat { id:type group }
maxpar := 0;
repeat {ids }
lcp := nil;
if sy = ident then
begin new(lcp,vars); ininam(lcp); curpar := 0;
with lcp^ do
begin klass := vars; strassvf(name, id); next := nxt;
idtype := nil; vkind := actual; vlev := level;
refer := false; isloc := false; threat := false; forcnt := 0;
part := ptval; hdr := false; vext := incact;
vmod := incstk; inilab := -1; ininxt := nil; dblptr := false;
end;
enterid(lcp);
nxt := lcp;
insymbol;
end
else error(2);
if (sy = lparent) and not iso7185 then begin
{ parameterized type specification }
if (nxt <> nil) and (lcp <>nil) then begin { gen code strip label }
lcp^.ininxt := display[top].inilst; display[top].inilst := lcp;
genlabel(lcp^.inilab); putlabel(lcp^.inilab);
genlabel(lcp^.skplab)
end;
insymbol;
repeat
expression(fsys+[comma,rparent], false); load; curpar := curpar+1;
if gattr.typtr <> nil then
if basetype(gattr.typtr) <> intptr then error(243);
if not (sy in [comma,rparent]) then
begin error(27);
skip(fsys+[comma,rparent,colon,semicolon]+typedels) end;
test := sy <> comma;
if not test then insymbol
until test;
if lcp <> nil then genujpxjpcal(57(*ujp*),lcp^.skplab);
if sy = rparent then insymbol else error(4)
end;
if (maxpar <> 0) and (curpar <> maxpar) then error(269);
if curpar > maxpar then maxpar := curpar;
if not (sy in fsys + [comma,colon] + typedels) then
begin error(6); skip(fsys+[comma,colon,semicolon]+typedels) end;
test := sy <> comma;
if not test then insymbol
until test;
{ At this point, initializers, if they exist, are on stack in groups
according to the id they belong to, and maxpar indicates how many per
id. This must be so because we don't know the type or location of the
assocated variable yet. }
if sy = colon then insymbol else error(5);
typ(fsys + [semicolon] + typedels,lsp,lsize);
cc := containers(lsp); { find # containers }
if cc > 0 then
{ change variable from size of base to pointer+template for containers }
lsize := ptrsize+cc*intsize;
resolvep; { resolve pointer defs before symbol generate }
if lsp <> nil then
if (lsp^.form = arrayc) and (maxpar = 0) then error(270)
else if maxpar <> containers(lsp) then error(271);
while nxt <> nil do
with nxt^ do
begin
idtype := lsp;
{ globals are alloc/increment, locals are decrement/alloc }
if level <= 1 then
begin alignu(lsp,gc); vaddr := gc; gc := gc + lsize end
else
begin lc := lc - lsize; alignd(lsp,lc); vaddr := lc end;
{ mark symbol }
if prcode then
if level <= 1 then wrtsym(nxt, 'g') else wrtsym(nxt, 'l');
if maxpar > 0 then begin
putlabel(nxt^.skplab);
{ load variable address }
if level <= 1 then gen1(37(*lao*),vaddr)
else gen2(50(*lda*),level-(level-vlev),vaddr);
if level <= 1 then
{ issue vector init ptr instruction }
gen2(97(*vip*),maxpar,containerbase(lsp))
else
{ issue vector init stack instruction }
gen2(96(*vis*),maxpar,containerbase(lsp));
gen0(90(*ret*)); { issue code strip return }
{ remove initializers, var addr }
mesl(maxpar*intsize+adrsize)
end;
nxt := next
end;
if sy = semicolon then
begin insymbol;
if not (sy in fsys + [ident]) then
begin error(6); skip(fsys + [ident]) end
end
else error(14)
until (sy <> ident) and not (sy in typedels);
resolvep
end (*vardeclaration*) ;
procedure fixeddeclaration;
var lcp: ctp; lsp: stp; lsize: addrrange;
v: integer; d: boolean; dummy: stp;
procedure fixeditem(fsys: setofsys; lsp: stp; size: integer; var v: integer; var d: boolean);
var fvalu: valu; lsp1: stp; lcp: ctp; i, min, max: integer;
test: boolean;
begin v := 0; d := false;
if lsp <> nil then begin
case lsp^.form of
scalar: if lsp^.scalkind = declared then begin
{ enumerated type }
if sy = ident then begin
searchid([konst],lcp);
if not comptypes(lsp, lcp^.idtype) then error(245);
if lcp^.values.intval then begin
if prcode then begin
if lsp = boolptr then
writeln(prr, 'c b ', lcp^.values.ival:1)
else if size = 1 then
writeln(prr, 'c x ', lcp^.values.ival:1)
else writeln(prr, 'c i ', lcp^.values.ival:1);
end;
v := lcp^.values.ival; d := true
end else error(513);
insymbol
end else error(2)
end else begin
{ get value to satisfy entry }
constexpr(fsys,lsp1,fvalu);
if lsp1 <> nil then
if (lsp = realptr) and (lsp1 = intptr) then begin
{ integer to real, convert }
if not fvalu.intval then error(515)
else if prcode then writeln(prr, 'c r ', fvalu.ival:1)
end else if comptypes(lsp, lsp1) then begin
{ constants possible are i: integer, r: real,
p: (power) set, s: string (including set), c: char,
b: boolean, x: byte integer }
if lsp = charptr then begin
if fvalu.intval then begin
if prcode then write(prr, 'c c ', fvalu.ival:1);
v := fvalu.ival; d := true
end
end else if fvalu.intval then begin
if (size = 1) and prcode then
write(prr, 'c x ', fvalu.ival:1)
else write(prr, 'c i ', fvalu.ival:1);
v := fvalu.ival; d := true
end else if (fvalu.valp^.cclass = reel) and prcode then
write(prr, 'c r ', fvalu.valp^.rval:23);
if prcode then writeln(prr)
end else error(245)
end;
subrange: begin fixeditem(fsys,lsp^.rangetype,lsp^.size,v,d);
if d then
if (v < lsp^.min.ival) or (v > lsp^.min.ival) then
error(246)
end;
power: begin { get value to satisfy entry }
constexpr(fsys,lsp1,fvalu);
if comptypes(lsp, lsp1) then begin
if prcode then begin
write(prr, 'c p (');
for i := setlow to sethigh do
if i in fvalu.valp^.pval then write(prr,' ',i:1);
writeln(prr, ')')
end
end else error(245)
end;
arrays: begin getbounds(lsp^.inxtype, min, max);
if (sy = stringconst) and stringt(lsp) then begin
constexpr(fsys,lsp1,fvalu);
if comptypes(lsp, lsp1) then begin
{ string constant matches array }
if fvalu.valp^.slgth <> max then error(245);
if prcode then begin
write(prr, 'c ');
write(prr, 's ''');
writev(prr, fvalu.valp^.sval, fvalu.valp^.slgth);
writeln(prr, '''')
end
end else error(245)
end else begin
{ iterate array elements }
i := min; if sy = arraysy then insymbol else error(28);
repeat
fixeditem(fsys+[comma,endsy],lsp^.aeltype, lsp^.aeltype^.size, v, d);
i := i+1;
if not (sy in [comma,endsy]) then
begin error(29); skip(fsys+[comma,endsy]+typedels) end;
test := sy <> comma;
if not test then insymbol
until test;
if i-1 <> max then error(247);
if sy = endsy then insymbol else error(13)
end
end;
records: begin lcp := lsp^.fstfld;
if lsp^.recvar <> nil then error(248);
if sy = recordsy then insymbol else error(28);
i := 1; max := 1;
repeat
if lcp = nil then
{ ran out of data items, dummy parse a constant }
constexpr(fsys+[comma,endsy],dummy,fvalu)
else fixeditem(fsys+[comma,endsy],lcp^.idtype,
lcp^.idtype^.size, v, d);
max := max+1;
if lcp <> nil then begin lcp := lcp^.next; i := i+1 end;
if not (sy in [comma,endsy]) then
begin error(29); skip(fsys+[comma,endsy]+typedels) end;
test := sy <> comma;
if not test then insymbol
until test;
if i <> max then error(247);
if sy = endsy then insymbol else error(13)
end;
pointer, arrayc, files, tagfld, variant,exceptf: error(244);
end
end
end;
begin
repeat { id:type group }
lcp := nil;
if sy = ident then
begin new(lcp,fixedt); ininam(lcp);
with lcp^ do
begin klass := fixedt; strassvf(name, id);
idtype := nil; floc := -1; fext := incact; fmod := incstk
end;
enterid(lcp);
insymbol;
end
else error(2);
if not (sy in fsys + [colon] + typedels) then
begin error(6); skip(fsys+[comma,colon,semicolon]+typedels) end;
if sy = colon then insymbol else error(5);
typ(fsys + [semicolon,relop] + typedels,lsp,lsize);
if lcp <> nil then lcp^.idtype := lsp;
if (sy = relop) and (op = eqop) then begin
insymbol;
{ start fixed constants }
if prcode then write(prr, 'n ');
genlabel(lcp^.floc); prtlabel(lcp^.floc);
if prcode then writeln(prr, ' ', lsize:1);
fixeditem(fsys+[semicolon], lsp, lsp^.size, v, d);
if prcode then writeln(prr, 'x')
end else error(16);
if sy = semicolon then
begin insymbol;
if not (sy in fsys + [ident]) then
begin error(6); skip(fsys + [ident]) end
end
else error(14)
until (sy <> ident) and not (sy in typedels)
end (*fixeddeclaration*) ;
procedure procdeclaration(fsy: symbol);
var oldlev: 0..maxlevel; lcp,lcp1,lcp2: ctp; lsp: stp;
forw,extl,virt,ovrl: boolean; oldtop: disprange;
llc: stkoff; lbname: integer; plst: boolean; fpat: fpattr;
ops: restr; opt: operatort;
procedure pushlvl(forw: boolean; lcp: ctp);
begin
if level < maxlevel then level := level + 1 else error(251);
if top < displimit then
begin top := top + 1;
with display[top] do
begin inidsp(display[top]);
if forw then fname := lcp^.pflist;
{ use the defining point status of the parent block }
define := display[top-1].define;
occur := blck; bname := lcp
end
end
else error(250);
end;
procedure parameterlist(fsy: setofsys; var fpar: ctp; var plst: boolean;
opr: boolean; opt: operatort);
var lcp,lcp1,lcp2,lcp3: ctp; lsp: stp; lkind: idkind;
llc,lsize: addrrange; count: integer; pt: partyp;
oldlev: 0..maxlevel; oldtop: disprange;
oldlevf: 0..maxlevel; oldtopf: disprange;
lcs: addrrange; test: boolean; dummy: boolean; first: boolean;
procedure joinlists;
var lcp, lcp3: ctp;
begin first := true;
{ we missed the type for this id list, meaning the types are nil. Add
the new list as is for error recovery }
if lcp2 <> nil then begin
lcp3 := lcp2; { save sublist head }
{ find sublist end }
lcp := nil;
while lcp2 <> nil do begin lcp := lcp2; lcp2 := lcp2^.next end;
{ join lists }
lcp^.next := lcp1;
lcp1 := lcp3
end
end;
begin { parameterlist }
plst := false;
if forw then begin { isolate duplicated list in level }
oldlevf := level; oldtopf := top; pushlvl(false, nil)
end;
lcp1 := nil;
if not (sy in fsy + [lparent]) then
begin error(7); skip(fsys + fsy + [lparent]) end;
if sy = lparent then
begin if forw and iso7185 then error(119); plst := true;
insymbol;
if not (sy in [ident,varsy,procsy,funcsy,viewsy,outsy]) then
begin error(7); skip(fsys + [ident,rparent]) end;
while sy in [ident,varsy,procsy,funcsy,viewsy,outsy] do
begin
if sy = procsy then
begin
insymbol; lcp := nil; if opr then error(285);
if sy = ident then
begin new(lcp,proc,declared,formal); ininam(lcp);
lc := lc-ptrsize*2; { mp and addr }
alignd(parmptr,lc);
with lcp^ do
begin klass:=proc; strassvf(name, id); idtype := nil;
next := lcp1;
pflev := level (*beware of parameter procedures*);
pfdeckind:=declared; pflist := nil;
pfkind:=formal; pfaddr := lc; pext := false;
pmod := nil; keep := true; pfattr := fpanone;
grpnxt := nil; grppar := lcp; pfvid := nil
end;
enterid(lcp);
lcp1 := lcp;
insymbol
end
else error(2);
oldlev := level; oldtop := top; pushlvl(false, lcp);
lcs := lc; parameterlist([semicolon,rparent],lcp2,dummy, false, noop);
lc := lcs; if lcp <> nil then lcp^.pflist := lcp2;
if not (sy in fsys+[semicolon,rparent]) then
begin error(7);skip(fsys+[semicolon,rparent]) end;
level := oldlev; putdsps(oldtop); top := oldtop
end
else
begin
if sy = funcsy then
begin lcp2 := nil; if opr then error(285);
insymbol;
if sy = ident then
begin new(lcp,func,declared,formal); ininam(lcp);
lc := lc-ptrsize*2; { mp and addr }
alignd(parmptr,lc);
with lcp^ do
begin klass:=func; strassvf(name, id);
idtype := nil; next := lcp1;
pflev := level (*beware param funcs*);
pfdeckind:=declared; pflist := nil;
pfkind:=formal; pfaddr:=lc; pext := false;
pmod := nil; keep := true; pfattr := fpanone;
grpnxt := nil; grppar := lcp; pfvid := nil
end;
enterid(lcp);
lcp1 := lcp;
insymbol;
end
else error(2);
oldlev := level; oldtop := top; pushlvl(false, lcp);
lcs := lc;
parameterlist([colon,semicolon,rparent],lcp2,dummy, false, noop);
lc := lcs; if lcp <> nil then lcp^.pflist := lcp2;
if not (sy in fsys+[colon]) then
begin error(7);skip(fsys+[comma,semicolon,rparent]) end;
if sy = colon then
begin insymbol;
if sy = ident then
begin searchid([types],lcp2);
lsp := lcp2^.idtype;
lcp^.idtype := lsp;
if lsp <> nil then
if not(lsp^.form in[scalar,subrange,pointer])
then begin error(120); lsp := nil end;
insymbol
end
else error(2);
if not (sy in fsys + [semicolon,rparent]) then
begin error(7);skip(fsys+[semicolon,rparent])end
end
else error(5);
level := oldlev; putdsps(oldtop); top := oldtop
end
else
begin
pt := ptval;
if sy = varsy then pt := ptvar
else if sy = viewsy then pt := ptview
else if sy = outsy then pt := ptout;
if opr then begin
if first and (opt = bcmop) then begin
if pt <> ptout then error(288)
end else if opr and (pt <> ptval) and (pt <> ptview) then
error(286)
end;
if (sy = varsy) or (sy = outsy) then
begin lkind := formal; insymbol end
else begin lkind := actual;
if sy = viewsy then insymbol
end;
lcp2 := nil;
count := 0;
repeat
if sy = ident then
begin new(lcp,vars); ininam(lcp);
with lcp^ do
begin klass:=vars; strassvf(name,id);
idtype:=nil; vkind := lkind; next := lcp2;
vlev := level; keep := true; refer := false;
isloc := false; threat := false; forcnt := 0;
part := pt; hdr := false; vext := false;
vmod := nil; vaddr := 0; inilab := -1;
ininxt := nil; dblptr := true
end;
enterid(lcp);
lcp2 := lcp; count := count+1;
insymbol;
end
else error(2);
if not (sy in [comma,colon] + fsys) then
begin error(7);skip(fsys+[comma,semicolon,rparent])
end;
test := sy <> comma;
if not test then insymbol
until test;
if sy = colon then
begin insymbol;
if sy = ident then
begin searchid([types],lcp);
lsp := lcp^.idtype;
lsize := ptrsize;
if lsp <> nil then begin
if lsp^.form = arrayc then lsize := ptrsize*2;
if lkind=actual then begin
if lsp^.form<=power then lsize := lsp^.size
else if lsp^.form=files then error(121);
{ type containing file not allowed either }
if filecomponent(lsp) then error(121)
end
end;
alignu(parmptr,lsize);
lcp3 := lcp2;
lc := lc-count*lsize;
alignd(parmptr,lc);
llc := lc;
while lcp2 <> nil do
begin lcp := lcp2;
with lcp2^ do
begin idtype := lsp;
vaddr := llc;
llc := llc+lsize;
{ if the type is structured, and is
a view parameter, promote to formal }
if lsp <> nil then
if (lsp^.form >= power) and
(part = ptview) then
vkind := formal
end;
lcp2 := lcp2^.next
end;
lcp^.next := lcp1; lcp1 := lcp3;
insymbol
end
else begin error(2); joinlists end;
if not (sy in fsys + [semicolon,rparent]) then
begin error(7);skip(fsys+[semicolon,rparent])end
end
else begin error(5); joinlists end
end;
end;
first := false;
if sy = semicolon then
begin insymbol;
if not (sy in fsys + [ident,varsy,procsy,funcsy,viewsy,outsy]) then
begin error(7); skip(fsys + [ident,rparent]) end
end
end (*while*) ;
if sy = rparent then
begin insymbol;
if not (sy in fsy + fsys) then
begin error(6); skip(fsy + fsys) end
end
else error(4);
lcp3 := nil;
(*reverse pointers and reserve local cells for copies of multiple
values*)
lc := -level*ptrsize; { set locals top }
while lcp1 <> nil do
with lcp1^ do
begin lcp2 := next; next := lcp3;
if klass = vars then
if idtype <> nil then
{ if value variable, and structured, we make a copy to
play with. However, structured is treated as var if
it is view, since that is protected }
if (vkind=actual) and (idtype^.form>power) and
(idtype^.form <> arrayc) then
begin
lc := lc-idtype^.size;
alignd(parmptr,lc);
vaddr := lc;
isloc := true { flag is a local now }
end;
lcp3 := lcp1; lcp1 := lcp2
end;
fpar := lcp3
end else begin fpar := nil; lc := -level*ptrsize end;
if forw then begin { isolate duplicated list in level }
level := oldlevf; putdsps(oldtopf); top := oldtopf
end
end (*parameterlist*) ;
{ for overloading, same as strict cmpparlst(), but includes read = integer
and string = char }
function compparamovl(pla, plb: ctp): boolean;
var f: boolean; t1, t2: stp;
begin f := true;
while (pla <> nil) and (plb <> nil) do begin
if not cmppar(pla,plb) then begin
{ incompatible, but check special cases }
t1 := basetype(pla^.idtype);
t2 := basetype(plb^.idtype);
if not ((intt(t1) and realt(t2)) or
(realt(t1) and intt(t2)) or
(chart(t1) and chart(t2))) then f := false
end;
pla := pla^.next; plb := plb^.next
end;
if (pla <> nil) or (plb <> nil) then f := false;
compparamovl := f
end;
{ check parameter lists converge with different modes }
function conpar(pla, plb: ctp): boolean;
var f: boolean;
{ find bidirectionally assignment compatible }
function comp(t1, t2: stp): boolean;
begin comp := false;
if comptypes(t1, t2) then comp := true
else if (intt(t1) and realt(t2)) or (realt(t1) and intt(t2)) or
(chart(t1) and chart(t2)) then comp := true
end;
begin f := false;
while (pla <> nil) and (plb <> nil) do begin
if comp(pla^.idtype,plb^.idtype) then
if pla^.part <> plb^.part then begin f := true; pla := nil end
else begin pla := pla^.next; plb := plb^.next end
else pla := nil
end;
conpar := f
end;
{ check overload proc/funcs against each other, first list is group }
procedure chkovlpar(lcp1, lcp2: ctp);
var e: boolean;
begin
e := false;
while lcp1 <> nil do begin
if (lcp1 <> lcp2) and (lcp1^.klass = lcp2^.klass) then begin
if compparamovl(lcp2^.pflist, lcp1^.pflist) then begin
if not e then if fsy = operatorsy then error(283)
else error(249);
e := true
end;
if conpar(lcp2^.pflist, lcp1^.pflist) then begin
if not e then if fsy = operatorsy then error(284)
else error(276);
e := true
end;
end;
lcp1 := lcp1^.grpnxt
end
end;
{ find space occupied by parameter list }
function parmspc(plst: ctp): addrrange;
var locpar: addrrange;
begin
locpar := 0;
while plst <> nil do begin
if (plst^.idtype <> nil) and (plst^.klass = vars) then begin
if (plst^.part = ptval) or (plst^.part = ptview) then begin
if plst^.idtype^.form <= power then
locpar := locpar+plst^.idtype^.size
else if plst^.idtype^.form = arrayc then
locpar := locpar+ptrsize*2
else locpar := locpar+ptrsize
end else begin
if plst^.idtype^.form = arrayc then locpar := locpar+ptrsize*2
else locpar := locpar+ptrsize
end
end else if (plst^.klass = proc) or (plst^.klass = func) then
locpar := locpar+ptrsize*2;
alignu(parmptr,locpar);
plst := plst^.next
end;
parmspc := locpar
end;
{ offset addresses in parameter list }
procedure parmoff(plst: ctp; off: addrrange);
begin
while plst <> nil do begin
if plst^.klass = vars then begin
if not plst^.isloc then plst^.vaddr := plst^.vaddr+off
end else if (plst^.klass = proc) or (plst^.klass = func) then
plst^.pfaddr := plst^.pfaddr+off;
plst := plst^.next
end
end;
begin (*procdeclaration*)
{ parse and skip any attribute }
fpat := fpanone;
opt := bcmop; { avoid undefined error }
if fsy in [overloadsy,staticsy,virtualsy,overridesy] then begin
chkstd;
case fsy of { attribute }
overloadsy: fpat := fpaoverload;
staticsy: fpat := fpastatic;
virtualsy: begin fpat := fpavirtual; if top > 1 then error(228) end;
overridesy: begin fpat := fpaoverride; if top > 1 then error(229) end;
end;
if (sy <> procsy) and (sy <> funcsy) and (sy <> operatorsy) then
if iso7185 then error(209) else error(279)
else fsy := sy; insymbol
end;
{ set parameter address start to zero, offset later }
llc := lc; lc := 0; forw := false; extl := false; virt := false;
ovrl := false;
if (sy = ident) or (fsy = operatorsy) then
begin
if fsy = operatorsy then begin { process operator definition }
if not (sy in [mulop,addop,relop,notsy,becomes]) then
begin error(281); lcp := nil;
skip(fsys+[mulop,addop,relop,notsy,arrow,lparent,semicolon])
end
else begin
if sy = notsy then op := notop
else if sy = becomes then op := bcmop;
lcp := display[top].oprprc[op] { pick up an operator leader }
end;
if fpat <> fpanone then error(280);
opt := op { save operator for later }
end else
searchsection(display[top].fname,lcp); { find previous definition }
if lcp <> nil then
begin
{ set flags according to attribute }
if lcp^.klass = proc then begin
forw := lcp^.forwdecl and (fsy=procsy) and (lcp^.pfkind=actual);
extl := lcp^.extern and (fsy=procsy) and (lcp^.pfkind=actual);
virt := (lcp^.pfattr = fpavirtual) and (fpat = fpaoverride) and
(fsy=procsy)and(lcp^.pfkind=actual);
ovrl := ((fsy=procsy)or(fsy=funcsy)) and (lcp^.pfkind=actual) and
(fpat = fpaoverload)
end else if lcp^.klass = func then begin
forw:=lcp^.forwdecl and (fsy=funcsy) and (lcp^.pfkind=actual);
extl:=lcp^.extern and (fsy=funcsy) and (lcp^.pfkind=actual);
virt := (lcp^.pfattr = fpavirtual) and (fpat = fpaoverride) and
(fsy=funcsy)and(lcp^.pfkind=actual);
ovrl := ((fsy=procsy)or(fsy=funcsy)) and (lcp^.pfkind=actual) and
(fpat = fpaoverload)
end else forw := false;
if not forw and not virt and not ovrl and
(fsy <> operatorsy) then error(160);
if virt and not chkext(lcp) then error (230);
if ovrl and (lcp^.pfattr = fpavirtual) then error(232);
end
else if fpat = fpaoverride then error(231);
lcp1 := lcp; { save original }
if not forw then { create a new proc/func entry }
begin
if (fsy = procsy) or ((fsy = operatorsy) and (opt = bcmop)) then
new(lcp,proc,declared,actual)
else { func/opr } new(lcp,func,declared,actual);
ininam(lcp);
with lcp^ do
begin
if (fsy = procsy) or
((fsy = operatorsy) and (opt = bcmop)) then
klass := proc else klass := func;
if fsy = operatorsy then begin
{ Synth a label based on the operator. This is done for
downstream diagnostics. }
case op of { operator }
mul: ops := '* '; rdiv: ops := '/ ';
andop: ops := 'and '; idiv: ops := 'div ';
imod: ops := 'div '; plus: ops := '+ ';
minus: ops := '- '; orop: ops := 'or ';
ltop: ops := '< '; leop: ops := '<= ';
geop: ops := '> '; gtop: ops := '>= ';
neop: ops := '<> '; eqop: ops := '= ';
inop: ops := 'in '; xorop: ops := 'xor ';
notop: ops := 'not '; bcmop: ops := ':= ';
end;
strassvr(name, ops)
end else strassvf(name, id);
idtype := nil; next := nil;
sysrot := false; extern := false; pflev := level;
genlabel(lbname); pfdeckind := declared; pfkind := actual;
pfname := lbname; pflist := nil; asgn := false;
pext := incact; pmod := incstk; refer := false;
pfattr := fpat; grpnxt := nil; grppar := lcp;
if pfattr in [fpavirtual, fpaoverride] then begin { alloc vector }
if pfattr = fpavirtual then begin
{ have to create a label for far references to virtual }
new(lcp2,vars); ininam(lcp2);
with lcp2^ do begin klass := vars;
strassvf(name, id); strcatvr(name, '__virtvec');
idtype := nilptr; vkind := actual; next := nil;
vlev := 0; vaddr := gc; isloc := false; threat := false;
forcnt := 0; part := ptval; hdr := false;
vext := incact; vmod := incstk; inilab := -1;
ininxt := nil; dblptr := false;
end;
enterid(lcp2); lcp^.pfvid := lcp2;
wrtsym(lcp2, 'g')
end;
pfvaddr := gc; gc := gc+adrsize
end
end;
if virt or ovrl then
{ just insert to group list for this proc/func }
begin lcp^.grpnxt := lcp1^.grpnxt; lcp1^.grpnxt := lcp;
lcp^.grppar := lcp1 end
else if fsy = operatorsy then begin
if display[top].oprprc[op] = nil then display[top].oprprc[op] := lcp
else begin { already an operator this level, insert into group }
lcp^.grpnxt := lcp1^.grpnxt; lcp1^.grpnxt := lcp;
lcp^.grppar := lcp1
end
end else enterid(lcp)
end
else
begin lcp1 := lcp^.pflist;
while lcp1 <> nil do
begin
with lcp1^ do
if klass = vars then
if idtype <> nil then
if vaddr < lc then lc := vaddr;
lcp1 := lcp1^.next
end
end;
insymbol
end
else
begin error(2);
if (fsy = procsy) or ((fsy = operatorsy) and (opt = bcmop)) then
lcp := uprcptr else lcp := ufctptr
end;
oldlev := level; oldtop := top;
{ procedure/functions have an odd defining status. The parameter list does
not have defining points, but the rest of the routine definition does. }
pushlvl(forw, lcp); display[top].define := false;
if (fsy = procsy) or ((fsy = operatorsy) and (opt = bcmop)) then
parameterlist([semicolon],lcp1,plst, fsy = operatorsy, opt)
else parameterlist([semicolon,colon],lcp1,plst, fsy = operatorsy, opt);
if not forw then begin
lcp^.pflist := lcp1; lcp^.locpar := parmspc(lcp^.pflist);
parmoff(lcp^.pflist, marksize+ptrsize+adrsize+lcp^.locpar);
if ovrl or (fsy = operatorsy) then begin { compare against overload group }
lcp2 := lcp^.grppar; { index top of overload group }
chkovlpar(lcp2, lcp)
end;
lcp^.locstr := lc { save locals counter }
end else begin
if plst then if not cmpparlst(lcp^.pflist, lcp1) then error(216);
putparlst(lcp1); { redeclare, dispose of copy }
lc := lcp^.locstr { reset locals counter }
end;
if (fsy = funcsy) or ((fsy = operatorsy) and not (opt = bcmop)) then
{ function }
if sy = colon then
begin insymbol;
if sy = ident then
begin if forw and iso7185 then error(122);
searchid([types],lcp1);
lsp := lcp1^.idtype;
if forw then begin
if not comptypes(lcp^.idtype, lsp) then error(216)
end else lcp^.idtype := lsp;
if lsp <> nil then
if iso7185 then begin
if not (lsp^.form in [scalar,subrange,pointer]) then
begin error(120); lcp^.idtype := nil end
end else begin
if not (lsp^.form in [scalar,subrange,pointer,power,
arrays,records]) then
begin error(274); lcp^.idtype := nil end
end;
insymbol
end
else begin error(2); skip(fsys + [semicolon]) end
end
else
if not forw or plst then error(123);
if sy = semicolon then insymbol else error(14);
if ((sy = ident) and strequri('forward ', id)) or (sy = forwardsy) or
(sy = externalsy) then
begin
if forw then { previously forwarded }
if (sy = externalsy) then error(294) else error(161);
if extl and not ovrl then error(295);
if sy = externalsy then begin chkstd; lcp^.extern := true end
else lcp^.forwdecl := true;
insymbol;
if sy = semicolon then insymbol else error(14);
if not (sy in fsys) then
begin error(6); skip(fsys) end
end
else
begin lcp^.forwdecl := false;
{ output block begin marker }
if prcode then begin
if lcp^.klass = proc then write(prr, 'b r ') else write(prr, 'b f ');
writev(prr, lcp^.name, lenpv(lcp^.name));
write(prr, '@'); { this keeps the user from aliasing it }
if lcp^.klass = proc then write(prr, 'p') else write(prr, 'f');
if lcp^.pflist <> nil then begin
write(prr, '_');
prtpartyp(lcp)
end;
writeln(prr);
end;
{ output parameter symbols }
lcp1 := lcp^.pflist;
while lcp1 <> nil do begin wrtsym(lcp1, 'p'); lcp1 := lcp1^.next end;
{ now we change to a block with defining points }
display[top].define := true;
declare(fsys);
lcp^.locspc := lcp^.locstr-lc;
lcs := lcp^.locspc;
body(fsys + [semicolon],lcp);
if sy = semicolon then
begin if prtables then printtables(false); insymbol;
if iso7185 then begin { handle according to standard }
if not (sy in [beginsy]+pfbegsys) then
begin error(6); skip(fsys) end
end else begin
if not (sy in
[labelsy,constsy,typesy,varsy,beginsy]+pfbegsys) then
begin error(6); skip(fsys) end
end
end
else begin error(14); skip([semicolon]) end;
{ output block end marker }
if prcode then
if lcp^.klass = proc then writeln(prr, 'e r')
else writeln(prr, 'e f');
if lcp^.klass = func then
if lcp <> ufctptr then
if not lcp^.asgn and not incact then
error(193) { no function result assign }
end;
level := oldlev; putdsps(oldtop); top := oldtop; lc := llc;
end (*procdeclaration*) ;
begin (*declare*)
dp := true;
repeat
repeat
if sy = privatesy then begin insymbol;
if level > 1 then error(266);
if incact and (level <= 1) then
incstk^.priv := true { flag private encountered }
end;
if not inpriv then begin { if private, get us out quickly }
if sy = labelsy then
begin insymbol; labeldeclaration end;
if sy = constsy then
begin insymbol; constdeclaration end;
if sy = typesy then
begin insymbol; typedeclaration end;
if sy = fixedsy then
begin insymbol; fixeddeclaration end;
if sy = varsy then
begin insymbol; vardeclaration end;
while sy in pfbegsys do
begin lsy := sy; insymbol; procdeclaration(lsy) end
end
until inpriv or iso7185 or (sy = beginsy) or eofinp or
not (sy in [privatesy,labelsy,constsy,typesy,varsy]+pfbegsys);
if (sy <> beginsy) and not inpriv then
begin error(18); skip(fsys) end
until (sy in statbegsys) or eofinp or inpriv;
dp := false;
end (*declare*) ;
procedure body{(fsys: setofsys)};
var
segsize, gblsize, stackbot: integer;
lcmin: stkoff;
llc1: stkoff; lcp: ctp;
llp: lbp;
fp: extfilep;
test: boolean;
printed: boolean;
lsize: addrrange;
stalvl: integer; { statement nesting level }
ilp: ctp;
{ add statement level }
procedure addlvl;
begin
stalvl := stalvl+1
end;
{ remove statement level }
procedure sublvl;
var llp: lbp;
begin
stalvl := stalvl-1;
{ traverse label list for current block and remove any label from
active status whose statement block has closed }
llp := display[top].flabel;
while llp <> nil do with llp^ do begin
if slevel > stalvl then bact := false;
if refer and (minlvl > stalvl) then
minlvl := stalvl;
llp := nextlab { link next }
end
end;
procedure genfjp(faddr: integer);
begin load;
if gattr.typtr <> nil then
if gattr.typtr <> boolptr then error(144);
if prcode then
begin write(prr,' ':8,mn[33]:4,' '); prtlabel(faddr); writeln(prr) end;
ic := ic + 1; mes(33)
end (*genfjp*) ;
procedure statement(fsys: setofsys);
var lcp: ctp; llp: lbp; inherit: boolean;
procedure assignment(fcp: ctp; skp: boolean);
var lattr, lattr2: attr; tagasc, schrcst: boolean; fcp2: ctp;
len: addrrange;
begin tagasc := false; selector(fsys + [becomes],fcp,skp);
if (sy = becomes) or skp then
begin
if gattr.kind = expr then error(287);
{ if function result, set assigned }
if fcp^.klass = func then fcp^.asgn := true
else if fcp^.klass = vars then with fcp^ do begin
if vlev < level then threat := true;
if forcnt > 0 then error(195);
if part = ptview then error(290)
end;
tagasc := false;
if gattr.kind = varbl then
tagasc := gattr.tagfield and (debug or chkvbk);
lattr2 := gattr; { save access before load }
if gattr.typtr <> nil then
if (gattr.access<>drct) or (gattr.typtr^.form>power) or
tagasc then { if tag checking, force address load }
if gattr.kind <> expr then loadaddress;
lattr := gattr;
insymbol; expression(fsys, false); schrcst := ischrcst(gattr);
if (lattr.typtr <> nil) and (gattr.typtr <> nil) then
{ process expression rights as load }
if (gattr.typtr^.form <= power) or (gattr.kind = expr) then begin
if (lattr.typtr^.form = arrayc) and schrcst then begin
{ load as string }
gen2(51(*ldc*),1,1);
gensca(chr(gattr.cval.ival))
end else load
end else loadaddress;
if (lattr.typtr <> nil) and (gattr.typtr <> nil) then begin
fndopr2(bcmop, lattr, fcp2);
if fcp2 <> nil then callop2(fcp2, lattr) else begin
if comptypes(realptr,lattr.typtr)and(gattr.typtr=intptr)then
begin gen0(10(*flt*));
gattr.typtr := realptr
end;
if comptypes(lattr.typtr,gattr.typtr) or
((lattr.typtr^.form = arrayc) and schrcst) then begin
if filecomponent(gattr.typtr) then error(191);
with lattr2 do
if kind = varbl then begin
if access = indrct then
if debug and tagfield and ptrref then
{ check tag assignment to pointer record }
genctaivtcvb(81(*cta*),idplmt,taglvl,vartl,
lattr2.typtr);
if chkvbk and tagfield then
genctaivtcvb(95(*cvb*),vartagoff,varssize,vartl,
lattr2.typtr);
if debug and tagfield then
genctaivtcvb(82(*ivt*),vartagoff,varssize,vartl,
lattr2.typtr)
end;
{ if tag checking, bypass normal store }
if tagasc then
gen0t(26(*sto*),lattr.typtr)
else case lattr.typtr^.form of
scalar,
subrange,
power: begin
if debug then checkbnds(lattr.typtr);
store(lattr)
end;
pointer: begin
if debug then begin
if taggedrec(lattr.typtr^.eltype) then
gen2t(80(*ckl*),0,maxaddr,nilptr)
else gen2t(45(*chk*),0,maxaddr,nilptr);
end;
store(lattr)
end;
arrays, arrayc: begin
containerop(lattr); { rationalize binary container op }
if (lattr.typtr^.form = arrayc) or
(gattr.typtr^.form = arrayc) then begin
{ assign complex pointer }
if (containers(lattr.typtr) = 1) or
(containers(gattr.typtr) = 1) then
gen1(101(*aps*),containerbase(gattr.typtr))
else gen2(102(*apc*),containers(lattr.typtr),
containerbase(gattr.typtr));
if gattr.kind = expr then begin
len := gattr.typtr^.size; alignu(parmptr,len);
gen1(71(*dmp*),len+ptrsize*2)
end
end else begin { standard array assign }
{ onstack from expr }
if gattr.kind = expr then store(lattr)
{ addressed }
else gen1(40(*mov*),lattr.typtr^.size)
end
end;
records: begin
{ onstack from expr }
if gattr.kind = expr then store(lattr)
{ addressed }
else gen1(40(*mov*),lattr.typtr^.size);
end;
files: error(146)
end;
end else error(129)
end
end
end (*sy = becomes*)
else error(51)
end (*assignment*) ;
procedure gotostatement;
var llp: lbp; ttop,ttop1: disprange;
wp: wtp;
begin
if (sy = intconst) or (sy = ident) then
begin
if sy = ident then chkstd;
ttop := top;
while display[ttop].occur <> blck do ttop := ttop - 1;
ttop1 := ttop;
repeat
searchlabel(llp, ttop, sy = ident); { find label }
if llp <> nil then with llp^ do begin
refer := true;
if defined then
if slevel > stalvl then { defining point level greater than
present statement level }
error(185) { goto references deeper nested statement }
else if (slevel > 1) and not bact then
error(187); { Goto references label in different nested
statement }
{ establish the minimum statement level a goto appeared at }
if minlvl > stalvl then minlvl := stalvl;
{ remove any with statement levels to target }
wp := wthstk;
while wp <> nil do begin
if wp^.sl <> slevel then gen0(120(*wbe*));
wp := wp^.next
end;
if ttop = ttop1 then
genujpxjpcal(57(*ujp*),labname)
else begin { interprocedural goto }
genipj(66(*ipj*),level-(level-vlevel),labname);
ipcref := true
end
end;
ttop := ttop - 1
until (llp <> nil) or (ttop = 0);
if llp = nil then begin
error(167); { undeclared label }
newlabel(llp, sy = ident); { create dummy label in current context }
llp^.refer := true
end;
insymbol
end
else if iso7185 then error(15) else error(22);
end (*gotostatement*) ;
procedure compoundstatement;
var test: boolean;
begin
addlvl;
repeat
repeat statement(fsys + [semicolon,endsy])
until not (sy in statbegsys);
test := sy <> semicolon;
if not test then insymbol
until test;
if sy = endsy then insymbol else error(13);
sublvl
end (*compoundstatemenet*) ;
procedure ifstatement;
var lcix1,lcix2: integer;
begin expression(fsys + [thensy], false);
genlabel(lcix1); genfjp(lcix1);
if sy = thensy then insymbol else error(52);
addlvl;
statement(fsys + [elsesy]);
sublvl;
if sy = elsesy then
begin genlabel(lcix2); genujpxjpcal(57(*ujp*),lcix2);
putlabel(lcix1);
markline;
insymbol;
addlvl;
statement(fsys);
sublvl;
putlabel(lcix2);
markline
end
else begin putlabel(lcix1); markline end
end (*ifstatement*) ;
procedure casestatement;
label 1;
var lsp,lsp1,lsp2: stp; fstptr,lpt1,lpt2,lpt3: cip; lvals,lvale: valu;
laddr, lcix, lcix1, lelse, lelse2, lmin, lmax: integer;
test: boolean; i,occ: integer; llc: addrrange;
function casecount(cp: cip): integer;
var c: integer;
begin c := 0;
while cp <> nil do
begin c := c+cp^.cslabe-cp^.cslabs+1; cp := cp^.next end;
casecount := c
end;
begin llc := lc; expression(fsys + [ofsy,comma,colon], false); load;
genlabel(lcix); lelse := 0;
lsp := gattr.typtr;
if lsp <> nil then
if (lsp^.form <> scalar) or (lsp = realptr) then
begin error(144); lsp := nil end
else if not comptypes(lsp,intptr) then gen0t(58(*ord*),lsp);
alignd(intptr,lc); lc := lc-intsize;
{ store start to temp }
gen2t(56(*str*),level,lc,intptr);
genujpxjpcal(57(*ujp*),lcix);
if sy = ofsy then insymbol else error(8);
fstptr := nil; genlabel(laddr);
repeat
lpt3 := nil; genlabel(lcix1);
if not(sy in [semicolon,endsy,elsesy]) then
begin
repeat constexpr(fsys + [comma,colon,range],lsp1,lvals);
if not lvals.intval then
begin lvals.intval := true; lvals.ival := 1 end;
lvale := lvals;
if sy = range then begin
chkstd; insymbol;
constexpr(fsys + [comma,colon],lsp2,lvale);
if not lvale.intval then
begin lvale.intval := true; lvale.ival := 1 end;
if lvale.ival < lvals.ival then error(225)
end;
if lsp <> nil then
if comptypes(lsp,lsp1) then
begin lpt1 := fstptr; lpt2 := nil;
while lpt1 <> nil do
with lpt1^ do
begin
if (cslabs <= lvale.ival) and
(cslabe >= lvals.ival) then error(156);
if cslabs <= lvals.ival then goto 1;
lpt2 := lpt1; lpt1 := next
end;
1: getcas(lpt3);
with lpt3^ do
begin next := lpt1; cslabs := lvals.ival;
cslabe := lvale.ival; csstart := lcix1
end;
if lpt2 = nil then fstptr := lpt3
else lpt2^.next := lpt3
end
else error(147);
test := sy <> comma;
if not test then insymbol
until test;
if sy = colon then insymbol else error(5);
putlabel(lcix1);
markline;
repeat
addlvl;
statement(fsys + [semicolon]);
sublvl
until not (sy in statbegsys);
if lpt3 <> nil then genujpxjpcal(57(*ujp*),laddr);
end;
test := sy <> semicolon;
if not test then insymbol
until test;
if sy = elsesy then begin chkstd; insymbol; genlabel(lelse);
genlabel(lelse2); putlabel(lelse2);
mesl(-intsize); { put selector on stack }
gen1(71(*dmp*),intsize);
putlabel(lelse);
markline;
addlvl;
statement(fsys + [semicolon]);
sublvl;
genujpxjpcal(57(*ujp*),laddr);
if sy = semicolon then insymbol
end;
putlabel(lcix);
markline;
if fstptr <> nil then
begin lmax := fstptr^.cslabe;
(*reverse pointers*)
lpt1 := fstptr; fstptr := nil;
repeat lpt2 := lpt1^.next; lpt1^.next := fstptr;
fstptr := lpt1; lpt1 := lpt2
until lpt1 = nil;
lmin := fstptr^.cslabs;
{ find occupancy }
occ := casecount(fstptr)*100 div (lmax-lmin+1);
if lmax - lmin < cixmax then
begin
{ put selector back on stack }
gen2t(54(*lod*),level,lc,intptr);
if occ >= minocc then begin { build straight vector table }
if lelse > 0 then begin
gen0t(76(*dup*),intptr);
gen2(51(*ldc*),1,lmin);
gen2(53(*les*),ord('i'),0);
genujpxjpcal(73(*tjp*),lelse2);
gen0t(76(*dup*),intptr);
gen2(51(*ldc*),1,lmax);
gen2(49(*grt*),ord('i'),0);
genujpxjpcal(73(*tjp*),lelse2);
end else gen2t(45(*chk*),lmin,lmax,intptr);
gen2(51(*ldc*),1,lmin); gen0(21(*sbi*)); genlabel(lcix);
genujpxjpcal(44(*xjp*),lcix); putlabel(lcix);
repeat
with fstptr^ do
begin
while cslabs > lmin do begin
if lelse > 0 then genujpxjpcal(57(*ujp*),lelse)
else gen0(60(*ujc error*));
lmin := lmin+1
end;
for i := cslabs to cslabe do
genujpxjpcal(57(*ujp*),csstart);
lpt1 := fstptr; fstptr := next; lmin := cslabe+1
end;
putcas(lpt1)
until fstptr = nil;
end else begin
{ devolve to comp/jmp seq }
repeat
with fstptr^ do begin
gencjp(87(*cjp*),cslabs,cslabe,csstart);
lpt1 := fstptr; fstptr := next; lmin := cslabe+1
end;
putcas(lpt1)
until fstptr = nil;
if lelse > 0 then genujpxjpcal(57(*ujp*),lelse2);
gen1(71(*dmp*),intsize);
gen0(60(*ujc error*))
end;
putlabel(laddr);
markline
end
else begin
error(157);
repeat
with fstptr^ do
begin lpt1 := fstptr; fstptr := next end;
putcas(lpt1);
until fstptr = nil
end
end;
if sy = endsy then insymbol else error(13);
lc := llc
end (*casestatement*) ;
procedure repeatstatement;
var laddr: integer;
begin genlabel(laddr); putlabel(laddr); markline;
addlvl;
repeat
statement(fsys + [semicolon,untilsy]);
if sy in statbegsys then error(14)
until not(sy in statbegsys);
while sy = semicolon do
begin insymbol;
repeat
statement(fsys + [semicolon,untilsy]);
if sy in statbegsys then error(14);
until not (sy in statbegsys);
end;
if sy = untilsy then
begin insymbol; expression(fsys, false); genfjp(laddr)
end
else error(53);
sublvl
end (*repeatstatement*) ;
procedure whilestatement;
var laddr, lcix: integer;
begin genlabel(laddr); putlabel(laddr); markline;
expression(fsys + [dosy], false); genlabel(lcix); genfjp(lcix);
if sy = dosy then insymbol else error(54);
addlvl;
statement(fsys);
sublvl;
genujpxjpcal(57(*ujp*),laddr); putlabel(lcix); markline
end (*whilestatement*) ;
procedure forstatement;
var lattr: attr; lsy: symbol;
lcix, laddr: integer;
llc, lcs: addrrange;
typind: char; (* added for typing [sam] *)
typ: stp;
begin lcp := nil; llc := lc;
with lattr do
begin symptr := nil; typtr := nil; kind := varbl;
access := drct; vlevel := level; dplmt := 0; packing := false
end;
typind := 'i'; (* default to integer [sam] *)
if sy = ident then
begin searchid([vars],lcp);
with lcp^, lattr do
begin typtr := idtype; kind := varbl; packing := false;
if threat or (forcnt > 0) then error(195); forcnt := forcnt+1;
if part = ptview then error(290);
if vkind = actual then
begin access := drct; vlevel := vlev;
if vlev <> level then error(183);
dplmt := vaddr
end
else begin error(155); typtr := nil end
end;
(* determine type of control variable [sam] *)
if lattr.typtr = boolptr then typind := 'b'
else if lattr.typtr = charptr then typind := 'c';
if lattr.typtr <> nil then
if (lattr.typtr^.form > subrange)
or comptypes(realptr,lattr.typtr) then
begin error(143); lattr.typtr := nil end;
insymbol
end
else
begin error(2); skip(fsys + [becomes,tosy,downtosy,dosy]) end;
if sy = becomes then
begin insymbol; expression(fsys + [tosy,downtosy,dosy], false);
typ := basetype(gattr.typtr); { get base type }
if typ <> nil then
if typ^.form <> scalar then error(144)
else
if comptypes(lattr.typtr,gattr.typtr) then begin
load; alignd(intptr,lc);
{ store start to temp }
gen2t(56(*str*),level,lc-intsize,intptr);
end else error(145)
end
else
begin error(51); skip(fsys + [tosy,downtosy,dosy]) end;
if sy in [tosy,downtosy] then
begin lsy := sy; insymbol; expression(fsys + [dosy], false);
typ := basetype(gattr.typtr); { get base type }
if typ <> nil then
if typ^.form <> scalar then error(144)
else
if comptypes(lattr.typtr,gattr.typtr) then
begin
load; alignd(intptr,lc);
if not comptypes(lattr.typtr,intptr) then
gen0t(58(*ord*),gattr.typtr);
gen2t(56(*str*),level,lc-intsize*2,intptr);
{ set initial value of index }
gen2t(54(*lod*),level,lc-intsize,intptr);
if debug and (lattr.typtr <> nil) then
checkbnds(lattr.typtr);
store(lattr);
genlabel(laddr); putlabel(laddr); markline;
gattr := lattr; load;
if not comptypes(gattr.typtr,intptr) then
gen0t(58(*ord*),gattr.typtr);
gen2t(54(*lod*),level,lc-intsize*2,intptr);
lcs := lc;
lc := lc - intsize*2;
if lc < lcmin then lcmin := lc;
if lsy = tosy then gen2(52(*leq*),ord(typind),1)
else gen2(48(*geq*),ord(typind),1);
end
else error(145)
end
else begin error(55); skip(fsys + [dosy]) end;
genlabel(lcix); genujpxjpcal(33(*fjp*),lcix);
if sy = dosy then insymbol else error(54);
addlvl;
statement(fsys);
sublvl;
gattr := lattr; load;
if not comptypes(gattr.typtr,intptr) then
gen0t(58(*ord*),gattr.typtr);
gen2t(54(*lod*),level,lcs-intsize*2,intptr);
gen2(47(*equ*),ord(typind),1);
genujpxjpcal(73(*tjp*),lcix);
gattr := lattr; load;
if lsy=tosy then gen1t(34(*inc*),1,gattr.typtr)
else gen1t(31(*dec*),1,gattr.typtr);
if debug and (lattr.typtr <> nil) then
checkbnds(lattr.typtr);
store(lattr);
genujpxjpcal(57(*ujp*),laddr); putlabel(lcix); markline;
gattr := lattr; loadaddress; gen0(79(*inv*));
lc := llc;
if lcp <> nil then lcp^.forcnt := lcp^.forcnt-1
end (*forstatement*) ;
procedure withstatement;
var lcp: ctp; lcnt1: disprange; llc: addrrange;
test: boolean;
wbscnt: integer;
begin lcnt1 := 0; llc := lc; wbscnt := 0;
repeat
if sy = ident then
begin searchid([vars,field],lcp); insymbol end
else begin error(2); lcp := uvarptr end;
selector(fsys + [comma,dosy],lcp,false);
if gattr.kind = expr then error(287);
if gattr.typtr <> nil then
if gattr.typtr^.form = records then
if top < displimit then
begin top := top + 1; lcnt1 := lcnt1 + 1;
with display[top] do
begin inidsp(display[top]); fname := gattr.typtr^.fstfld;
packing := gattr.packing;
packcom := gattr.packcom;
ptrref := gattr.ptrref
end;
if gattr.access = drct then
with display[top] do
begin occur := crec; clev := gattr.vlevel;
cdspl := gattr.dplmt
end
else
begin loadaddress;
if debug and gattr.ptrref then
begin gen0(119(*wbs*)); wbscnt := wbscnt+1; pshwth(stalvl) end;
alignd(nilptr,lc);
lc := lc-ptrsize;
gen2t(56(*str*),level,lc,nilptr);
with display[top] do
begin occur := vrec; vdspl := lc end;
if lc < lcmin then lcmin := lc
end
end
else error(250)
else error(140);
test := sy <> comma;
if not test then insymbol
until test;
if sy = dosy then insymbol else error(54);
addlvl;
statement(fsys);
sublvl;
while wbscnt > 0 do begin gen0(120(*wbe*)); wbscnt := wbscnt-1; popwth end;
{ purge display levels }
while lcnt1 > 0 do begin
{ don't recycle the record context }
display[top].fname := nil;
putdsp(display[top]); { purge }
top := top-1; lcnt1 := lcnt1-1; { count off }
end;
lc := llc;
end (*withstatement*) ;
procedure trystatement;
var test: boolean; lcp: ctp; lattr: attr;
endlbl, noexplbl, bgnexplbl, onendlbl,onstalbl: integer;
begin genlabel(endlbl); genlabel(noexplbl); genlabel(bgnexplbl);
genujpxjpcal(84(*bge*),bgnexplbl);
addlvl;
repeat
statement(fsys + [semicolon,onsy,exceptsy,elsesy]);
if sy in statbegsys then error(14)
until not(sy in statbegsys);
while sy = semicolon do
begin insymbol;
repeat
statement(fsys + [semicolon,onsy,exceptsy,elsesy]);
if sy in statbegsys then error(14);
until not (sy in statbegsys);
end;
sublvl;
genujpxjpcal(57(*ujp*),noexplbl);
putlabel(bgnexplbl); markline;
if (sy <> onsy) and (sy <> exceptsy) then error(24);
while sy = onsy do begin insymbol; genlabel(onstalbl);
genlabel(onendlbl);
repeat
if sy = ident then begin
searchid([vars],lcp);
with lcp^, lattr do
begin typtr := idtype; kind := varbl; packing := false;
if threat or (forcnt > 0) then error(195); forcnt := forcnt+1;
if part = ptview then error(290);
if vkind = actual then
begin access := drct; vlevel := vlev;
if vlev <> level then error(183);
dplmt := vaddr
end
else begin error(155); typtr := nil end
end;
if lcp^.idtype <> nil then
if lcp^.idtype^.form <> exceptf then error(226);
insymbol;
gen0t(76(*dup*),nilptr);{ make copy of original vector }
gattr := lattr; loadaddress; { load compare vector }
gen2(47(*equ*),ord('a'),lsize);
genujpxjpcal(73(*tjp*),onstalbl);
end else begin error(2); skip(fsys+[onsy,exceptsy,elsesy]) end;
test := sy <> comma;
if not test then insymbol
until test;
genujpxjpcal(57(*ujp*),onendlbl);
if sy = exceptsy then insymbol else
begin error(23); skip(fsys+[onsy,exceptsy,elsesy]) end;
putlabel(onstalbl);
markline;
addlvl;
statement(fsys+[exceptsy]);
sublvl;
genujpxjpcal(57(*ujp*),endlbl);
putlabel(onendlbl);
markline
end;
if sy = exceptsy then begin addlvl;
insymbol; statement(fsys+[elsesy]); sublvl;
genujpxjpcal(57(*ujp*),endlbl)
end;
gen0(86(*mse*));
putlabel(noexplbl);
markline;
if sy = elsesy then begin addlvl;
insymbol; statement(fsys); sublvl
end;
sublvl;
putlabel(endlbl);
markline;
gen0(85(*ede*))
end (*trystatement*) ;
begin (*statement*)
if (sy = intconst) or (sy = ident) then begin (*label*)
{ and here is why Wirth didn't include symbolic labels in Pascal.
We are ambiguous with assigns and calls, so must look ahead for
the ':' }
searchlabel(llp, level, sy = ident); { search label }
insymbol; { look ahead }
if sy = colon then begin { process as label }
insymbol; { skip ':' }
if llp <> nil then with llp^ do begin { found }
if defined then error(165); { multidefined label }
bact := true; { set in active block now }
slevel := stalvl; { establish statement level }
defined := true; { set defined }
if ipcref and (stalvl > 1) then
error(184) { intraprocedure goto does not reference outter block }
else if minlvl < stalvl then
{ Label referenced by goto at lesser statement level or
differently nested statement }
error(186);
putlabel(labname); { output label to intermediate }
markline
end else begin { not found }
error(167); { undeclared label }
newlabel(llp, false) { create a dummy level }
end
end else pushback { back to ident }
end;
if not (sy in fsys + statbegsys + [ident,resultsy,inheritedsy]) then
begin error(6); skip(fsys) end;
inherit := false;
if sy in statbegsys + [ident,resultsy,inheritedsy] then
begin
case sy of
inheritedsy,
ident: begin
if sy = inheritedsy then
begin insymbol; inherit := true end;
searchid([vars,field,func,proc],lcp); insymbol;
if hasovlproc(lcp) then begin
if hasovlfunc(lcp) then begin
{ could be proc or func, need disambiguate }
if sy = becomes then begin
if inherit then error(233);
assignment(ovlfunc(lcp), false)
end else call(fsys,lcp,inherit,false)
end else call(fsys,lcp,inherit,false)
end else begin if inherit then error(233);
if hasovlfunc(lcp) then assignment(ovlfunc(lcp), false)
else assignment(lcp, false)
end
end;
beginsy: begin insymbol; compoundstatement end;
gotosy: begin insymbol; gotostatement end;
ifsy: begin insymbol; ifstatement end;
casesy: begin insymbol; casestatement end;
whilesy: begin insymbol; whilestatement end;
repeatsy: begin insymbol; repeatstatement end;
forsy: begin insymbol; forstatement end;
withsy: begin insymbol; withstatement end;
trysy: begin insymbol; trystatement end;
{ process result as a pseudostatement }
resultsy: begin
if fprocp <> nil then
if fprocp^.klass <> func then error(210)
else begin
if fprocp^.asgn then error(212);
fprocp^.asgn := true
end;
assignment(fprocp, true);
if not (sy = endsy) or (stalvl > 1) then error(211)
end
end;
if not (sy in [semicolon,endsy,elsesy,untilsy,exceptsy,onsy]) then
begin error(6); skip(fsys) end
end
end (*statement*) ;
{ validate and start external header files }
procedure externalheader;
var valp: csp; saveid: idstr; llcp:ctp;
begin
saveid := id;
while fextfilep <> nil do begin
with fextfilep^ do begin
id := filename;
searchidne([vars],llcp);
if llcp = nil then begin
{ a header file was never defined in a var statement }
writeln(output);
writeln('*** Error: Undeclared external file ''',
fextfilep^.filename:8, '''');
toterr := toterr+1;
llcp := uvarptr
end;
if llcp^.idtype<>nil then
if (llcp^.idtype^.form<>files) and (llcp^.idtype <> intptr) and
(llcp^.idtype <> realptr) then
begin writeln(output);
writeln('*** Error: Undeclared external file ''',
fextfilep^.filename:8, '''');
toterr := toterr+1
end
else begin { process header file }
llcp^.hdr := true; { appears in header }
{ check is a standard header file }
if not (strequri('input ', filename) or
strequri('output ', filename) or
strequri('prd ', filename) or
strequri('prr ', filename) or
strequri('error ', filename) or
strequri('list ', filename) or
strequri('command ', filename)) then begin
gen1(37(*lao*),llcp^.vaddr); { load file/variable address }
{ put name in constants table }
new(valp,strg); valp^.cclass := strg;
valp^.slgth := lenpv(llcp^.name);
valp^.sval := llcp^.name;
if cstptrix >= cstoccmax then error(254)
else begin cstptrix := cstptrix + 1;
cstptr[cstptrix] := valp;
gen1(38(*lca*),cstptrix)
end;
cstptrix := cstptrix - 1;
{ load length of name }
gen2(51(*ldc*),1,valp^.slgth);
if llcp^.idtype = intptr then { integer }
gen1(30(*csp*),83(*rdie*))
else if llcp^.idtype = realptr then { real }
gen1(30(*csp*),84(*rdir*))
else if llcp^.idtype = textptr then { text }
gen1(30(*csp*),81(*aeft*))
else { binary }
gen1(30(*csp*),82(*aefb*));
dispose(valp,strg)
end
end
end;
fp := fextfilep; fextfilep := fextfilep^.nextfile; putfil(fp)
end;
id := saveid
end;
procedure initvirt;
procedure schvirt(lcp: ctp);
var lcp1,lcp2: ctp;
begin
if lcp <> nil then begin
if lcp^.klass in [proc,func] then begin
if not chkext(lcp) then begin
if (lcp^.pfattr = fpavirtual) then
gensuv(lcp^.pfname,lcp^.pfvaddr,lcp)
else if lcp^.pfattr = fpaoverride then begin
lcp1 := lcp^.grppar; { link parent }
if lcp1 <> nil then begin
lcp2 := lcp1^.pfvid; { get vector symbol }
if lcp2 <> nil then begin
{ copy old vector to store }
gen1ts(39(*ldo*),lcp2^.vaddr,lcp2^.idtype,lcp2);
gen1t(43(*sro*),lcp^.pfvaddr,nilptr);
{ place new vector }
gensuv(lcp^.pfname,lcp2^.pfvaddr,lcp2);
end
end
end
end;
schvirt(lcp^.grpnxt);
end;
schvirt(lcp^.llink); schvirt(lcp^.rlink)
end
end;
begin
schvirt(display[top].fname)
end;
begin (*body*)
stalvl := 0; { clear statement nesting level }
cstptrix := 0; topnew := 0; topmin := 0;
{ if processing procedure/function, use that entry label, otherwise set
at program }
if fprocp <> nil then putlabel(fprocp^.pfname) else putlabel(entname);
markline;
genlabel(segsize); genlabel(stackbot);
genlabel(gblsize);
genmst(level-1,segsize,stackbot);
if fprocp <> nil then (*copy multiple values into local cells*)
begin llc1 := marksize+ptrsize+adrsize+fprocp^.locpar; { index params }
lcp := fprocp^.pflist;
while lcp <> nil do
with lcp^ do
begin
if klass = vars then
if idtype <> nil then begin
if idtype^.form > power then
begin
if idtype^.form = arrayc then llc1 := llc1 - ptrsize*2
else llc1 := llc1-ptrsize;
alignd(parmptr,llc1);
if vkind = actual then
if idtype^.form = arrayc then begin
{ Container array. These are not preallocated, so we
have to create a copy on stack. }
gen2(50(*lda*),level,llc1); { index the pointer }
gen0(111(*ldp*)); { load complex pointer }
{ copy complex to stack }
gen2(109(*ccs*),containers(idtype),containerbase(idtype));
gen2(50(*lda*),level,vaddr); { load dest addr }
gen1(72(*swp*),stackelsize*2); { swap that under cp }
gen0(110(*scp*)) { store complex pointer }
end else begin
gen2(50(*lda*),level,vaddr);
gen2t(54(*lod*),level,llc1,nilptr);
gen1(40(*mov*),idtype^.size);
end
end
else
begin
if vkind = formal then llc1 := llc1-ptrsize
else llc1 := llc1-idtype^.size;
alignd(parmptr,llc1);
end;
if chkvbk and (vkind = formal) then begin
{ establish var block }
gen2t(54(*lod*),level,llc1,nilptr);
gen1(93(*vbs*),idtype^.size)
end
end;
lcp := lcp^.next;
end;
end;
lcmin := lc;
addlvl;
if (level = 1) and not incact then begin { perform module setup tasks }
externalheader; { process external header files }
initvirt { process virtual procedure/function sets }
end;
{ call initializer code strips }
ilp := display[top].inilst;
while ilp <> nil do
begin genujpxjpcal(89(*cal*),ilp^.inilab); ilp := ilp^.ininxt end;
if sy = beginsy then insymbol else error(17);
repeat
repeat statement(fsys + [semicolon,endsy])
until not (sy in statbegsys);
test := sy <> semicolon;
if not test then insymbol
until test;
{ deinitialize containers }
if level = 1 then begin
ilp := display[top].inilst;
while ilp <> nil do begin
gen1t(39(*ldo*),ilp^.vaddr,nilptr);
gen0(107(*vdp*));
ilp := ilp^.ininxt end
end;
sublvl;
if sy = endsy then insymbol else error(13);
llp := display[top].flabel; (*test for undefined and unreferenced labels*)
while llp <> nil do
with llp^ do
begin
if not defined or not refer then
begin if not defined then error(168);
writeln(output); write('label ',labval:11);
if not refer and not incact then write(' unreferenced');
writeln;
write(' ':chcnt+16)
end;
llp := nextlab
end;
printed := false;
if (fprocp <> nil) or iso7185 then chkrefs(display[top].fname, printed);
if toterr = 0 then
if (topnew <> 0) and prcode then
error(504); { stack should have wound to zero }
if fprocp <> nil then
begin
{ output var block ends for each var parameter }
lcp := fprocp^.pflist;
while lcp <> nil do
with lcp^ do begin
if klass = vars then
if chkvbk and (vkind = formal) then gen0(94(*vbe*));
lcp := next
end;
if fprocp^.idtype = nil then gen2(42(*ret*),ord('p'),fprocp^.locpar)
else if fprocp^.idtype^.form in [records, arrays] then
gen2t(42(*ret*),fprocp^.locpar,fprocp^.idtype^.size,basetype(fprocp^.idtype))
else gen1t(42(*ret*),fprocp^.locpar,basetype(fprocp^.idtype));
alignd(parmptr,lcmin);
if prcode then
begin prtlabel(segsize); writeln(prr,'=',-level*ptrsize-lcmin:1);
prtlabel(stackbot); writeln(prr,'=',-topmin:1)
end
end
else
begin gen2(42(*ret*),ord('p'),0);
alignd(parmptr,lcmin);
if prcode then
begin
prtlabel(segsize); writeln(prr,'=',-level*ptrsize-lcmin:1);
prtlabel(stackbot); writeln(prr,'=',-topmin:1)
end;
ic := 0;
if prtables then
begin writeln(output); printtables(true)
end
end;
end (*body*) ;
procedure openinput(var ff: boolean);
var fp: filptr; i, x: integer; es: packed array [1..4] of char;
{ for any error, back out the include level }
procedure err;
begin
incstk := incstk^.next;
dispose(fp);
ff := false
end;
begin ff := true; es := extsrc;
{ have not previously parsed this module }
new(fp);
with fp^ do begin
next := incstk; incstk := fp; strassvf(mn, id); priv := false;
linecounts := linecount; lineouts := lineout;
fn := id; i := fillen; while (i > 1) and (fn[i] = ' ') do i := i-1;
if i > fillen-4-1 then begin err; error(265) end
else begin
for x := 1 to 4 do begin i := i+1; fn[i] := es[x] end;
if not existsfile(fn) then begin err; error(264) end
else begin assigntext(f, fn); reset(f) end
end
end
end;
procedure closeinput;
var fp: filptr;
begin
if not incact then error(505);
closetext(incstk^.f);
linecount := incstk^.linecounts; lineout := incstk^.lineouts;
{ remove top include entry }
fp := incstk; incstk := incstk^.next;
fp^.next := inclst; { put on discard list }
inclst := fp
end;
procedure putinp(var fl: filptr);
var fp: filptr;
begin
while fl <> nil do begin
fp := fl; fl := fl^.next; putstrs(fp^.mn); dispose(fp)
end
end;
procedure cancelfwd(fcp: ctp);
begin
if fcp <> nil then begin
if fcp^.klass in [proc, func] then fcp^.forwdecl := false;
cancelfwd(fcp^.llink); cancelfwd(fcp^.rlink)
end
end;
procedure modulep(fsys:setofsys); forward;
procedure usesjoins;
var sys: symbol; prcodes: boolean; ff: boolean; chs: char; eols: boolean;
lists: boolean; nammods, modnams, thismod: strvsp; gcs: addrrange;
curmods: modtyp; entnames: integer; sym: symbol;
function schnam(fp: filptr): boolean;
begin schnam := false;
while fp <> nil do
begin if fp^.fn = id then schnam := true; fp := fp^.next end
end;
begin
sym := sy; insymbol; { skip uses/joins }
thismod := nil;
repeat { modules }
if sy <> ident then error(2) else begin
if not schnam(incstk) and not schnam(inclst) then begin
chs := ch; eols := eol; prcodes := prcode; lists := list; gcs := gc;
nammods := nammod; curmods := curmod; entnames := entname;
openinput(ff);
if ff then begin
ch := ' '; eol := true; prcode := false; list := false;
readline; insymbol; modnams := display[top].modnam;
display[top].modnam := nil;
modulep(blockbegsys+statbegsys-[casesy]);
thismod := display[top].modnam; display[top].modnam := modnams;
cancelfwd(display[top].fname); closeinput
end;
ch := chs; eol := eols;prcode := prcodes; list := lists; gc := gcs;
nammod := nammods; curmod := curmods; entname := entnames
end;
insymbol; { skip id }
if sym = joinssy then begin { post process joins level }
if ptop >= displimit then error(267)
else begin
pile[ptop] := display[top]; { copy out definitions from display }
pile[ptop].modnam := thismod; { put back module name }
ptop := ptop+1;
{ clear display for next }
with display[top] do
begin fname := nil; flabel := nil; fconst := nil; fstruct := nil;
packing := false; packcom := false; ptrref := false;
define := true; occur := blck; bname := nil end
end
end else putstrs(thismod)
end;
sys := sy;
if sy = comma then insymbol
until sys <> comma;
if sy = semicolon then insymbol else error(14)
end;
function searchext: boolean;
var fp: extfilep; f: boolean;
begin f := false; fp := fextfilep;
while fp <> nil do
begin if id = fp^.filename then f := true; fp := fp^.nextfile end;
searchext := f
end;
procedure modulep{(fsys:setofsys)};
var extfp,newfl:extfilep; segsize, stackbot: integer;
nulllab: integer;
begin
cstptrix := 0; topnew := 0; topmin := 0; nammod := nil; genlabel(entname);
genlabel(extname); genlabel(nxtname);
chkudtf := chkudtc; { finalize undefined tag checking flag }
{ set type of module parsing }
curmod := mtprogram;
if sy = modulesy then curmod := mtmodule;
if (sy = progsy) or (sy = modulesy) then
begin insymbol;
if sy <> ident then error(2) else begin
strassvf(nammod, id); { place module name }
strassvf(display[top].modnam, id);
if prcode then begin
writeln(prr, '!');
if curmod = mtprogram then
begin write(prr, '! Program '); writevp(prr, nammod); writeln(prr) end
else
begin write(prr, '! Module '); writevp(prr, nammod); writeln(prr) end;
writeln(prr, '!');
if curmod = mtmodule then
writeln(prr, 'b', ' ':7, 'm', ' ':7, id:kk) { mark module block start }
else
writeln(prr, 'b', ' ':7, 'p', ' ':7, id:kk) { mark program block start }
end;
insymbol;
{ mark stack, generate call to startup block }
genlabel(nulllab); gensfr(nulllab);
if prcode then begin prtlabel(nulllab); writeln(prr,'=0') end;
gencupcuf(46(*cup*),0,entname,nil);
if curmod = mtmodule then begin
{ for module we need call next in module stack, then call exit
module }
genujpxjpcal(89(*cal*),nxtname);
gensfr(nulllab); gencupcuf(46(*cup*),0,extname,nil)
end;
gen0(90(*ret*)) { return last module stack }
end;
if not (sy in [lparent,semicolon]) then error(14);
if sy = lparent then
begin
newfl := nil;
repeat insymbol;
if sy = ident then
begin
if not incact then begin
getfil(extfp); if searchext then error(240);
with extfp^ do
begin filename := id; nextfile := fextfilep end;
fextfilep := extfp
end;
{ check 'input' or 'output' appears in header for defaults }
if strequri('input ', id) then inputptr^.hdr := true
else if strequri('output ', id) then outputptr^.hdr := true
else if strequri('prd ', id) then prdptr^.hdr := true
else if strequri('prr ', id) then prrptr^.hdr := true
else if strequri('error ', id) then errorptr^.hdr := true
else if strequri('list ', id) then listptr^.hdr := true
else if strequri('command ', id) then commandptr^.hdr := true;
insymbol;
if not ( sy in [comma,rparent] ) then error(20)
end
else error(2)
until sy <> comma;
{ reverse the header list into order }
if not incact then begin
newfl := nil;
while fextfilep <> nil do
begin extfp := fextfilep; fextfilep := fextfilep^.nextfile;
extfp^.nextfile := newfl; newfl := extfp end;
fextfilep := newfl
end;
if sy <> rparent then error(4);
insymbol;
if sy <> semicolon then error(14)
end;
if sy = semicolon then insymbol
end else error(3);
{ must process joins first so that the module (1) display level is clean.
Otherwise this could create a situation where joins rely on other
modules }
if sy = joinssy then usesjoins; { process joins }
if sy = usessy then usesjoins; { process uses }
declare(fsys);
if not inpriv then body(fsys,nil);
if curmod = mtmodule then begin
if sy = semicolon then begin
insymbol;
if sy <> beginsy then error(17)
end;
if sy = beginsy then begin
{ gen exit block }
entname := extname; body(fsys, nil);
end else begin { generate dummy terminator block }
genlabel(segsize); genlabel(stackbot); putlabel(extname);
genmst(level,segsize,stackbot);
gen2(42(*ret*),ord('p'),0);
if prcode then begin
prtlabel(segsize); writeln(prr,'=',0:1);
prtlabel(stackbot); writeln(prr,'=',0:1)
end
end;
if prcode then begin
putlabel(nxtname); { set skip module stack }
writeln(prr,'g ',gc:1);
writeln(prr, 'e m') { mark module block end }
end
end else begin { program }
if prcode then begin
writeln(prr,'g', ' ':7,gc:1);
writeln(prr, 'e', ' ':7, 'p') { mark program block end }
end
end;
if (sy <> period) and not inpriv then begin error(21); skip([period]) end;
if prcode then begin
writeln(prr, 'f', ' ':7, toterr:1);
{ only terminate intermediate if we are a cap cell (program) }
if curmod = mtprogram then writeln(prr,'q')
end;
if list then writeln;
if errinx <> 0 then
begin list := false; endofline end;
putstrs(nammod) { release module name }
end (*modulep*) ;
procedure stdnames;
begin
{ 'mark' and 'release' were removed and replaced with placeholders }
na[ 1] := 'false '; na[ 2] := 'true '; na[ 3] := 'input ';
na[ 4] := 'output '; na[ 5] := 'get '; na[ 6] := 'put ';
na[ 7] := 'reset '; na[ 8] := 'rewrite '; na[ 9] := 'read ';
na[10] := 'write '; na[11] := 'pack '; na[12] := 'unpack ';
na[13] := 'new '; na[14] := 'assign '; na[15] := 'readln ';
na[16] := 'writeln '; na[17] := 'abs '; na[18] := 'sqr ';
na[19] := 'trunc '; na[20] := 'odd '; na[21] := 'ord ';
na[22] := 'chr '; na[23] := 'pred '; na[24] := 'succ ';
na[25] := 'eof '; na[26] := 'eoln '; na[27] := 'sin ';
na[28] := 'cos '; na[29] := 'exp '; na[30] := 'sqrt ';
na[31] := 'ln '; na[32] := 'arctan '; na[33] := 'prd ';
na[34] := 'prr '; na[35] := 'close '; na[36] := 'maxint ';
na[37] := 'round '; na[38] := 'page '; na[39] := 'dispose ';
na[40] := 'length '; na[41] := 'location '; na[42] := 'position ';
na[43] := 'update '; na[44] := 'append '; na[45] := 'exists ';
na[46] := 'delete '; na[47] := 'change '; na[48] := 'error ';
na[49] := 'list '; na[50] := 'command '; na[51] := 'halt ';
na[52] := 'linteger '; na[53] := 'maxlint '; na[54] := 'cardinal ';
na[55] := 'maxcrd '; na[56] := 'lcardinal'; na[57] := 'maxlcrd ';
na[58] := 'sreal '; na[59] := 'lreal '; na[60] := 'maxreal ';
na[61] := 'maxsreal '; na[62] := 'maxlreal '; na[63] := 'integer ';
na[64] := 'real '; na[65] := 'char '; na[66] := 'boolean ';
na[67] := 'text '; na[68] := 'maxchr '; na[69] := 'assert ';
na[70] := 'error '; na[71] := 'list '; na[72] := 'command ';
na[73] := 'exception'; na[74] := 'throw '; na[75] := 'max ';
na[76] := 'string '; na[77] := 'pstring '; na[78] := 'byte ';
na[79] := 'vector '; na[80] := 'matrix '; na[81] := 'abyte ';
na[82] := 'schar ';
end (*stdnames*) ;
procedure enterstdtypes;
begin (*type underlying:*)
(******************)
new(intptr,scalar,standard); pshstc(intptr); (*integer*)
with intptr^ do
begin form := scalar; size := intsize; scalkind := standard;
packing := false end;
new(crdptr,subrange); pshstc(crdptr); (*cardinal*)
with crdptr^ do
begin form := subrange; size := intsize; rangetype := intptr;
min.intval := true; min.ival := 0;
max.intval := true; max.ival := pmmaxint; packing := false end;
new(realptr,scalar,standard); pshstc(realptr); (*real*)
with realptr^ do
begin form := scalar; size := realsize; scalkind := standard;
packing := false end;
new(charptr,scalar,standard); pshstc(charptr); (*char*)
with charptr^ do
begin form := scalar; size := charsize; scalkind := standard;
packing := false end;
new(boolptr,scalar,declared); pshstc(boolptr); (*boolean*)
with boolptr^ do
begin form := scalar; size := boolsize; scalkind := declared;
packing := false end;
new(nilptr,pointer); pshstc(nilptr); (*nil*)
with nilptr^ do
begin form := pointer; eltype := nil; size := ptrsize;
packing := false end;
(*for alignment of parameters*)
new(parmptr,scalar,standard); pshstc(parmptr);
with parmptr^ do
begin form := scalar; size := parmsize; scalkind := standard;
packing := false end ;
new(textptr,files); pshstc(textptr); (*text*)
with textptr^ do
begin form := files; filtype := charptr; size := filesize+charsize;
packing := false end;
new(exceptptr,exceptf); pshstc(exceptptr); (*exception*)
with exceptptr^ do
begin form := exceptf; size := exceptsize; packing := false end;
{ common types }
new(stringptr,arrayc); pshstc(stringptr); (*string*)
with stringptr^ do
begin form := arrayc; size := 0; packing := true; abstype := charptr end;
new(pstringptr,pointer); pshstc(pstringptr); (*string pointer*)
with pstringptr^ do
begin form := pointer; size := ptrsize; packing := false;
eltype := stringptr end;
new(byteptr,subrange); pshstc(byteptr);
with byteptr^ do
begin form := subrange; size := 1; packing := false; rangetype := intptr;
min.intval := true; min.ival := 0; max.intval := true;
max.ival := 255 end;
new(abyteptr,arrayc); pshstc(abyteptr); (*byte array*)
with abyteptr^ do
begin form := arrayc; size := 0; packing := false; abstype := byteptr end;
new(vectorptr,arrayc); pshstc(vectorptr); (*vector*)
with vectorptr^ do
begin form := arrayc; size := 0; packing := false; abstype := intptr end;
new(matrixptr,arrayc); pshstc(matrixptr); (*matrix*)
with matrixptr^ do
begin form := arrayc; size := 0; packing := false;
abstype := vectorptr end;
new(scharptr,power); pshstc(scharptr); (*set of char*)
with scharptr^ do
begin form := power; size := setsize; packing := false; elset := charptr;
matchpack := true end;
end (*enterstdtypes*) ;
procedure entstdnames;
var cp,cp1: ctp; i: integer;
procedure entstdprocfunc(idc: idclass; sn: stdrng; kn: keyrng; idt: stp);
begin
if idc = proc then new(cp,proc,standard)
else new(cp,func,standard);
ininam(cp);
with cp^ do
begin klass := idc; strassvr(name, na[sn]); idtype := idt;
pflist := nil; next := nil; key := kn;
pfdeckind := standard; pfaddr := 0; pext := false;
pmod := nil; pfattr := fpanone; grpnxt := nil; grppar := cp;
pfvid := nil; pflist := nil
end; enterid(cp)
end;
procedure entstdtyp(sn: stdrng; idt: stp);
begin
new(cp,types); ininam(cp);
with cp^ do
begin klass := types; strassvr(name, na[sn]); idtype := idt end;
enterid(cp)
end;
procedure entstdintcst(sn: stdrng; idt: stp; i: integer);
begin
new(cp,konst); ininam(cp);
with cp^ do
begin klass := konst; strassvr(name, na[sn]); idtype := idt; next := nil;
values.intval := true; values.ival := i end;
enterid(cp)
end;
procedure entstdrlcst(sn: stdrng; idt: stp; r: real);
var lvp: csp;
begin
new(cp,konst); ininam(cp); new(lvp,reel); pshcst(lvp); lvp^.cclass := reel;
lvp^.rval := r;
with cp^ do
begin klass := konst; strassvr(name, na[sn]); idtype := idt; next := nil;
values.intval := false; values.valp := lvp end;
enterid(cp)
end;
procedure entstdhdr(sn: stdrng);
begin
new(cp,vars); ininam(cp);
with cp^ do
begin klass := vars; strassvr(name, na[sn]); idtype := textptr;
vkind := actual; next := nil; vlev := 1;
vaddr := gc; gc := gc+filesize+charsize; { files are global now }
isloc := false; threat := false; forcnt := 0; part := ptval; hdr := false;
vext := false; vmod := nil; inilab := -1; ininxt := nil; dblptr := false
end;
enterid(cp)
end;
procedure entstdexp(en: expstr);
begin
new(cp,vars); ininam(cp);
with cp^ do
begin klass := vars; strassve(name, en); idtype := exceptptr;
vkind := actual; next := nil; vlev := 1;
vaddr := gc; gc := gc+exceptsize;
isloc := false; threat := false; forcnt := 0; part := ptval; hdr := false;
vext := false; vmod := nil; inilab := -1; ininxt := nil; dblptr := false
end;
enterid(cp)
end;
begin (*name:*)
(*******)
entstdtyp(63, intptr); (*integer*)
entstdtyp(52, intptr); (*linteger*)
entstdtyp(54, crdptr); (*cardinal*)
entstdtyp(56, crdptr); (*lcardinal*)
entstdtyp(64, realptr); (*real*)
entstdtyp(58, realptr); (*sreal*)
entstdtyp(59, realptr); (*lreal*)
entstdtyp(65, charptr); (*char*)
entstdtyp(66, boolptr); (*boolean*)
usclrptr := cp; { save to satisfy broken tags }
entstdtyp(67, textptr); (*text*)
entstdtyp(73, exceptptr); (*exception*)
entstdtyp(76, stringptr); (*string*)
entstdtyp(77, pstringptr); (*pointer to string*)
entstdtyp(78, byteptr); (*byte*)
entstdtyp(79, vectorptr); (*vector*)
entstdtyp(80, matrixptr); (*matrix*)
entstdtyp(81, abyteptr); (*array of bytes*)
entstdtyp(82, scharptr); (*set of char*)
cp1 := nil;
for i := 1 to 2 do
begin new(cp,konst); ininam(cp); (*false,true*)
with cp^ do
begin klass := konst; strassvr(name, na[i]); idtype := boolptr;
next := cp1; values.intval := true; values.ival := i - 1;
end;
enterid(cp); cp1 := cp
end;
boolptr^.fconst := cp;
entstdhdr(3); inputptr := cp; (*input*)
entstdhdr(4); outputptr := cp; (*output*)
entstdhdr(33); prdptr := cp; (*prd*)
entstdhdr(34); prrptr := cp; (*prr*)
entstdhdr(70); errorptr := cp; (*error*)
entstdhdr(71); listptr := cp; (*list*)
entstdhdr(72); commandptr := cp; (*command*)
for i := 27 to 32 do
begin
new(cp,vars); ininam(cp); (*parameter of predeclared functions*)
with cp^ do
begin klass := vars; strassvr(name, ' '); idtype := realptr;
vkind := actual; next := nil; vlev := 1; vaddr := 0;
isloc := false; threat := false; forcnt := 0; part := ptval;
hdr := false; vext := false; vmod := nil; inilab := -1;
ininxt := nil; dblptr := false
end;
new(cp1,func,declared,actual); ininam(cp1); (*sin,cos,exp*)
with cp1^ do (*sqrt,ln,arctan*)
begin klass := func; strassvr(name, na[i]); idtype := realptr;
pflist := cp; forwdecl := false; sysrot := true; extern := false;
pflev := 0; pfname := i - 12; pfdeckind := declared;
pfkind := actual; pfaddr := 0; pext := false; pmod := nil;
pfattr := fpanone; grpnxt := nil; grppar := cp1; pfvid := nil
end;
enterid(cp1)
end;
entstdintcst(36, intptr, pmmaxint); (*maxint*)
entstdintcst(53, intptr, pmmaxint); (*maxlint*)
entstdintcst(55, crdptr, pmmaxint); (*maxcrd*)
entstdintcst(57, crdptr, pmmaxint); (*maxlcrd*)
entstdintcst(68, charptr, ordmaxchar); (*maxlcrd*)
entstdrlcst(60, realptr, 1.797693134862314e308); (*maxreal*)
entstdrlcst(61, realptr, 1.797693134862314e308); (*maxsreal*)
entstdrlcst(62, realptr, 1.797693134862314e308); (*maxlreal*)
entstdprocfunc(proc, 5, 1, nil); { get }
entstdprocfunc(proc, 6, 2, nil); { put }
entstdprocfunc(proc, 7, 3, nil); { reset }
entstdprocfunc(proc, 8, 4, nil); { rewrite }
entstdprocfunc(proc, 9, 5, nil); { read }
entstdprocfunc(proc, 10, 6, nil); { write }
entstdprocfunc(proc, 11, 7, nil); { pack }
entstdprocfunc(proc, 12, 8, nil); { unpack }
entstdprocfunc(proc, 13, 9, nil); { new }
entstdprocfunc(proc, 15, 11, nil); { readln }
entstdprocfunc(proc, 16, 12, nil); { writeln }
entstdprocfunc(func, 17, 1, nil); { abs }
entstdprocfunc(func, 18, 2, nil); { sqr }
entstdprocfunc(func, 19, 3, nil); { trunc }
entstdprocfunc(func, 20, 4, nil); { odd }
entstdprocfunc(func, 21, 5, nil); { ord }
entstdprocfunc(func, 22, 6, nil); { chr }
entstdprocfunc(func, 23, 7, nil); { pred }
entstdprocfunc(func, 24, 8, nil); { succ }
entstdprocfunc(func, 25, 9, nil); { eof }
entstdprocfunc(func, 26, 10, nil); { eoln }
entstdprocfunc(func, 37, 16, nil); { round }
entstdprocfunc(proc, 38, 17, nil); { page }
entstdprocfunc(proc, 39, 18, nil); { dispose }
{ Note: I was to lazy to overload the keys on these }
entstdprocfunc(proc, 14, 19, nil); { assign }
entstdprocfunc(proc, 35, 20, nil); { close }
entstdprocfunc(func, 40, 21, intptr); { length }
entstdprocfunc(func, 41, 22, intptr); { location }
entstdprocfunc(proc, 42, 23, nil); { position }
entstdprocfunc(proc, 43, 24, nil); { update }
entstdprocfunc(proc, 44, 25, nil); { append }
entstdprocfunc(func, 45, 26, boolptr); { exists }
entstdprocfunc(proc, 46, 27, nil); { delete }
entstdprocfunc(proc, 47, 28, nil); { change }
entstdprocfunc(proc, 51, 29, nil); { halt }
entstdprocfunc(proc, 69, 30, nil); { assert }
entstdprocfunc(proc, 74, 31, nil); { throw }
entstdprocfunc(func, 75, 32, intptr); { max }
{ standard exceptions }
entstdexp('ValueOutOfRange ');
entstdexp('ArrayLengthMatch ');
entstdexp('CaseValueNotFound ');
entstdexp('ZeroDivide ');
entstdexp('InvalidOperand ');
entstdexp('NilPointerDereference ');
entstdexp('RealOverflow ');
entstdexp('RealUnderflow ');
entstdexp('RealProcessingFault ');
entstdexp('TagValueNotActive ');
entstdexp('TooManyFiles ');
entstdexp('FileIsOpen ');
entstdexp('FileAlreadyNamed ');
entstdexp('FileNotOpen ');
entstdexp('FileModeIncorrect ');
entstdexp('InvalidFieldSpecification ');
entstdexp('InvalidRealNumber ');
entstdexp('InvalidFractionSpecification ');
entstdexp('InvalidIntegerFormat ');
entstdexp('IntegerValueOverflow ');
entstdexp('InvalidRealFormat ');
entstdexp('EndOfFile ');
entstdexp('InvalidFilePosition ');
entstdexp('FilenameTooLong ');
entstdexp('FileOpenFail ');
entstdexp('FileSIzeFail ');
entstdexp('FileCloseFail ');
entstdexp('FileReadFail ');
entstdexp('FileWriteFail ');
entstdexp('FilePositionFail ');
entstdexp('FileDeleteFail ');
entstdexp('FileNameChangeFail ');
entstdexp('SpaceAllocateFail ');
entstdexp('SpaceReleaseFail ');
entstdexp('SpaceAllocateNegative ');
entstdexp('CannotPerformSpecial ');
entstdexp('CommandLineTooLong ');
entstdexp('ReadPastEOF ');
entstdexp('FileTransferLengthZero ');
entstdexp('FileSizeTooLarge ');
entstdexp('FilenameEmpty ');
entstdexp('CannotOpenStandard ');
entstdexp('TooManyTemporaryFiles ');
entstdexp('InputBufferOverflow ');
entstdexp('TooManyThreads ');
entstdexp('CannotStartThread ');
entstdexp('InvalidThreadHandle ');
entstdexp('CannotStopThread ');
entstdexp('TooManyIntertaskLocks ');
entstdexp('InvalidLockHandle ');
entstdexp('LockSequenceFail ');
entstdexp('TooManySignals ');
entstdexp('CannotCreateSignal ');
entstdexp('InvalidSignalHandle ');
entstdexp('CannotDeleteSignal ');
entstdexp('CannotSendSignal ');
entstdexp('WaitForSignalFail ');
entstdexp('FieldNotBlank ');
entstdexp('ReadOnWriteOnlyFile ');
entstdexp('WriteOnReadOnlyFile ');
entstdexp('FileBufferVariableUndefined ');
entstdexp('NondecimalRadixOfNegative ');
entstdexp('InvalidArgumentToLn ');
entstdexp('InvalidArgumentToSqrt ');
entstdexp('CannotResetOrRewriteStandardFile');
entstdexp('CannotResetWriteOnlyFile ');
entstdexp('CannotRewriteReadOnlyFile ');
entstdexp('SetElementOutOfRange ');
entstdexp('RealArgumentTooLarge ');
entstdexp('BooleanOperatorOfNegative ');
entstdexp('InvalidDivisorToMod ');
entstdexp('PackElementsOutOfBounds ');
entstdexp('UnpackElementsOutOfBounds ');
entstdexp('CannotResetClosedTempFile ');
end (*entstdnames*) ;
procedure enterundecl;
begin
new(utypptr,types); ininam(utypptr);
with utypptr^ do
begin klass := types; strassvr(name, ' '); idtype := nil end;
new(ucstptr,konst); ininam(ucstptr);
with ucstptr^ do
begin klass := konst; strassvr(name, ' '); idtype := nil;
next := nil; values.intval := true; values.ival := 0
end;
new(uvarptr,vars); ininam(uvarptr);
with uvarptr^ do
begin klass := vars; strassvr(name, ' '); idtype := nil;
vkind := actual; next := nil; vlev := 0; vaddr := 0;
isloc := false; threat := false; forcnt := 0; part := ptval;
hdr := false; vext := false; vmod := nil; inilab := -1; ininxt := nil;
dblptr := false
end;
new(ufldptr,field); ininam(ufldptr);
with ufldptr^ do
begin klass := field; strassvr(name, ' '); idtype := nil;
next := nil; fldaddr := 0; varnt := nil; varlb := nil;
tagfield := false; taglvl := 0; varsaddr := 0;
varssize := 0; vartl := -1
end;
new(uprcptr,proc,declared,actual); ininam(uprcptr);
with uprcptr^ do
begin klass := proc; strassvr(name, ' '); idtype := nil;
forwdecl := false; next := nil; sysrot := false; extern := false;
pflev := 0; genlabel(pfname); pflist := nil; pfdeckind := declared;
pfkind := actual; pmod := nil; grpnxt := nil; grppar := uprcptr;
pfvid := nil
end;
new(ufctptr,func,declared,actual); ininam(ufctptr);
with ufctptr^ do
begin klass := func; strassvr(name, ' '); idtype := nil;
next := nil; forwdecl := false; sysrot := false; extern := false;
pflev := 0; genlabel(pfname); pflist := nil; pfdeckind := declared;
pfkind := actual; pmod := nil; grpnxt := nil; grppar := ufctptr;
pfvid := nil
end
end (*enterundecl*) ;
{ tear down storage allocations from enterundecl }
procedure exitundecl;
begin
putnam(utypptr);
putnam(ucstptr);
putnam(uvarptr);
putnam(ufldptr);
putnam(uprcptr);
putnam(ufctptr);
end (*exitundecl*) ;
{ place options in flags }
procedure plcopt;
var oi: 1..maxopt;
begin
for oi := 1 to 26 do if options[oi] then
case oi of
2: doprtlab := option[oi];
3: prcode := option[oi];
4: debug := option[oi];
9: chkvbk := option[oi];
10: experr := option[oi];
12: list := option[oi];
18: chkref := option[oi];
19: iso7185 := option[oi];
20: prtables := option[oi];
21: chkudtc := option[oi];
22: chkvar := option[oi];
24: dodmplex := option[oi];
25: dodmpdsp := option[oi];
{ these are backend options }
1:; 5:; 6:; 7:; 8:; 11:; 13:; 14:; 15:; 16:;
17:; 23:; 26:;
end
end;
procedure initscalars;
var i: integer; oi: 1..maxopt;
begin fwptr := nil;
for oi := 1 to maxopt do
begin option[oi] := false; options[oi] := false end;
prtables := false; option[20] := false; list := true; option[12] := true;
prcode := true; option[3] := true; debug := true; option[4] := true;
chkvar := true; option[22] := true; chkref := true; option[18] := true;
chkudtc := true; option[21] := true; option[19] := false; iso7185 := false;
dodmplex := false; doprtryc := false; doprtlab := false; dodmpdsp := false;
chkvbk := true; option[9] := true; experr := true; option[10] := true;
dp := true; errinx := 0;
intlabel := 0; kk := maxids; fextfilep := nil; wthstk := nil;
{ single display entry for top level }
lc := -ptrsize; gc := 0;
(* note in the above reservation of buffer store for 2 text files *)
ic := 3; eol := true; linecount := 0; lineout := 0;
incstk := nil; inclst := nil; cbblst := nil;
ch := ' '; chcnt := 0;
mxint10 := maxint div 10;
maxpow10 := 1; while maxpow10 < mxint10 do maxpow10 := maxpow10*10;
for i := 1 to maxftl do errtbl[i] := 0; { initialize error tracking }
toterr := 0; { clear error count }
{ clear the recycling tracking counters }
strcnt := 0; { strings }
cspcnt := 0; { constants }
stpcnt := 0; { structures }
ctpcnt := 0; { identifiers }
lbpcnt := 0; { label counts }
filcnt := 0; { file tracking counts }
cipcnt := 0; { case entry tracking counts }
ttpcnt := 0; { tag tracking entry counts }
wtpcnt := 0; { with tracking entry counts }
{ clear id counts }
ctpsnm := 0;
stpsnm := 0
end (*initscalars*) ;
procedure initsets;
begin
constbegsys := [lparent,notsy,intconst,realconst,stringconst,ident,lbrack];
simptypebegsys := [lparent,addop,intconst,realconst,stringconst,ident];
typebegsys:=[arrow,packedsy,arraysy,recordsy,setsy,filesy]+simptypebegsys;
typedels := [arraysy,recordsy,setsy,filesy];
pfbegsys := [procsy,funcsy,overloadsy,staticsy,virtualsy,overridesy,
operatorsy];
blockbegsys := [privatesy,labelsy,constsy,typesy,fixedsy,varsy,beginsy]+pfbegsys;
selectsys := [arrow,period,lbrack];
facbegsys := [intconst,realconst,stringconst,ident,lparent,lbrack,notsy,nilsy,
inheritedsy];
statbegsys := [beginsy,gotosy,ifsy,whilesy,repeatsy,forsy,withsy,casesy,
trysy];
end (*initsets*) ;
procedure inittables;
procedure reswords;
begin
rw[ 1] := 'if '; rw[ 2] := 'do '; rw[ 3] := 'of ';
rw[ 4] := 'to '; rw[ 5] := 'in '; rw[ 6] := 'or ';
rw[ 7] := 'end '; rw[ 8] := 'for '; rw[ 9] := 'var ';
rw[10] := 'div '; rw[11] := 'mod '; rw[12] := 'set ';
rw[13] := 'and '; rw[14] := 'not '; rw[15] := 'nil ';
rw[16] := 'then '; rw[17] := 'else '; rw[18] := 'with ';
rw[19] := 'goto '; rw[20] := 'case '; rw[21] := 'type ';
rw[22] := 'file '; rw[23] := 'begin '; rw[24] := 'until ';
rw[25] := 'while '; rw[26] := 'array '; rw[27] := 'const ';
rw[28] := 'label '; rw[29] := 'repeat '; rw[30] := 'record ';
rw[31] := 'downto '; rw[32] := 'packed '; rw[33] := 'program ';
rw[34] := 'function '; rw[35] := 'procedure'; rw[36] := 'forward ';
rw[37] := 'module '; rw[38] := 'uses '; rw[39] := 'private ';
rw[40] := 'external '; rw[41] := 'view '; rw[42] := 'fixed ';
rw[43] := 'process '; rw[44] := 'monitor '; rw[45] := 'share ';
rw[46] := 'class '; rw[47] := 'is '; rw[48] := 'overload ';
rw[49] := 'override '; rw[50] := 'reference'; rw[51] := 'joins ';
rw[52] := 'static '; rw[53] := 'inherited'; rw[54] := 'self ';
rw[55] := 'virtual '; rw[56] := 'try '; rw[57] := 'except ';
rw[58] := 'extends '; rw[59] := 'on '; rw[60] := 'result ';
rw[61] := 'operator '; rw[62] := 'out '; rw[63] := 'property ';
rw[64] := 'channel '; rw[65] := 'stream '; rw[66] := 'xor ';
end (*reswords*) ;
procedure symbols;
var i: integer;
begin
rsy[ 1] := ifsy; rsy[ 2] := dosy; rsy[ 3] := ofsy;
rsy[ 4] := tosy; rsy[ 5] := relop; rsy[ 6] := addop;
rsy[ 7] := endsy; rsy[ 8] := forsy; rsy[ 9] := varsy;
rsy[10] := mulop; rsy[11] := mulop; rsy[12] := setsy;
rsy[13] := mulop; rsy[14] := notsy; rsy[15] := nilsy;
rsy[16] := thensy; rsy[17] := elsesy; rsy[18] := withsy;
rsy[19] := gotosy; rsy[20] := casesy; rsy[21] := typesy;
rsy[22] := filesy; rsy[23] := beginsy; rsy[24] := untilsy;
rsy[25] := whilesy; rsy[26] := arraysy; rsy[27] := constsy;
rsy[28] := labelsy; rsy[29] := repeatsy; rsy[30] := recordsy;
rsy[31] := downtosy; rsy[32] := packedsy; rsy[33] := progsy;
rsy[34] := funcsy; rsy[35] := procsy; rsy[36] := forwardsy;
rsy[37] := modulesy; rsy[38] := usessy; rsy[39] := privatesy;
rsy[40] := externalsy; rsy[41] := viewsy; rsy[42] := fixedsy;
rsy[43] := processsy; rsy[44] := monitorsy; rsy[45] := sharesy;
rsy[46] := classsy; rsy[47] := issy; rsy[48] := overloadsy;
rsy[49] := overridesy; rsy[50] := referencesy; rsy[51] := joinssy;
rsy[52] := staticsy; rsy[53] := inheritedsy; rsy[54] := selfsy;
rsy[55] := virtualsy; rsy[56] := trysy; rsy[57] := exceptsy;
rsy[58] := extendssy; rsy[59] := onsy; rsy[60] := resultsy;
rsy[61] := operatorsy; rsy[62] := outsy; rsy[63] := propertysy;
rsy[64] := channelsy; rsy[65] := streamsy; rsy[66] := addop;
for i := ordminchar to ordmaxchar do ssy[chr(i)] := othersy;
ssy['+'] := addop ; ssy['-'] := addop; ssy['*'] := mulop;
ssy['/'] := mulop ; ssy['('] := lparent; ssy[')'] := rparent;
ssy['$'] := othersy ; ssy['='] := relop; ssy[' '] := othersy;
ssy[','] := comma ; ssy['.'] := period; ssy['''']:= othersy;
ssy['['] := lbrack ; ssy[']'] := rbrack; ssy[':'] := colon;
ssy['^'] := arrow ; ssy['<'] := relop; ssy['>'] := relop;
ssy[';'] := semicolon; ssy['@'] := arrow; ssy['#'] := numsy;
ssy['}'] := othersy;
end (*symbols*) ;
procedure rators;
var i: integer;
begin
for i := 1 to maxres (*nr of res words*) do rop[i] := noop;
rop[5] := inop; rop[10] := idiv; rop[11] := imod;
rop[6] := orop; rop[13] := andop; rop[66] := xorop;
for i := ordminchar to ordmaxchar do sop[chr(i)] := noop;
sop['+'] := plus; sop['-'] := minus; sop['*'] := mul; sop['/'] := rdiv;
sop['='] := eqop; sop['<'] := ltop; sop['>'] := gtop;
end (*rators*) ;
procedure procmnemonics;
begin
{ There are two mnemonics that have no counterpart in the
assembler/interpreter: wro, pak. I didn't find a generator for them, and
suspect they are abandoned. }
sna[ 1] :='get '; sna[ 2] :='put '; sna[ 3] :='rdi '; sna[ 4] :='rdr ';
sna[ 5] :='rdc '; sna[ 6] :='wri '; sna[ 7] :='wro '; sna[ 8] :='wrr ';
sna[ 9] :='wrc '; sna[10] :='wrs '; sna[11] :='pak '; sna[12] :='new ';
sna[13] :='rst '; sna[14] :='eln '; sna[15] :='sin '; sna[16] :='cos ';
sna[17] :='exp '; sna[18] :='sqt '; sna[19] :='log '; sna[20] :='atn ';
sna[21] :='rln '; sna[22] :='wln '; sna[23] :='sav ';
{ new procedure/function memonics for p5/p6 }
sna[24] :='pag '; sna[25] :='rsf '; sna[26] :='rwf '; sna[27] :='wrb ';
sna[28] :='wrf '; sna[29] :='dsp '; sna[30] :='wbf '; sna[31] :='wbi ';
sna[32] :='wbr '; sna[33] :='wbc '; sna[34] :='wbb '; sna[35] :='rbf ';
sna[36] :='rsb '; sna[37] :='rwb '; sna[38] :='gbf '; sna[39] :='pbf ';
sna[40] :='rib '; sna[41] :='rcb '; sna[42] :='nwl '; sna[43] :='dsl ';
sna[44] :='eof '; sna[45] :='efb '; sna[46] :='fbv '; sna[47] :='fvb ';
sna[48] :='wbx '; sna[49] :='asst'; sna[50] :='clst'; sna[51] :='pos ';
sna[52] :='upd '; sna[53] :='appt'; sna[54] :='del '; sna[55] :='chg ';
sna[56] :='len '; sna[57] :='loc '; sna[58] :='exs '; sna[59] :='assb';
sna[60] :='clsb'; sna[61] :='appb'; sna[62] :='hlt '; sna[63] :='ast ';
sna[64] :='asts'; sna[65] :='wrih'; sna[66] :='wrio'; sna[67] :='wrib';
sna[68] :='wrsp'; sna[69] :='wiz '; sna[70] :='wizh'; sna[71] :='wizo';
sna[72] :='wizb'; sna[73] :='rds '; sna[74] :='ribf'; sna[75] :='rdif';
sna[76] :='rdrf'; sna[77] :='rcbf'; sna[78] :='rdcf'; sna[79] :='rdsf';
sna[80] :='rdsp'; sna[81] :='aeft'; sna[82] :='aefb'; sna[83] :='rdie';
sna[84] :='rdre'; sna[85] :=' thw';
end (*procmnemonics*) ;
procedure instrmnemonics;
begin { --- are unused codes }
mn[ 0] :='abi'; mn[ 1] :='abr'; mn[ 2] :='adi'; mn[ 3] :='adr';
mn[ 4] :='and'; mn[ 5] :='dif'; mn[ 6] :='dvi'; mn[ 7] :='dvr';
mn[ 8] :='ltc'; mn[ 9] :='flo'; mn[ 10] :='flt'; mn[ 11] :='inn';
mn[ 12] :='int'; mn[ 13] :='ior'; mn[ 14] :='mod'; mn[ 15] :='mpi';
mn[ 16] :='mpr'; mn[ 17] :='ngi'; mn[ 18] :='ngr'; mn[ 19] :='not';
mn[ 20] :='odd'; mn[ 21] :='sbi'; mn[ 22] :='sbr'; mn[ 23] :='sgs';
mn[ 24] :='sqi'; mn[ 25] :='sqr'; mn[ 26] :='sto'; mn[ 27] :='trc';
mn[ 28] :='uni'; mn[ 29] :='stp'; mn[ 30] :='csp'; mn[ 31] :='dec';
mn[ 32] :='rip'; mn[ 33] :='fjp'; mn[ 34] :='inc'; mn[ 35] :='ind';
mn[ 36] :='ixa'; mn[ 37] :='lao'; mn[ 38] :='lca'; mn[ 39] :='ldo';
mn[ 40] :='mov'; mn[ 41] :='mst'; mn[ 42] :='ret'; mn[ 43] :='sro';
mn[ 44] :='xjp'; mn[ 45] :='chk'; mn[ 46] :='cup'; mn[ 47] :='equ';
mn[ 48] :='geq'; mn[ 49] :='grt'; mn[ 50] :='lda'; mn[ 51] :='ldc';
mn[ 52] :='leq'; mn[ 53] :='les'; mn[ 54] :='lod'; mn[ 55] :='neq';
mn[ 56] :='str'; mn[ 57] :='ujp'; mn[ 58] :='ord'; mn[ 59] :='chr';
mn[ 60] :='ujc'; mn[ 61] :='rnd'; mn[ 62] :='pck'; mn[ 63] :='upk';
mn[ 64] :='rgs'; mn[ 65] :='???'; mn[ 66] :='ipj'; mn[ 67] :='cip';
mn[ 68] :='lpa'; mn[ 69] :='???'; mn[ 70] :='???'; mn[ 71] :='dmp';
mn[ 72] :='swp'; mn[ 73] :='tjp'; mn[ 74] :='lip'; mn[ 75] :='ckv';
mn[ 76] :='dup'; mn[ 77] :='cke'; mn[ 78] :='cks'; mn[ 79] :='inv';
mn[ 80] :='ckl'; mn[ 81] :='cta'; mn[ 82] :='ivt'; mn[ 83] :='xor';
mn[ 84] :='bge'; mn[ 85] :='ede'; mn[ 86] :='mse'; mn[ 87] :='cjp';
mn[ 88] :='lnp'; mn[ 89] :='cal'; mn[ 90] :='ret'; mn[ 91] :='cuv';
mn[ 92] :='suv'; mn[ 93] :='vbs'; mn[ 94] :='vbe'; mn[ 95] :='cvb';
mn[ 96] :='vis'; mn[ 97] :='vip'; mn[ 98] :='lcp'; mn[ 99] :='cps';
mn[100] :='cpc'; mn[101] :='aps'; mn[102] :='apc'; mn[103] :='cxs';
mn[104] :='cxc'; mn[105] :='lft'; mn[106] :='max'; mn[107] :='vdp';
mn[108] :='spc'; mn[109] :='ccs'; mn[110] :='scp'; mn[111] :='ldp';
mn[112] :='vin'; mn[113] :='vdd'; mn[114] :='lto'; mn[115] :='ctb';
mn[116] :='cpp'; mn[117] :='cpr'; mn[118] :='lsa'; mn[119] :='wbs';
mn[120] :='wbe'; mn[121] :='sfr'; mn[122] :='cuf'; mn[123] :='cif';
end (*instrmnemonics*) ;
procedure chartypes;
var i : integer;
begin
for i := ordminchar to ordmaxchar do chartp[chr(i)] := illegal;
chartp['a'] := letter ;
chartp['b'] := letter ; chartp['c'] := letter ;
chartp['d'] := letter ; chartp['e'] := letter ;
chartp['f'] := letter ; chartp['g'] := letter ;
chartp['h'] := letter ; chartp['i'] := letter ;
chartp['j'] := letter ; chartp['k'] := letter ;
chartp['l'] := letter ; chartp['m'] := letter ;
chartp['n'] := letter ; chartp['o'] := letter ;
chartp['p'] := letter ; chartp['q'] := letter ;
chartp['r'] := letter ; chartp['s'] := letter ;
chartp['t'] := letter ; chartp['u'] := letter ;
chartp['v'] := letter ; chartp['w'] := letter ;
chartp['x'] := letter ; chartp['y'] := letter ;
chartp['z'] := letter ;
chartp['A'] := letter ;
chartp['B'] := letter ; chartp['C'] := letter ;
chartp['D'] := letter ; chartp['E'] := letter ;
chartp['F'] := letter ; chartp['G'] := letter ;
chartp['H'] := letter ; chartp['I'] := letter ;
chartp['J'] := letter ; chartp['K'] := letter ;
chartp['L'] := letter ; chartp['M'] := letter ;
chartp['N'] := letter ; chartp['O'] := letter ;
chartp['P'] := letter ; chartp['Q'] := letter ;
chartp['R'] := letter ; chartp['S'] := letter ;
chartp['T'] := letter ; chartp['U'] := letter ;
chartp['V'] := letter ; chartp['W'] := letter ;
chartp['X'] := letter ; chartp['Y'] := letter ;
chartp['Z'] := letter ;
chartp['_'] := letter ;
chartp['0'] := number ;
chartp['1'] := number ; chartp['2'] := number ;
chartp['3'] := number ; chartp['4'] := number ;
chartp['5'] := number ; chartp['6'] := number ;
chartp['7'] := number ; chartp['8'] := number ;
chartp['9'] := number ; chartp['+'] := special ;
chartp['-'] := special ; chartp['*'] := special ;
chartp['/'] := special ; chartp['('] := chlparen;
chartp[')'] := special ; chartp['$'] := special ;
chartp['='] := special ; chartp[' '] := chspace ;
chartp[','] := special ; chartp['.'] := chperiod;
chartp['''']:= chstrquo; chartp['['] := special ;
chartp[']'] := special ; chartp[':'] := chcolon ;
chartp['^'] := special ; chartp[';'] := special ;
chartp['<'] := chlt ; chartp['>'] := chgt ;
chartp['{'] := chlcmt ; chartp['}'] := special ;
chartp['@'] := special ; chartp['!'] := chrem ;
chartp['$'] := chhex ; chartp['&'] := choct ;
chartp['%'] := chbin ; chartp['#'] := special ;
for i := ordminchar to ordmaxchar do ordint[chr(i)] := 0;
ordint['0'] := 0; ordint['1'] := 1; ordint['2'] := 2;
ordint['3'] := 3; ordint['4'] := 4; ordint['5'] := 5;
ordint['6'] := 6; ordint['7'] := 7; ordint['8'] := 8;
ordint['9'] := 9; ordint['a'] := 10; ordint['b'] := 11;
ordint['c'] := 12; ordint['d'] := 13; ordint['e'] := 14;
ordint['f'] := 15; ordint['A'] := 10; ordint['B'] := 11;
ordint['C'] := 12; ordint['D'] := 13; ordint['E'] := 14;
ordint['F'] := 15;
end;
procedure initdx;
begin
{ [sam] if your sizes are not even multiples of
stackelsize, you are going to need to compensate this.
entries marked with * go to secondary table }
cdx[ 0] := 0; cdx[ 1] := 0;
cdx[ 2] := +intsize; cdx[ 3] := +realsize;
cdx[ 4] := +intsize; cdx[ 5] := +setsize;
cdx[ 6] := +intsize; cdx[ 7] := +realsize;
cdx[ 8] := 4{*}; cdx[ 9] := +intsize-realsize;
cdx[ 10] := -realsize+intsize; cdx[ 11] := +setsize;
cdx[ 12] := +setsize; cdx[ 13] := +intsize;
cdx[ 14] := +intsize; cdx[ 15] := +intsize;
cdx[ 16] := +realsize; cdx[ 17] := 0;
cdx[ 18] := 0; cdx[ 19] := 2{*};
cdx[ 20] := 0; cdx[ 21] := +intsize;
cdx[ 22] := +realsize; cdx[ 23] := +intsize-setsize;
cdx[ 24] := 0; cdx[ 25] := 0;
cdx[ 26] := 1{*}; cdx[ 27] := +realsize-intsize;
cdx[ 28] := +setsize; cdx[ 29] := 0;
cdx[ 30] := 0; cdx[ 31] := 2{*};
cdx[ 32] := 0; cdx[ 33] := +intsize;
cdx[ 34] := 2{*}; cdx[ 35] := 3{*};
cdx[ 36] := +intsize; cdx[ 37] := -adrsize;
cdx[ 38] := -adrsize; cdx[ 39] := 4{*};
cdx[ 40] := +adrsize*2; cdx[ 41] := 0;
cdx[ 42] := 2{*}; cdx[ 43] := 5{*};
cdx[ 44] := +intsize; cdx[ 45] := 2{*};
cdx[ 46] := 0; cdx[ 47] := 6{*};
cdx[ 48] := 6{*}; cdx[ 49] := 6{*};
cdx[ 50] := -adrsize; cdx[ 51] := 4{*};
cdx[ 52] := 6{*}; cdx[ 53] := 6{*};
cdx[ 54] := 4{*}; cdx[ 55] := 6{*};
cdx[ 56] := 5{*}; cdx[ 57] := 0;
cdx[ 58] := 2{*}; cdx[ 59] := 0;
cdx[ 60] := 0; cdx[ 61] := +realsize-intsize;
cdx[ 62] := +adrsize*3; cdx[ 63] := +adrsize*3;
cdx[ 64] := +intsize*2-setsize; cdx[ 65] := 0;
cdx[ 66] := 0; cdx[ 67] := +ptrsize;
cdx[ 68] := -adrsize*2; cdx[ 69] := 0;
cdx[ 70] := 0; cdx[ 71] := +ptrsize;
cdx[ 72] := 0; cdx[ 73] := +intsize;
cdx[ 74] := -adrsize*2; cdx[ 75] := 2{*};
cdx[ 76] := 4{*}; cdx[ 77] := +intsize*2;
cdx[ 78] := -intsize; cdx[ 79] := +adrsize;
cdx[ 80] := 2{*}; cdx[ 81] := 0;
cdx[ 82] := 0; cdx[ 83] := +intsize;
cdx[ 84] := -adrsize; cdx[ 85] := +adrsize;
cdx[ 86] := 0; cdx[ 87] := 0;
cdx[ 88] := 0; cdx[ 89] := 0;
cdx[ 90] := 0; cdx[ 91] := 0;
cdx[ 92] := 0; cdx[ 93] := +intsize;
cdx[ 94] := 0; cdx[ 95] := 0;
cdx[ 96] := 0; cdx[ 97] := 0;
cdx[ 98] := -adrsize; cdx[ 99] := 0;
cdx[100] := 0; cdx[101] := +ptrsize*4;
cdx[102] := +ptrsize*4; cdx[103] := +intsize+ptrsize;
cdx[104] := +intsize; cdx[105] := -adrsize;
cdx[106] := +ptrsize*2; cdx[107] := +ptrsize;
cdx[108] := 0; cdx[109] := 0;
cdx[110] := +ptrsize*3; cdx[111] := -adrsize;
cdx[112] := 0; cdx[113] := +ptrsize;
cdx[114] := -adrsize; cdx[115] := 0;
cdx[116] := 0; cdx[117] := 0;
cdx[118] := -adrsize; cdx[119] := 0;
cdx[120] := 0; cdx[121] := 0;
cdx[122] := 0; cdx[123] := +ptrsize;
{ secondary table order is i, r, b, c, a, s, m }
cdxs[1][1] := +(adrsize+intsize); { stoi }
cdxs[1][2] := +(adrsize+realsize); { stor }
cdxs[1][3] := +(adrsize+intsize); { stob }
cdxs[1][4] := +(adrsize+intsize); { stoc }
cdxs[1][5] := +(adrsize+adrsize); { stoa }
cdxs[1][6] := +(adrsize+setsize); { stos }
cdxs[1][7] := 0;
cdxs[1][8] := 0;
cdxs[2][1] := 0; { deci/inci/ordi/chki/reti/noti }
cdxs[2][2] := 0; { chkr/retr }
cdxs[2][3] := 0; { decb/incb/ordb/chkb/retb/notb }
cdxs[2][4] := 0; { decc/incc/ordc/chkc/retc }
cdxs[2][5] := 0; { chka/reta/ckl }
cdxs[2][6] := 0; { chks }
cdxs[2][7] := 0;
cdxs[2][8] := 0;
cdxs[3][1] := +adrsize-intsize; { indi }
cdxs[3][2] := +adrsize-realsize; { indr }
cdxs[3][3] := +adrsize-intsize; { indb }
cdxs[3][4] := +adrsize-intsize; { indc }
cdxs[3][5] := +adrsize-adrsize; { inda }
cdxs[3][6] := +adrsize-setsize; { inds }
cdxs[3][7] := 0;
cdxs[3][8] := 0;
cdxs[4][1] := -intsize; { ldoi/ldc/lodi/dupi/ltc }
cdxs[4][2] := -realsize; { ldor/ldc/lodr/dupr/ltc }
cdxs[4][3] := -intsize; { ldob/ldc/lodb/dupb/ltc }
cdxs[4][4] := -intsize; { ldoc/ldc/lodc/dupc/ltc }
cdxs[4][5] := -adrsize; { ldoa/ldc/loda/dupa/ltc }
cdxs[4][6] := -setsize; { ldos/ldc/lods/dups/ltc }
cdxs[4][7] := 0;
cdxs[4][8] := 0;
cdxs[5][1] := +intsize; { sroi/stri }
cdxs[5][2] := +realsize; { sror/strr }
cdxs[5][3] := +intsize; { srob/strb }
cdxs[5][4] := +intsize; { sroc/strc }
cdxs[5][5] := +adrsize; { sroa/stra }
cdxs[5][6] := +setsize; { sros/strs }
cdxs[5][7] := 0;
cdxs[5][8] := 0;
{ note that all of the comparisions share the same table }
cdxs[6][1] := +(intsize+intsize)-intsize; { equi/neqi/geqi/grti/leqi/lesi }
cdxs[6][2] := +(realsize+realsize)-intsize; { equr/neqr/geqr/grtr/leqr/lesr }
cdxs[6][3] := +(intsize+intsize)-intsize; { equb/neqb/geqb/grtb/leqb/lesb }
cdxs[6][4] := +(intsize+intsize)-intsize; { equc/neqc/geqc/grtc/leqc/lesc }
cdxs[6][5] := +(adrsize+intsize)-adrsize; { equa/neqa/geqa/grta/leqa/lesa }
cdxs[6][6] := +(setsize+setsize)-intsize; { equs/neqs/geqs/grts/leqs/less }
cdxs[6][7] := +(adrsize+adrsize)-intsize; { equm/neqm/geqm/grtm/leqm/lesm }
cdxs[6][8] := +(adrsize*2+adrsize*2)-intsize; { equv/neqv/geqv/grtv/leqv/lesv }
pdx[ 1] := +adrsize; pdx[ 2] := +adrsize;
pdx[ 3] := +adrsize; pdx[ 4] := +adrsize;
pdx[ 5] := +adrsize; pdx[ 6] := +adrsize*2;
pdx[ 7] := 0; pdx[ 8] := +(realsize+intsize);
pdx[ 9] := +intsize*2; pdx[10] := +(adrsize+intsize*2);
pdx[11] := 0; pdx[12] := +ptrsize*2;
pdx[13] := 0; pdx[14] := +adrsize-intsize;
pdx[15] := 0; pdx[16] := 0;
pdx[17] := 0; pdx[18] := 0;
pdx[19] := 0; pdx[20] := 0;
pdx[21] := 0; pdx[22] := 0;
pdx[23] := 0; pdx[24] := +adrsize;
pdx[25] := +adrsize; pdx[26] := +adrsize;
pdx[27] := +intsize*2; pdx[28] := +(realsize+intsize*2);
pdx[29] := +adrsize*2; pdx[30] := +(adrsize+intsize);
pdx[31] := +intsize; pdx[32] := +realsize;
pdx[33] := +intsize; pdx[34] := +intsize;
pdx[35] := +(intsize+adrsize); pdx[36] := +adrsize;
pdx[37] := +adrsize; pdx[38] := +(intsize+adrsize);
pdx[39] := +(intsize+adrsize); pdx[40] := +(adrsize+intsize*2);
pdx[41] := +(adrsize+intsize*2); pdx[42] := +(adrsize+intsize*2);
pdx[43] := +(adrsize+intsize*2); pdx[44] := +adrsize-intsize;
pdx[45] := +adrsize-intsize; pdx[46] := 0;
pdx[47] := +intsize; pdx[48] := +intsize;
pdx[49] := +adrsize*2+intsize; pdx[50] := +adrsize;
pdx[51] := +adrsize+intsize; pdx[52] := +adrsize;
pdx[53] := +adrsize; pdx[54] := +adrsize+intsize;
pdx[55] := +adrsize*2+intsize*2; pdx[56] := +adrsize-intsize;
pdx[57] := +adrsize-intsize; pdx[58] := +adrsize+intsize-intsize;
pdx[59] := +adrsize*2+intsize; pdx[60] := +adrsize;
pdx[61] := +adrsize; pdx[62] := 0;
pdx[63] := +intsize; pdx[64] := +adrsize+intsize+intsize;
pdx[65] := +adrsize*2; pdx[66] := +adrsize*2;
pdx[67] := +adrsize*2; pdx[68] := +(adrsize+intsize);
pdx[69] := +adrsize*2; pdx[70] := +adrsize*2;
pdx[71] := +adrsize*2; pdx[72] := +adrsize*2;
pdx[73] := +adrsize+intsize; pdx[74] := +(adrsize+intsize*3);
pdx[75] := +adrsize+intsize; pdx[76] := +adrsize+intsize;
pdx[77] := +(adrsize+intsize*3); pdx[78] := +adrsize+intsize;
pdx[79] := +adrsize+intsize*2; pdx[80] := +adrsize+intsize;
pdx[81] := +adrsize*2+intsize; pdx[82] := +adrsize*2+intsize;
pdx[83] := +adrsize*2+intsize; pdx[84] := +adrsize*2+intsize;
pdx[85] := +adrsize;
end;
begin (*inittables*)
reswords; symbols; rators;
instrmnemonics; procmnemonics;
chartypes; initdx;
end (*inittables*) ;
begin
{ Suppress unreferenced errors. These are all MPB (machine parameter
block) equations that need to stay the same between front end and backend. }
if heapal = 0 then;
if inthex = 0 then;
if market = 0 then;
if markep = 0 then;
if marksb = 0 then;
if maxsize = 0 then;
(*initialize*)
(************)
initscalars; initsets; inittables;
extendinit; { initialize extentions package };
write('P6 Pascal compiler vs. ', majorver:1, '.', minorver:1);
if experiment then write('.x');
writeln;
if iso7185 then begin
writeln('Pascal-P6 complies with the requirements of level 0 of ISO/IEC 7185.');
writeln
end else begin
writeln('Pascal-P6 complies with the requirements of Pascaline version 0.4');
writeln('and the following annexes: A,B,C,E.');
writeln
end;
(*enter standard names and standard types:*)
(******************************************)
level := 0; top := 0; ptop := 0;
with display[0] do
begin inidsp(display[0]); define := true; occur := blck; bname := nil end;
enterstdtypes; stdnames; entstdnames; enterundecl;
top := 1; level := 1;
with display[1] do
begin inidsp(display[1]); define := true; occur := blck; bname := nil end;
{ get command line }
getcommandline(cmdlin, cmdlen);
cmdpos := 1;
paroptions; { load command line options }
plcopt; { place options in flags }
(*compile:*)
(**********)
{ !!! remove these statements for self compile }
#ifndef SELF_COMPILE
reset(prd); rewrite(prr); { open output file }
#endif
{ write generator comment }
if prcode then begin
writeln(prr, '!');
writeln(prr, '! Pascal intermediate file Generated by P6 Pascal compiler vs. ',
majorver:1, '.', minorver:1);
writeln(prr, '!');
{ write initial option values }
write(prr, 'o ');
for oi := 1 to maxopt do
{ exclude pint options and unused }
if not (oi in [7,8,14,15,16,13,17,19,23,1,6,5,18,11,26]) then
begin
for oni := 1 to optlen do
if optsl[oi, oni] <> ' ' then write(prr, optsl[oi, oni]);
if option[oi] then write(prr, '+') else write(prr, '-');
write(prr, ' ')
end;
writeln(prr)
end;
nvalid := false; { set no lookahead }
{ init for lookahead }
sy := ident; op := mul; lgth := 0; kk := 1; ch := ' ';
readline;
insymbol;
modulep(blockbegsys+statbegsys-[casesy]);
{ release file tracking entries }
putinp(incstk); putinp(inclst);
outline;
{ dispose of levels 0 and 1 }
putdsp(display[1]);
putdsp(display[0]);
{ dispose of the pile }
putpile;
{ remove undeclared ids }
exitundecl;
writeln;
writeln('Errors in program: ', toterr:1);
{ output error report as required }
f := true;
for i := 1 to maxftl do if errtbl[i] > 0 then begin
if f then begin
writeln;
writeln('Error numbers in listing:');
writeln('-------------------------');
f := false
end;
write(i:3, ' ', errtbl[i]:3, ' '); errmsg(i); writeln
end;
if not f then writeln;
if doprtryc then begin { print recyling tracking counts }
writeln;
writeln('Recycling tracking counts:');
writeln;
writeln('string quants: ', strcnt:1);
writeln('constants: ', cspcnt:1);
writeln('structures: ', stpcnt:1);
writeln('identifiers: ', ctpcnt:1);
writeln('label counts: ', lbpcnt:1);
writeln('file tracking counts: ', filcnt:1);
writeln('case entry tracking counts: ', cipcnt:1);
writeln('tag entry tracking counts: ', ttpcnt:1);
writeln('with entry tracking counts: ', wtpcnt:1);
writeln;
end;
if doprtlab then prtlabels; { dump labels}
if dodmpdsp then prtdsp; { dump display }
{ perform errors for recycling balance }
if strcnt <> 0 then
writeln('*** Error: Compiler internal error: string recycle balance: ',
strcnt:1);
if cspcnt <> 0 then
writeln('*** Error: Compiler internal error: constant recycle balance: ',
cspcnt:1);
if stpcnt <> 0 then
writeln('*** Error: Compiler internal error: structure recycle balance: ',
stpcnt:1);
if ctpcnt <> 0 then
writeln('*** Error: Compiler internal error: identifier recycle balance: ',
ctpcnt:1);
if lbpcnt <> 0 then
writeln('*** Error: Compiler internal error: label recycle balance: ',
lbpcnt:1);
if filcnt <> 0 then
writeln('*** Error: Compiler internal error: file recycle balance: ',
filcnt:1);
if cipcnt <> 0 then
writeln('*** Error: Compiler internal error: case recycle balance: ',
cipcnt:1);
if ttpcnt <> 0 then
writeln('*** Error: Compiler internal error: tag recycle balance: ',
cipcnt:1);
if wtpcnt <> 0 then
writeln('*** Error: Compiler internal error: with recycle balance: ',
wtpcnt:1);
99:
end.
|
unit focusNfeCommunicator;
interface
uses
Forms, iniFiles, Classes, sysUtils, Dialogs, windows, IdHTTP;
type
TTipoLog = (tlErro, tlAviso, tlEvento);
TFocusNFeCommunicator = class
private
FsendDir: string;
FToken: string;
FreceiveDir: string;
FUrl: string;
FlogDir: string;
ref: string; //Feio isso ser uma global, mas por hora acho que é o suficiente
function getNomeArquivoIni: string;
procedure ensureDir(nomeDir: string);
procedure ensureDirs;
procedure log(tipoLog: TTipoLog; msg: string);
procedure parseParams;
procedure criaArquivoPendenciaRetorno(ref: string);
function getPendenciaRetornoDir: string;
function getSendDir: string;
function enviarArquivo(nomeArquivo: string): boolean;
function getArquivosProcessadosDir: string;
procedure consultarRetorno(ref: string);
function getReceiveDir: string;
procedure baixarArquivos(chave: string);
function cancelarNota(ref: string): boolean;
public
class procedure startProcess;
constructor create;
private
HTTPClient: TIdHTTP;
property sendDir: string read getSendDir write FsendDir;
property logDir: string read FlogDir write FlogDir;
property receiveDir: string read getReceiveDir write FreceiveDir;
property token: string read FToken write FToken;
property url: string read FUrl write FUrl;
procedure readConfiguration;
procedure processFilesToSend;
procedure processFilesToReceive;
function getBaseDir: string;
end;
implementation
uses StrUtils;
class procedure TFocusNFeCommunicator.startProcess;
var
inicio, fim1, fim2: cardinal;
begin
with TFocusNFeCommunicator.create do
begin
try
readConfiguration;
parseParams;
if ref <> '' then
criaArquivoPendenciaRetorno(ref);
Write('Iniciou em ');
Writeln(GetTickCount);
processFilesToSend;
Write('Enviados em ');
Writeln(GetTickCount);
processFilesToReceive;
Write('Retornados em ');
Writeln(GetTickCount);
except
on e: exception do
log(tlErro, e.Message);
end;
end;
end;
constructor TFocusNFeCommunicator.create;
begin
ref := '';
HTTPClient := TIdHTTP.Create(nil);
HTTPClient.HandleRedirects := true;
end;
procedure TFocusNFeCommunicator.readConfiguration;
var
ini: TIniFile;
iniFileName: string;
begin
iniFileName := getBaseDir + getNomeArquivoIni;
Ini := TIniFile.Create(iniFileName);
try
sendDir := Ini.ReadString('Diretorios', 'envio', getBaseDir + 'envios');
receiveDir := Ini.ReadString('Diretorios', 'retorno', getBaseDir + 'retornos');
logDir := Ini.ReadString('Diretorios', 'logs', getBaseDir + 'logs');
url := Ini.ReadString('Conexao', 'url', 'http://producao.acrasnfe.acras.com.br/');
token := Ini.ReadString('Conexao', 'token', '{token-enviado-pelo-suporte-focusnfe}');
if not(fileExists(iniFileName)) then
begin
Ini.WriteString('Diretorios', 'envio', sendDir);
Ini.WriteString('Diretorios', 'retorno', receiveDir);
Ini.WriteString('Diretorios', 'logs', logDir);
Ini.WriteString('Conexao', 'url', url);
Ini.WriteString('Conexao', 'token', token);
end;
ensureDirs;
finally
FreeAndNil(ini);
end;
end;
procedure TFocusNFeCommunicator.processFilesToSend;
var
ref: string;
FindResult: integer;
SearchRec : TSearchRec;
nomeArquivo, nomeArquivoDestino: string;
begin
FindResult := FindFirst(sendDir + '*.nfe', faAnyFile - faDirectory, SearchRec);
while FindResult = 0 do
begin
nomeArquivo := sendDir + SearchRec.Name;
log(tlEvento, 'Processando arquivo ' + quotedStr(nomeArquivo));
if enviarArquivo(nomeArquivo) then
begin
nomeArquivoDestino := getArquivosProcessadosDir + ExtractFileName(nomeArquivo);
moveFile(Pchar(nomeArquivo), PChar(nomeArquivoDestino));
criaArquivoPendenciaRetorno(copy(ExtractFileName(nomeArquivo), 1, length(ExtractFileName(nomeArquivo))- 4));
end;
FindResult := FindNext(SearchRec);
end;
FindResult := FindFirst(sendDir + '*.can', faAnyFile - faDirectory, SearchRec);
while FindResult = 0 do
begin
nomeArquivo := sendDir + SearchRec.Name;
ref := copy(SearchRec.Name, 1, length(SearchRec.Name) - 4);
log(tlEvento, 'Processando arquivo ' + quotedStr(nomeArquivo));
if cancelarNota(ref) then
begin
nomeArquivoDestino := getArquivosProcessadosDir + ExtractFileName(nomeArquivo);
if not moveFile(Pchar(nomeArquivo), PChar(nomeArquivoDestino)) then
log(tlErro, 'Impossível mover arquivo para processados: ' + nomeArquivo);
criaArquivoPendenciaRetorno(ref);
end;
FindResult := FindNext(SearchRec);
end;
end;
procedure TFocusNFeCommunicator.processFilesToReceive;
var
FindResult: integer;
SearchRec : TSearchRec;
nomeArquivo: string;
begin
FindResult := FindFirst(getPendenciaRetornoDir + '*.ref', faAnyFile - faDirectory, SearchRec);
while FindResult = 0 do
begin
nomeArquivo := getPendenciaRetornoDir + SearchRec.Name;
log(tlEvento, 'Consultando retorno ' + quotedStr(nomeArquivo));
consultarRetorno(copy(SearchRec.Name, 0, length(SearchRec.Name) - 4));
FindResult := FindNext(SearchRec);
end;
end;
function TFocusNFeCommunicator.getBaseDir: string;
begin
result := IncludeTrailingPathDelimiter(ExtractFileDir(Application.ExeName));
end;
function TFocusNFeCommunicator.getPendenciaRetornoDir: string;
begin
result := IncludeTrailingPathDelimiter(getBaseDir + 'pendenciasRetornos');
end;
function TFocusNFeCommunicator.getArquivosProcessadosDir: string;
begin
result := IncludeTrailingPathDelimiter(getBaseDir + 'arquivosProcessados');
end;
function TFocusNFeCommunicator.getNomeArquivoIni: string;
begin
result := 'focusFin.ini';
end;
procedure TFocusNFeCommunicator.ensureDir(nomeDir: string);
begin
if not(DirectoryExists(nomeDir)) then
CreateDir(nomeDir);
end;
procedure TFocusNFeCommunicator.ensureDirs;
begin
ensureDir(sendDir);
ensureDir(receiveDir);
ensureDir(receiveDir + 'DANFEs');
ensureDir(receiveDir + 'XMLs');
ensureDir(logDir);
ensureDir(getPendenciaRetornoDir);
ensureDir(getArquivosProcessadosDir);
end;
procedure TFocusNFeCommunicator.log(tipoLog: TTipoLog; msg: string);
var
logFile: TStringList;
nomeLogFile, logMessage: string;
begin
nomeLogFile := IncludeTrailingPathDelimiter(logDir) +
formatDateTime('yyyymmdd', date) + '.log';
logFile := TStringList.create;
try
if FileExists(nomeLogFile) then
logFile.loadFromFile(nomeLogFile);
logMessage := FormatDateTime('[hh:nn:ss - ', now);
case tipoLog of
tlErro: logMessage := logMessage + 'ERRO] ';
tlAviso: logMessage := logMessage + 'AVISO] ';
tlEvento: logMessage := logMessage + 'EVENTO] ';
end;
logMessage := logMessage + msg;
logFile.Add(logMessage);
logFile.SaveToFile(nomeLogFile);
finally
FreeAndNil(logFile);
end;
end;
procedure TFocusNFeCommunicator.parseParams;
var
i: integer;
nomeParam, valorParam: string;
begin
valorParam := '';
for i := 1 to ParamCount do
begin
nomeParam := copy(ParamStr(i), 1, pos('=', ParamStr(i))-1);
if UpperCase(nomeParam) = 'REF' then
ref := copy(ParamStr(i), pos('=', ParamStr(i)) + 1, MaxInt)
else
log(tlErro, 'Chamado com parâmetros inválidos: ' + ParamStr(i));
end;
end;
procedure TFocusNFeCommunicator.criaArquivoPendenciaRetorno(ref: string);
begin
with TStringList.create do
begin
SaveToFile(getPendenciaRetornoDir + ref + '.ref');
free;
end;
end;
function TFocusNFeCommunicator.getSendDir: string;
begin
Result := IncludeTrailingPathDelimiter(FsendDir);
end;
function TFocusNFeCommunicator.getReceiveDir: string;
begin
Result := IncludeTrailingPathDelimiter(FreceiveDir);
end;
function TFocusNFeCommunicator.enviarArquivo(nomeArquivo: string): boolean;
var
urlReq: string;
request, response: TStringStream;
dados: TStringList;
refNota: string;
begin
result := true;
refNota := copy(extractFileName(nomeArquivo), 1, length(extractFileName(nomeArquivo)) - 4);
urlReq := '?token=' + token + '&ref=' + refNota;
response := TStringStream.Create('');
dados := TStringList.create;
try
dados.LoadFromFile(nomeArquivo);
request := TStringStream.Create(UTF8Encode(dados.Text));
finally
FreeAndNil(dados);
end;
try
HTTPClient.Post(url + '/nfe2/autorizar' + urlReq, request, response);
log(tlEvento, 'Nota enviada com sucesso, ref = ' + refNota);
except
on e: EIdHTTPProtocolException do
begin
result := false;
log(tlErro, e.ErrorMessage);
end;
on e: Exception do
begin
result := false;
log(tlErro, e.Message);
end;
end;
end;
procedure TFocusNFeCommunicator.consultarRetorno(ref: string);
var
urlReq, chave, valor, chaveNfe, mensagemStatus, mensagemSefaz: string;
res: TStringList;
i, separatorPosition: integer;
final: boolean;
begin
//final será a flag indicando que a resposta é final, autorizado ou não autorizado, com isso
// podemos apagar o arquivo da pendência de consulta
final := false;
urlReq := url + '/nfe2/consultar?token=' + token + '&ref=' + ref;
res := TStringList.Create;
try
res.Text := Utf8ToAnsi(HTTPClient.Get(urlReq));
res.SaveToFile(receiveDir + ref + '.ret');
log(tlAviso, 'Salvo arquivo de retorno: ' + QuotedStr(receiveDir + ref + '.ret'));
for i := 1 to res.Count -1 do
begin
separatorPosition := pos(':', res[i]);
chave := Trim(copy(res[i], 1, separatorPosition - 1));
valor := Trim(copy(res[i], separatorPosition + 1, MaxInt));
if chave = 'status' then
mensagemStatus := valor;
if chave = 'mensagem_sefaz' then
mensagemSefaz := valor;
if chave = 'chave_nfe' then
chaveNfe := valor;
end;
if mensagemStatus = 'processando_autorizacao' then
log(tlAviso, 'A nota ainda está em processamento: ' + ref);
if mensagemStatus = 'erro_autorizacao' then
begin
log(tlErro, 'A nota não foi autorizada: ' + ref + #13#10 +
#9 + mensagemSefaz);
final := true;
end;
if mensagemStatus = 'autorizado' then
begin
log(tlAviso, 'A nota foi autorizada com sucesso: ' + ref);
baixarArquivos(chaveNfe);
final := true;
end;
if mensagemStatus = 'cancelado' then
begin
log(tlAviso, 'O cancelamento da nota foi autorizado: ' + ref);
final := true;
end;
if final then
DeleteFile(PChar(getPendenciaRetornoDir + ref + '.ref'));
finally
FreeAndNil(res);
end;
end;
procedure TFocusNFeCommunicator.baixarArquivos(chave: string);
var
fileName: string;
fileStream: TMemoryStream;
begin
//DANFE
fileName := getReceiveDir + 'DANFEs\' + chave + '.pdf';
fileStream := TMemoryStream.Create;
try
HTTPClient.Get(url + '/notas_fiscais/' + trim(chave) + '.pdf', fileStream);
fileStream.SaveToFile(fileName);
finally
fileStream.free;
end;
//XML
fileName := getReceiveDir + 'XMLs\' + chave + '.xml';
fileStream := TMemoryStream.Create;
try
HTTPClient.Get(url + '/notas_fiscais/' + trim(chave) + '.xml', fileStream);
fileStream.SaveToFile(fileName);
finally
fileStream.free;
end;
end;
function TFocusNFeCommunicator.cancelarNota(ref: string): boolean;
var
motivo, urlReq: string;
response: TStringStream;
arq: TStringList;
begin
result := false;
arq := TStringList.Create;
response := TStringStream.Create('');
try try
arq.LoadFromFile(getSendDir + ref + '.can');
motivo := trim(arq.GetText);
urlReq := trim(url + '/nfe2/cancelar?token=' + token +
'&ref=' + ref + '&justificativa=' + AnsiReplaceStr(motivo, ' ', '+'));
HTTPClient.Get(urlReq, response);
log(tlAviso, 'Retorno do cancelamento: ' + response.DataString);
result := true;
except
on e: EIdHTTPProtocolException do
log(tlErro, e.ErrorMessage);
on e: Exception do
log(tlErro, e.Message);
end;
finally
FreeAndNil(response);
freeAndNil(arq);
end;
end;
end.
|
{*********************************************}
{ TeeChart Storage functions }
{ Copyright (c) 1997-2004 by David Berneda }
{ All rights reserved }
{*********************************************}
unit TeeStore;
{$I TeeDefs.inc}
interface
Uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
Classes,
TeeProcs, TeEngine, Chart;
{ Read a Chart from a file (example: Chart1,'c:\demo.tee' ) }
Procedure LoadChartFromFile(Var AChart:TCustomChart; Const AFileName:String);
{ Write a Chart to a file (example: Chart1,'c:\demo.tee' ) }
Procedure SaveChartToFile(AChart:TCustomChart; Const AFileName:String;
IncludeData:Boolean=True;
TextFormat:Boolean=False);
{ The same using TStream components (good for BLOB fields, etc) }
Procedure LoadChartFromStream(Var AChart:TCustomChart; AStream:TStream);
Procedure SaveChartToStream(AChart:TCustomChart; AStream:TStream;
IncludeData:Boolean=True;
TextFormat:Boolean=False);
{ (Advanced) Read charts and check for errors }
{ return True if ok, False to stop loading }
type TProcTeeCheckError=function(const Message: string): Boolean of object;
Procedure LoadChartFromStreamCheck( Var AChart:TCustomChart;
AStream:TStream;
ACheckError:TProcTeeCheckError=nil;
// For compatibility with version 5 saved
// charts.
// Pass FALSE to skip past-reading
TryReadData:Boolean=True // 6.01
);
Procedure LoadChartFromFileCheck( Var AChart:TCustomChart;
Const AName:String;
ACheckError:TProcTeeCheckError
);
// Convert a binary *.tee file to text format
Procedure ConvertTeeFileToText(Const InputFile,OutputFile:String);
// Convert a text *.tee file to binary format
Procedure ConvertTeeFileToBinary(Const InputFile,OutputFile:String);
type
TSeriesData=class(TTeeExportData)
private
FIncludeColors : Boolean;
FIncludeIndex : Boolean;
FIncludeHeader : Boolean;
FIncludeLabels : Boolean;
FChart : TCustomChart;
FSeries : TChartSeries;
IFormat : TeeFormatFlag;
Procedure Prepare;
protected
Procedure GuessSeriesFormat; virtual;
Function MaxSeriesCount:Integer;
Function PointToString(Index:Integer):String; virtual;
public
Constructor Create(AChart:TCustomChart; ASeries:TChartSeries=nil); virtual;
Function AsString:String; override;
property Chart:TCustomChart read FChart write FChart;
property IncludeColors:Boolean read FIncludeColors write FIncludeColors default False;
property IncludeHeader:Boolean read FIncludeHeader write FIncludeHeader default False;
property IncludeIndex:Boolean read FIncludeIndex write FIncludeIndex default False;
property IncludeLabels:Boolean read FIncludeLabels write FIncludeLabels default True;
property Series:TChartSeries read FSeries write FSeries;
end;
TSeriesDataText=class(TSeriesData)
private
FTextDelimiter : {$IFDEF CLX}WideChar{$ELSE}Char{$ENDIF};
FTextQuotes : String;
FValueFormat : String;
protected
procedure GuessSeriesFormat; override; // 7.0
Function PointToString(Index:Integer):String; override;
public
Constructor Create(AChart:TCustomChart;
ASeries:TChartSeries=nil); override;
Function AsString:String; override;
property TextDelimiter:{$IFDEF CLX}WideChar{$ELSE}Char{$ENDIF}
read FTextDelimiter write FTextDelimiter default TeeTabDelimiter;
property TextQuotes:String read FTextQuotes write FTextQuotes; // 7.0
property ValueFormat:String read FValueFormat write FValueFormat; // 7.0 #1249
end;
TSeriesDataXML=class(TSeriesData)
private
FEncoding : String;
function DefaultEncoding:String;
function IsEncodingStored:Boolean;
public
Constructor Create(AChart:TCustomChart; ASeries:TChartSeries=nil); override;
Function AsString:String; override;
published
property Encoding:String read FEncoding write FEncoding stored IsEncodingStored; // 7.0
property IncludeHeader default True;
end;
TSeriesDataHTML=class(TSeriesData)
protected
Function PointToString(Index:Integer):String; override;
public
Function AsString:String; override;
end;
TSeriesDataXLS=class(TSeriesData)
public
Procedure SaveToStream(AStream:TStream); override;
end;
Const TeeTextLineSeparator= #13#10;
// Makes sure AFileName contains the ".tee" extension
Function TeeCheckExtension(Const AFileName:String):String;
implementation
Uses {$IFDEF CLX}
QGraphics, QClipbrd,
{$ELSE}
Graphics, Clipbrd,
{$ENDIF}
SysUtils,
TeCanvas, TeeConst;
Const MagicTeeFile =$3060;
{$IFDEF D7}
VersionTeeFile=$0157; { Delphi 7 }
{$ELSE}
{$IFDEF CLX}
VersionTeeFile=$0145; { Delphi 6 CLX / Kylix }
{$ELSE}
{$IFDEF D6}
VersionTeeFile=$0150; { Delphi 6 }
{$ELSE}
{$IFDEF C5}
VersionTeeFile=$0140; { C++ Builder 5 }
{$ELSE}
{$IFDEF D5}
VersionTeeFile=$0130; { Delphi 5 }
{$ELSE}
{$IFDEF C4}
VersionTeeFile=$0125; { C++ Builder 4 }
{$ELSE}
{$IFDEF D4}
VersionTeeFile=$0120; { Delphi 4 }
{$ELSE}
{$IFDEF C3}
VersionTeeFile=$0110; { C++ Builder 3 }
{$ELSE}
VersionTeeFile=$0100; { Delphi 3 }
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
type
TTeeFileHeader=Packed Record
Magic : Word; { secure checking }
Version : Word; { Chart file version }
end;
TSeriesAccess=class(TChartSeries);
// compatibility with previous versions saved *.tee files
Procedure ReadChartData(AStream:TStream; AChart:TCustomChart);
Var t : Integer;
begin { read each Series data }
for t:=0 to AChart.SeriesCount-1 do TSeriesAccess(AChart[t]).ReadData(AStream);
end;
{ Special reader to skip Delphi 3 or 4 new properties when
reading Charts in Delphi 1.0 or 2.0 }
type
TChartReader=class(TReader)
protected
procedure FindMethodEvent(Reader: TReader; const MethodName: string;
var Address: {$IFDEF CLR}TMethodCode{$ELSE}Pointer{$ENDIF};
var Error: Boolean);
function Error(const Message: string): Boolean; override;
public
CheckError:TProcTeeCheckError;
end;
function TChartReader.Error(const Message: string): Boolean;
begin
if Assigned(CheckError) then result:=CheckError(Message)
else result:=True;
end;
procedure TChartReader.FindMethodEvent(Reader: TReader; const MethodName: string;
var Address: {$IFDEF CLR}TMethodCode{$ELSE}Pointer{$ENDIF};
var Error: Boolean);
begin
Error:=False;
end;
Procedure ReadHeader(Stream:TStream; var Header: TTeeFileHeader);
begin
{$IFDEF CLR}
Stream.Read(Header.Magic,SizeOf(Header.Magic));
Stream.Read(Header.Version,SizeOf(Header.Version));
{$ELSE}
Stream.Read(Header,SizeOf(Header));
{$ENDIF}
end;
function TeeFileIsValid(Stream:TStream):Boolean;
var Pos : Integer;
Header : TTeeFileHeader;
begin
Pos := Stream.Position;
ReadHeader(Stream,Header);
{ check is a valid Tee file }
result:=Header.Magic=MagicTeeFile;
if not result then
result:={$IFDEF CLR}AnsiChar{$ELSE}Char{$ENDIF}(Header.Magic) in ['o','O'];
Stream.Position := Pos;
end;
function TeeFileIsBinary(Stream:TStream):Boolean;
var Pos : Integer;
Header : TTeeFileHeader;
begin
Pos := Stream.Position;
ReadHeader(Stream,Header);
{ check is a valid Tee file }
result:=Header.Magic=MagicTeeFile;
Stream.Position := Pos;
end;
Procedure TeeWriteHeader(AStream:TStream);
var Header : TTeeFileHeader;
begin
{ write file header, with "magic" number and version }
Header.Magic:=MagicTeeFile;
Header.Version:=VersionTeeFile;
{$IFDEF CLR}
AStream.Write(Header.Magic,SizeOf(Header.Magic));
AStream.Write(Header.Version,SizeOf(Header.Version));
{$ELSE}
AStream.Write(Header,SizeOf(Header));
{$ENDIF}
end;
Procedure ConvertTeeToBinary(SInput,SOutput:TStream);
begin
if TeeFileIsValid(SInput) then
begin
if not TeeFileIsBinary(SInput) then
begin
TeeWriteHeader(SOutput);
ObjectTextToBinary(SInput,SOutput);
end
else
SOutput.CopyFrom(SInput,SInput.Size);
end
else Raise ChartException.Create(TeeMsg_WrongTeeFileFormat); { 5.01 }
end;
Procedure ConvertTeeToText(SInput,SOutput:TStream);
var Header : TTeeFileHeader;
begin
if TeeFileIsValid(SInput) then
begin
if TeeFileIsBinary(SInput) then
begin
ReadHeader(SInput,Header);
ObjectBinaryToText(SInput,SOutput);
end
else SOutput.CopyFrom(SInput,SInput.Size);
end
else Raise ChartException.Create(TeeMsg_WrongTeeFileFormat); { 5.01 }
end;
{ Reads Series and Points from a Stream into a Chart }
Procedure LoadChartFromStreamCheck( Var AChart:TCustomChart;
AStream:TStream;
ACheckError:TProcTeeCheckError=nil;
TryReadData:Boolean=True);
var Reader : TChartReader;
tmp : TCustomChart;
tmpName : TComponentName;
DestStream : TStream;
Header : TTeeFileHeader;
begin
{ 5.01 commented: This allows saving more things to the AStream
before calling here.
AStream.Position:=0; <--- commented out
}
if AStream.Size=0 then
raise ChartException.Create(TeeMsg_EmptyTeeFile);
if TeeFileIsValid(AStream) then
begin
{ disable auto-repaint }
AChart.AutoRepaint:=False;
{ remove all child Series and Tools }
AChart.FreeAllSeries;
AChart.Tools.Clear;
DestStream:=AStream;
if not TeeFileIsBinary(AStream) then
begin
AStream:=TMemoryStream.Create;
ConvertTeeToBinary(DestStream,AStream);
AStream.Position:=0;
end;
ReadHeader(AStream,Header);
{ read the Chart, Series and Tools properties }
Reader:=TChartReader.Create(AStream, 4096);
try
Reader.OnFindMethod:=Reader.FindMethodEvent;
Reader.CheckError:=ACheckError;
tmp:=AChart;
try
tmpName:=tmp.Name; { 5.01 preserve the Chart Name }
Reader.ReadRootComponent(AChart);
finally
AChart:=tmp;
end;
if tmpName<>'' then
AChart.Name:=tmpName; { 5.01 set back the same Chart Name }
finally
Reader.Free;
end;
if Assigned(AChart) then
begin
// compatibility with previous versions saved *.tee files
// read the Series points
if TryReadData and (AStream.Size>AStream.Position) then
ReadChartData(AStream,AChart);
(*
{ change each Series ownership }
{ 5.01 Doing this breaks TeeFunction objects as DataSource !! }
if AChart.Owner<>nil then
for t:=0 to AChart.SeriesCount-1 do
begin
AChart[t].Owner.RemoveComponent(AChart[t]);
AChart.Owner.InsertComponent(AChart[t]);
end;
*)
{ restore AutoRepaint }
AChart.AutoRepaint:=True;
AChart.Invalidate;
end
else raise ChartException.Create(TeeMsg_InvalidTeeFile);
if DestStream<>AStream then AStream.Free;
end
else { is the Stream.Position maybe not zero ? }
raise ChartException.Create(TeeMsg_WrongTeeFileFormat);
end;
Procedure LoadChartFromStream(Var AChart:TCustomChart; AStream:TStream);
begin
LoadChartFromStreamCheck(AChart,AStream);
end;
Function TeeCheckExtension(Const AFileName:String):String;
begin // Append ".tee" to filename if the extension is missing
if ExtractFileExt(AFileName)='' then
result:=AFileName+'.'+TeeMsg_TeeExtension
else
result:=AFileName;
end;
Procedure LoadChartFromFileCheck( Var AChart:TCustomChart;
Const AName:String;
ACheckError:TProcTeeCheckError );
Var tmp : TFileStream;
begin
tmp:=TFileStream.Create(TeeCheckExtension(AName),fmOpenRead or fmShareDenyWrite);
try
LoadChartFromStreamCheck(AChart,tmp,ACheckError);
finally
tmp.Free;
end;
end;
Procedure LoadChartFromFile(Var AChart:TCustomChart; Const AFileName:String);
begin
LoadChartFromFileCheck(AChart,AFileName,nil);
end;
Procedure ConvertTeeFile(Const InputFile,OutputFile:String; ToText:Boolean);
var SInput : TFileStream;
SOutput : TFileStream;
begin
SInput:=TFileStream.Create(InputFile,fmOpenRead);
try
SOutput:=TFileStream.Create(OutputFile,fmCreate);
try
if ToText then ConvertTeeToText(SInput,SOutput)
else ConvertTeeToBinary(SInput,SOutput);
finally
SOutput.Free;
end;
finally
SInput.Free;
end;
end;
{ Create a text file from a binary *.tee file }
Procedure ConvertTeeFileToText(Const InputFile,OutputFile:String);
begin
ConvertTeeFile(InputFile,OutputFile,True);
end;
{ Create a binary file from a text *.tee file }
Procedure ConvertTeeFileToBinary(Const InputFile,OutputFile:String);
begin
ConvertTeeFile(InputFile,OutputFile,False);
end;
{
Procedure WriteChartData(AStream:TStream; AChart:TCustomChart);
Var t : Integer;
begin
for t:=0 to AChart.SeriesCount-1 do TSeriesAccess(AChart[t]).WriteData(AStream);
end;
}
{$IFDEF D5}
type
{$IFDEF CLR}
TWriterAccess=class(TWriter)
protected
procedure DoSetRoot(Value: TComponent);
end;
procedure TWriterAccess.DoSetRoot(Value: TComponent);
begin
SetRoot(Value);
end;
{$ELSE}
TWriterAccess=class(TWriter);
{$ENDIF}
{$ENDIF}
Procedure SaveChartToStream(AChart:TCustomChart; AStream:TStream;
IncludeData:Boolean=True;
TextFormat:Boolean=False);
var tmp : TCustomChart;
OldName : TComponentName;
{$IFDEF D5}
Writer : {$IFDEF CLR}TWriterAccess{$ELSE}TWriter{$ENDIF};
tmpOwner : TComponent;
{$ENDIF}
DestStream : TStream;
t : Integer;
tmpSeries : TChartSeries;
begin
DestStream:=AStream;
if TextFormat then AStream:=TMemoryStream.Create;
TeeWriteHeader(AStream);
{ write the Chart, Series and Tools properties }
tmp:=AChart;
if not (csDesigning in AChart.ComponentState) then
begin
OldName:=AChart.Name;
AChart.Name:='';
end;
for t:=0 to AChart.SeriesCount-1 do
begin
tmpSeries:=AChart[t];
if IncludeData then
TSeriesAccess(tmpSeries).ForceSaveData:=True
else
TSeriesAccess(tmpSeries).DontSaveData:=True;
end;
try
{$IFDEF D5}
Writer := {$IFDEF CLR}TWriterAccess{$ELSE}TWriter{$ENDIF}.Create(AStream, 4096);
try
tmpOwner:=AChart.Owner;
if not Assigned(tmpOwner) then tmpOwner:=AChart;
{$IFDEF CLR}
Writer.DoSetRoot(tmpOwner); { 5.01 }
{$ELSE}
TWriterAccess(Writer).SetRoot(tmpOwner); { 5.01 }
{$ENDIF}
Writer.WriteSignature;
Writer.WriteComponent(AChart);
finally
Writer.Free;
end;
{$ELSE}
AStream.WriteComponent(AChart);
{$ENDIF}
finally
for t:=0 to AChart.SeriesCount-1 do
begin
tmpSeries:=AChart[t];
TSeriesAccess(tmpSeries).ForceSaveData:=False;
TSeriesAccess(tmpSeries).DontSaveData:=False;
end;
end;
AChart:=tmp;
if not (csDesigning in AChart.ComponentState) then
AChart.Name:=OldName;
{ write the Series data points }
//if IncludeData then WriteChartData(AStream,AChart);
if TextFormat then
begin
AStream.Position:=0;
ConvertTeeToText(AStream,DestStream);
AStream.Free;
end;
end;
Procedure SaveChartToFile(AChart:TCustomChart; Const AFileName:String;
IncludeData:Boolean=True;
TextFormat:Boolean=False);
Var tmp : TFileStream;
begin
tmp:=TFileStream.Create(TeeCheckExtension(AFileName),fmCreate);
try
SaveChartToStream(AChart,tmp,IncludeData,TextFormat);
finally
tmp.Free;
end;
end;
Function ColorToHex(Color:TColor):String;
begin
with RGBValue(ColorToRGB(Color)) do
result:=Format('#%.2x%.2x%.2x',[rgbtRed,rgbtGreen,rgbtBlue]);
end;
{ TSeriesData }
Constructor TSeriesData.Create(AChart:TCustomChart; ASeries:TChartSeries=nil);
begin
inherited Create;
FChart:=AChart;
FSeries:=ASeries;
FIncludeLabels:=True;
end;
Procedure TSeriesData.GuessSeriesFormat;
var tmp : TChartSeries;
begin
if Assigned(FSeries) then tmp:=FSeries
else if FChart.SeriesCount>0 then tmp:=Chart[0]
else tmp:=nil;
if Assigned(tmp) then IFormat:=SeriesGuessContents(tmp);
end;
Procedure TSeriesData.Prepare;
begin
GuessSeriesFormat;
if not IncludeLabels then Exclude(IFormat,tfLabel);
if not IncludeColors then Exclude(IFormat,tfColor);
end;
Function TSeriesData.AsString:String;
Var tmp : Integer;
t : Integer;
begin
Prepare;
result:='';
tmp:=MaxSeriesCount;
for t:=0 to tmp-1 do result:=result+PointToString(t)+TeeTextLineSeparator;
end;
Function TSeriesData.MaxSeriesCount:Integer;
var t : Integer;
begin
if Assigned(FSeries) then result:=FSeries.Count
else
begin
result:=-1;
for t:=0 to FChart.SeriesCount-1 do
if (result=-1) or (FChart[t].Count>result) then
result:=FChart[t].Count;
end;
end;
function TSeriesData.PointToString(Index: Integer): String;
begin
result:='';
end;
{ TSeriesDataText }
Constructor TSeriesDataText.Create(AChart:TCustomChart;
ASeries: TChartSeries=nil); { 5.01 }
begin
inherited;
FTextDelimiter:=TeeTabDelimiter;
FTextQuotes:='';
end;
function TSeriesDataText.AsString: String;
Function Header:String;
Function HeaderSeries(ASeries:TChartSeries):String;
Procedure AddToResult(const S:String);
begin
if result='' then result:=TextQuotes+S+TextQuotes
else result:=result+TextDelimiter+TextQuotes+S+TextQuotes;
end;
var t : Integer;
begin
result:='';
With ASeries do
begin
if tfNoMandatory in IFormat then
result:=TextQuotes+NotMandatoryValueList.Name+TextQuotes;
if ValuesList.Count=2 then
AddToResult(SeriesTitleOrName(ASeries))
else
begin
AddToResult(MandatoryValueList.Name);
for t:=2 to ValuesList.Count-1 do
AddToResult(ValuesList[t].Name);
end;
end;
end;
var t : Integer;
begin
if IncludeIndex then result:=TextQuotes+TeeMsg_Index+TextQuotes
else result:='';
if tfLabel in IFormat then
begin
if result<>'' then result:=result+TextDelimiter;
result:=result+TextQuotes+TeeMsg_Text+TextQuotes;
end;
if tfColor in IFormat then
begin
if result<>'' then result:=result+TextDelimiter;
result:=result+TextQuotes+TeeMsg_Colors+TextQuotes;
end;
if result<>'' then result:=result+TextDelimiter;
if Assigned(Series) then result:=result+HeaderSeries(Series)
else
if Chart.SeriesCount>0 then
begin
result:=result+HeaderSeries(Chart[0]);
for t:=1 to Chart.SeriesCount-1 do
result:=result+TextDelimiter+HeaderSeries(Chart[t]);
end;
end;
Begin
Prepare;
if IncludeHeader then result:=Header+TeeTextLineSeparator
else result:='';
result:=result+inherited AsString+TeeTextLineSeparator;
end;
procedure TSeriesDataText.GuessSeriesFormat;
var t : Integer;
tmp : TeeFormatFlag;
begin
inherited;
if (not Assigned(Series)) and IncludeLabels and (not (tfLabel in IFormat)) then
for t:=0 to Chart.SeriesCount-1 do
begin
tmp:=SeriesGuessContents(Chart[t]);
if tfLabel in tmp then
begin
Include(IFormat, tfLabel);
break;
end;
end;
end;
function TSeriesDataText.PointToString(Index: Integer): String;
Procedure Add(Const St:String);
begin
if result='' then result:=St
else result:=result+TextDelimiter+St;
end;
var tmpNum : Integer;
Procedure DoSeries(ASeries:TChartSeries);
Function ValueToStr(ValueList:TChartValueList; Index:Integer):String; // 6.02
begin
if ASeries.Count>Index then
if ValueList.DateTime then
result:=TextQuotes+DateTimeToStr(ValueList.Value[Index])+TextQuotes
else
if FValueFormat='' then
result:=FloatToStr(ValueList.Value[Index])
else
result:=FormatFloat(FValueFormat,ValueList.Value[Index])
else
result:='';
end;
Function FirstSeriesLabel(Index:Integer):String; // 7.0
var t : Integer;
begin
result:='';
if Assigned(Series) then
begin
if Series.Count>Index then result:=Series.Labels[Index];
end
else
for t:=0 to Chart.SeriesCount-1 do
if Chart[t].Count>Index then
begin
result:=Chart[t].Labels[Index];
if result<>'' then break;
end;
if result<>'' then result:=TextQuotes+result+TextQuotes;
end;
Var tt : Integer;
begin
{ current number of exported Series }
Inc(tmpNum);
{ the point Label text, if exists, and only for first Series }
if (tmpNum=1) and (tfLabel in IFormat) then
Add(FirstSeriesLabel(Index));
{ the point Color, if exists, and only for first Series }
if (tmpNum=1) and (tfColor in IFormat) then
if ASeries.Count>Index then Add(ColorToHex(ASeries.ValueColor[Index]))
else Add(ColorToHex(clTeeColor));
{ the "X" point value, if exists }
if tfNoMandatory in IFormat then
Add(ValueToStr(ASeries.NotMandatoryValueList,Index));
{ the "Y" point value }
Add(ValueToStr(ASeries.MandatoryValueList,Index));
{ write the rest of values (always) }
for tt:=2 to ASeries.ValuesList.Count-1 do
result:=result+TextDelimiter+ValueToStr(ASeries.ValuesList[tt],Index);
end;
var t : Integer;
begin
{ Point number? }
if IncludeIndex then Str(Index,result) else result:='';
{ Export Series data }
tmpNum:=0;
if Assigned(Series) then DoSeries(Series)
else
for t:=0 to Chart.SeriesCount-1 do DoSeries(Chart[t]);
end;
{ TSeriesDataXML }
constructor TSeriesDataXML.Create(AChart: TCustomChart;
ASeries: TChartSeries);
begin
inherited;
FIncludeHeader:=True;
FEncoding:=DefaultEncoding;
end;
function TSeriesDataXML.DefaultEncoding:String;
begin
{$IFNDEF LINUX}
if SysLocale.PriLangID=LANG_JAPANESE then
result:='shift_jis'
else
{$ENDIF}
result:='ISO-8859-1';
end;
function TSeriesDataXML.IsEncodingStored:Boolean;
begin
result:=(Encoding<>'') and (Encoding<>DefaultEncoding);
end;
Function TSeriesDataXML.AsString:String;
Function SeriesPoints(ASeries:TChartSeries):String;
Function GetPointString(Index:Integer):String;
Procedure AddResult(Const St:String);
begin
if result='' then result:=St else result:=result+St;
end;
Function Get(AList:TChartValueList):String;
begin
with AList do
result:=' '+Name+'="'+FloatToStr(Value[Index])+'"';
end;
var tt : Integer;
begin
if IncludeIndex then result:='index="'+TeeStr(Index)+'"'
else result:='';
With ASeries do
begin
{ the point Label text, if exists }
if tfLabel in IFormat then result:=result+' text="'+Labels[Index]+'"';
{ the point Color, if exists }
if tfColor in IFormat then
result:=result+' color="'+ColorToHex(ValueColor[Index])+'"';
{ the "X" point value, if exists }
if tfNoMandatory in IFormat then AddResult(Get(NotMandatoryValueList));
{ the "Y" point value }
AddResult(Get(MandatoryValueList));
{ write the rest of values (always) }
for tt:=2 to ValuesList.Count-1 do result:=result+Get(ValuesList[tt]);
end;
end;
var t : Integer;
begin
result:='';
if ASeries.Count>0 then
for t:=0 to ASeries.Count-1 do
result:=result+'<point '+GetPointString(t)+'/>'+TeeTextLineSeparator;
end;
Function XMLSeries(ASeries:TChartSeries):String;
begin
result:=
'<series title="'+SeriesTitleOrName(ASeries)+'" type="'+
GetGallerySeriesName(ASeries)+'" color="'+
ColorToHex(ASeries.Color)+'">'+TeeTextLineSeparator+
'<points count="'+TeeStr(ASeries.Count)+'">'+TeeTextLineSeparator+
SeriesPoints(ASeries)+
'</points>'+TeeTextLineSeparator+
'</series>'+TeeTextLineSeparator+TeeTextLineSeparator;
end;
var t : Integer;
begin
Prepare; { 5.02 }
if IncludeHeader then
begin
result:='<?xml version="1.0"';
if Encoding<>'' then
result:=result+' encoding="'+Encoding+'"';
result:=result+'?>'+TeeTextLineSeparator;
end
else
result:='';
if Assigned(FSeries) then result:=result+XMLSeries(FSeries)
else
begin
result:=result+'<chart>'+TeeTextLineSeparator;
for t:=0 to FChart.SeriesCount-1 do result:=result+XMLSeries(FChart[t]);
result:=result+'</chart>';
end;
end;
{ TSeriesDataHTML }
function TSeriesDataHTML.AsString: String;
Function Header:String;
Function HeaderSeries(ASeries:TChartSeries):String;
Procedure AddCol(Const ColTitle:String);
begin
result:=result+'<td>'+ColTitle+'</td>'
end;
var t : Integer;
begin
result:='';
if tfLabel in IFormat then AddCol(TeeMsg_Text);
if tfColor in IFormat then AddCol(TeeMsg_Colors);
With ASeries do
begin
if tfNoMandatory in IFormat then AddCol(NotMandatoryValueList.Name);
if ValuesList.Count=2 then AddCol(SeriesTitleOrName(ASeries))
else
begin
AddCol(MandatoryValueList.Name);
for t:=2 to ValuesList.Count-1 do AddCol(ValuesList[t].Name);
end;
end;
end;
var t : Integer;
begin
result:='<tr>';
if IncludeIndex then result:=result+'<td>'+TeeMsg_Index+'</td>';
if Assigned(FSeries) then result:=result+HeaderSeries(FSeries)
else
for t:=0 to FChart.SeriesCount-1 do result:=result+HeaderSeries(FChart[t]);
result:=result+'</tr>';
end;
begin
Prepare;
result:='<table border="1">'+TeeTextLineSeparator;
if IncludeHeader then result:=result+Header+TeeTextLineSeparator;
result:=result+inherited AsString+TeeTextLineSeparator+'</table>';
end;
Function TSeriesDataHTML.PointToString(Index:Integer):String;
Function GetPointString:String;
Function GetPointStringSeries(ASeries:TChartSeries):String;
Function CellDouble(Const Value:Double):String;
begin
result:='<td>'+FloatToStr(Value)+'</td>';
end;
Const EmptyCell='<td></td>';
Var tt : Integer;
begin
result:='';
With ASeries do
if (Count-1)<Index then
begin
if tfLabel in IFormat then result:=result+EmptyCell;
if tfColor in IFormat then result:=result+EmptyCell;
if tfNoMandatory in IFormat then result:=result+EmptyCell;
result:=result+EmptyCell;
for tt:=2 to ValuesList.Count-1 do result:=result+EmptyCell;
end
else
begin
{ the point Label text, if exists }
if tfLabel in IFormat then result:=result+'<td>'+Labels[Index]+'</td>';
{ the point Label text, if exists }
if tfColor in IFormat then
result:=result+'<td>'+ColorToHex(ValueColor[Index])+'</td>';
{ the "X" point value, if exists }
if tfNoMandatory in IFormat then
result:=result+CellDouble(NotMandatoryValueList.Value[Index]);
{ the "Y" point value }
result:=result+CellDouble(MandatoryValueList.Value[Index]);
{ write the rest of values (always) }
for tt:=2 to ValuesList.Count-1 do
result:=result+CellDouble(ValuesList[tt].Value[Index]);
end;
end;
var t : Integer;
begin
if IncludeIndex then result:='<td>'+TeeStr(Index)+'</td>'
else result:='';
if Assigned(FSeries) then result:=result+GetPointStringSeries(FSeries)
else
for t:=0 to FChart.SeriesCount-1 do
result:=result+GetPointStringSeries(FChart[t])
end;
begin
result:='<tr>'+GetPointString+'</tr>';
end;
{ TSeriesDataXLS }
Procedure TSeriesDataXLS.SaveToStream(AStream:TStream);
var Buf : Array[0..4] of Word;
Row : Integer;
Col : Integer;
Procedure WriteBuf(Value,Size:Word);
begin
{$IFDEF CLR}
AStream.Write(Value);
AStream.Write(Size);
{$ELSE}
Buf[0]:=Value;
Buf[1]:=Size;
AStream.Write(Buf,2*SizeOf(Word));
{$ENDIF}
end;
Procedure WriteParams(Value,Size:Word);
Const Attr:Array[0..2] of Byte=(0,0,0);
begin
WriteBuf(Value,Size+2*SizeOf(Word)+SizeOf(Attr));
if IncludeHeader then WriteBuf(Row+1,Col)
else WriteBuf(Row,Col);
{$IFDEF CLR}
AStream.Write(Attr[0]);
AStream.Write(Attr[1]);
AStream.Write(Attr[2]);
{$ELSE}
AStream.Write(Attr,SizeOf(Attr));
{$ENDIF}
end;
procedure WriteDouble(Const Value:Double);
begin
WriteParams(3,SizeOf(Double));
{$IFDEF CLR}
AStream.Write(Value);
{$ELSE}
AStream.WriteBuffer(Value,SizeOf(Double));
{$ENDIF}
end;
procedure WriteText(Const Value:ShortString);
{$IFDEF CLR}
var l : Byte;
{$ENDIF}
begin
WriteParams(4,Length(Value)+1);
{$IFDEF CLR}
l:=Length(Value);
AStream.Write(l);
AStream.Write(BytesOf(Value),l);
{$ELSE}
AStream.Write(Value,Length(Value)+1)
{$ENDIF}
end;
procedure WriteNull;
begin
WriteParams(1,0);
end;
Procedure WriteHeaderSeries(ASeries:TChartSeries);
var tt : Integer;
begin
if tfLabel in IFormat then
begin
WriteText(TeeMsg_Text);
Inc(Col);
end;
if tfColor in IFormat then
begin
WriteText(TeeMsg_Colors);
Inc(Col);
end;
if tfNoMandatory in IFormat then
begin
WriteText(ASeries.NotMandatoryValueList.Name);
Inc(Col);
end;
for tt:=1 to ASeries.ValuesList.Count-1 do
begin
WriteText(ASeries.ValuesList[tt].Name);
Inc(Col);
end;
end;
Procedure WriteSeries(ASeries:TChartSeries);
var tt : Integer;
begin
if (ASeries.Count-1)<Row then
begin
if tfLabel in IFormat then
begin
WriteText('');
Inc(Col);
end;
if tfColor in IFormat then
begin
WriteText('');
Inc(Col);
end;
if tfNoMandatory in IFormat then
begin
WriteNull;
Inc(Col);
end;
for tt:=1 to ASeries.ValuesList.Count-1 do
begin
WriteNull;
Inc(Col);
end;
end
else
begin
if tfLabel in IFormat then
begin
WriteText(ASeries.Labels[Row]);
Inc(Col);
end;
if tfColor in IFormat then
begin
WriteText(ColorToHex(ASeries.ValueColor[Row]));
Inc(Col);
end;
if tfNoMandatory in IFormat then
begin
WriteDouble(ASeries.NotMandatoryValueList.Value[Row]);
Inc(Col);
end;
if ASeries.IsNull(Row) then
for tt:=1 to ASeries.ValuesList.Count-1 do
begin
WriteNull;
Inc(Col);
end
else
begin
WriteDouble(ASeries.MandatoryValueList.Value[Row]);
Inc(Col);
for tt:=2 to ASeries.ValuesList.Count-1 do
begin
WriteDouble(ASeries.ValuesList[tt].Value[Row]);
Inc(Col);
end;
end;
end;
end;
Const BeginExcel : Array[0..5] of Word=($809,8,0,$10,0,0);
EndExcel : Array[0..1] of Word=($A,0);
Var tt : Integer;
tmp : Integer;
begin
Prepare;
{$IFDEF CLR}
AStream.Write(BeginExcel[0]); { begin and BIF v5 }
AStream.Write(BeginExcel[1]);
AStream.Write(BeginExcel[2]);
AStream.Write(BeginExcel[3]);
AStream.Write(BeginExcel[4]);
AStream.Write(BeginExcel[5]);
{$ELSE}
AStream.WriteBuffer(BeginExcel,SizeOf(BeginExcel)); { begin and BIF v5 }
{$ENDIF}
WriteBuf($0200,5*SizeOf(Word)); { row x col }
Buf[0]:=0;
Buf[2]:=0;
Buf[3]:=0; { columns }
Buf[4]:=0;
Buf[1]:=MaxSeriesCount; { rows }
if IncludeHeader then Inc(Buf[1]);
if IncludeIndex then Inc(Buf[3]);
if Assigned(FSeries) then tmp:=1
else tmp:=FChart.SeriesCount;
if tfLabel in IFormat then Inc(Buf[3],tmp);
if tfColor in IFormat then Inc(Buf[3],tmp);
if tfNoMandatory in IFormat then Inc(Buf[3],tmp);
if Assigned(FSeries) then
Inc(Buf[3],FSeries.ValuesList.Count-1)
else
for Row:=0 to FChart.SeriesCount-1 do
Inc(Buf[3],FChart[Row].ValuesList.Count-1);
{$IFDEF CLR}
AStream.Write(Buf[0]);
AStream.Write(Buf[1]);
AStream.Write(Buf[2]);
AStream.Write(Buf[3]);
AStream.Write(Buf[4]);
{$ELSE}
AStream.Write(Buf,5*SizeOf(Word));
{$ENDIF}
if IncludeHeader then
begin
Row:=-1;
Col:=0;
if IncludeIndex then
begin
WriteText(TeeMsg_Index);
Inc(Col);
end;
if Assigned(FSeries) then WriteHeaderSeries(FSeries)
else
for tt:=0 to FChart.SeriesCount-1 do WriteHeaderSeries(FChart[tt]);
end;
for Row:=0 to MaxSeriesCount-1 do
begin
Col:=0;
if IncludeIndex then
begin
WriteDouble(Row);
Inc(Col);
end;
if Assigned(FSeries) then WriteSeries(FSeries)
else
for tt:=0 to FChart.SeriesCount-1 do WriteSeries(FChart[tt]);
end;
{$IFDEF CLR}
AStream.Write(EndExcel[0]); { end }
AStream.Write(EndExcel[1]); { end }
{$ELSE}
AStream.WriteBuffer(EndExcel,SizeOf(EndExcel)); { end }
{$ENDIF}
end;
{$IFNDEF TEEOCX}
type TChartChart=class(TChart) end;
TODBCChart=class(TChartChart) end;
initialization
RegisterClasses([TChartChart,TODBCChart]);
finalization
UnRegisterClasses([TChartChart,TODBCChart]); // 6.01
{$ENDIF}
end.
|
unit uMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, ImgList, Math;
const
MUR = $004080A0; // definition des couleurs
AIR = $0080C0E0;
VAISSEAU = $00999999;
type
TPointReal = record
x,y:real;
end;
TJoueur = record
pos:tpoint; // position réelle
Rpos:TPointReal; // position relative par rapport au bord de l'ecran
vecteur:tpoint; // vecteur de deplacement
vecteurinertie:TPointREal; // vecteur d'inertie
angle:integer; // angle du joueur
puissance,PuissanceImpulsion:real; // puissance accumulée du moteur
moteur:boolean; // moteur en route ou pas
touche:integer; // touche frappée
IndexTir:integer; // nombre de tir
end;
TTir = record
pos:tpoint; // position réelle
posR:TpointReal; // position relative par rapport au bord de l'ecran
Delta:TpointReal;
Actif:boolean; // tir actif ou pas
angle:integer;
Explosion:integer; // explosion ou pas
end;
TForm1 = class(TForm)
ImgVaisseau: TImageList; // contient les differentes images du vaisseau
Aire: TPaintBox;
Button2: TButton;
pbVecteur: TPaintBox;
Vue: TPaintBox;
imgExplosion: TImageList;
Timer1: TTimer;
GroupBox1: TGroupBox;
Button1: TButton;
Button3: TButton;
Edit1: TEdit;
Edit3: TEdit;
Fond: TImage;
Function DessinerVaisseau(pos:tpoint;angle:integer;Dessiner:boolean):boolean;
procedure Button1Click(Sender: TObject);
procedure Init;
procedure Button2Click(Sender: TObject);
procedure LireLesTouchesEnAttente;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure MajVecteur(dessiner:boolean);
procedure DessinerFond;
procedure DessinerVue;
function VerifierImpact:boolean;
procedure explosion(pos:tpoint);
procedure AjouterTir(StartPos:Tpoint);
procedure GererTir;
procedure DessinerTir(index:integer;Dessiner:boolean);
procedure Button3Click(Sender: TObject);
procedure UneExplosion(pos:tpoint;index:integer);
procedure Timer1Timer(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
Joueur:Tjoueur;
Touche:integer;
Stop:boolean;
AirePos:tpoint;
Tir:array[1..30] of Ttir;
end;
var
Form1: TForm1;
Function StartHook :Boolean; stdcall; external 'DllHook.dll'; // gere l'appuie sur
Function StopHook :Boolean; stdcall; external 'DllHook.dll';
Function GetNextKey(Var Key,ID:Integer) :Boolean; stdcall; external 'DllHook.dll'; // les touches
implementation
{$R *.DFM}
procedure Tform1.Init;
var
i:integer;
begin
for i:=1 to 30 do
begin
Tir[i].pos.x:=0;
Tir[i].pos.y:=0;
Tir[i].posR.x:=0; // mie à Z des tirs
Tir[i].posR.y:=0;
Tir[i].Delta.x:=0;
Tir[i].Delta.y:=0;
Tir[i].Actif:=false;
Tir[i].angle:=0;
Tir[i].Explosion:=-1;
end;
with Aire.canvas do
begin
pen.Color:=clblack;
brush.color:=clblack; // efface l'aire de dessin
rectangle(0,0,Aire.width,Aire.height);
end;
with pbVecteur.canvas do
begin
pen.Color:=clBlack;
brush.color:=clBlack;
rectangle(0,0,PbVecteur.width,PbVecteur.height); // efface l'affichage du vecteur
pen.Color:=clLime;
brush.color:=clBlack;
ellipse(0,0,PbVecteur.width,PbVecteur.height);
end;
Joueur.pos:=point(300,300);
Joueur.Rpos.X:=300;
Joueur.Rpos.Y:=300;
Joueur.vecteur:=point(0,0);
Joueur.angle:=0; // mise à Z des param du joueur
Joueur.puissance:=1;
Joueur.vecteurinertie.x:=0;
Joueur.vecteurinertie.y:=0;
Joueur.IndexTir:=0;
AirePos:=point(1,1);
DessinerFond; // dessine le fond
end;
Function TForm1.DessinerVaisseau(pos:tpoint;angle:integer;Dessiner:boolean):boolean;
var
Srect,Drect:trect;
x,y:real;
begin
DRect:=rect(pos.x,pos.y,pos.x+60,pos.y+60);
pos.x:=pos.x-Airepos.x; // definition de la position du joueur dans l'aire de dessin
Pos.y:=pos.y-Airepos.Y;
if dessiner=true then // si on dessine le joueur
begin
//imgVaisseau.DrawingStyle:=
imgVaisseau.Draw(Aire.canvas,pos.x,pos.y,floor(angle/15)); // dessine le vaisseau en fonction de l'angle
if joueur.moteur=true then // si le moteur est allumé
begin
y:=30+cos(Joueur.angle/360*2*PI)*16; // on calcule la poussée donée par le moteur
x:=30-sin(Joueur.angle/360*2*PI)*16;
with aire.canvas do
begin
pen.color:=clred; // et on dessine le feu du moteur
brush.color:=clred;
rectangle(floor(pos.x+x-2),floor(pos.y+y-2),floor(pos.x+x+2),floor(pos.y+y+2));
end;
end;
end
else // si on efface le joueur
begin
Srect:=rect(pos.x,pos.y,pos.x+60,pos.y+60); // on copie la zone vierge du fond
Aire.canvas.CopyRect(Srect,Fond.canvas,DRect); // sur l'aire de dessin
//Aire.Canvas.Rectangle(pos.x,pos.y,pos.x+60,pos.y+60);
end;
if dessiner=true then
result:=VerifierImpact // si on dessine le joueur alors il faut verifier si il y a impact
else
result:=false;
end;
function TForm1.VerifierImpact:boolean;
var
x,y:integer;
Image1:tbitmap;
oRect:Trect;
begin
image1:=Tbitmap.Create; // mise en cache du dessin actuel du vaisseau
Image1.width:=60;
Image1.height:=60;
oRect := Rect(0,0, Image1.Width, Image1.Height);
Image1.canvas.brush.Color:=clblack;
Image1.Canvas.FillRect(oRect);
//imgVaisseau.GetBitmap(floor(Joueur.angle/15),Image1);
imgvaisseau.Draw(Image1.canvas,0,0,floor(Joueur.angle/15),true);
//application.processmessages;
for x:=1 to 60 do // pour chaque pixel du vaisseau
for y:=1 to 60 do
begin
if Fond.Canvas.Pixels[x+Joueur.pos.x,y+Joueur.pos.y]=MUR then // si on est sur un mur
begin
if Image1.Canvas.Pixels[x,y]=VAISSEAU then // et que c'est le vaisseau
begin
result:=true; // alors le vaisseau touche le mur
edit3.text:='Touche'; // on est mort
exit;
end
else
begin
Edit3.text:='Sauf';
end;
end;
// application.processmessages;
end;
result:=false;
//image1.free;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
x,x2,y:integer;
begin
for x:=0 to 23 do
begin
y:=40;
x2:=x*50;
if x>10 then
begin
y:=100;
x2:=x*50-(550);
end;
if x>20 then
begin
y:=160;
x2:=x*50-(1050);
end;
DessinerVaisseau(point(x2,y),x*15,true);
end;
end;
procedure TForm1.Button2Click(Sender: TObject); // moteur principal du jeu
var
x,y:real;
begin
init; // debut initialisation
stop:=false;
x:=0;
y:=0;
Joueur.touche:=0;
dessinerFOnd; // Fin initialisation
while stop=false do
begin
LireLesTouchesEnAttente; // on lit les touches frappées depuis la derniere boucle
MajVecteur(false); // maj affichage vecteur de poussée
DessinerVaisseau(joueur.pos,Joueur.angle,false); // effacer vaisseau
case joueur.touche of
25:dec(Joueur.angle,15); // selon touche changer angle du vaisseau
27:inc(Joueur.angle,15);
26:begin
if timer1.enabled=false then
begin
AjouterTir(Joueur.pos);
timer1.enabled:=true;
end;
end;
end;
if joueur.angle=-15 then Joueur.angle:=345; // correction de l'angle
if joueur.angle=360 then Joueur.angle:=0; // si <0 ou >360
GererTir;
if Joueur.moteur=true then // si les moteurs sont en route
begin
Joueur.puissance:=Joueur.puissance+0.5; // la puissance augmente
y:=cos(Joueur.angle/360*2*PI)*Joueur.puissance; // calcul de la force selon X et y
x:=sin(Joueur.angle/360*2*PI)*Joueur.puissance; // donné par cette puissance = impulsion
Joueur.vecteurinertie.x:=Joueur.vecteurinertie.x+x; // ajout de l'impulsion
Joueur.vecteurinertie.y:=Joueur.vecteurinertie.y-y; // au vecteur de deplacement du vaisseau
Joueur.Rpos.X:=Joueur.Rpos.X+Joueur.vecteurinertie.x; // puis deplacement
Joueur.Rpos.Y:=Joueur.Rpos.Y+Joueur.vecteurinertie.y; // du
Joueur.pos:=point(floor(Joueur.Rpos.X),floor(Joueur.Rpos.Y)); // vaisseau
end
else
begin // si les moteurs ne sont PAS en route
Joueur.puissance:=Joueur.puissance-1; // la puissance diminue
Joueur.Rpos.X:=Joueur.Rpos.X+Joueur.vecteurinertie.x; // on deplace le vaisseau
Joueur.Rpos.Y:=Joueur.Rpos.Y+Joueur.vecteurinertie.y; // selon son vecteur de dpl
Joueur.pos:=point(floor(Joueur.Rpos.X),floor(Joueur.Rpos.Y));
end;
Joueur.vecteurinertie.y:=Joueur.vecteurinertie.y+0.2; // l'inertie verticale est augmentée
// pour simuler la gravité
if Joueur.puissance<0 then Joueur.puissance:=0; // correction de la puissance
if Joueur.puissance>1 then Joueur.puissance:=1;
DessinerFond; // redessine le fond en fonction place du joueur
if DessinerVaisseau(joueur.pos,Joueur.angle,true)=true then // si impact du joueur contre mur
begin
explosion(Joueur.pos);
exit;
end;
MajVecteur(true); // maj du dessin du vecteur
//edit1.text:=format('%d %d',[Joueur.pos.X,Joueur.pos.y]);
application.processmessages;
sleep(50);
end;
end;
procedure Tform1.MajVecteur(dessiner:boolean); // dessine un trait partant du centre du cercle
var // en fonction de l'angle de poussée du vaisseau
x,y:real; // dans la paintbox vecteur
Impulsion:Tpointreal;
begin
y:=cos(Joueur.angle/360*2*PI);
x:=sin(Joueur.angle/360*2*PI);
Impulsion.x:=sin(Joueur.vecteurinertie.x/360*2*PI);
Impulsion.y:=sin(Joueur.vecteurinertie.y/360*2*PI);
with pbVecteur.canvas do
begin
pen.Color:=clLime;
brush.color:=clBlack;
brush.style:=bsclear;
ellipse(0,0,PbVecteur.width,PbVecteur.height);
brush.Style:=bssolid;
if dessiner=true then
begin
Pen.color:=clred;
brush.color:=clred;
end
else
begin
Pen.color:=clblack;
brush.color:=clblack;
end;
moveto(75,75);
lineto(floor(75+x*75),floor(75-y*75));
if dessiner=true then
begin
Pen.color:=cllime;
brush.color:=cllime;
end
else
begin
Pen.color:=clblack;
brush.color:=clblack;
end;
moveto(75,75);
lineto(floor(75+Joueur.vecteurinertie.x*75),floor(75+Joueur.vecteurinertie.y*75));
end;
//Edit2.text:=format('%.2f %.2f',[x,y]);
end;
procedure Tform1.LireLesTouchesEnAttente;
var
key,id:integer;
begin
if stop=true then exit;
//TimerHook.enabled:=false;
while getnextkey(key,id) do // lire la prochaine touche en attente
begin
if inttohex(key,8)='00000010' then //shift appuyé
Joueur.moteur:=true; // donc on allume le moteur
if inttohex(key,8)='80000010' then // sinon on l'éteind
begin
//elan:=floor((TabPuissance[0]/15)*sin(Joueur.angle*2*PI/360));
Joueur.moteur:=false;
end;
if inttohex(Key,8)='0000001B' then Stop:=true;
if inttohex(Key,8)='00000027' then Joueur.touche:=27; //fleche droite
if inttohex(Key,8)='00000044' then Joueur.touche:=27; //touche D
if inttohex(Key,8)='00000025' then Joueur.touche:=25; //fleche gauche
if inttohex(Key,8)='00000051' then Joueur.touche:=25; //touche Q
if inttohex(Key,8)='00000026' then Joueur.touche:=26; // fleche haut
if inttohex(Key,8)='0000005A' then Joueur.touche:=26; // touche Z
if inttohex(Key,8)='80000027' then Joueur.touche:=0; //fleche droite relachée
if inttohex(Key,8)='80000044' then Joueur.touche:=0; //touche D relachée
if inttohex(Key,8)='80000025' then Joueur.touche:=0; //fleche gauche relachée
if inttohex(Key,8)='80000051' then Joueur.touche:=0; //touche Q realchée
if inttohex(Key,8)='80000026' then Joueur.touche:=0; //fleche haut relachée
if inttohex(Key,8)='8000005A' then Joueur.touche:=0; // touche Z relachée
Edit1.text:=inttohex(key,8);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
//imgVaisseau.BkColor:=clnone;
//imgexplosion.BkColor:=clnone;
//imgexplosion.DrawingStyle:=dstransparent;
fond.Picture.LoadFromFile('.\bitmap\Fond.bmp'); // chargement du niveau
stop:=true;
StartHook; // mise en route du Hook clavier
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
stop:=true; // forcer la fin de la boucle moteur en cas de sortie sans mort
stophook; // arret hook clavier
end;
procedure TForm1.DessinerFond; // dessine le fond dans l'aire de jeu
var // focalisé sur la zone visible
Srect,Drect:trect;
bool,bool2:boolean;
begin
//Joueur.pos.y-(floor(Joueur.pos.y/600)*600)>550 then
//Edit2.text:=format('%d',[Joueur.pos.y-(floor(Joueur.pos.y/600)*600)]);
//Bool2:=Joueur.pos.x-(floor(Joueur.pos.x/600)*600)>550;
Srect.top:=floor(Joueur.pos.y/600)*600; // chargement du fond du niveau
Srect.Left:=floor(Joueur.pos.x/600)*600; // correspondant à l'endroit
Srect.Right:=Srect.Left+600; // ou se trouve le joueur
Srect.Bottom:=Srect.Top+600; // en memoire
if (Srect.top<>Airepos.y) or
(Srect.Left<>AirePos.x) then
begin
Drect:=Rect(0,0,600,600); // destination aire de jeu
with Aire.canvas do
begin
copyrect(Drect,Fond.canvas,Srect); // copie de la zone dans l'aire de jeux
end;
AirePos.x:=Srect.Left; // mise à jour des coordonnées de l'aire de jeux
AirePos.y:=Srect.Top;
DessinerVue; // dessiner l'aire de jeu
end;
AirePos.x:=Srect.Left;
AirePos.y:=Srect.Top;
//Edit1.text:=format('%d %d',[Airepos.x,Airepos.y]);
end;
procedure Tform1.DessinerVue; // dessine le fond du niveau complet dans l'aperçu
var
coord:trect;
begin
coord:=rect(0,0,Vue.width,vue.height);
with vue.canvas do
begin
StretchDraw(coord,FOnd.Picture.Bitmap);
pen.color:=clred;
brush.style:=bsclear;
rectangle(floor(Airepos.x/10),floor(AIrepos.y/10),floor(Airepos.x/10+60),floor(airepos.y/10+60));
end;
end;
procedure TForm1.explosion(pos:Tpoint); // dessine l'explosion du vaisseau
var
i:integer;
Srect,Drect:trect;
begin
Drect:=rect(pos.x-Airepos.x,pos.y-Airepos.y,pos.x-Airepos.x+60,pos.y-Airepos.y+60);
Srect:=rect(pos.x,pos.y,pos.x+60,pos.y+60);
for i:=0 to 19 do // l'explosion est découpée en 20 images
begin
with Aire.canvas do
begin
Copyrect(Drect,fond.canvas,Srect);
end;
imgExplosion.draw(Aire.canvas,pos.x-Airepos.x,pos.y-AIrepos.y,i,true);// que l'on dessine successivement
sleep(50); // ou se trouve le joueur
end;
end;
procedure Tform1.UneExplosion(pos:tpoint;index:integer); //charge une des 20 images de l'explosion
var // du joueur
Srect,Drect:trect;
begin
Drect:=rect(pos.x-Airepos.x,pos.y-Airepos.y,pos.x-Airepos.x+60,pos.y-Airepos.y+60);
Srect:=rect(pos.x,pos.y,pos.x+60,pos.y+60);
with Aire.canvas do
begin
Copyrect(Drect,fond.canvas,Srect); // lire en mémoire l'image concernée
end;
imgExplosion.draw(Aire.canvas,pos.x-Airepos.x,pos.y-AIrepos.y,index,true); // dessiner
end;
procedure Tform1.AjouterTir(StartPos:Tpoint); // rajouter un tir dans la liste
var
i:integer;
bool:boolean;
begin
i:=1;
bool:=false;
while (i<30) and (bool=false) do // faire le tour des 30 tirs possibles
begin
if Tir[i].Actif=false // pour un trouver qui n'est pas utilisé
then bool:=true
else
inc(i);
end;
if bool=true then // on a trouvé un tir non utilisé
begin // alors on le met en route
Tir[i].posR.x:=Startpos.x;
Tir[i].posR.y:=Startpos.y; // en notant sa position
Tir[i].Delta.x:=sin(Joueur.angle/360*2*PI); // et sa direction
Tir[i].Delta.y:=cos(Joueur.angle/360*2*PI);
Tir[i].pos.x:=floor(Startpos.x); // et son point de départ
Tir[i].pos.y:=floor(Startpos.y);
Tir[i].angle:=Joueur.angle; // et son angle
Tir[i].Actif:=true; // on le défini comme actif
end;
end;
procedure TForm1.GererTir; //gestion du déplacement des tirs
var
i:integer;
begin
for i:=1 to 30 do
begin
if (tir[i].Actif=true) and (tir[i].Explosion=-1) then // pour chaque tir actif
begin // et pas en train d'exploser
DessinerTir(i,false); // on efface le tir de son ancienne position
Tir[i].posR.x:=Tir[i].posR.x+10*Tir[i].Delta.x; // on le deplace selon x et y
Tir[i].posR.y:=Tir[i].posR.y-10*Tir[i].Delta.y;
Tir[i].pos.x:=floor(Tir[i].posR.x);
Tir[i].pos.y:=floor(Tir[i].posR.y);
DessinerTir(i,true); // et on dessine sa nouvelle position
end;
if tir[i].Explosion<>-1 then // si le tir explose
begin
UneExplosion(tir[i].pos,Tir[i].explosion); // on dessine son explosion en cours
inc(tir[i].explosion); // au prochain passage on dessine l'image d'explosion suivante
if tir[i].Explosion>19 then // si on a affiché toute les images
begin
tir[i].Actif:=false; // on desactive ce tir
tir[i].Explosion:=-1;
end;
end;
end;
end;
procedure TForm1.DessinerTir(index:integer;dessiner:boolean);
var
pos:tpoint;
begin
pos.x:=floor(Tir[index].Pos.x+30+sin(Tir[index].angle/360*2*PI)*16); // calcul de la pos réélle du tir
pos.y:=floor(Tir[index].Pos.y+30-cos(Tir[index].angle/360*2*PI)*16);
if Fond.Canvas.Pixels[pos.x,pos.y]=MUR then // si le tir touche le décor
begin
//explosion(point(pos.x-30,pos.y-30));
//tir[index].Actif:=false;
tir[index].Explosion:=0; // il est terminé
dessiner:=false;
end;
pos.x:=Pos.x-AirePOs.x;
pos.y:=Pos.y-AirePOs.y;
with Aire.canvas do
begin
brush.style:=bssolid;
if dessiner=true then // si on dessine c'est du rouge
begin
pen.color:=clred;
brush.color:=clred;
end
else // si on efface c'est couleur AIR
begin
pen.color:=AIR;
brush.color:=AIr;
end;
rectangle(Pos.x-2,Pos.y-2,Pos.x+2,Pos.y+2); // on dessine
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
fond.Picture.LoadFromFile('.\bitmap\Fond.bmp');
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
timer1.Enabled:=false;
end;
end.
|
program HelloWorld; // プログラム名をつける
(*
comment
*)
{
変数:大文字小文字の区別なし
}
const
author = 'someya';
var
// message: string;
message: string = 'hello!';
begin
// message := 'hello';
// writeln : 改行付き
// writeln('hello world');
//author := 'xxxx'; コンパイルエラー
writeln(message);
writeln(author);
end. // ピリオド
|
unit SIP_Status;
interface
uses SyncObjs,Classes;
type
TSIPStatus=class(TCriticalSection)
private
FStatus,FEvent,FScript,FAction:array of String;
public
procedure Status(ID:Integer;const Event,Script,Action,Status:String);
function Get:String;
constructor Create(ChannelCount:Integer);
end;
implementation
uses SysUtils, Util;
{ TSIPStatus }
constructor TSIPStatus.Create;
begin
inherited Create;
SetLength(FStatus,ChannelCount);
SetLength(FEvent,ChannelCount);
SetLength(FScript,ChannelCount);
SetLength(FAction,ChannelCount);
end;
procedure TSIPStatus.Status(ID: Integer; const Event,Script,Action,Status:String);
begin
Acquire;
try
ID:=ID-1;
if (ID>=0) and (ID<Length(FStatus)) then
begin
FEvent[ID]:=Event;
FScript[ID]:=Script;
FAction[ID]:=Action;
FStatus[ID]:=Status;
end
else
raise Exception.Create('Invalid status ID='+intTostr(ID)+' (status = '+Status+')');
finally
Release;
end;
end;
function TSIPStatus.Get: String;
var R:String;
procedure Add(const S:String);
begin
if R='' then R:=S else
if S<>'' then R:=R+','+S;
end;
var I,J:Integer;
begin
Result:='{}';
R:='';
J:=Length(FStatus) div 2;
Acquire;
try
for I := 0 to Length(FStatus)-1 do
begin
if I=J then
begin
Result:='{chanlo:['+R+']';
R:='';
end;
Add(Format('{channel:%d,status:%s,event:%s,script:%s,action:%s}',[
I+1,
StrEscape(FStatus[I]),
StrEscape(FEvent[I]),
StrEscape(FScript[I]),
StrEscape(FAction[I])
]));
end;
Result:=Result+',chanhi:['+R+']}'
finally
Release;
end;
end;
end.
|
unit UnitMainFormDaf;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Menus, Vcl.ComCtrls,
Vcl.StdCtrls, Vcl.ToolWin, Vcl.Imaging.pngimage, System.ImageList,
server_data_types, Vcl.ImgList, UnitFormProductData;
type
EHostApplicationPanic = class(Exception);
TMainFormDaf = class(TForm)
ImageList4: TImageList;
PageControlMain: TPageControl;
TabSheetParty: TTabSheet;
TabSheetConsole: TTabSheet;
PanelMessageBox: TPanel;
ImageError: TImage;
ImageInfo: TImage;
PanelMessageBoxTitle: TPanel;
ToolBar2: TToolBar;
ToolButton3: TToolButton;
RichEditlMessageBoxText: TRichEdit;
PanelTop: TPanel;
LabelStatusTop: TLabel;
ToolBar3: TToolBar;
ToolButton1: TToolButton;
ToolButton4: TToolButton;
PanelDelay: TPanel;
LabelDelayElepsedTime: TLabel;
LabelProgress: TLabel;
ToolBar6: TToolBar;
ToolButtonStop: TToolButton;
Panel2: TPanel;
ProgressBar1: TProgressBar;
ToolBarStop: TToolBar;
ToolButton2: TToolButton;
TimerPerforming: TTimer;
LabelStatusBottom1: TLabel;
TabSheetData: TTabSheet;
MainMenu1: TMainMenu;
N2: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
N5: TMenuItem;
MODBUS1: TMenuItem;
N1: TMenuItem;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure PageControlMainDrawTab(Control: TCustomTabControl;
TabIndex: Integer; const Rect: TRect; Active: Boolean);
procedure PageControlMainChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ToolButton4Click(Sender: TObject);
procedure TimerPerformingTimer(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure ToolButton2Click(Sender: TObject);
procedure ToolButton3Click(Sender: TObject);
procedure ToolButtonStopClick(Sender: TObject);
procedure ToolButton1Click(Sender: TObject);
procedure N3Click(Sender: TObject);
procedure N4Click(Sender: TObject);
procedure MODBUS1Click(Sender: TObject);
procedure N1Click(Sender: TObject);
private
{ Private declarations }
procedure AppException(Sender: TObject; E: Exception);
procedure HandleCopydata(var Message: TMessage); message WM_COPYDATA;
procedure SetupDelay(i: TDelayInfo);
procedure OnWorkComplete(x: TWorkResultInfo);
procedure OnWarning(content: string);
procedure SetAddresClick(Sender: TObject);
public
{ Public declarations }
end;
var
MainFormDaf: TMainFormDaf;
implementation
{$R *.dfm}
uses Vcl.FileCtrl, UnitFormLastParty, vclutils, JclDebug, ioutils, app,
services, UnitFormAppConfig, notify_services, HttpRpcClient, superobject,
dateutils, math, HttpExceptions, UnitFormData,
stringgridutils, UnitFormModalMessage, UnitFormEditText, UnitFormDataTable,
UnitFormSelectWorksDlg, UnitFormConsole, UnitFormModbus;
function color_work_result(r: Integer): Tcolor;
begin
if r = 0 then
exit(clNavy)
else if r = 1 then
exit(clMaroon)
else
exit(clRed);
end;
procedure TMainFormDaf.FormCreate(Sender: TObject);
begin
Application.OnException := AppException;
LabelStatusTop.Caption := '';
PanelMessageBox.Width := 700;
PanelMessageBox.Height := 350;
LabelStatusBottom1.Caption := '';
end;
procedure TMainFormDaf.FormClose(Sender: TObject; var Action: TCloseAction);
var
wp: WINDOWPLACEMENT;
fs: TFileStream;
begin
NotifyServices_SetEnabled(false);
HttpRpcClient.TIMEOUT_CONNECT := 10;
TRunnerSvc.Cancel;
// notify_services.CloseServerWindow;
fs := TFileStream.Create(ChangeFileExt(paramstr(0), '.position'),
fmOpenWrite or fmCreate);
if not GetWindowPlacement(Handle, wp) then
raise Exception.Create('GetWindowPlacement: false');
fs.Write(wp, SizeOf(wp));
fs.Free;
end;
procedure TMainFormDaf.FormShow(Sender: TObject);
var
FileName: String;
wp: WINDOWPLACEMENT;
fs: TFileStream;
begin
FileName := ChangeFileExt(paramstr(0), '.position');
if FileExists(FileName) then
begin
fs := TFileStream.Create(FileName, fmOpenRead);
fs.Read(wp, SizeOf(wp));
fs.Free;
SetWindowPlacement(Handle, wp);
end;
with FormProductData do
begin
Font.Assign(self.Font);
BorderStyle := bsNone;
Align := alClient;
end;
with FormLastParty do
begin
Font.Assign(self.Font);
Parent := TabSheetParty;
BorderStyle := bsNone;
Align := alClient;
reload_data;
Show;
end;
with FormData do
begin
Font.Assign(self.Font);
Parent := TabSheetData;
BorderStyle := bsNone;
Align := alClient;
Show;
// FetchYearsMonths;
end;
with FormConsole do
begin
Font.Assign(self.Font);
Parent := TabSheetConsole;
BorderStyle := bsNone;
Align := alClient;
// FFileName := ExtractFileDir(paramstr(0)) + '\elco.log';
FFileName := '';
Show;
end;
with FormModbus do
begin
Font.Assign(self.Font);
Parent := TabSheetParty;
BorderStyle := bsNone;
Align := alRight;
// FFileName := ExtractFileDir(paramstr(0)) + '\elco.log';
Hide;
end;
PageControlMain.ActivePageIndex := 0;
SetOnWorkStarted(
procedure(s: string)
begin
PanelMessageBox.Hide;
ToolBarStop.Show;
LabelStatusTop.Caption := TimeToStr(now) + ' ' + s;
TimerPerforming.Enabled := true;
LabelStatusBottom1.Caption := '';
end);
SetOnWorkComplete(OnWorkComplete);
SetOnPlaceConnection(FormLastParty.OnProductConnection);
SetOnDelay(SetupDelay);
SetOnEndDelay(
procedure(s: string)
begin
PanelDelay.Hide;
end);
SetOnWarning(OnWarning);
SetOnStatus(
procedure(s: string)
begin
LabelStatusTop.Caption := TimeToStr(now) + ' ' + s;
end);
SetOnProductDataChanged(FormProductData.OnProductDataChanged);
SetOnWriteConsole(
procedure(s: String)
begin
FormConsole.NewLine(s);
if not TabSheetConsole.TabVisible then
TabSheetConsole.TabVisible := true;
Application.ProcessMessages;
end);
TRunnerSvc.Cancel;
NotifyServices_SetEnabled(true);
end;
procedure TMainFormDaf.FormResize(Sender: TObject);
begin
if PanelMessageBox.Visible then
begin
PanelMessageBox.Left := ClientWidth div 2 - PanelMessageBox.Width div 2;
PanelMessageBox.Top := ClientHeight div 2 -
PanelMessageBox.Height div 2;
end;
end;
procedure TMainFormDaf.PageControlMainChange(Sender: TObject);
var
PageControl: TPageControl;
begin
PageControl := Sender as TPageControl;
PageControl.Repaint;
PanelMessageBox.Hide;
if PageControl.ActivePage = TabSheetData then
begin
// FormProductData.Parent :=FormData;
FormData.FetchYearsMonths;
end
else if PageControl.ActivePage = TabSheetParty then
begin
FormLastParty.setup_products;
end;
end;
procedure TMainFormDaf.PageControlMainDrawTab(Control: TCustomTabControl;
TabIndex: Integer; const Rect: TRect; Active: Boolean);
begin
PageControl_DrawVerticalTab(Control, TabIndex, Rect, Active);
end;
procedure TMainFormDaf.TimerPerformingTimer(Sender: TObject);
var
v: Integer;
begin
with LabelStatusTop.Font do
if Color = clRed then
Color := clblue
else
Color := clRed;
end;
procedure TMainFormDaf.ToolButton1Click(Sender: TObject);
begin
FormEditText.Show;
end;
procedure TMainFormDaf.ToolButton2Click(Sender: TObject);
begin
TRunnerSvc.Cancel;
end;
procedure TMainFormDaf.ToolButton3Click(Sender: TObject);
begin
PanelMessageBox.Hide;
end;
procedure TMainFormDaf.ToolButton4Click(Sender: TObject);
begin
with ToolButton4 do
with ClientToScreen(Point(0, Height)) do
begin
with FormAppconfig do
begin
Left := x - 5 - Width;
Top := Y + 5;
Show;
end;
end;
end;
procedure TMainFormDaf.ToolButtonStopClick(Sender: TObject);
begin
TRunnerSvc.SkipDelay;
end;
procedure TMainFormDaf.HandleCopydata(var Message: TMessage);
begin
notify_services.HandleCopydata(Message);
end;
procedure TMainFormDaf.MODBUS1Click(Sender: TObject);
begin
FormModbus.Visible := not FormModbus.Visible;
end;
procedure TMainFormDaf.N1Click(Sender: TObject);
begin
TPartySvc.Report();
end;
procedure TMainFormDaf.N3Click(Sender: TObject);
begin
TThread.CreateAnonymousThread(TRunnerSvc.RunReadVars).Start;
end;
procedure TMainFormDaf.N4Click(Sender: TObject);
begin
FormSelectWorksDlg.Position := poScreenCenter;
FormSelectWorksDlg.Show;
ShowWindow(FormSelectWorksDlg.Handle, SW_RESTORE);
end;
procedure TMainFormDaf.AppException(Sender: TObject; E: Exception);
var
stackList: TJclStackInfoList; // JclDebug.pas
sl: TStringList;
stacktrace: string;
FErrorLog: TextFile;
ErrorLogFileName: string;
begin
stackList := JclCreateStackList(false, 0, Caller(0, false));
sl := TStringList.Create;
stackList.AddToStrings(sl, true, false, true, false);
stacktrace := sl.Text;
sl.Free;
stackList.Free;
OutputDebugStringW(PWideChar(E.Message + #10#13 + stacktrace));
ErrorLogFileName := ChangeFileExt(paramstr(0), '.log');
AssignFile(FErrorLog, ErrorLogFileName, CP_UTF8);
if FileExists(ErrorLogFileName) then
Append(FErrorLog)
else
Rewrite(FErrorLog);
Writeln(FErrorLog, FormatDateTime('dd/MM/yy hh:nn:ss', now), ' ',
'delphi_exception', ' ', E.ClassName, ' ', stringreplace(Trim(E.Message),
#13, ' ', [rfReplaceAll, rfIgnoreCase]));
Writeln(FErrorLog, StringOfChar('-', 120));
Writeln(FErrorLog, stringreplace(Trim(stacktrace), #13, ' ',
[rfReplaceAll, rfIgnoreCase]));
Writeln(FErrorLog, StringOfChar('-', 120));
CloseFile(FErrorLog);
if E is EHostApplicationPanic then
begin
Application.ShowException(E);
Application.Terminate;
exit;
end;
if MessageDlg(E.Message, mtError, [mbAbort, mbIgnore], 0) = mrAbort then
begin
NotifyServices_SetEnabled(false);
HttpRpcClient.TIMEOUT_CONNECT := 10;
// notify_services.CloseServerWindow;
Application.OnException := nil;
Application.Terminate;
exit;
end;
end;
procedure TMainFormDaf.SetupDelay(i: TDelayInfo);
var
v: TDateTime;
begin
PanelDelay.Visible := true;
LabelProgress.Caption := '';
ProgressBar1.Position := i.ElapsedSeconds * 1000;
ProgressBar1.Max := i.TotalSeconds * 1000;
v := 0;
LabelDelayElepsedTime.Caption := FormatDateTime('HH:mm:ss',
IncSecond(0, i.ElapsedSeconds));
LabelProgress.Caption :=
Inttostr(ceil(ProgressBar1.Position * 100 / ProgressBar1.Max)) + '%';
end;
procedure TMainFormDaf.OnWorkComplete(x: TWorkResultInfo);
var
s: string;
begin
ToolBarStop.Visible := false;
TimerPerforming.Enabled := false;
if RichEditlMessageBoxText.Lines.Count > 14 then
RichEditlMessageBoxText.ScrollBars := ssVertical
else
RichEditlMessageBoxText.ScrollBars := ssNone;
LabelStatusTop.Caption := TimeToStr(now) + ': ' + x.Work;
case x.Result of
0:
begin
ImageInfo.Show;
ImageError.Hide;
LabelStatusTop.Font.Color := clNavy;
RichEditlMessageBoxText.Font.Color := clNavy;
PanelMessageBoxTitle.Caption := x.Work;
LabelStatusTop.Caption := LabelStatusTop.Caption + ': успешно';
end;
1:
begin
ImageInfo.Show;
ImageError.Hide;
LabelStatusTop.Font.Color := clMaroon;
RichEditlMessageBoxText.Font.Color := clMaroon;
PanelMessageBoxTitle.Caption := x.Work;
LabelStatusTop.Caption := LabelStatusTop.Caption + ': прервано';
end;
2:
begin
ImageInfo.Hide;
ImageError.Show;
LabelStatusTop.Font.Color := clRed;
RichEditlMessageBoxText.Font.Color := clRed;
PanelMessageBoxTitle.Caption := x.Work + ': ошибка';
LabelStatusTop.Caption := LabelStatusTop.Caption +
': не выполнено';
end;
else
raise Exception.Create('unknown work result: ' + Inttostr(x.Result));
end;
RichEditlMessageBoxText.Text := stringreplace(x.Message, ': ',
#13#10#9' - ', [rfReplaceAll, rfIgnoreCase]);
LabelStatusBottom1.Caption := '';
PanelMessageBox.Show;
PanelMessageBox.BringToFront;
FormResize(self);
FormLastParty.OnWorkComplete;
end;
procedure TMainFormDaf.OnWarning(content: string);
var
s: string;
begin
s := content + #10#13#10#13;
s := s + '"Принять" - игнорировать ошибку и продолжить.'#10#13#10#13;
s := s + '"Отмена" - прервать выполнение.';
FormModalMessage.PanelMessageBoxTitle.Caption := 'Предупреждение';
FormModalMessage.RichEditlMessageBoxText.Text := content;
FormModalMessage.ImageInfo.Hide;
FormModalMessage.ImageError.Show;
FormModalMessage.ShowModal;
if FormModalMessage.ModalResult <> mrOk then
TRunnerSvc.Cancel;
end;
procedure TMainFormDaf.SetAddresClick(Sender: TObject);
begin
TRunnerSvc.SetNetAddress((Sender as TComponent).Tag);
end;
end.
|
{ Module of routines that manipulate the GUI_ENTER_T object. This object
* is used for getting the user to enter a string.
}
module gui_enter;
define gui_enter_create;
define gui_enter_delete;
define gui_enter_get;
define gui_enter_create_msg;
define gui_enter_get_fp;
define gui_enter_get_int;
%include 'gui2.ins.pas';
const
back_red = 1.00; {ENTER window background color}
back_grn = 1.00;
back_blu = 1.00;
{
*************************************************************************
*
* Local subroutine GUI_ENTER_DRAW (WIN, ENT)
*
* This is the official drawing routine for the private ENTER window.
* WIN is the private ENTER window, and ENT is the ENTER object.
}
procedure gui_enter_draw ( {official draw routine for ENTER object}
in out win: gui_win_t; {window of private enter object}
in out ent: gui_enter_t); {the enter object}
val_param; internal;
var
lspace: real; {size of gap between sequential text lines}
tp: rend_text_parms_t; {local copy of our text control parameters}
begin
lspace := ent.tparm.size * ent.tparm.lspace; {size of gap between text lines}
{
* Clear to background and draw border.
}
rend_set.rgb^ (back_red, back_grn, back_blu); {clear all to background color}
rend_prim.clear_cwind^;
rend_set.rgb^ (0.0, 0.0, 0.0); {draw outer window border}
rend_set.cpnt_2d^ (0.4, 0.4);
rend_prim.vect_2d^ (0.4, win.rect.dy - 0.4);
rend_prim.vect_2d^ (win.rect.dx - 0.4, win.rect.dy - 0.4);
rend_prim.vect_2d^ (win.rect.dx - 0.4, 0.4);
rend_prim.vect_2d^ (0.4, 0.4);
{
* Draw the border around the edit string.
}
if gui_win_clip (win, {this region drawable ?}
2.0, win.rect.dx - 2.0, ent.e1 - 1.0, ent.e2 + 1.0)
then begin
rend_set.rgb^ (0.0, 0.0, 0.0); {set border color}
rend_set.cpnt_2d^ (2.4, ent.e1 - 0.6); {draw border around user entry string}
rend_prim.vect_2d^ (2.4, ent.e2 + 0.6);
rend_prim.vect_2d^ (win.rect.dx - 2.4, ent.e2 + 0.6);
rend_prim.vect_2d^ (win.rect.dx - 2.4, ent.e1 - 0.6);
rend_prim.vect_2d^ (2.4, ent.e1 - 0.6);
end;
{
* Draw top part with prompt lines.
}
if gui_win_clip ( {this region drawable ?}
win, 1.0, win.rect.dx - 1.0, ent.e1 + 0.1, win.rect.dy - 1.0)
then begin
rend_set.rgb^ (0.0, 0.0, 0.0); {set text color}
if ent.prompt.n <= 1
then begin {only one prompt line, center it}
rend_set.text_parms^ (ent.tparm); {set our text control parameters}
rend_set.cpnt_2d^ ( {go to top center of the prompt line}
win.rect.dx * 0.5,
win.rect.dy - 1.0 - lspace);
end
else begin {multiple line, left justify them}
tp := ent.tparm; {make local copy of our text parameters}
tp.start_org := rend_torg_ul_k; {anchor to upper left corner}
rend_set.text_parms^ (tp); {set text control parameters}
rend_set.cpnt_2d^ ( {go to top left corner of top prompt line}
1.0 + tp.size * tp.width * 0.5,
win.rect.dy - 1.0 - lspace);
end
;
string_list_pos_abs (ent.prompt, 1); {get first prompt line}
while ent.prompt.str_p <> nil do begin {once for each prompt line}
rend_prim.text^ (ent.prompt.str_p^.str, ent.prompt.str_p^.len);
string_list_pos_rel (ent.prompt, 1); {advance to next prompt line in list}
end; {back to draw this new prompt line}
end;
{
* Draw bottom part with error message, if any.
}
if gui_win_clip ( {this region drawable ?}
win, 1.0, win.rect.dx - 1.0, 1.0, ent.e1 - 1.0)
then begin
if ent.err.len > 0 then begin {there is an error string to draw ?}
rend_set.rgb^ (0.7, 0.0, 0.0); {set error text color}
rend_set.cpnt_2d^ ( {go to top center of error text}
win.rect.dx * 0.5,
ent.e1 - 1.0 - lspace);
rend_set.text_parms^ (ent.tparm); {set our text control parameters}
rend_prim.text^ (ent.err.str, ent.err.len);
end;
end;
end;
{
*************************************************************************
*
* Subroutine GUI_ENTER_CREATE (ENTER, PARENT, PROMPT, SEED)
*
* Create a new ENTER object. This object is used to let the user enter
* a string. PARENT is the window to draw the user entry dialog in.
* PROMPT is the string that will be displayed to the user that should
* prompt or explain to the user what to enter. The string the user
* enters and edits will be initialized to SEED.
}
procedure gui_enter_create ( {create user string entry object}
out enter: gui_enter_t; {newly created enter object}
in out parent: gui_win_t; {window to draw enter object within}
in prompt: univ string_var_arg_t; {message to prompt user for input with}
in seed: univ string_var_arg_t); {string to seed user input with}
val_param;
var
lspace: real; {size of gap between sequential text lines}
thigh: real; {height of each text line}
high: real; {desired height for whole window}
begin
rend_dev_set (parent.all_p^.rend_dev); {make sure right RENDlib device is current}
rend_set.enter_rend^; {push one level into graphics mode}
gui_win_child ( {create private window for user entry object}
enter.win, {window to create}
parent, {parent window}
0.0, 0.0, parent.rect.dx, parent.rect.dy); {init to full size of parent window}
gui_win_set_app_pnt ( {set pointer passed to our drawing routine}
enter.win, {window setting app pointer for}
addr(enter)); {we pass pointer to enter object}
rend_get.text_parms^ (enter.tparm); {save current text control properties}
enter.tparm.start_org := rend_torg_um_k;
enter.tparm.end_org := rend_torg_down_k;
enter.tparm.rot := 0.0;
rend_set.text_parms^ (enter.tparm); {set our text parameters as current}
lspace := enter.tparm.size * enter.tparm.lspace; {height of gap between text lines}
thigh := enter.tparm.size * enter.tparm.height; {raw height of text lines}
string_list_init (enter.prompt, enter.win.mem_p^); {create prompt lines list}
enter.prompt.deallocable := false; {allocate strings from pool if possible}
gui_string_wrap ( {make prompt lines list}
prompt, {string to break up into lines}
enter.win.rect.dx - 2.0 - enter.tparm.size * enter.tparm.width, {max text width}
enter.prompt); {string list to add prompt lines to}
enter.err.max := size_char(enter.err.str); {init error message to empty}
enter.err.len := 0;
{
* Figure out where things are vertically, then adjust the window
* size and placement accordingly.
}
enter.e1 := {bottom of edit string area}
2.0 + {outer and edit string borders}
thigh + lspace * 2.0; {error message height with vertical space}
enter.e1 := trunc(enter.e1 + 0.9); {round up to whole pixels}
enter.e2 := enter.e1 + thigh + lspace * 2.0; {top of edit string area}
enter.e2 := trunc(enter.e2 + 0.9); {round up to whole pixels}
high := enter.e2 + {top of whole window}
2.0 + {enter area and outer window borders}
enter.prompt.n * thigh + {height of all the prompt lines}
(enter.prompt.n + 1) * lspace; {gaps around all the prompt lines}
high := trunc(high + 0.99); {round up to whole pixels}
high := min(high, enter.win.rect.dy); {clip to max available height}
gui_win_resize ( {adjust window size and position}
enter.win, {window to adjust}
0.0, (parent.rect.dy - high) * 0.5, {bottom left corner}
parent.rect.dx, {width}
high); {height}
{
* Create and initialize edit string object.
}
gui_estr_create ( {create the edit string object}
enter.estr, {object to create}
enter.win, {parent window}
3.0, enter.win.rect.dx - 3.0, {left and right edges}
enter.e1, enter.e2); {bottom and top edges}
gui_estr_set_string ( {set initial edit string}
enter.estr, {edit string object}
seed, {initial seed string}
seed.len + 1, {initial cursor position}
true); {treat as original unedited seed string}
rend_set.exit_rend^; {pop one level out of graphics mode}
end;
{
*************************************************************************
*
* Subroutine GUI_ENTER_DELETE (ENTER)
*
* Delete the ENTER object and erase it if appropriate.
}
procedure gui_enter_delete ( {delete user string entry object}
in out enter: gui_enter_t); {object to delete}
val_param;
begin
gui_estr_delete (enter.estr); {delete the nested edit string object}
gui_win_delete (enter.win); {delete the window and deallocate memory}
end;
{
*************************************************************************
*
* Function GUI_ENTER_GET (ENTER, ERR, RESP)
*
* Get the string entered by the user. ENTER is the user string entry
* object that was previously created with GUI_ENTER_CREATE. The string
* in ERR will be displayed as an error message. It may be empty.
* RESP is returned as the string entered by the user. Its length will
* be set to zero if the entry was cancelled. The function returns
* TRUE if a string was entered, FALSE if the entry was cancelled.
*
* *** NOTE ***
* The ENTER object is deleted on cancel. The calling routine must not try
* to delete the enter object if this function returns FALSE.
*
* The entry dialog box will be displayed, and will remain displayed
* when this routine returns unless the entry was cancelled.
}
function gui_enter_get ( {get string entered by user}
in out enter: gui_enter_t; {user string entry object}
in err: univ string_var_arg_t; {error message string}
in out resp: univ string_var_arg_t) {response string from user, len = 0 on cancel}
:boolean; {FALSE with ENTER deleted on cancelled}
val_param;
var
rend_level: sys_int_machine_t; {initial RENDlib graphics mode level}
ev: rend_event_t; {event descriptor}
p: vect_2d_t; {scratch 2D coordinate}
pnt: vect_2d_t; {pointer coordinate in our window space}
xb, yb, ofs: vect_2d_t; {save copy of old RENDlib 2D transform}
kid: gui_key_k_t; {key ID}
modk: rend_key_mod_t; {modifier keys}
label
event_next, entered, cancelled, leave;
begin
rend_dev_set (enter.win.all_p^.rend_dev); {make sure right RENDlib device current}
rend_get.enter_level^ (rend_level); {save initial graphics mode level}
rend_set.enter_rend^; {make sure we are in graphics mode}
rend_get.xform_2d^ (xb, yb, ofs); {save 2D transform}
gui_win_xf2d_set (enter.win); {set 2D transform for our window}
string_copy (err, enter.err); {set the error message string}
gui_estr_make_seed (enter.estr); {set up current string as seed string}
if enter.win.draw = nil then begin {make sure our window is showing}
gui_win_set_draw ( {make our private window drawable}
enter.win, univ_ptr(addr(gui_enter_draw)));
end;
gui_win_draw_all (enter.win); {draw the entire window}
{
* Back here to get and process the next event.
}
event_next:
rend_set.enter_level^ (0); {make sure not in graphics mode}
gui_estr_edit (enter.estr); {do edits until unhandled event}
rend_event_get (ev); {get the event not handled by ESTR object}
case ev.ev_type of {what kind of event is this ?}
{
************************************************
*
* Event POINTER MOTION
}
rend_ev_pnt_move_k: ; {these are ignored}
{
************************************************
*
* Event KEY
}
rend_ev_key_k: begin {a key just transitioned}
if not ev.key.down then goto event_next; {ignore key releases}
modk := ev.key.modk; {get set of active modifier keys}
if rend_key_mod_alt_k in modk {ALT active, this key not for us ?}
then goto cancelled;
modk := modk - [rend_key_mod_shiftlock_k]; {ignore shift lock modifier}
kid := gui_key_k_t(ev.key.key_p^.id_user); {make GUI library ID for this key}
p.x := ev.key.x;
p.y := ev.key.y;
rend_get.bxfpnt_2d^ (p, pnt); {PNT is pointer coordinate in our space}
case kid of {which one of our keys is it ?}
gui_key_esc_k: begin {key ESCAPE, abort from this menu level}
if modk <> [] then goto event_next;
ev.ev_type := rend_ev_none_k; {indicate the event got used up}
goto cancelled; {abort from this menu level}
end;
gui_key_enter_k: begin {key ENTER, user confirmed edited string}
if modk <> [] then goto event_next;
goto entered;
end;
gui_key_mouse_left_k,
gui_key_mouse_right_k: begin {mouse buttons}
if {pointer outside our area ?}
(pnt.x < 0.0) or (pnt.x > enter.win.rect.dx) or
(pnt.y < 0.0) or (pnt.y > enter.win.rect.dy)
then begin
goto cancelled; {this event is for someone else}
end;
end;
otherwise {any key not explicitly handled}
goto cancelled; {assume this event is for someone else}
end; {end of key ID cases}
end; {end of event KEY case}
{
************************************************
*
* Event WIPED_RECT
}
rend_ev_wiped_rect_k: begin {rectangular region needs redraw}
gui_win_draw ( {redraw a region}
enter.win.all_p^.root_p^, {redraw from the root window down}
ev.wiped_rect.x, {left X}
ev.wiped_rect.x + ev.wiped_rect.dx, {right X}
enter.win.all_p^.root_p^.rect.dy - ev.wiped_rect.y - ev.wiped_rect.dy, {bottom Y}
enter.win.all_p^.root_p^.rect.dy - ev.wiped_rect.y); {top Y}
end;
{
************************************************
}
otherwise {any event type we don't explicitly handle}
goto cancelled;
end; {end of event type cases}
goto event_next; {back to process next event}
{
* The entry was completed normally.
}
entered:
gui_enter_get := true; {indicate returning with string from user}
string_copy (enter.estr.str, resp); {return the entered string}
goto leave;
{
* No entry was selected because the selection process was terminated for some
* reason. If EV contains an event (EV.EV_TYPE not REND_EV_NONE_K), then it
* is assumed that this event is for someone else and must be pushed back
* onto the event queue.
}
cancelled:
gui_enter_get := false; {indicate entry was cancelled}
resp.len := 0;
if ev.ev_type <> rend_ev_none_k then begin {we took an event for someone else ?}
rend_event_push (ev); {put event back at head of queue}
end;
gui_enter_delete (enter); {delete the user entry object}
{
* Common exit point. Return values and event state already take care of.
}
leave:
rend_set.xform_2d^ (xb, yb, ofs); {restore original 2D transform}
rend_set.enter_level^ (rend_level); {restore original graphics mode level}
end;
{
*************************************************************************
*
* Subroutine GUI_ENTER_CREATE_MSG (ENTER, PARENT, SEED,
* SUBSYS, MSG, PARMS, N_PARMS)
*
* Create an ENTER object. The prompt text will be the expansion of the
* message specified by standard message arguments SUBSYS, MSG, PARMS,
* and N_PARMS. PARENT is the window in which to display the user entry
* dialog box. The initial string for the user to edit will be set to
* SEED.
}
procedure gui_enter_create_msg ( {create enter string object from message}
out enter: gui_enter_t; {newly created enter object}
in out parent: gui_win_t; {window to draw enter object within}
in seed: univ string_var_arg_t; {string to seed user input with}
in subsys: string; {name of subsystem, used to find message file}
in msg: string; {message name withing subsystem file}
in parms: univ sys_parm_msg_ar_t; {array of parameter descriptors}
in n_parms: sys_int_machine_t); {number of parameters in PARMS}
val_param;
var
prompt: string_var8192_t; {prompt string expanded from message}
begin
prompt.max := size_char(prompt.str); {init local var string}
string_f_message (prompt, subsys, msg, parms, n_parms); {expand message into PARMS}
gui_enter_create (enter, parent, prompt, seed); {create the string entry object}
end;
{
*************************************************************************
*
* Subroutine GUI_ENTER_GET_FP (ENTER, ERR, FLAGS, FP)
*
* Get a floating point value from the user. ENTER is the previously created
* user string entry object. ERR will be displayed as an error message to
* the user. It may be empty. The floating point value is returned in FP.
*
* If the entry was cancelled by the user, the function returns FALSE and
* the enter object is deleted. Otherwise, the function returns TRUE and
* the enter object is not deleted.
}
function gui_enter_get_fp ( {get floating point value entered by user}
in out enter: gui_enter_t; {user string entry object}
in err: univ string_var_arg_t; {error message string}
out fp: real) {returned FP value, unchanged on cancel}
:boolean; {FALSE with ENTER deleted on cancelled}
val_param;
var
resp: string_var8192_t; {response string entered by user}
e: string_var132_t; {local copy of error message string}
fpmax: sys_fp_max_t; {internal floating point value}
stat: sys_err_t; {string to floating point conversion status}
label
loop;
begin
resp.max := size_char(resp.str); {init local var strings}
e.max := size_char(e.str);
string_copy (err, e); {init local copy of error message string}
loop: {back here on string conversion error}
if not gui_enter_get (enter, e, resp) then begin {get response string from user}
gui_enter_get_fp := false;
return;
end;
string_t_fpmax ( {try convert response string to FP value}
resp, {string to convert}
fpmax, {returned FP value}
[string_tfp_group_k], {allow digits group characters}
stat); {returned conversion status}
if sys_error(stat) then begin {string conversion error ?}
string_f_message (e, 'gui', 'err_enter_fp', nil, 0); {make error message}
goto loop; {back and ask user again}
end;
fp := fpmax; {pass back floating point value}
gui_enter_get_fp := true; {indicate entry not aborted}
end;
{
*************************************************************************
*
* Subroutine GUI_ENTER_GET_INT (ENTER, ERR, I, STAT)
*
* Get an integer value from the user. ENTER is the previously created
* user string entry object. ERR will be displayed as an error message to
* the user. It may be may be empty. The integer value is returned in I.
*
* If the entry was cancelled by the user, the function returns FALSE and
* the enter object is deleted. Otherwise, the function returns TRUE and
* the enter object is not deleted.
}
function gui_enter_get_int ( {get integer value entered by user}
in out enter: gui_enter_t; {user string entry object}
in err: univ string_var_arg_t; {error message string}
out i: sys_int_machine_t) {returned integer value, unchanged on cancel}
:boolean; {FALSE with ENTER deleted on cancelled}
val_param;
var
resp: string_var8192_t; {response string entered by user}
e: string_var132_t; {local copy of error message string}
ii: sys_int_machine_t; {internal integer value}
stat: sys_err_t; {string to integer conversion status}
label
loop;
begin
resp.max := size_char(resp.str); {init local var strings}
e.max := size_char(e.str);
string_copy (err, e); {init local copy of error message string}
loop: {back here on string conversion error}
if not gui_enter_get (enter, e, resp) then begin {get response string from user}
gui_enter_get_int := false;
return;
end;
string_t_int (resp, ii, stat); {try to convert response to integer value}
if sys_error(stat) then begin {string conversion error ?}
string_f_message (e, 'gui', 'err_enter_int', nil, 0); {make error message}
goto loop; {back and ask user again}
end;
i := ii; {pass back final integer value}
gui_enter_get_int := true; {indicate entry not aborted}
end;
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLManager<p>
Managers are used to manage many different kinds of clients in GLScene.
They are registered so that when clients are loaded, the client can
look up the manager + register themselves with it.<p>
<b>History : </b><font size=-1><ul>
<li>11/11/09 - DaStr - Added $I GLScene.inc
<li>05/10/08 - DanB - Created from GLTexture.pas split
</ul></font>
}
unit GLManager;
interface
{$i GLScene.inc}
uses
Classes, Types;
procedure RegisterManager(aManager : TComponent);
procedure DeRegisterManager(aManager : TComponent);
function FindManager(classType : TComponentClass; const managerName : String) : TComponent;
implementation
var
vManagers : TList;
// RegisterManager
//
procedure RegisterManager(aManager : TComponent);
begin
if not Assigned(vManagers) then
vManagers:=TList.Create;
if vManagers.IndexOf(aManager)<0 then
vManagers.Add(aManager);
end;
// DeRegisterManager
//
procedure DeRegisterManager(aManager : TComponent);
begin
if Assigned(vManagers) then
vManagers.Remove(aManager);
end;
// FindManager
//
function FindManager(classType : TComponentClass; const managerName : String) : TComponent;
var
i : Integer;
begin
Result:=nil;
if Assigned(vManagers) then
for i:=0 to vManagers.Count-1 do with TComponent(vManagers[i]) do
if InheritsFrom(classType) and (Name=managerName) then begin
Result:=TComponent(vManagers[i]);
Break;
end;
end;
initialization
finalization
vManagers.Free;
vManagers:=nil;
end.
|
unit Demo.Audio;
interface
uses
ECMA.TypedArray, W3C.DOM4, W3C.Html5, W3C.WebAudio, Demo.Framework, Demo.Hrtf;
type
TNotifyEvent = procedure(Sender: TObject);
TTrack = class
private
FAudioBuffer: JAudioBuffer;
FAudioBufferSource: JAudioBufferSourceNode;
FConvolverNode: JConvolverNode;
FText: String;
FHrtfIndex: Integer;
FOnReady: TNotifyEvent;
FOnEnded: TNotifyEvent;
procedure RequestAudio;
procedure SetupAudioBufferNode;
public
constructor Create(Text: String; OnReady: TNotifyEvent);
procedure FromHrtf(Hrtfs: THrtfs; Index: Integer);
property Text: String read FText;
property HrtfIndex: Integer read FHrtfIndex;
property AudioBufferSource: JAudioBufferSourceNode read FAudioBufferSource;
property OnEnded: TNotifyEvent read FOnEnded write FOnEnded;
end;
var
GAudioContext external 'AudioContext': JAudioContext;
implementation
uses
WHATWG.Console, WHATWG.XHR;
{ TTrack }
constructor TTrack.Create(Text: String; OnReady: TNotifyEvent);
begin
FText := Text;
FOnReady := OnReady;
// create convolver node
FConvolverNode := GAudioContext.createConvolver;
FConvolverNode.normalize := false;
FConvolverNode.connect(GAudioContext.destination);
RequestAudio;
end;
procedure TTrack.RequestAudio;
begin
var Request := new JXMLHttpRequest;
Request.open('GET', 'Audio\' + FText + '.wav', True);
Request.responseType := 'arraybuffer';
Request.OnLoad := lambda
if Assigned(GAudioContext) then
begin
GAudioContext.decodeAudioData(JArrayBuffer(Request.response),
lambda(DecodedData: JAudioBuffer)
FAudioBuffer := DecodedData;
SetupAudioBufferNode;
if Assigned(FOnReady) then
FOnReady(Self);
end,
lambda(error: JDOMException)
Console.Log('Error loading file ' + Text);
end);
end
else
Result := False;
end;
Request.OnError := lambda
Console.Log('Error loading file!');
Result := False;
end;
Request.send;
end;
procedure TTrack.FromHrtf(Hrtfs: THrtfs; Index: Integer);
begin
var HrtfBuffer := GAudioContext.createBuffer(2, Hrtfs.SampleFrames, GAudioContext.SampleRate);
HrtfBuffer.copyToChannel(Hrtfs.Measurement[Index].Left, 0);
HrtfBuffer.copyToChannel(Hrtfs.Measurement[Index].Right, 1);
FHrtfIndex := Index;
if GAudioContext.SampleRate <> Hrtfs.SampleRate then
begin
var OfflineAudioContext: JOfflineAudioContext;
asm
var OfflineAudioContext = window.OfflineAudioContext || window.webkitOfflineAudioContext;
@OfflineAudioContext = new OfflineAudioContext(2, @Hrtfs.FSampleFrames, @GAudioContext.sampleRate);
end;
var Buffer := GAudioContext.createBuffer(2, Hrtfs.SampleFrames, GAudioContext.SampleRate);
var BufferSource = OfflineAudioContext.createBufferSource;
BufferSource.buffer := HrtfBuffer;
BufferSource.connect(OfflineAudioContext.destination);
BufferSource.start(0);
OfflineAudioContext.oncomplete := lambda(Event: JEvent)
var OfflineAudioEvent := JOfflineAudioCompletionEvent(Event);
HrtfBuffer := OfflineAudioEvent.renderedBuffer;
Result := False;
end;
OfflineAudioContext.startRendering;
end;
Assert(HrtfBuffer.sampleRate = GAudioContext.SampleRate);
FConvolverNode.buffer := HrtfBuffer;
end;
procedure TTrack.SetupAudioBufferNode;
begin
FAudioBufferSource := GAudioContext.createBufferSource;
FAudioBufferSource.buffer := FAudioBuffer;
FAudioBufferSource.connect(FConvolverNode);
FAudioBufferSource.onended := lambda
SetupAudioBufferNode;
if Assigned(FOnEnded) then
FOnEnded(Self);
Result := False;
end;
end;
initialization
asm
var AudioContext = window.AudioContext || window.webkitAudioContext;
@GAudioContext = new AudioContext();
end;
end. |
unit CurrencyExchange;
interface
uses
Money, SysUtils;
type
TCurrencyExchange = class
public
class function ChangeCurrency(const FromMoney : IMoney; const ToFormatSettings : TFormatSettings; const ExchangeRate : Double): IMoney;
end;
implementation
{ TCurrencyExchange }
class function TCurrencyExchange.ChangeCurrency(const FromMoney: IMoney; const ToFormatSettings: TFormatSettings; const ExchangeRate : Double): IMoney;
var
NewAmount : integer;
begin
result := TMoney.Create(FromMoney.Multiply(ExchangeRate).Amount, ToFormatSettings);
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Androidapi.Glesext;
interface
uses Posix.SysTypes,
Androidapi.KhrPlatform,
Androidapi.Gles;
{$I Androidapi.inc}
const
{ ------------------------------------------------------------------------
OES extension tokens
------------------------------------------------------------------------ }
{ GL_OES_blend_equation_separate }
{ BLEND_EQUATION_RGB_OES same as BLEND_EQUATION_OES }
GL_BLEND_EQUATION_RGB_OES = $8009;
{$EXTERNALSYM GL_BLEND_EQUATION_RGB_OES}
GL_BLEND_EQUATION_ALPHA_OES = $883D;
{$EXTERNALSYM GL_BLEND_EQUATION_ALPHA_OES}
{ GL_OES_blend_func_separate }
GL_BLEND_DST_RGB_OES = $80C8;
{$EXTERNALSYM GL_BLEND_DST_RGB_OES}
GL_BLEND_SRC_RGB_OES = $80C9;
{$EXTERNALSYM GL_BLEND_SRC_RGB_OES}
GL_BLEND_DST_ALPHA_OES = $80CA;
{$EXTERNALSYM GL_BLEND_DST_ALPHA_OES}
GL_BLEND_SRC_ALPHA_OES = $80CB;
{$EXTERNALSYM GL_BLEND_SRC_ALPHA_OES}
{ GL_OES_blend_subtract }
GL_BLEND_EQUATION_OES = $8009;
{$EXTERNALSYM GL_BLEND_EQUATION_OES}
GL_FUNC_ADD_OES = $8006;
{$EXTERNALSYM GL_FUNC_ADD_OES}
GL_FUNC_SUBTRACT_OES = $800A;
{$EXTERNALSYM GL_FUNC_SUBTRACT_OES}
GL_FUNC_REVERSE_SUBTRACT_OES = $800B;
{$EXTERNALSYM GL_FUNC_REVERSE_SUBTRACT_OES}
{ GL_OES_compressed_ETC1_RGB8_texture }
GL_ETC1_RGB8_OES = $8D64;
{$EXTERNALSYM GL_ETC1_RGB8_OES}
{ GL_OES_depth24 }
GL_DEPTH_COMPONENT24_OES = $81A6;
{$EXTERNALSYM GL_DEPTH_COMPONENT24_OES}
{ GL_OES_depth32 }
GL_DEPTH_COMPONENT32_OES = $81A7;
{$EXTERNALSYM GL_DEPTH_COMPONENT32_OES}
{ GL_OES_draw_texture }
GL_TEXTURE_CROP_RECT_OES = $8B9D;
{$EXTERNALSYM GL_TEXTURE_CROP_RECT_OES}
type
{ GL_OES_EGL_image }
GLeglImageOES = Pointer;
const
{ GL_OES_element_index_uint }
GL_UNSIGNED_INT = $1405;
{$EXTERNALSYM GL_UNSIGNED_INT}
{ GL_OES_fixed_point }
GL_FIXED_OES = $140C;
{$EXTERNALSYM GL_FIXED_OES}
{ GL_OES_framebuffer_object }
GL_NONE_OES = 0;
{$EXTERNALSYM GL_NONE_OES}
GL_FRAMEBUFFER_OES = $8D40;
{$EXTERNALSYM GL_FRAMEBUFFER_OES}
GL_RENDERBUFFER_OES = $8D41;
{$EXTERNALSYM GL_RENDERBUFFER_OES}
GL_RGBA4_OES = $8056;
{$EXTERNALSYM GL_RGBA4_OES}
GL_RGB5_A1_OES = $8057;
{$EXTERNALSYM GL_RGB5_A1_OES}
GL_RGB565_OES = $8D62;
{$EXTERNALSYM GL_RGB565_OES}
GL_DEPTH_COMPONENT16_OES = $81A5;
{$EXTERNALSYM GL_DEPTH_COMPONENT16_OES}
GL_RENDERBUFFER_WIDTH_OES = $8D42;
{$EXTERNALSYM GL_RENDERBUFFER_WIDTH_OES}
GL_RENDERBUFFER_HEIGHT_OES = $8D43;
{$EXTERNALSYM GL_RENDERBUFFER_HEIGHT_OES}
GL_RENDERBUFFER_INTERNAL_FORMAT_OES = $8D44;
{$EXTERNALSYM GL_RENDERBUFFER_INTERNAL_FORMAT_OES}
GL_RENDERBUFFER_RED_SIZE_OES = $8D50;
{$EXTERNALSYM GL_RENDERBUFFER_RED_SIZE_OES}
GL_RENDERBUFFER_GREEN_SIZE_OES = $8D51;
{$EXTERNALSYM GL_RENDERBUFFER_GREEN_SIZE_OES}
GL_RENDERBUFFER_BLUE_SIZE_OES = $8D52;
{$EXTERNALSYM GL_RENDERBUFFER_BLUE_SIZE_OES}
GL_RENDERBUFFER_ALPHA_SIZE_OES = $8D53;
{$EXTERNALSYM GL_RENDERBUFFER_ALPHA_SIZE_OES}
GL_RENDERBUFFER_DEPTH_SIZE_OES = $8D54;
{$EXTERNALSYM GL_RENDERBUFFER_DEPTH_SIZE_OES}
GL_RENDERBUFFER_STENCIL_SIZE_OES = $8D55;
{$EXTERNALSYM GL_RENDERBUFFER_STENCIL_SIZE_OES}
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES = $8CD0;
{$EXTERNALSYM GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES}
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES = $8CD1;
{$EXTERNALSYM GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES}
GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES = $8CD2;
{$EXTERNALSYM GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES}
GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES = $8CD3;
{$EXTERNALSYM GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES}
GL_COLOR_ATTACHMENT0_OES = $8CE0;
{$EXTERNALSYM GL_COLOR_ATTACHMENT0_OES}
GL_DEPTH_ATTACHMENT_OES = $8D00;
{$EXTERNALSYM GL_DEPTH_ATTACHMENT_OES}
GL_STENCIL_ATTACHMENT_OES = $8D20;
{$EXTERNALSYM GL_STENCIL_ATTACHMENT_OES}
GL_FRAMEBUFFER_COMPLETE_OES = $8CD5;
{$EXTERNALSYM GL_FRAMEBUFFER_COMPLETE_OES}
GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_OES = $8CD6;
{$EXTERNALSYM GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_OES}
GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_OES = $8CD7;
{$EXTERNALSYM GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_OES}
GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_OES = $8CD9;
{$EXTERNALSYM GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_OES}
GL_FRAMEBUFFER_INCOMPLETE_FORMATS_OES = $8CDA;
{$EXTERNALSYM GL_FRAMEBUFFER_INCOMPLETE_FORMATS_OES}
GL_FRAMEBUFFER_UNSUPPORTED_OES = $8CDD;
{$EXTERNALSYM GL_FRAMEBUFFER_UNSUPPORTED_OES}
GL_FRAMEBUFFER_BINDING_OES = $8CA6;
{$EXTERNALSYM GL_FRAMEBUFFER_BINDING_OES}
GL_RENDERBUFFER_BINDING_OES = $8CA7;
{$EXTERNALSYM GL_RENDERBUFFER_BINDING_OES}
GL_MAX_RENDERBUFFER_SIZE_OES = $84E8;
{$EXTERNALSYM GL_MAX_RENDERBUFFER_SIZE_OES}
GL_INVALID_FRAMEBUFFER_OPERATION_OES = $0506;
{$EXTERNALSYM GL_INVALID_FRAMEBUFFER_OPERATION_OES}
{ GL_OES_mapbuffer }
GL_WRITE_ONLY_OES = $88B9;
{$EXTERNALSYM GL_WRITE_ONLY_OES}
GL_BUFFER_ACCESS_OES = $88BB;
{$EXTERNALSYM GL_BUFFER_ACCESS_OES}
GL_BUFFER_MAPPED_OES = $88BC;
{$EXTERNALSYM GL_BUFFER_MAPPED_OES}
GL_BUFFER_MAP_POINTER_OES = $88BD;
{$EXTERNALSYM GL_BUFFER_MAP_POINTER_OES}
{ GL_OES_matrix_get }
GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES = $898D;
{$EXTERNALSYM GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES}
GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES = $898E;
{$EXTERNALSYM GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES}
GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES = $898F;
{$EXTERNALSYM GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES}
{ GL_OES_matrix_palette }
GL_MAX_VERTEX_UNITS_OES = $86A4;
{$EXTERNALSYM GL_MAX_VERTEX_UNITS_OES}
GL_MAX_PALETTE_MATRICES_OES = $8842;
{$EXTERNALSYM GL_MAX_PALETTE_MATRICES_OES}
GL_MATRIX_PALETTE_OES = $8840;
{$EXTERNALSYM GL_MATRIX_PALETTE_OES}
GL_MATRIX_INDEX_ARRAY_OES = $8844;
{$EXTERNALSYM GL_MATRIX_INDEX_ARRAY_OES}
GL_WEIGHT_ARRAY_OES = $86AD;
{$EXTERNALSYM GL_WEIGHT_ARRAY_OES}
GL_CURRENT_PALETTE_MATRIX_OES = $8843;
{$EXTERNALSYM GL_CURRENT_PALETTE_MATRIX_OES}
GL_MATRIX_INDEX_ARRAY_SIZE_OES = $8846;
{$EXTERNALSYM GL_MATRIX_INDEX_ARRAY_SIZE_OES}
GL_MATRIX_INDEX_ARRAY_TYPE_OES = $8847;
{$EXTERNALSYM GL_MATRIX_INDEX_ARRAY_TYPE_OES}
GL_MATRIX_INDEX_ARRAY_STRIDE_OES = $8848;
{$EXTERNALSYM GL_MATRIX_INDEX_ARRAY_STRIDE_OES}
GL_MATRIX_INDEX_ARRAY_POINTER_OES = $8849;
{$EXTERNALSYM GL_MATRIX_INDEX_ARRAY_POINTER_OES}
GL_MATRIX_INDEX_ARRAY_BUFFER_BINDING_OES = $8B9E;
{$EXTERNALSYM GL_MATRIX_INDEX_ARRAY_BUFFER_BINDING_OES}
GL_WEIGHT_ARRAY_SIZE_OES = $86AB;
{$EXTERNALSYM GL_WEIGHT_ARRAY_SIZE_OES}
GL_WEIGHT_ARRAY_TYPE_OES = $86A9;
{$EXTERNALSYM GL_WEIGHT_ARRAY_TYPE_OES}
GL_WEIGHT_ARRAY_STRIDE_OES = $86AA;
{$EXTERNALSYM GL_WEIGHT_ARRAY_STRIDE_OES}
GL_WEIGHT_ARRAY_POINTER_OES = $86AC;
{$EXTERNALSYM GL_WEIGHT_ARRAY_POINTER_OES}
GL_WEIGHT_ARRAY_BUFFER_BINDING_OES = $889E;
{$EXTERNALSYM GL_WEIGHT_ARRAY_BUFFER_BINDING_OES}
{ GL_OES_packed_depth_stencil }
GL_DEPTH_STENCIL_OES = $84F9;
{$EXTERNALSYM GL_DEPTH_STENCIL_OES}
GL_UNSIGNED_INT_24_8_OES = $84FA;
{$EXTERNALSYM GL_UNSIGNED_INT_24_8_OES}
GL_DEPTH24_STENCIL8_OES = $88F0;
{$EXTERNALSYM GL_DEPTH24_STENCIL8_OES}
{ GL_OES_rgb8_rgba8 }
GL_RGB8_OES = $8051;
{$EXTERNALSYM GL_RGB8_OES}
GL_RGBA8_OES = $8058;
{$EXTERNALSYM GL_RGBA8_OES}
{ GL_OES_stencil1 }
GL_STENCIL_INDEX1_OES = $8D46;
{$EXTERNALSYM GL_STENCIL_INDEX1_OES}
{ GL_OES_stencil4 }
GL_STENCIL_INDEX4_OES = $8D47;
{$EXTERNALSYM GL_STENCIL_INDEX4_OES}
{ GL_OES_stencil8 }
GL_STENCIL_INDEX8_OES = $8D48;
{$EXTERNALSYM GL_STENCIL_INDEX8_OES}
{ GL_OES_stencil_wrap }
GL_INCR_WRAP_OES = $8507;
{$EXTERNALSYM GL_INCR_WRAP_OES}
GL_DECR_WRAP_OES = $8508;
{$EXTERNALSYM GL_DECR_WRAP_OES}
{ GL_OES_texture_cube_map }
GL_NORMAL_MAP_OES = $8511;
{$EXTERNALSYM GL_NORMAL_MAP_OES}
GL_REFLECTION_MAP_OES = $8512;
{$EXTERNALSYM GL_REFLECTION_MAP_OES}
GL_TEXTURE_CUBE_MAP_OES = $8513;
{$EXTERNALSYM GL_TEXTURE_CUBE_MAP_OES}
GL_TEXTURE_BINDING_CUBE_MAP_OES = $8514;
{$EXTERNALSYM GL_TEXTURE_BINDING_CUBE_MAP_OES}
GL_TEXTURE_CUBE_MAP_POSITIVE_X_OES = $8515;
{$EXTERNALSYM GL_TEXTURE_CUBE_MAP_POSITIVE_X_OES}
GL_TEXTURE_CUBE_MAP_NEGATIVE_X_OES = $8516;
{$EXTERNALSYM GL_TEXTURE_CUBE_MAP_NEGATIVE_X_OES}
GL_TEXTURE_CUBE_MAP_POSITIVE_Y_OES = $8517;
{$EXTERNALSYM GL_TEXTURE_CUBE_MAP_POSITIVE_Y_OES}
GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_OES = $8518;
{$EXTERNALSYM GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_OES}
GL_TEXTURE_CUBE_MAP_POSITIVE_Z_OES = $8519;
{$EXTERNALSYM GL_TEXTURE_CUBE_MAP_POSITIVE_Z_OES}
GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_OES = $851A;
{$EXTERNALSYM GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_OES}
GL_MAX_CUBE_MAP_TEXTURE_SIZE_OES = $851C;
{$EXTERNALSYM GL_MAX_CUBE_MAP_TEXTURE_SIZE_OES}
GL_TEXTURE_GEN_MODE_OES = $2500;
{$EXTERNALSYM GL_TEXTURE_GEN_MODE_OES}
GL_TEXTURE_GEN_STR_OES = $8D60;
{$EXTERNALSYM GL_TEXTURE_GEN_STR_OES}
{ GL_OES_texture_mirrored_repeat }
GL_MIRRORED_REPEAT_OES = $8370;
{$EXTERNALSYM GL_MIRRORED_REPEAT_OES}
{ GL_OES_vertex_array_object }
GL_VERTEX_ARRAY_BINDING_OES = $85B5;
{$EXTERNALSYM GL_VERTEX_ARRAY_BINDING_OES}
{ GL_OES_EGL_image_external }
GL_TEXTURE_EXTERNAL_OES = $8D65;
{$EXTERNALSYM GL_TEXTURE_EXTERNAL_OES}
GL_SAMPLER_EXTERNAL_OES = $8D66;
{$EXTERNALSYM GL_SAMPLER_EXTERNAL_OES}
GL_TEXTURE_BINDING_EXTERNAL_OES = $8D67;
{$EXTERNALSYM GL_TEXTURE_BINDING_EXTERNAL_OES}
GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES = $8D68;
{$EXTERNALSYM GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES}
{ ------------------------------------------------------------------------
AMD extension tokens
------------------------------------------------------------------------ }
{ GL_AMD_compressed_3DC_texture }
GL_3DC_X_AMD = $87F9;
{$EXTERNALSYM GL_3DC_X_AMD}
GL_3DC_XY_AMD = $87FA;
{$EXTERNALSYM GL_3DC_XY_AMD}
{ GL_AMD_compressed_ATC_texture }
GL_ATC_RGB_AMD = $8C92;
{$EXTERNALSYM GL_ATC_RGB_AMD}
GL_ATC_RGBA_EXPLICIT_ALPHA_AMD = $8C93;
{$EXTERNALSYM GL_ATC_RGBA_EXPLICIT_ALPHA_AMD}
GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD = $87EE;
{$EXTERNALSYM GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD}
{ ------------------------------------------------------------------------
APPLE extension tokens
------------------------------------------------------------------------ }
{ GL_APPLE_texture_2D_limited_npot }
{ No new tokens introduced by this extension. }
{ ------------------------------------------------------------------------
EXT extension tokens
------------------------------------------------------------------------ }
{ GL_EXT_blend_minmax }
GL_MIN_EXT = $8007;
{$EXTERNALSYM GL_MIN_EXT}
GL_MAX_EXT = $8008;
{$EXTERNALSYM GL_MAX_EXT}
{ GL_EXT_discard_framebuffer }
GL_COLOR_EXT = $1800;
{$EXTERNALSYM GL_COLOR_EXT}
GL_DEPTH_EXT = $1801;
{$EXTERNALSYM GL_DEPTH_EXT}
GL_STENCIL_EXT = $1802;
{$EXTERNALSYM GL_STENCIL_EXT}
{ GL_EXT_multi_draw_arrays }
{ No new tokens introduced by this extension. }
{ GL_EXT_read_format_bgra }
GL_BGRA_EXT = $80E1;
{$EXTERNALSYM GL_BGRA_EXT}
GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT = $8365;
{$EXTERNALSYM GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT}
GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT = $8366;
{$EXTERNALSYM GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT}
{ GL_EXT_texture_filter_anisotropic }
GL_TEXTURE_MAX_ANISOTROPY_EXT = $84FE;
{$EXTERNALSYM GL_TEXTURE_MAX_ANISOTROPY_EXT}
GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT = $84FF;
{$EXTERNALSYM GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT}
{ GL_EXT_texture_format_BGRA8888 }
// GL_BGRA_EXT = $80E1;
// {$EXTERNALSYM GL_BGRA_EXT}
{ GL_EXT_texture_lod_bias }
GL_MAX_TEXTURE_LOD_BIAS_EXT = $84FD;
{$EXTERNALSYM GL_MAX_TEXTURE_LOD_BIAS_EXT}
GL_TEXTURE_FILTER_CONTROL_EXT = $8500;
{$EXTERNALSYM GL_TEXTURE_FILTER_CONTROL_EXT}
GL_TEXTURE_LOD_BIAS_EXT = $8501;
{$EXTERNALSYM GL_TEXTURE_LOD_BIAS_EXT}
{ ------------------------------------------------------------------------
IMG extension tokens
------------------------------------------------------------------------ }
{ GL_IMG_read_format }
GL_BGRA_IMG = $80E1;
{$EXTERNALSYM GL_BGRA_IMG}
GL_UNSIGNED_SHORT_4_4_4_4_REV_IMG = $8365;
{$EXTERNALSYM GL_UNSIGNED_SHORT_4_4_4_4_REV_IMG}
{ GL_IMG_texture_compression_pvrtc }
GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = $8C00;
{$EXTERNALSYM GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG}
GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG = $8C01;
{$EXTERNALSYM GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG}
GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = $8C02;
{$EXTERNALSYM GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG}
GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = $8C03;
{$EXTERNALSYM GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}
{ GL_IMG_texture_env_enhanced_fixed_function }
GL_MODULATE_COLOR_IMG = $8C04;
{$EXTERNALSYM GL_MODULATE_COLOR_IMG}
GL_RECIP_ADD_SIGNED_ALPHA_IMG = $8C05;
{$EXTERNALSYM GL_RECIP_ADD_SIGNED_ALPHA_IMG}
GL_TEXTURE_ALPHA_MODULATE_IMG = $8C06;
{$EXTERNALSYM GL_TEXTURE_ALPHA_MODULATE_IMG}
GL_FACTOR_ALPHA_MODULATE_IMG = $8C07;
{$EXTERNALSYM GL_FACTOR_ALPHA_MODULATE_IMG}
GL_FRAGMENT_ALPHA_MODULATE_IMG = $8C08;
{$EXTERNALSYM GL_FRAGMENT_ALPHA_MODULATE_IMG}
GL_ADD_BLEND_IMG = $8C09;
{$EXTERNALSYM GL_ADD_BLEND_IMG}
GL_DOT3_RGBA_IMG = $86AF;
{$EXTERNALSYM GL_DOT3_RGBA_IMG}
{ GL_IMG_user_clip_plane }
GL_CLIP_PLANE0_IMG = $3000;
{$EXTERNALSYM GL_CLIP_PLANE0_IMG}
GL_CLIP_PLANE1_IMG = $3001;
{$EXTERNALSYM GL_CLIP_PLANE1_IMG}
GL_CLIP_PLANE2_IMG = $3002;
{$EXTERNALSYM GL_CLIP_PLANE2_IMG}
GL_CLIP_PLANE3_IMG = $3003;
{$EXTERNALSYM GL_CLIP_PLANE3_IMG}
GL_CLIP_PLANE4_IMG = $3004;
{$EXTERNALSYM GL_CLIP_PLANE4_IMG}
GL_CLIP_PLANE5_IMG = $3005;
{$EXTERNALSYM GL_CLIP_PLANE5_IMG}
GL_MAX_CLIP_PLANES_IMG = $0D32;
{$EXTERNALSYM GL_MAX_CLIP_PLANES_IMG}
{ GL_IMG_multisampled_render_to_texture }
GL_RENDERBUFFER_SAMPLES_IMG = $9133;
{$EXTERNALSYM GL_RENDERBUFFER_SAMPLES_IMG}
GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG = $9134;
{$EXTERNALSYM GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG}
GL_MAX_SAMPLES_IMG = $9135;
{$EXTERNALSYM GL_MAX_SAMPLES_IMG}
GL_TEXTURE_SAMPLES_IMG = $9136;
{$EXTERNALSYM GL_TEXTURE_SAMPLES_IMG}
{ ------------------------------------------------------------------------
NV extension tokens
------------------------------------------------------------------------ }
{ GL_NV_fence }
GL_ALL_COMPLETED_NV = $84F2;
{$EXTERNALSYM GL_ALL_COMPLETED_NV}
GL_FENCE_STATUS_NV = $84F3;
{$EXTERNALSYM GL_FENCE_STATUS_NV}
GL_FENCE_CONDITION_NV = $84F4;
{$EXTERNALSYM GL_FENCE_CONDITION_NV}
{ ------------------------------------------------------------------------
QCOM extension tokens
------------------------------------------------------------------------ }
{ GL_QCOM_driver_control }
{ No new tokens introduced by this extension. }
{ GL_QCOM_extended_get }
GL_TEXTURE_WIDTH_QCOM = $8BD2;
{$EXTERNALSYM GL_TEXTURE_WIDTH_QCOM}
GL_TEXTURE_HEIGHT_QCOM = $8BD3;
{$EXTERNALSYM GL_TEXTURE_HEIGHT_QCOM}
GL_TEXTURE_DEPTH_QCOM = $8BD4;
{$EXTERNALSYM GL_TEXTURE_DEPTH_QCOM}
GL_TEXTURE_INTERNAL_FORMAT_QCOM = $8BD5;
{$EXTERNALSYM GL_TEXTURE_INTERNAL_FORMAT_QCOM}
GL_TEXTURE_FORMAT_QCOM = $8BD6;
{$EXTERNALSYM GL_TEXTURE_FORMAT_QCOM}
GL_TEXTURE_TYPE_QCOM = $8BD7;
{$EXTERNALSYM GL_TEXTURE_TYPE_QCOM}
GL_TEXTURE_IMAGE_VALID_QCOM = $8BD8;
{$EXTERNALSYM GL_TEXTURE_IMAGE_VALID_QCOM}
GL_TEXTURE_NUM_LEVELS_QCOM = $8BD9;
{$EXTERNALSYM GL_TEXTURE_NUM_LEVELS_QCOM}
GL_TEXTURE_TARGET_QCOM = $8BDA;
{$EXTERNALSYM GL_TEXTURE_TARGET_QCOM}
GL_TEXTURE_OBJECT_VALID_QCOM = $8BDB;
{$EXTERNALSYM GL_TEXTURE_OBJECT_VALID_QCOM}
GL_STATE_RESTORE = $8BDC;
{$EXTERNALSYM GL_STATE_RESTORE}
{ GL_QCOM_extended_get2 }
{ No new tokens introduced by this extension. }
{ GL_QCOM_perfmon_global_mode }
GL_PERFMON_GLOBAL_MODE_QCOM = $8FA0;
{$EXTERNALSYM GL_PERFMON_GLOBAL_MODE_QCOM}
{ GL_QCOM_writeonly_rendering }
GL_WRITEONLY_RENDERING_QCOM = $8823;
{$EXTERNALSYM GL_WRITEONLY_RENDERING_QCOM}
{ GL_QCOM_tiled_rendering }
GL_COLOR_BUFFER_BIT0_QCOM = $00000001;
{$EXTERNALSYM GL_COLOR_BUFFER_BIT0_QCOM}
GL_COLOR_BUFFER_BIT1_QCOM = $00000002;
{$EXTERNALSYM GL_COLOR_BUFFER_BIT1_QCOM}
GL_COLOR_BUFFER_BIT2_QCOM = $00000004;
{$EXTERNALSYM GL_COLOR_BUFFER_BIT2_QCOM}
GL_COLOR_BUFFER_BIT3_QCOM = $00000008;
{$EXTERNALSYM GL_COLOR_BUFFER_BIT3_QCOM}
GL_COLOR_BUFFER_BIT4_QCOM = $00000010;
{$EXTERNALSYM GL_COLOR_BUFFER_BIT4_QCOM}
GL_COLOR_BUFFER_BIT5_QCOM = $00000020;
{$EXTERNALSYM GL_COLOR_BUFFER_BIT5_QCOM}
GL_COLOR_BUFFER_BIT6_QCOM = $00000040;
{$EXTERNALSYM GL_COLOR_BUFFER_BIT6_QCOM}
GL_COLOR_BUFFER_BIT7_QCOM = $00000080;
{$EXTERNALSYM GL_COLOR_BUFFER_BIT7_QCOM}
GL_DEPTH_BUFFER_BIT0_QCOM = $00000100;
{$EXTERNALSYM GL_DEPTH_BUFFER_BIT0_QCOM}
GL_DEPTH_BUFFER_BIT1_QCOM = $00000200;
{$EXTERNALSYM GL_DEPTH_BUFFER_BIT1_QCOM}
GL_DEPTH_BUFFER_BIT2_QCOM = $00000400;
{$EXTERNALSYM GL_DEPTH_BUFFER_BIT2_QCOM}
GL_DEPTH_BUFFER_BIT3_QCOM = $00000800;
{$EXTERNALSYM GL_DEPTH_BUFFER_BIT3_QCOM}
GL_DEPTH_BUFFER_BIT4_QCOM = $00001000;
{$EXTERNALSYM GL_DEPTH_BUFFER_BIT4_QCOM}
GL_DEPTH_BUFFER_BIT5_QCOM = $00002000;
{$EXTERNALSYM GL_DEPTH_BUFFER_BIT5_QCOM}
GL_DEPTH_BUFFER_BIT6_QCOM = $00004000;
{$EXTERNALSYM GL_DEPTH_BUFFER_BIT6_QCOM}
GL_DEPTH_BUFFER_BIT7_QCOM = $00008000;
{$EXTERNALSYM GL_DEPTH_BUFFER_BIT7_QCOM}
GL_STENCIL_BUFFER_BIT0_QCOM = $00010000;
{$EXTERNALSYM GL_STENCIL_BUFFER_BIT0_QCOM}
GL_STENCIL_BUFFER_BIT1_QCOM = $00020000;
{$EXTERNALSYM GL_STENCIL_BUFFER_BIT1_QCOM}
GL_STENCIL_BUFFER_BIT2_QCOM = $00040000;
{$EXTERNALSYM GL_STENCIL_BUFFER_BIT2_QCOM}
GL_STENCIL_BUFFER_BIT3_QCOM = $00080000;
{$EXTERNALSYM GL_STENCIL_BUFFER_BIT3_QCOM}
GL_STENCIL_BUFFER_BIT4_QCOM = $00100000;
{$EXTERNALSYM GL_STENCIL_BUFFER_BIT4_QCOM}
GL_STENCIL_BUFFER_BIT5_QCOM = $00200000;
{$EXTERNALSYM GL_STENCIL_BUFFER_BIT5_QCOM}
GL_STENCIL_BUFFER_BIT6_QCOM = $00400000;
{$EXTERNALSYM GL_STENCIL_BUFFER_BIT6_QCOM}
GL_STENCIL_BUFFER_BIT7_QCOM = $00800000;
{$EXTERNALSYM GL_STENCIL_BUFFER_BIT7_QCOM}
GL_MULTISAMPLE_BUFFER_BIT0_QCOM = $01000000;
{$EXTERNALSYM GL_MULTISAMPLE_BUFFER_BIT0_QCOM}
GL_MULTISAMPLE_BUFFER_BIT1_QCOM = $02000000;
{$EXTERNALSYM GL_MULTISAMPLE_BUFFER_BIT1_QCOM}
GL_MULTISAMPLE_BUFFER_BIT2_QCOM = $04000000;
{$EXTERNALSYM GL_MULTISAMPLE_BUFFER_BIT2_QCOM}
GL_MULTISAMPLE_BUFFER_BIT3_QCOM = $08000000;
{$EXTERNALSYM GL_MULTISAMPLE_BUFFER_BIT3_QCOM}
GL_MULTISAMPLE_BUFFER_BIT4_QCOM = $10000000;
{$EXTERNALSYM GL_MULTISAMPLE_BUFFER_BIT4_QCOM}
GL_MULTISAMPLE_BUFFER_BIT5_QCOM = $20000000;
{$EXTERNALSYM GL_MULTISAMPLE_BUFFER_BIT5_QCOM}
GL_MULTISAMPLE_BUFFER_BIT6_QCOM = $40000000;
{$EXTERNALSYM GL_MULTISAMPLE_BUFFER_BIT6_QCOM}
GL_MULTISAMPLE_BUFFER_BIT7_QCOM = $80000000;
{$EXTERNALSYM GL_MULTISAMPLE_BUFFER_BIT7_QCOM}
{ ------------------------------------------------------------------------
End of extension tokens, start of corresponding extension functions
------------------------------------------------------------------------ }
{ ------------------------------------------------------------------------
OES extension functions
------------------------------------------------------------------------ }
{ GL_OES_blend_equation_separate }
const
GL_OES_blend_equation_separate = 1;
{$EXTERNALSYM GL_OES_blend_equation_separate}
procedure glBlendEquationSeparateOES(modeRGB: GLenum; modeAlpha: GLenum); cdecl;
external AndroidEglLib name 'glBlendEquationSeparateOES';
{$EXTERNALSYM glBlendEquationSeparateOES}
type
PFNGLBLENDEQUATIONSEPARATEOESPROC = procedure(modeRGB: GLenum; modeAlpha: GLenum);
{$EXTERNALSYM PFNGLBLENDEQUATIONSEPARATEOESPROC}
{ GL_OES_blend_func_separate }
const
GL_OES_blend_func_separate = 1;
{$EXTERNALSYM GL_OES_blend_func_separate}
procedure glBlendFuncSeparateOES(srcRGB: GLenum; dstRGB: GLenum; srcAlpha: GLenum; dstAlpha: GLenum); cdecl;
external AndroidEglLib name 'glBlendFuncSeparateOES';
{$EXTERNALSYM glBlendFuncSeparateOES}
type
PFNGLBLENDFUNCSEPARATEOESPROC = procedure(srcRGB: GLenum; dstRGB: GLenum; srcAlpha: GLenum; dstAlpha: GLenum);
{$EXTERNALSYM PFNGLBLENDFUNCSEPARATEOESPROC}
{ GL_OES_blend_subtract }
const
GL_OES_blend_subtract = 1;
{$EXTERNALSYM GL_OES_blend_subtract}
procedure glBlendEquationOES(mode: GLenum); cdecl;
external AndroidEglLib name 'glBlendEquationOES';
{$EXTERNALSYM glBlendEquationOES}
type
PFNGLBLENDEQUATIONOESPROC = procedure(mode: GLenum);
{$EXTERNALSYM PFNGLBLENDEQUATIONOESPROC}
{ GL_OES_byte_coordinates }
const
GL_OES_byte_coordinates = 1;
{$EXTERNALSYM GL_OES_byte_coordinates}
{ GL_OES_compressed_ETC1_RGB8_texture }
GL_OES_compressed_ETC1_RGB8_texture = 1;
{$EXTERNALSYM GL_OES_compressed_ETC1_RGB8_texture}
{ GL_OES_depth24 }
GL_OES_depth24 = 1;
{$EXTERNALSYM GL_OES_depth24}
{ GL_OES_depth32 }
GL_OES_depth32 = 1;
{$EXTERNALSYM GL_OES_depth32}
{ GL_OES_draw_texture }
GL_OES_draw_texture = 1;
{$EXTERNALSYM GL_OES_draw_texture}
procedure glDrawTexsOES(x: GLshort; y: GLshort; z: GLshort; width: GLshort; height: GLshort); cdecl;
external AndroidEglLib name 'glDrawTexsOES';
{$EXTERNALSYM glDrawTexsOES}
procedure glDrawTexiOES(x: GLint; y: GLint; z: GLint; width: GLint; height: GLint); cdecl;
external AndroidEglLib name 'glDrawTexiOES';
{$EXTERNALSYM glDrawTexiOES}
procedure glDrawTexxOES(x: GLfixed; y: GLfixed; z: GLfixed; width: GLfixed; height: GLfixed); cdecl;
external AndroidEglLib name 'glDrawTexxOES';
{$EXTERNALSYM glDrawTexxOES}
procedure glDrawTexsvOES(const coords: PGLshort); cdecl;
external AndroidEglLib name 'glDrawTexsvOES';
{$EXTERNALSYM glDrawTexsvOES}
procedure glDrawTexivOES(const coords: PGLint); cdecl;
external AndroidEglLib name 'glDrawTexivOES';
{$EXTERNALSYM glDrawTexivOES}
procedure glDrawTexxvOES(const coords: PGLfixed); cdecl;
external AndroidEglLib name 'glDrawTexxvOES';
{$EXTERNALSYM glDrawTexxvOES}
procedure glDrawTexfOES(x: GLfloat; y: GLfloat; z: GLfloat; width: GLfloat; height: GLfloat); cdecl;
external AndroidEglLib name 'glDrawTexfOES';
{$EXTERNALSYM glDrawTexfOES}
procedure glDrawTexfvOES(const coords: PGLfloat); cdecl;
external AndroidEglLib name 'glDrawTexfvOES';
{$EXTERNALSYM glDrawTexfvOES}
type
PFNGLDRAWTEXSOESPROC = procedure(x: GLshort; y: GLshort; z: GLshort; width: GLshort; height: GLshort);
{$EXTERNALSYM PFNGLDRAWTEXSOESPROC}
PFNGLDRAWTEXIOESPROC = procedure(x: GLint; y: GLint; z: GLint; width: GLint; height: GLint);
{$EXTERNALSYM PFNGLDRAWTEXIOESPROC}
PFNGLDRAWTEXXOESPROC = procedure(x: GLfixed; y: GLfixed; z: GLfixed; width: GLfixed; height: GLfixed);
{$EXTERNALSYM PFNGLDRAWTEXXOESPROC}
PFNGLDRAWTEXSVOESPROC = procedure(const coords: PGLshort);
{$EXTERNALSYM PFNGLDRAWTEXSVOESPROC}
PFNGLDRAWTEXIVOESPROC = procedure(const coords: PGLint);
{$EXTERNALSYM PFNGLDRAWTEXIVOESPROC}
PFNGLDRAWTEXXVOESPROC = procedure(const coords: PGLfixed);
{$EXTERNALSYM PFNGLDRAWTEXXVOESPROC}
PFNGLDRAWTEXFOESPROC = procedure(x: GLfloat; y: GLfloat; z: GLfloat; width: GLfloat; height: GLfloat);
{$EXTERNALSYM PFNGLDRAWTEXFOESPROC}
PFNGLDRAWTEXFVOESPROC = procedure(const coords: PGLfloat);
{$EXTERNALSYM PFNGLDRAWTEXFVOESPROC}
{ GL_OES_EGL_image }
const
GL_OES_EGL_image = 1;
{$EXTERNALSYM GL_OES_EGL_image}
procedure glEGLImageTargetTexture2DOES(target: GLenum; image: GLeglImageOES); cdecl;
external AndroidEglLib name 'glEGLImageTargetTexture2DOES';
{$EXTERNALSYM glEGLImageTargetTexture2DOES}
procedure glEGLImageTargetRenderbufferStorageOES(target: GLenum; image: GLeglImageOES); cdecl;
external AndroidEglLib name 'glEGLImageTargetRenderbufferStorageOES';
{$EXTERNALSYM glEGLImageTargetRenderbufferStorageOES}
type
PFNGLEGLIMAGETARGETTEXTURE2DOESPROC = procedure(target: GLenum; image: GLeglImageOES);
{$EXTERNALSYM PFNGLEGLIMAGETARGETTEXTURE2DOESPROC}
PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC = procedure(target: GLenum; image: GLeglImageOES);
{$EXTERNALSYM PFNGLEGLIMAGETARGETRENDERBUFFERSTORAGEOESPROC}
const
{ GL_OES_element_index_uint }
GL_OES_element_index_uint = 1;
{$EXTERNALSYM GL_OES_element_index_uint}
{ GL_OES_extended_matrix_palette }
GL_OES_extended_matrix_palette = 1;
{$EXTERNALSYM GL_OES_extended_matrix_palette}
{ GL_OES_fbo_render_mipmap }
GL_OES_fbo_render_mipmap = 1;
{$EXTERNALSYM GL_OES_fbo_render_mipmap}
{ GL_OES_fixed_point }
GL_OES_fixed_point = 1;
{$EXTERNALSYM GL_OES_fixed_point}
procedure glAlphaFuncxOES(func: GLenum; ref: GLclampx); cdecl;
external AndroidEglLib name 'glAlphaFuncxOES';
{$EXTERNALSYM glAlphaFuncxOES}
procedure glClearColorxOES(red: GLclampx; green: GLclampx; blue: GLclampx; alpha: GLclampx); cdecl;
external AndroidEglLib name 'glClearColorxOES';
{$EXTERNALSYM glClearColorxOES}
procedure glClearDepthxOES(depth: GLclampx); cdecl;
external AndroidEglLib name 'glClearDepthxOES';
{$EXTERNALSYM glClearDepthxOES}
procedure glClipPlanexOES(plane: GLenum; const equation: PGLfixed); cdecl;
external AndroidEglLib name 'glClipPlanexOES';
{$EXTERNALSYM glClipPlanexOES}
procedure glColor4xOES(red: GLfixed; green: GLfixed; blue: GLfixed; alpha: GLfixed); cdecl;
external AndroidEglLib name 'glColor4xOES';
{$EXTERNALSYM glColor4xOES}
procedure glDepthRangexOES(zNear: GLclampx; zFar: GLclampx); cdecl;
external AndroidEglLib name 'glDepthRangexOES';
{$EXTERNALSYM glDepthRangexOES}
procedure glFogxOES(pname: GLenum; param: GLfixed); cdecl;
external AndroidEglLib name 'glFogxOES';
{$EXTERNALSYM glFogxOES}
procedure glFogxvOES(pname: GLenum; const params: PGLfixed); cdecl;
external AndroidEglLib name 'glFogxvOES';
{$EXTERNALSYM glFogxvOES}
procedure glFrustumxOES(left: GLfixed; right: GLfixed; bottom: GLfixed; top: GLfixed; zNear: GLfixed; zFar: GLfixed); cdecl;
external AndroidEglLib name 'glFrustumxOES';
{$EXTERNALSYM glFrustumxOES}
procedure glGetClipPlanexOES(pname: GLenum; eqn: PGLfixed{array [0..3]}); cdecl;
external AndroidEglLib name 'glGetClipPlanexOES';
{$EXTERNALSYM glGetClipPlanexOES}
procedure glGetFixedvOES(pname: GLenum; params: PGLfixed); cdecl;
external AndroidEglLib name 'glGetFixedvOES';
{$EXTERNALSYM glGetFixedvOES}
procedure glGetLightxvOES(light: GLenum; pname: GLenum; params: PGLfixed); cdecl;
external AndroidEglLib name 'glGetLightxvOES';
{$EXTERNALSYM glGetLightxvOES}
procedure glGetMaterialxvOES(face: GLenum; pname: GLenum; params: PGLfixed); cdecl;
external AndroidEglLib name 'glGetMaterialxvOES';
{$EXTERNALSYM glGetMaterialxvOES}
procedure glGetTexEnvxvOES(env: GLenum; pname: GLenum; params: PGLfixed); cdecl;
external AndroidEglLib name 'glGetTexEnvxvOES';
{$EXTERNALSYM glGetTexEnvxvOES}
procedure glGetTexParameterxvOES(target: GLenum; pname: GLenum; params: PGLfixed); cdecl;
external AndroidEglLib name 'glGetTexParameterxvOES';
{$EXTERNALSYM glGetTexParameterxvOES}
procedure glLightModelxOES(pname: GLenum; param: GLfixed); cdecl;
external AndroidEglLib name 'glLightModelxOES';
{$EXTERNALSYM glLightModelxOES}
procedure glLightModelxvOES(pname: GLenum; const params: PGLfixed); cdecl;
external AndroidEglLib name 'glLightModelxvOES';
{$EXTERNALSYM glLightModelxvOES}
procedure glLightxOES(light: GLenum; pname: GLenum; param: GLfixed); cdecl;
external AndroidEglLib name 'glLightxOES';
{$EXTERNALSYM glLightxOES}
procedure glLightxvOES(light: GLenum; pname: GLenum; const params: PGLfixed); cdecl;
external AndroidEglLib name 'glLightxvOES';
{$EXTERNALSYM glLightxvOES}
procedure glLineWidthxOES(width: GLfixed); cdecl;
external AndroidEglLib name 'glLineWidthxOES';
{$EXTERNALSYM glLineWidthxOES}
procedure glLoadMatrixxOES(const m: PGLfixed); cdecl;
external AndroidEglLib name 'glLoadMatrixxOES';
{$EXTERNALSYM glLoadMatrixxOES}
procedure glMaterialxOES(face: GLenum; pname: GLenum; param: GLfixed); cdecl;
external AndroidEglLib name 'glMaterialxOES';
{$EXTERNALSYM glMaterialxOES}
procedure glMaterialxvOES(face: GLenum; pname: GLenum; const params: PGLfixed); cdecl;
external AndroidEglLib name 'glMaterialxvOES';
{$EXTERNALSYM glMaterialxvOES}
procedure glMultMatrixxOES(const m: PGLfixed); cdecl;
external AndroidEglLib name 'glMultMatrixxOES';
{$EXTERNALSYM glMultMatrixxOES}
procedure glMultiTexCoord4xOES(target: GLenum; s: GLfixed; t: GLfixed; r: GLfixed; q: GLfixed); cdecl;
external AndroidEglLib name 'glMultiTexCoord4xOES';
{$EXTERNALSYM glMultiTexCoord4xOES}
procedure glNormal3xOES(nx: GLfixed; ny: GLfixed; nz: GLfixed); cdecl;
external AndroidEglLib name 'glNormal3xOES';
{$EXTERNALSYM glNormal3xOES}
procedure glOrthoxOES(left: GLfixed; right: GLfixed; bottom: GLfixed; top: GLfixed; zNear: GLfixed; zFar: GLfixed); cdecl;
external AndroidEglLib name 'glOrthoxOES';
{$EXTERNALSYM glOrthoxOES}
procedure glPointParameterxOES(pname: GLenum; param: GLfixed); cdecl;
external AndroidEglLib name 'glPointParameterxOES';
{$EXTERNALSYM glPointParameterxOES}
procedure glPointParameterxvOES(pname: GLenum; const params: PGLfixed); cdecl;
external AndroidEglLib name 'glPointParameterxvOES';
{$EXTERNALSYM glPointParameterxvOES}
procedure glPointSizexOES(size: GLfixed); cdecl;
external AndroidEglLib name 'glPointSizexOES';
{$EXTERNALSYM glPointSizexOES}
procedure glPolygonOffsetxOES(factor: GLfixed; units: GLfixed); cdecl;
external AndroidEglLib name 'glPolygonOffsetxOES';
{$EXTERNALSYM glPolygonOffsetxOES}
procedure glRotatexOES(angle: GLfixed; x: GLfixed; y: GLfixed; z: GLfixed); cdecl;
external AndroidEglLib name 'glRotatexOES';
{$EXTERNALSYM glRotatexOES}
procedure glSampleCoveragexOES(value: GLclampx; invert: GLboolean); cdecl;
external AndroidEglLib name 'glSampleCoveragexOES';
{$EXTERNALSYM glSampleCoveragexOES}
procedure glScalexOES(x: GLfixed; y: GLfixed; z: GLfixed); cdecl;
external AndroidEglLib name 'glScalexOES';
{$EXTERNALSYM glScalexOES}
procedure glTexEnvxOES(target: GLenum; pname: GLenum; param: GLfixed); cdecl;
external AndroidEglLib name 'glTexEnvxOES';
{$EXTERNALSYM glTexEnvxOES}
procedure glTexEnvxvOES(target: GLenum; pname: GLenum; const params: PGLfixed); cdecl;
external AndroidEglLib name 'glTexEnvxvOES';
{$EXTERNALSYM glTexEnvxvOES}
procedure glTexParameterxOES(target: GLenum; pname: GLenum; param: GLfixed); cdecl;
external AndroidEglLib name 'glTexParameterxOES';
{$EXTERNALSYM glTexParameterxOES}
procedure glTexParameterxvOES(target: GLenum; pname: GLenum; const params: PGLfixed); cdecl;
external AndroidEglLib name 'glTexParameterxvOES';
{$EXTERNALSYM glTexParameterxvOES}
procedure glTranslatexOES(x: GLfixed; y: GLfixed; z: GLfixed); cdecl;
external AndroidEglLib name 'glTranslatexOES';
{$EXTERNALSYM glTranslatexOES}
type
PFNGLALPHAFUNCXOESPROC = procedure(func: GLenum; ref: GLclampx);
{$EXTERNALSYM PFNGLALPHAFUNCXOESPROC}
PFNGLCLEARCOLORXOESPROC = procedure(red: GLclampx; green: GLclampx; blue: GLclampx; alpha: GLclampx);
{$EXTERNALSYM PFNGLCLEARCOLORXOESPROC}
PFNGLCLEARDEPTHXOESPROC = procedure(depth: GLclampx);
{$EXTERNALSYM PFNGLCLEARDEPTHXOESPROC}
PFNGLCLIPPLANEXOESPROC = procedure(plane: GLenum; const equation: PGLfixed);
{$EXTERNALSYM PFNGLCLIPPLANEXOESPROC}
PFNGLCOLOR4XOESPROC = procedure(red: GLfixed; green: GLfixed; blue: GLfixed; alpha: GLfixed);
{$EXTERNALSYM PFNGLCOLOR4XOESPROC}
PFNGLDEPTHRANGEXOESPROC = procedure(zNear: GLclampx; zFar: GLclampx);
{$EXTERNALSYM PFNGLDEPTHRANGEXOESPROC}
PFNGLFOGXOESPROC = procedure(pname: GLenum; param: GLfixed);
{$EXTERNALSYM PFNGLFOGXOESPROC}
PFNGLFOGXVOESPROC = procedure(pname: GLenum; const params: PGLfixed);
{$EXTERNALSYM PFNGLFOGXVOESPROC}
PFNGLFRUSTUMXOESPROC = procedure(left: GLfixed; right: GLfixed; bottom: GLfixed; top: GLfixed; zNear: GLfixed; zFar: GLfixed);
{$EXTERNALSYM PFNGLFRUSTUMXOESPROC}
PFNGLGETCLIPPLANEXOESPROC = procedure(pname: GLenum; eqn: PGLfixed{array [0..3]});
{$EXTERNALSYM PFNGLGETCLIPPLANEXOESPROC}
PFNGLGETFIXEDVOESPROC = procedure(pname: GLenum; params: PGLfixed);
{$EXTERNALSYM PFNGLGETFIXEDVOESPROC}
PFNGLGETLIGHTXVOESPROC = procedure(light: GLenum; pname: GLenum; params: PGLfixed);
{$EXTERNALSYM PFNGLGETLIGHTXVOESPROC}
PFNGLGETMATERIALXVOESPROC = procedure(face: GLenum; pname: GLenum; params: PGLfixed);
{$EXTERNALSYM PFNGLGETMATERIALXVOESPROC}
PFNGLGETTEXENVXVOESPROC = procedure(env: GLenum; pname: GLenum; params: PGLfixed);
{$EXTERNALSYM PFNGLGETTEXENVXVOESPROC}
PFNGLGETTEXPARAMETERXVOESPROC = procedure(target: GLenum; pname: GLenum; params: PGLfixed);
{$EXTERNALSYM PFNGLGETTEXPARAMETERXVOESPROC}
PFNGLLIGHTMODELXOESPROC = procedure(pname: GLenum; param: GLfixed);
{$EXTERNALSYM PFNGLLIGHTMODELXOESPROC}
PFNGLLIGHTMODELXVOESPROC = procedure(pname: GLenum; const params: PGLfixed);
{$EXTERNALSYM PFNGLLIGHTMODELXVOESPROC}
PFNGLLIGHTXOESPROC = procedure(light: GLenum; pname: GLenum; param: GLfixed);
{$EXTERNALSYM PFNGLLIGHTXOESPROC}
PFNGLLIGHTXVOESPROC = procedure(light: GLenum; pname: GLenum; const params: PGLfixed);
{$EXTERNALSYM PFNGLLIGHTXVOESPROC}
PFNGLLINEWIDTHXOESPROC = procedure(width: GLfixed);
{$EXTERNALSYM PFNGLLINEWIDTHXOESPROC}
PFNGLLOADMATRIXXOESPROC = procedure(const m: PGLfixed);
{$EXTERNALSYM PFNGLLOADMATRIXXOESPROC}
PFNGLMATERIALXOESPROC = procedure(face: GLenum; pname: GLenum; param: GLfixed);
{$EXTERNALSYM PFNGLMATERIALXOESPROC}
PFNGLMATERIALXVOESPROC = procedure(face: GLenum; pname: GLenum; const params: PGLfixed);
{$EXTERNALSYM PFNGLMATERIALXVOESPROC}
PFNGLMULTMATRIXXOESPROC = procedure(const m: PGLfixed);
{$EXTERNALSYM PFNGLMULTMATRIXXOESPROC}
PFNGLMULTITEXCOORD4XOESPROC = procedure(target: GLenum; s: GLfixed; t: GLfixed; r: GLfixed; q: GLfixed);
{$EXTERNALSYM PFNGLMULTITEXCOORD4XOESPROC}
PFNGLNORMAL3XOESPROC = procedure(nx: GLfixed; ny: GLfixed; nz: GLfixed);
{$EXTERNALSYM PFNGLNORMAL3XOESPROC}
PFNGLORTHOXOESPROC = procedure(left: GLfixed; right: GLfixed; bottom: GLfixed; top: GLfixed; zNear: GLfixed; zFar: GLfixed);
{$EXTERNALSYM PFNGLORTHOXOESPROC}
PFNGLPOINTPARAMETERXOESPROC = procedure(pname: GLenum; param: GLfixed);
{$EXTERNALSYM PFNGLPOINTPARAMETERXOESPROC}
PFNGLPOINTPARAMETERXVOESPROC = procedure(pname: GLenum; const params: PGLfixed);
{$EXTERNALSYM PFNGLPOINTPARAMETERXVOESPROC}
PFNGLPOINTSIZEXOESPROC = procedure(size: GLfixed);
{$EXTERNALSYM PFNGLPOINTSIZEXOESPROC}
PFNGLPOLYGONOFFSETXOESPROC = procedure(factor: GLfixed; units: GLfixed);
{$EXTERNALSYM PFNGLPOLYGONOFFSETXOESPROC}
PFNGLROTATEXOESPROC = procedure(angle: GLfixed; x: GLfixed; y: GLfixed; z: GLfixed);
{$EXTERNALSYM PFNGLROTATEXOESPROC}
PFNGLSAMPLECOVERAGEXOESPROC = procedure(value: GLclampx; invert: GLboolean);
{$EXTERNALSYM PFNGLSAMPLECOVERAGEXOESPROC}
PFNGLSCALEXOESPROC = procedure(x: GLfixed; y: GLfixed; z: GLfixed);
{$EXTERNALSYM PFNGLSCALEXOESPROC}
PFNGLTEXENVXOESPROC = procedure(target: GLenum; pname: GLenum; param: GLfixed);
{$EXTERNALSYM PFNGLTEXENVXOESPROC}
PFNGLTEXENVXVOESPROC = procedure(target: GLenum; pname: GLenum; const params: PGLfixed);
{$EXTERNALSYM PFNGLTEXENVXVOESPROC}
PFNGLTEXPARAMETERXOESPROC = procedure(target: GLenum; pname: GLenum; param: GLfixed);
{$EXTERNALSYM PFNGLTEXPARAMETERXOESPROC}
PFNGLTEXPARAMETERXVOESPROC = procedure(target: GLenum; pname: GLenum; const params: PGLfixed);
{$EXTERNALSYM PFNGLTEXPARAMETERXVOESPROC}
PFNGLTRANSLATEXOESPROC = procedure(x: GLfixed; y: GLfixed; z: GLfixed);
{$EXTERNALSYM PFNGLTRANSLATEXOESPROC}
const
{ GL_OES_framebuffer_object }
GL_OES_framebuffer_object = 1;
{$EXTERNALSYM GL_OES_framebuffer_object}
function glIsRenderbufferOES (renderbuffer: GLuint): GLboolean; cdecl;
external AndroidEglLib name 'glIsRenderbufferOES';
{$EXTERNALSYM glIsRenderbufferOES}
procedure glBindRenderbufferOES(target: GLenum; renderbuffer: GLuint); cdecl;
external AndroidEglLib name 'glBindRenderbufferOES';
{$EXTERNALSYM glBindRenderbufferOES}
procedure glDeleteRenderbuffersOES(n: GLsizei; const renderbuffers: PGLuint); cdecl;
external AndroidEglLib name 'glDeleteRenderbuffersOES';
{$EXTERNALSYM glDeleteRenderbuffersOES}
procedure glGenRenderbuffersOES(n: GLsizei; renderbuffers: PGLuint); cdecl;
external AndroidEglLib name 'glGenRenderbuffersOES';
{$EXTERNALSYM glGenRenderbuffersOES}
procedure glRenderbufferStorageOES(target: GLenum; internalformat: GLenum; width: GLsizei; height: GLsizei); cdecl;
external AndroidEglLib name 'glRenderbufferStorageOES';
{$EXTERNALSYM glRenderbufferStorageOES}
procedure glGetRenderbufferParameterivOES(target: GLenum; pname: GLenum; params: PGLint); cdecl;
external AndroidEglLib name 'glGetRenderbufferParameterivOES';
{$EXTERNALSYM glGetRenderbufferParameterivOES}
function glIsFramebufferOES (framebuffer: GLuint): GLboolean; cdecl;
external AndroidEglLib name 'glIsFramebufferOES';
{$EXTERNALSYM glIsFramebufferOES}
procedure glBindFramebufferOES(target: GLenum; framebuffer: GLuint); cdecl;
external AndroidEglLib name 'glBindFramebufferOES';
{$EXTERNALSYM glBindFramebufferOES}
procedure glDeleteFramebuffersOES(n: GLsizei; const framebuffers: PGLuint); cdecl;
external AndroidEglLib name 'glDeleteFramebuffersOES';
{$EXTERNALSYM glDeleteFramebuffersOES}
procedure glGenFramebuffersOES(n: GLsizei; framebuffers: PGLuint); cdecl;
external AndroidEglLib name 'glGenFramebuffersOES';
{$EXTERNALSYM glGenFramebuffersOES}
function glCheckFramebufferStatusOES (target: GLenum): GLenum; cdecl;
external AndroidEglLib name 'glCheckFramebufferStatusOES';
{$EXTERNALSYM glCheckFramebufferStatusOES}
procedure glFramebufferRenderbufferOES(target: GLenum; attachment: GLenum; renderbuffertarget: GLenum; renderbuffer: GLuint); cdecl;
external AndroidEglLib name 'glFramebufferRenderbufferOES';
{$EXTERNALSYM glFramebufferRenderbufferOES}
procedure glFramebufferTexture2DOES(target: GLenum; attachment: GLenum; textarget: GLenum; texture: GLuint; level: GLint); cdecl;
external AndroidEglLib name 'glFramebufferTexture2DOES';
{$EXTERNALSYM glFramebufferTexture2DOES}
procedure glGetFramebufferAttachmentParameterivOES(target: GLenum; attachment: GLenum; pname: GLenum; params: PGLint); cdecl;
external AndroidEglLib name 'glGetFramebufferAttachmentParameterivOES';
{$EXTERNALSYM glGetFramebufferAttachmentParameterivOES}
procedure glGenerateMipmapOES(target: GLenum); cdecl;
external AndroidEglLib name 'glGenerateMipmapOES';
{$EXTERNALSYM glGenerateMipmapOES}
type
PFNGLISRENDERBUFFEROESPROC = function(renderbuffer: GLuint): GLboolean;
{$EXTERNALSYM PFNGLISRENDERBUFFEROESPROC}
PFNGLBINDRENDERBUFFEROESPROC = procedure(target: GLenum; renderbuffer: GLuint);
{$EXTERNALSYM PFNGLBINDRENDERBUFFEROESPROC}
PFNGLDELETERENDERBUFFERSOESPROC = procedure(n: GLsizei; const renderbuffers: PGLuint);
{$EXTERNALSYM PFNGLDELETERENDERBUFFERSOESPROC}
PFNGLGENRENDERBUFFERSOESPROC = procedure(n: GLsizei; renderbuffers: PGLuint);
{$EXTERNALSYM PFNGLGENRENDERBUFFERSOESPROC}
PFNGLRENDERBUFFERSTORAGEOESPROC = procedure(target: GLenum; internalformat: GLenum; width: GLsizei; height: GLsizei);
{$EXTERNALSYM PFNGLRENDERBUFFERSTORAGEOESPROC}
PFNGLGETRENDERBUFFERPARAMETERIVOESPROC = procedure(target: GLenum; pname: GLenum; params: PGLint);
{$EXTERNALSYM PFNGLGETRENDERBUFFERPARAMETERIVOESPROC}
PFNGLISFRAMEBUFFEROESPROC = function(framebuffer: GLuint): GLboolean;
{$EXTERNALSYM PFNGLISFRAMEBUFFEROESPROC}
PFNGLBINDFRAMEBUFFEROESPROC = procedure(target: GLenum; framebuffer: GLuint);
{$EXTERNALSYM PFNGLBINDFRAMEBUFFEROESPROC}
PFNGLDELETEFRAMEBUFFERSOESPROC = procedure(n: GLsizei; const framebuffers: PGLuint);
{$EXTERNALSYM PFNGLDELETEFRAMEBUFFERSOESPROC}
PFNGLGENFRAMEBUFFERSOESPROC = procedure(n: GLsizei; framebuffers: PGLuint);
{$EXTERNALSYM PFNGLGENFRAMEBUFFERSOESPROC}
PFNGLCHECKFRAMEBUFFERSTATUSOESPROC = function(target: GLenum): GLenum;
{$EXTERNALSYM PFNGLCHECKFRAMEBUFFERSTATUSOESPROC}
PFNGLFRAMEBUFFERRENDERBUFFEROESPROC = procedure(target: GLenum; attachment: GLenum; renderbuffertarget: GLenum; renderbuffer: GLuint);
{$EXTERNALSYM PFNGLFRAMEBUFFERRENDERBUFFEROESPROC}
PFNGLFRAMEBUFFERTEXTURE2DOESPROC = procedure(target: GLenum; attachment: GLenum; textarget: GLenum; texture: GLuint; level: GLint);
{$EXTERNALSYM PFNGLFRAMEBUFFERTEXTURE2DOESPROC}
PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVOESPROC = procedure(target: GLenum; attachment: GLenum; pname: GLenum; params: PGLint);
{$EXTERNALSYM PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVOESPROC}
PFNGLGENERATEMIPMAPOESPROC = procedure(target: GLenum);
{$EXTERNALSYM PFNGLGENERATEMIPMAPOESPROC}
const
{ GL_OES_mapbuffer }
GL_OES_mapbuffer = 1;
{$EXTERNALSYM GL_OES_mapbuffer}
function glMapBufferOES(target: GLenum; access: GLenum): Pointer; cdecl;
external AndroidEglLib name 'glMapBufferOES';
{$EXTERNALSYM glMapBufferOES}
function glUnmapBufferOES (target: GLenum): GLboolean; cdecl;
external AndroidEglLib name 'glUnmapBufferOES';
{$EXTERNALSYM glUnmapBufferOES}
procedure glGetBufferPointervOES(target: GLenum; pname: GLenum; params: PPGLvoid); cdecl;
external AndroidEglLib name 'glGetBufferPointervOES';
{$EXTERNALSYM glGetBufferPointervOES}
type
PFNGLMAPBUFFEROESPROC = function(target: GLenum; access: GLenum): Pointer;
{$EXTERNALSYM PFNGLMAPBUFFEROESPROC}
PFNGLUNMAPBUFFEROESPROC = function(target: GLenum): GLboolean;
{$EXTERNALSYM PFNGLUNMAPBUFFEROESPROC}
PFNGLGETBUFFERPOINTERVOESPROC = procedure(target: GLenum; pname: GLenum; params: PPGLvoid);
{$EXTERNALSYM PFNGLGETBUFFERPOINTERVOESPROC}
const
{ GL_OES_matrix_get }
GL_OES_matrix_get = 1;
{$EXTERNALSYM GL_OES_matrix_get}
{ GL_OES_matrix_palette }
GL_OES_matrix_palette = 1;
{$EXTERNALSYM GL_OES_matrix_palette}
procedure glCurrentPaletteMatrixOES(matrixpaletteindex: GLuint); cdecl;
external AndroidEglLib name 'glCurrentPaletteMatrixOES';
{$EXTERNALSYM glCurrentPaletteMatrixOES}
procedure glLoadPaletteFromModelViewMatrixOES; cdecl;
external AndroidEglLib name 'glLoadPaletteFromModelViewMatrixOES';
{$EXTERNALSYM glLoadPaletteFromModelViewMatrixOES}
procedure glMatrixIndexPointerOES(size: GLint; _type: GLenum; stride: GLsizei; const pointer: PGLvoid); cdecl;
external AndroidEglLib name 'glMatrixIndexPointerOES';
{$EXTERNALSYM glMatrixIndexPointerOES}
procedure glWeightPointerOES(size: GLint; _type: GLenum; stride: GLsizei; const pointer: PGLvoid); cdecl;
external AndroidEglLib name 'glWeightPointerOES';
{$EXTERNALSYM glWeightPointerOES}
type
PFNGLCURRENTPALETTEMATRIXOESPROC = procedure(matrixpaletteindex: GLuint);
{$EXTERNALSYM PFNGLCURRENTPALETTEMATRIXOESPROC}
PFNGLLOADPALETTEFROMMODELVIEWMATRIXOESPROC = procedure;
{$EXTERNALSYM PFNGLLOADPALETTEFROMMODELVIEWMATRIXOESPROC}
PFNGLMATRIXINDEXPOINTEROESPROC = procedure(size: GLint; _type: GLenum; stride: GLsizei; const pointer: PGLvoid);
{$EXTERNALSYM PFNGLMATRIXINDEXPOINTEROESPROC}
PFNGLWEIGHTPOINTEROESPROC = procedure(size: GLint; _type: GLenum; stride: GLsizei; const pointer: PGLvoid);
{$EXTERNALSYM PFNGLWEIGHTPOINTEROESPROC}
const
{ GL_OES_packed_depth_stencil }
GL_OES_packed_depth_stencil = 1;
{$EXTERNALSYM GL_OES_packed_depth_stencil}
{ GL_OES_query_matrix }
GL_OES_query_matrix = 1;
{$EXTERNALSYM GL_OES_query_matrix}
function glQueryMatrixxOES (mantissa: PGLfixed{array [0..15]}; exponent: PGLfixed{array [0..15]}): GLbitfield; cdecl;
external AndroidEglLib name 'glQueryMatrixxOES';
{$EXTERNALSYM glQueryMatrixxOES}
type
PFNGLQUERYMATRIXXOESPROC = function(mantissa: PGLfixed{array [0..15]}; exponent: PGLfixed{array [0..15]}): GLbitfield;
{$EXTERNALSYM PFNGLQUERYMATRIXXOESPROC}
const
{ GL_OES_rgb8_rgba8 }
GL_OES_rgb8_rgba8 = 1;
{$EXTERNALSYM GL_OES_rgb8_rgba8}
{ GL_OES_single_precision }
GL_OES_single_precision = 1;
{$EXTERNALSYM GL_OES_single_precision}
procedure glDepthRangefOES(zNear: GLclampf; zFar: GLclampf); cdecl;
external AndroidEglLib name 'glDepthRangefOES';
{$EXTERNALSYM glDepthRangefOES}
procedure glFrustumfOES(left: GLfloat; right: GLfloat; bottom: GLfloat; top: GLfloat; zNear: GLfloat; zFar: GLfloat); cdecl;
external AndroidEglLib name 'glFrustumfOES';
{$EXTERNALSYM glFrustumfOES}
procedure glOrthofOES(left: GLfloat; right: GLfloat; bottom: GLfloat; top: GLfloat; zNear: GLfloat; zFar: GLfloat); cdecl;
external AndroidEglLib name 'glOrthofOES';
{$EXTERNALSYM glOrthofOES}
procedure glClipPlanefOES(plane: GLenum; const equation: PGLfloat); cdecl;
external AndroidEglLib name 'glClipPlanefOES';
{$EXTERNALSYM glClipPlanefOES}
procedure glGetClipPlanefOES(pname: GLenum; eqn: PGLfloat{array [0..3]}); cdecl;
external AndroidEglLib name 'glGetClipPlanefOES';
{$EXTERNALSYM glGetClipPlanefOES}
procedure glClearDepthfOES(depth: GLclampf); cdecl;
external AndroidEglLib name 'glClearDepthfOES';
{$EXTERNALSYM glClearDepthfOES}
type
PFNGLDEPTHRANGEFOESPROC = procedure(zNear: GLclampf; zFar: GLclampf);
{$EXTERNALSYM PFNGLDEPTHRANGEFOESPROC}
PFNGLFRUSTUMFOESPROC = procedure(left: GLfloat; right: GLfloat; bottom: GLfloat; top: GLfloat; zNear: GLfloat; zFar: GLfloat);
{$EXTERNALSYM PFNGLFRUSTUMFOESPROC}
PFNGLORTHOFOESPROC = procedure(left: GLfloat; right: GLfloat; bottom: GLfloat; top: GLfloat; zNear: GLfloat; zFar: GLfloat);
{$EXTERNALSYM PFNGLORTHOFOESPROC}
PFNGLCLIPPLANEFOESPROC = procedure(plane: GLenum; const equation: PGLfloat);
{$EXTERNALSYM PFNGLCLIPPLANEFOESPROC}
PFNGLGETCLIPPLANEFOESPROC = procedure(pname: GLenum; eqn: PGLfloat{array [0..3]});
{$EXTERNALSYM PFNGLGETCLIPPLANEFOESPROC}
PFNGLCLEARDEPTHFOESPROC = procedure(depth: GLclampf);
{$EXTERNALSYM PFNGLCLEARDEPTHFOESPROC}
const
{ GL_OES_stencil1 }
GL_OES_stencil1 = 1;
{$EXTERNALSYM GL_OES_stencil1}
{ GL_OES_stencil4 }
GL_OES_stencil4 = 1;
{$EXTERNALSYM GL_OES_stencil4}
{ GL_OES_stencil8 }
GL_OES_stencil8 = 1;
{$EXTERNALSYM GL_OES_stencil8}
{ GL_OES_stencil_wrap }
GL_OES_stencil_wrap = 1;
{$EXTERNALSYM GL_OES_stencil_wrap}
{ GL_OES_texture_cube_map }
GL_OES_texture_cube_map = 1;
{$EXTERNALSYM GL_OES_texture_cube_map}
procedure glTexGenfOES(coord: GLenum; pname: GLenum; param: GLfloat); cdecl;
external AndroidEglLib name 'glTexGenfOES';
{$EXTERNALSYM glTexGenfOES}
procedure glTexGenfvOES(coord: GLenum; pname: GLenum; const params: PGLfloat); cdecl;
external AndroidEglLib name 'glTexGenfvOES';
{$EXTERNALSYM glTexGenfvOES}
procedure glTexGeniOES(coord: GLenum; pname: GLenum; param: GLint); cdecl;
external AndroidEglLib name 'glTexGeniOES';
{$EXTERNALSYM glTexGeniOES}
procedure glTexGenivOES(coord: GLenum; pname: GLenum; const params: PGLint); cdecl;
external AndroidEglLib name 'glTexGenivOES';
{$EXTERNALSYM glTexGenivOES}
procedure glTexGenxOES(coord: GLenum; pname: GLenum; param: GLfixed); cdecl;
external AndroidEglLib name 'glTexGenxOES';
{$EXTERNALSYM glTexGenxOES}
procedure glTexGenxvOES(coord: GLenum; pname: GLenum; const params: PGLfixed); cdecl;
external AndroidEglLib name 'glTexGenxvOES';
{$EXTERNALSYM glTexGenxvOES}
procedure glGetTexGenfvOES(coord: GLenum; pname: GLenum; params: PGLfloat); cdecl;
external AndroidEglLib name 'glGetTexGenfvOES';
{$EXTERNALSYM glGetTexGenfvOES}
procedure glGetTexGenivOES(coord: GLenum; pname: GLenum; params: PGLint); cdecl;
external AndroidEglLib name 'glGetTexGenivOES';
{$EXTERNALSYM glGetTexGenivOES}
procedure glGetTexGenxvOES(coord: GLenum; pname: GLenum; params: PGLfixed); cdecl;
external AndroidEglLib name 'glGetTexGenxvOES';
{$EXTERNALSYM glGetTexGenxvOES}
type
PFNGLTEXGENFOESPROC = procedure(coord: GLenum; pname: GLenum; param: GLfloat);
{$EXTERNALSYM PFNGLTEXGENFOESPROC}
PFNGLTEXGENFVOESPROC = procedure(coord: GLenum; pname: GLenum; const params: PGLfloat);
{$EXTERNALSYM PFNGLTEXGENFVOESPROC}
PFNGLTEXGENIOESPROC = procedure(coord: GLenum; pname: GLenum; param: GLint);
{$EXTERNALSYM PFNGLTEXGENIOESPROC}
PFNGLTEXGENIVOESPROC = procedure(coord: GLenum; pname: GLenum; const params: PGLint);
{$EXTERNALSYM PFNGLTEXGENIVOESPROC}
PFNGLTEXGENXOESPROC = procedure(coord: GLenum; pname: GLenum; param: GLfixed);
{$EXTERNALSYM PFNGLTEXGENXOESPROC}
PFNGLTEXGENXVOESPROC = procedure(coord: GLenum; pname: GLenum; const params: PGLfixed);
{$EXTERNALSYM PFNGLTEXGENXVOESPROC}
PFNGLGETTEXGENFVOESPROC = procedure(coord: GLenum; pname: GLenum; params: PGLfloat);
{$EXTERNALSYM PFNGLGETTEXGENFVOESPROC}
PFNGLGETTEXGENIVOESPROC = procedure(coord: GLenum; pname: GLenum; params: PGLint);
{$EXTERNALSYM PFNGLGETTEXGENIVOESPROC}
PFNGLGETTEXGENXVOESPROC = procedure(coord: GLenum; pname: GLenum; params: PGLfixed);
{$EXTERNALSYM PFNGLGETTEXGENXVOESPROC}
const
{ GL_OES_texture_env_crossbar }
GL_OES_texture_env_crossbar = 1;
{$EXTERNALSYM GL_OES_texture_env_crossbar}
{ GL_OES_texture_mirrored_repeat }
GL_OES_texture_mirrored_repeat = 1;
{$EXTERNALSYM GL_OES_texture_mirrored_repeat}
{ GL_OES_vertex_array_object }
GL_OES_vertex_array_object = 1;
{$EXTERNALSYM GL_OES_vertex_array_object}
{procedure glBindVertexArrayOES(_array: GLuint); cdecl;
external AndroidEglLib name 'glBindVertexArrayOES';
{$EXTERNALSYM glBindVertexArrayOES}
{procedure glDeleteVertexArraysOES(n: GLsizei; const arrays: PGLuint); cdecl;
external AndroidEglLib name 'glDeleteVertexArraysOES';
{$EXTERNALSYM glDeleteVertexArraysOES}
{procedure glGenVertexArraysOES(n: GLsizei; arrays: PGLuint); cdecl;
external AndroidEglLib name 'glGenVertexArraysOES';
{$EXTERNALSYM glGenVertexArraysOES}
{
function glIsVertexArrayOES (_array: GLuint): GLboolean; cdecl;
external AndroidEglLib name 'glIsVertexArrayOES';
{$EXTERNALSYM glIsVertexArrayOES}
{type
{PFNGLBINDVERTEXARRAYOESPROC = procedure(_array: GLuint);
{$EXTERNALSYM PFNGLBINDVERTEXARRAYOESPROC}
{PFNGLDELETEVERTEXARRAYSOESPROC = procedure(n: GLsizei; const arrays: PGLuint);
{$EXTERNALSYM PFNGLDELETEVERTEXARRAYSOESPROC}
{PFNGLGENVERTEXARRAYSOESPROC = procedure(n: GLsizei; arrays: PGLuint);
{$EXTERNALSYM PFNGLGENVERTEXARRAYSOESPROC}
{PFNGLISVERTEXARRAYOESPROC = function(_array: GLuint): GLboolean;
{$EXTERNALSYM PFNGLISVERTEXARRAYOESPROC}
const
{ GL_OES_EGL_image_external }
GL_OES_EGL_image_external = 1;
{$EXTERNALSYM GL_OES_EGL_image_external}
{ ------------------------------------------------------------------------
AMD extension functions
------------------------------------------------------------------------ }
{ GL_AMD_compressed_3DC_texture }
GL_AMD_compressed_3DC_texture = 1;
{$EXTERNALSYM GL_AMD_compressed_3DC_texture}
{ GL_AMD_compressed_ATC_texture }
GL_AMD_compressed_ATC_texture = 1;
{$EXTERNALSYM GL_AMD_compressed_ATC_texture}
{ ------------------------------------------------------------------------
APPLE extension functions
------------------------------------------------------------------------ }
{ GL_APPLE_texture_2D_limited_npot }
GL_APPLE_texture_2D_limited_npot = 1;
{$EXTERNALSYM GL_APPLE_texture_2D_limited_npot}
{ ------------------------------------------------------------------------
EXT extension functions
------------------------------------------------------------------------ }
{ GL_EXT_blend_minmax }
GL_EXT_blend_minmax = 1;
{$EXTERNALSYM GL_EXT_blend_minmax}
{ GL_EXT_discard_framebuffer }
GL_EXT_discard_framebuffer = 1;
{$EXTERNALSYM GL_EXT_discard_framebuffer}
{procedure glDiscardFramebufferEXT(target: GLenum; numAttachments: GLsizei; const attachments: PGLenum); cdecl;
external AndroidEglLib name 'glDiscardFramebufferEXT';
{$EXTERNALSYM glDiscardFramebufferEXT}
{type
PFNGLDISCARDFRAMEBUFFEREXTPROC = procedure(target: GLenum; numAttachments: GLsizei; const attachments: PGLenum);
{$EXTERNALSYM PFNGLDISCARDFRAMEBUFFEREXTPROC}
const
{ GL_EXT_multi_draw_arrays }
GL_EXT_multi_draw_arrays = 1;
{$EXTERNALSYM GL_EXT_multi_draw_arrays}
{procedure glMultiDrawArraysEXT(mode: GLenum; first: PGLint; count: PGLsizei; primcount: GLsizei); cdecl;
external AndroidEglLib name 'glMultiDrawArraysEXT';
{$EXTERNALSYM glMultiDrawArraysEXT}
{procedure glMultiDrawElementsEXT(mode: GLenum; const count: PGLsizei; _type: GLenum; const indices: PPGLvoid; primcount: GLsizei); cdecl;
external AndroidEglLib name 'glMultiDrawElementsEXT';
{$EXTERNALSYM glMultiDrawElementsEXT}
{type
{PFNGLMULTIDRAWARRAYSEXTPROC = procedure(mode: GLenum; first: PGLint; count: PGLsizei; primcount: GLsizei);
{$EXTERNALSYM PFNGLMULTIDRAWARRAYSEXTPROC}
{PFNGLMULTIDRAWELEMENTSEXTPROC = procedure(mode: GLenum; const count: PGLsizei; _type: GLenum; const indices: PPGLvoid; primcount: GLsizei);
{$EXTERNALSYM PFNGLMULTIDRAWELEMENTSEXTPROC}
const
{ GL_EXT_read_format_bgra }
GL_EXT_read_format_bgra = 1;
{$EXTERNALSYM GL_EXT_read_format_bgra}
{ GL_EXT_texture_filter_anisotropic }
GL_EXT_texture_filter_anisotropic = 1;
{$EXTERNALSYM GL_EXT_texture_filter_anisotropic}
{ GL_EXT_texture_format_BGRA8888 }
GL_EXT_texture_format_BGRA8888 = 1;
{$EXTERNALSYM GL_EXT_texture_format_BGRA8888}
{ GL_EXT_texture_lod_bias }
GL_EXT_texture_lod_bias = 1;
{$EXTERNALSYM GL_EXT_texture_lod_bias}
{ ------------------------------------------------------------------------
IMG extension functions
------------------------------------------------------------------------ }
{ GL_IMG_read_format }
GL_IMG_read_format = 1;
{$EXTERNALSYM GL_IMG_read_format}
{ GL_IMG_texture_compression_pvrtc }
GL_IMG_texture_compression_pvrtc = 1;
{$EXTERNALSYM GL_IMG_texture_compression_pvrtc}
{ GL_IMG_texture_env_enhanced_fixed_function }
GL_IMG_texture_env_enhanced_fixed_function = 1;
{$EXTERNALSYM GL_IMG_texture_env_enhanced_fixed_function}
{ GL_IMG_user_clip_plane }
GL_IMG_user_clip_plane = 1;
{$EXTERNALSYM GL_IMG_user_clip_plane}
{procedure glClipPlanefIMG(p: GLenum; const eqn: PGLfloat); cdecl;
external AndroidEglLib name 'glClipPlanefIMG';
{$EXTERNALSYM glClipPlanefIMG}
{procedure glClipPlanexIMG(p: GLenum; const eqn: PGLfixed); cdecl;
external AndroidEglLib name 'glClipPlanexIMG';
{$EXTERNALSYM glClipPlanexIMG}
{type
{PFNGLCLIPPLANEFIMGPROC = procedure(p: GLenum; const eqn: PGLfloat);
{$EXTERNALSYM PFNGLCLIPPLANEFIMGPROC}
{PFNGLCLIPPLANEXIMGPROC = procedure(p: GLenum; const eqn: PGLfixed);
{$EXTERNALSYM PFNGLCLIPPLANEXIMGPROC}
const
{ GL_IMG_multisampled_render_to_texture }
GL_IMG_multisampled_render_to_texture = 1;
{$EXTERNALSYM GL_IMG_multisampled_render_to_texture}
{procedure glRenderbufferStorageMultisampleIMG(target: GLenum; samples: GLsizei; internalformat: GLenum; width: GLsizei; height: GLsizei); cdecl;
external AndroidEglLib name 'glRenderbufferStorageMultisampleIMG';
{$EXTERNALSYM glRenderbufferStorageMultisampleIMG}
{procedure glFramebufferTexture2DMultisampleIMG(target: GLenum; attachment: GLenum; textarget: GLenum; texture: GLuint; level: GLint; samples: GLsizei); cdecl;
external AndroidEglLib name 'glFramebufferTexture2DMultisampleIMG';
{$EXTERNALSYM glFramebufferTexture2DMultisampleIMG}
{type
{PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMG = procedure(target: GLenum; samples: GLsizei; internalformat: GLenum; width: GLsizei; height: GLsizei);
{$EXTERNALSYM PFNGLRENDERBUFFERSTORAGEMULTISAMPLEIMG}
{PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMG = procedure(target: GLenum; attachment: GLenum; textarget: GLenum; texture: GLuint; level: GLint; samples: GLsizei);
{$EXTERNALSYM PFNGLFRAMEBUFFERTEXTURE2DMULTISAMPLEIMG}
{ ------------------------------------------------------------------------
NV extension functions
------------------------------------------------------------------------ }
const
{ NV_fence }
GL_NV_fence = 1;
{$EXTERNALSYM GL_NV_fence}
{procedure glDeleteFencesNV(n: GLsizei; const fences: PGLuint); cdecl;
external AndroidEglLib name 'glDeleteFencesNV';
{$EXTERNALSYM glDeleteFencesNV}
{procedure glGenFencesNV(n: GLsizei; fences: PGLuint); cdecl;
external AndroidEglLib name 'glGenFencesNV';
{$EXTERNALSYM glGenFencesNV}
{function glIsFenceNV (fence: GLuint): GLboolean; cdecl;
external AndroidEglLib name 'glIsFenceNV';
{$EXTERNALSYM glIsFenceNV}
{function glTestFenceNV (fence: GLuint): GLboolean; cdecl;
external AndroidEglLib name 'glTestFenceNV';
{$EXTERNALSYM glTestFenceNV}
{procedure glGetFenceivNV(fence: GLuint; pname: GLenum; params: PGLint); cdecl;
external AndroidEglLib name 'glGetFenceivNV';
{$EXTERNALSYM glGetFenceivNV}
{procedure glFinishFenceNV(fence: GLuint); cdecl;
external AndroidEglLib name 'glFinishFenceNV';
{$EXTERNALSYM glFinishFenceNV}
{procedure glSetFenceNV(fence: GLuint; condition: GLenum); cdecl;
external AndroidEglLib name 'glSetFenceNV';
{$EXTERNALSYM glSetFenceNV}
{type
PFNGLDELETEFENCESNVPROC = procedure(n: GLsizei; const fences: PGLuint);
{$EXTERNALSYM PFNGLDELETEFENCESNVPROC}
{PFNGLGENFENCESNVPROC = procedure(n: GLsizei; fences: PGLuint);
{$EXTERNALSYM PFNGLGENFENCESNVPROC}
{PFNGLISFENCENVPROC = function(fence: GLuint): GLboolean;
{$EXTERNALSYM PFNGLISFENCENVPROC}
{PFNGLTESTFENCENVPROC = function(fence: GLuint): GLboolean;
{$EXTERNALSYM PFNGLTESTFENCENVPROC}
{PFNGLGETFENCEIVNVPROC = procedure(fence: GLuint; pname: GLenum; params: PGLint);
{$EXTERNALSYM PFNGLGETFENCEIVNVPROC}
{PFNGLFINISHFENCENVPROC = procedure(fence: GLuint);
{$EXTERNALSYM PFNGLFINISHFENCENVPROC}
{PFNGLSETFENCENVPROC = procedure(fence: GLuint; condition: GLenum);
{$EXTERNALSYM PFNGLSETFENCENVPROC}
{ ------------------------------------------------------------------------
QCOM extension functions
------------------------------------------------------------------------ }
const
{ GL_QCOM_driver_control }
GL_QCOM_driver_control = 1;
{$EXTERNALSYM GL_QCOM_driver_control}
{procedure glGetDriverControlsQCOM(num: PGLint; size: GLsizei; driverControls: PGLuint); cdecl;
external AndroidEglLib name 'glGetDriverControlsQCOM';
{$EXTERNALSYM glGetDriverControlsQCOM}
{procedure glGetDriverControlStringQCOM(driverControl: GLuint; bufSize: GLsizei; length: PGLsizei; driverControlString: PGLchar); cdecl;
external AndroidEglLib name 'glGetDriverControlStringQCOM';
{$EXTERNALSYM glGetDriverControlStringQCOM}
{procedure glEnableDriverControlQCOM(driverControl: GLuint); cdecl;
external AndroidEglLib name 'glEnableDriverControlQCOM';
{$EXTERNALSYM glEnableDriverControlQCOM}
{procedure glDisableDriverControlQCOM(driverControl: GLuint); cdecl;
external AndroidEglLib name 'glDisableDriverControlQCOM';
{$EXTERNALSYM glDisableDriverControlQCOM}
{type
{PFNGLGETDRIVERCONTROLSQCOMPROC = procedure(num: PGLint; size: GLsizei; driverControls: PGLuint);
{$EXTERNALSYM PFNGLGETDRIVERCONTROLSQCOMPROC}
{PFNGLGETDRIVERCONTROLSTRINGQCOMPROC = procedure(driverControl: GLuint; bufSize: GLsizei; length: PGLsizei; driverControlString: PGLchar);
{$EXTERNALSYM PFNGLGETDRIVERCONTROLSTRINGQCOMPROC}
{PFNGLENABLEDRIVERCONTROLQCOMPROC = procedure(driverControl: GLuint);
{$EXTERNALSYM PFNGLENABLEDRIVERCONTROLQCOMPROC}
{PFNGLDISABLEDRIVERCONTROLQCOMPROC = procedure(driverControl: GLuint);
{$EXTERNALSYM PFNGLDISABLEDRIVERCONTROLQCOMPROC}
const
{ GL_QCOM_extended_get }
GL_QCOM_extended_get = 1;
{$EXTERNALSYM GL_QCOM_extended_get}
{procedure glExtGetTexturesQCOM(textures: PGLuint; maxTextures: GLint; numTextures: PGLint); cdecl;
external AndroidEglLib name 'glExtGetTexturesQCOM';
{$EXTERNALSYM glExtGetTexturesQCOM}
{procedure glExtGetBuffersQCOM(buffers: PGLuint; maxBuffers: GLint; numBuffers: PGLint); cdecl;
external AndroidEglLib name 'glExtGetBuffersQCOM';
{$EXTERNALSYM glExtGetBuffersQCOM}
{procedure glExtGetRenderbuffersQCOM(renderbuffers: PGLuint; maxRenderbuffers: GLint; numRenderbuffers: PGLint); cdecl;
external AndroidEglLib name 'glExtGetRenderbuffersQCOM';
{$EXTERNALSYM glExtGetRenderbuffersQCOM}
{procedure glExtGetFramebuffersQCOM(framebuffers: PGLuint; maxFramebuffers: GLint; numFramebuffers: PGLint); cdecl;
external AndroidEglLib name 'glExtGetFramebuffersQCOM';
{$EXTERNALSYM glExtGetFramebuffersQCOM}
{procedure glExtGetTexLevelParameterivQCOM(texture: GLuint; face: GLenum; level: GLint; pname: GLenum; params: PGLint); cdecl;
external AndroidEglLib name 'glExtGetTexLevelParameterivQCOM';
{$EXTERNALSYM glExtGetTexLevelParameterivQCOM}
{procedure glExtTexObjectStateOverrideiQCOM(target: GLenum; pname: GLenum; param: GLint); cdecl;
external AndroidEglLib name 'glExtTexObjectStateOverrideiQCOM';
{$EXTERNALSYM glExtTexObjectStateOverrideiQCOM}
{procedure glExtGetTexSubImageQCOM(target: GLenum; level: GLint; xoffset: GLint; yoffset: GLint; zoffset: GLint; width: GLsizei; height: GLsizei; depth: GLsizei; format: GLenum; _type: GLenum; texels: PGLvoid); cdecl;
external AndroidEglLib name 'glExtGetTexSubImageQCOM';
{$EXTERNALSYM glExtGetTexSubImageQCOM}
{procedure glExtGetBufferPointervQCOM(target: GLenum; params: PPGLvoid); cdecl;
external AndroidEglLib name 'glExtGetBufferPointervQCOM';
{$EXTERNALSYM glExtGetBufferPointervQCOM}
{type
{PFNGLEXTGETTEXTURESQCOMPROC = procedure(textures: PGLuint; maxTextures: GLint; numTextures: PGLint);
{$EXTERNALSYM PFNGLEXTGETTEXTURESQCOMPROC}
{PFNGLEXTGETBUFFERSQCOMPROC = procedure(buffers: PGLuint; maxBuffers: GLint; numBuffers: PGLint);
{$EXTERNALSYM PFNGLEXTGETBUFFERSQCOMPROC}
{PFNGLEXTGETRENDERBUFFERSQCOMPROC = procedure(renderbuffers: PGLuint; maxRenderbuffers: GLint; numRenderbuffers: PGLint);
{$EXTERNALSYM PFNGLEXTGETRENDERBUFFERSQCOMPROC}
{PFNGLEXTGETFRAMEBUFFERSQCOMPROC = procedure(framebuffers: PGLuint; maxFramebuffers: GLint; numFramebuffers: PGLint);
{$EXTERNALSYM PFNGLEXTGETFRAMEBUFFERSQCOMPROC}
{PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC = procedure(texture: GLuint; face: GLenum; level: GLint; pname: GLenum; params: PGLint);
{$EXTERNALSYM PFNGLEXTGETTEXLEVELPARAMETERIVQCOMPROC}
{PFNGLEXTTEXOBJECTSTATEOVERRIDEIQCOMPROC = procedure(target: GLenum; pname: GLenum; param: GLint);
{$EXTERNALSYM PFNGLEXTTEXOBJECTSTATEOVERRIDEIQCOMPROC}
{PFNGLEXTGETTEXSUBIMAGEQCOMPROC = procedure(target: GLenum; level: GLint; xoffset: GLint; yoffset: GLint; zoffset: GLint; width: GLsizei; height: GLsizei; depth: GLsizei; format: GLenum; _type: GLenum; texels: PGLvoid);
{$EXTERNALSYM PFNGLEXTGETTEXSUBIMAGEQCOMPROC}
{PFNGLEXTGETBUFFERPOINTERVQCOMPROC = procedure(target: GLenum; params: PPGLvoid);
{$EXTERNALSYM PFNGLEXTGETBUFFERPOINTERVQCOMPROC}
const
{ GL_QCOM_extended_get2 }
GL_QCOM_extended_get2 = 1;
{$EXTERNALSYM GL_QCOM_extended_get2}
{procedure glExtGetShadersQCOM(shaders: PGLuint; maxShaders: GLint; numShaders: PGLint); cdecl;
external AndroidEglLib name 'glExtGetShadersQCOM';
{$EXTERNALSYM glExtGetShadersQCOM}
{procedure glExtGetProgramsQCOM(programs: PGLuint; maxPrograms: GLint; numPrograms: PGLint); cdecl;
external AndroidEglLib name 'glExtGetProgramsQCOM';
{$EXTERNALSYM glExtGetProgramsQCOM}
{function glExtIsProgramBinaryQCOM (_program: GLuint): GLboolean; cdecl;
external AndroidEglLib name 'glExtIsProgramBinaryQCOM';
{$EXTERNALSYM glExtIsProgramBinaryQCOM}
{procedure glExtGetProgramBinarySourceQCOM(_program: GLuint; shadertype: GLenum; source: PGLchar; length: PGLint); cdecl;
external AndroidEglLib name 'glExtGetProgramBinarySourceQCOM';
{$EXTERNALSYM glExtGetProgramBinarySourceQCOM}
{type
{PFNGLEXTGETSHADERSQCOMPROC = procedure(shaders: PGLuint; maxShaders: GLint; numShaders: PGLint);
{$EXTERNALSYM PFNGLEXTGETSHADERSQCOMPROC}
{PFNGLEXTGETPROGRAMSQCOMPROC = procedure(programs: PGLuint; maxPrograms: GLint; numPrograms: PGLint);
{$EXTERNALSYM PFNGLEXTGETPROGRAMSQCOMPROC}
{PFNGLEXTISPROGRAMBINARYQCOMPROC = function(_program: GLuint): GLboolean;
{$EXTERNALSYM PFNGLEXTISPROGRAMBINARYQCOMPROC}
{PFNGLEXTGETPROGRAMBINARYSOURCEQCOMPROC = procedure(_program: GLuint; shadertype: GLenum; source: PGLchar; length: PGLint);
{$EXTERNALSYM PFNGLEXTGETPROGRAMBINARYSOURCEQCOMPROC}
const
{ GL_QCOM_perfmon_global_mode }
GL_QCOM_perfmon_global_mode = 1;
{$EXTERNALSYM GL_QCOM_perfmon_global_mode}
{ GL_QCOM_writeonly_rendering }
GL_QCOM_writeonly_rendering = 1;
{$EXTERNALSYM GL_QCOM_writeonly_rendering}
{ GL_QCOM_tiled_rendering }
GL_QCOM_tiled_rendering = 1;
{$EXTERNALSYM GL_QCOM_tiled_rendering}
{procedure glStartTilingQCOM(x: GLuint; y: GLuint; width: GLuint; height: GLuint; preserveMask: GLbitfield); cdecl;
external AndroidEglLib name 'glStartTilingQCOM';
{$EXTERNALSYM glStartTilingQCOM}
{procedure glEndTilingQCOM(preserveMask: GLbitfield); cdecl;
external AndroidEglLib name 'glEndTilingQCOM';
{$EXTERNALSYM glEndTilingQCOM}
{type
{PFNGLSTARTTILINGQCOMPROC = procedure(x: GLuint; y: GLuint; width: GLuint; height: GLuint; preserveMask: GLbitfield);
{$EXTERNALSYM PFNGLSTARTTILINGQCOMPROC}
{PFNGLENDTILINGQCOMPROC = procedure(preserveMask: GLbitfield);
{$EXTERNALSYM PFNGLENDTILINGQCOMPROC}
implementation
end.
|
unit UI.Json;
interface
uses
System.JSON, System.SysUtils;
type
TJSONObjectHelper = class Helper for System.JSON.TJSONObject
private
procedure SetBoolean(const Key: string; const Value: Boolean);
procedure SetFloat(const Key: string; const Value: Double);
procedure SetInt64(const Key: string; const Value: Int64);
procedure SetJsonObject(const Key: string; const Value: TJSONObject);
procedure SetString(const Key, Value: string);
procedure SetJsonArray(const Key: string; const Value: TJSONArray);
procedure SetDateTime(const Key: string; const Value: TDateTime);
public
procedure Parse(const Value: string); overload;
function Exist(const Key: string): Boolean;
procedure Add(const Key: string; const Value: string; const DefaultValue: string = ''); overload;
procedure Add(const Key: string; const Value: Boolean; const DefaultValue: Boolean = False); overload;
procedure Add(const Key: string; const Value: Int64; const DefaultValue: Int64 = 0); overload;
procedure Add(const Key: string; const Value: Double; const DefaultValue: Double = 0); overload;
procedure AddDateTime(const Key: string; const Value: TDateTime; const DefaultValue: TDateTime = 0); overload;
function AddJsonArray(const Key: string): TJSONArray; overload;
function AddJsonObject(const Key: string): TJSONObject; overload;
function GetBoolean(const Key: string): Boolean;
function GetFloat(const Key: string): Double;
function GetInt64(const Key: string): Int64;
function GetString(const Key: string): string;
function GetDateTime(const Key: string): TDateTime;
function GetJsonArray(const Key: string): TJSONArray;
function GetJsonObject(const Key: string): TJSONObject;
function TryGetBoolean(const Key: string; var Value: Boolean): Boolean;
function TryGetFloat(const Key: string; var Value: Double): Boolean; overload;
function TryGetFloat(const Key: string; var Value: Single): Boolean; overload;
function TryGetInt(const Key: string; var Value: Integer): Boolean; overload;
function TryGetInt(const Key: string; var Value: Int64): Boolean; overload;
function TryGetInt(const Key: string; var Value: NativeInt): Boolean; overload;
function TryGetInt(const Key: string; var Value: Cardinal): Boolean; overload;
function TryGetString(const Key: string; var Value: string): Boolean;
function TryGetDateTime(const Key: string; var Value: TDateTime): Boolean;
property S[const Key: string]: string read GetString write SetString;
property I[const Key: string]: Int64 read GetInt64 write SetInt64;
property F[const Key: string]: Double read GetFloat write SetFloat;
property B[const Key: string]: Boolean read GetBoolean write SetBoolean;
property D[const Key: string]: TDateTime read GetDateTime write SetDateTime;
property O[const Key: string]: TJSONObject read GetJsonObject write SetJsonObject;
property A[const Key: string]: TJSONArray read GetJsonArray write SetJsonArray;
end;
implementation
{ TJSONObjectHelper }
procedure TJSONObjectHelper.Add(const Key: string; const Value: Double; const DefaultValue: Double);
begin
if Value = DefaultValue then
Exit;
Self.AddPair(Key, TJSONNumber.Create(Value));
end;
procedure TJSONObjectHelper.Add(const Key: string; const Value: Int64; const DefaultValue: Int64);
begin
if Value = DefaultValue then
Exit;
Self.AddPair(Key, TJSONNumber.Create(Value));
end;
procedure TJSONObjectHelper.Add(const Key, Value, DefaultValue: string);
begin
if Value = DefaultValue then
Exit;
Self.AddPair(Key, Value);
end;
procedure TJSONObjectHelper.Add(const Key: string; const Value, DefaultValue: Boolean);
begin
if Value = DefaultValue then
Exit;
Self.AddPair(Key, TJSONBool.Create(Value));
end;
procedure TJSONObjectHelper.AddDateTime(const Key: string; const Value, DefaultValue: TDateTime);
begin
if Value = DefaultValue then
Exit;
Self.AddPair(Key, FormatDateTime('yyyy-mm-dd hh:nn:ss', Value));
end;
function TJSONObjectHelper.AddJsonArray(const Key: string): TJSONArray;
begin
Result := TJSONArray.Create;
Self.AddPair(Key, Result);
end;
function TJSONObjectHelper.AddJsonObject(const Key: string): TJSONObject;
begin
Result := TJSONObject.Create;
Self.AddPair(Key, Result);
end;
function TJSONObjectHelper.Exist(const Key: string): Boolean;
begin
Result := Assigned(GetValue(Key));
end;
function TJSONObjectHelper.GetBoolean(const Key: string): Boolean;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then
Result := V.GetValue<Boolean>()
else
Result := False;
end;
function TJSONObjectHelper.GetDateTime(const Key: string): TDateTime;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then
Result := V.GetValue<TDateTime>()
else
Result := 0;
end;
function TJSONObjectHelper.GetFloat(const Key: string): Double;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then
Result := V.GetValue<Double>()
else
Result := 0;
end;
function TJSONObjectHelper.GetInt64(const Key: string): Int64;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then
Result := V.GetValue<Int64>()
else
Result := 0;
end;
function TJSONObjectHelper.GetJsonArray(const Key: string): TJSONArray;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then begin
if V is TJSONArray then
Result := V as TJSONArray
else
Result := nil;
end else
Result := nil;
end;
function TJSONObjectHelper.GetJsonObject(const Key: string): TJSONObject;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) and (V is TJSONObject) then
Result := V as TJSONObject
else
Result := nil;
end;
function TJSONObjectHelper.GetString(const Key: string): string;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then
Result := V.GetValue<string>()
else
Result := '';
end;
procedure TJSONObjectHelper.Parse(const Value: string);
var
V: TArray<Byte>;
begin
V := TEncoding.Default.GetBytes(Value);
Self.Parse(V, 0);
end;
procedure TJSONObjectHelper.SetBoolean(const Key: string; const Value: Boolean);
begin
RemovePair(Key);
Add(Key, Value);
end;
procedure TJSONObjectHelper.SetDateTime(const Key: string;
const Value: TDateTime);
begin
RemovePair(Key);
Add(Key, Value);
end;
procedure TJSONObjectHelper.SetFloat(const Key: string; const Value: Double);
begin
RemovePair(Key);
Add(Key, Value);
end;
procedure TJSONObjectHelper.SetInt64(const Key: string; const Value: Int64);
begin
RemovePair(Key);
Add(Key, Value);
end;
procedure TJSONObjectHelper.SetJsonArray(const Key: string;
const Value: TJSONArray);
begin
RemovePair(Key);
AddPair(Key, Value);
end;
procedure TJSONObjectHelper.SetJsonObject(const Key: string;
const Value: TJSONObject);
begin
RemovePair(Key);
AddPair(Key, Value);
end;
procedure TJSONObjectHelper.SetString(const Key, Value: string);
begin
RemovePair(Key);
Add(Key, Value);
end;
function TJSONObjectHelper.TryGetBoolean(const Key: string;
var Value: Boolean): Boolean;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then begin
Result := True;
Value := V.GetValue<Boolean>()
end else
Result := False;
end;
function TJSONObjectHelper.TryGetDateTime(const Key: string;
var Value: TDateTime): Boolean;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then begin
Result := True;
Value := V.GetValue<TDateTime>()
end else
Result := False;
end;
function TJSONObjectHelper.TryGetFloat(const Key: string;
var Value: Double): Boolean;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then begin
Result := True;
Value := V.GetValue<Double>()
end else
Result := False;
end;
function TJSONObjectHelper.TryGetFloat(const Key: string;
var Value: Single): Boolean;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then begin
Result := True;
Value := V.GetValue<Single>()
end else
Result := False;
end;
function TJSONObjectHelper.TryGetInt(const Key: string;
var Value: NativeInt): Boolean;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then begin
Result := True;
Value := V.GetValue<NativeInt>()
end else
Result := False;
end;
function TJSONObjectHelper.TryGetInt(const Key: string;
var Value: Int64): Boolean;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then begin
Result := True;
Value := V.GetValue<Int64>()
end else
Result := False;
end;
function TJSONObjectHelper.TryGetInt(const Key: string;
var Value: Integer): Boolean;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then begin
Result := True;
Value := V.GetValue<Integer>()
end else
Result := False;
end;
function TJSONObjectHelper.TryGetInt(const Key: string;
var Value: Cardinal): Boolean;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then begin
Result := True;
Value := V.GetValue<Cardinal>()
end else
Result := False;
end;
function TJSONObjectHelper.TryGetString(const Key: string;
var Value: string): Boolean;
var
V: TJSONValue;
begin
V := GetValue(Key);
if Assigned(V) then begin
Result := True;
Value := V.GetValue<string>()
end else
Result := False;
end;
end.
|
unit functionsUnit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Grids, StdCtrls,
ComCtrls, ExtCtrls, math;
procedure ReportError(s:String; lbl:TLabel);
function IsInBounds(x,y:Integer; grid:TStringGrid):Boolean;
function IsStringCorrect(s:String; alowedChars:String):Boolean;
function IsStringCorrectInv(s:String; disalowedChars:String):Boolean;
function roundToN(x:Real; n:Integer):Real;
implementation
procedure ReportError(s:String; lbl:TLabel);
Begin
lbl.Caption := s;
end;
function IsInBounds(x,y:Integer; grid:TStringGrid):Boolean;
Begin
If ((x >= 0) and (x < grid.ColCount)) and ( (y >=0) and (y < grid.RowCount))
then result := true
else result := false;
end;
//Checks if all symbols in the string 's' are in string 'alowedChars'
function IsStringCorrect(s:String; alowedChars:String):Boolean;
var
i,j:Integer;
stringCorrect:Boolean;
symbolCorrect:Boolean;
Begin
If s.Length > 0 then stringCorrect := true
else stringCorrect := false;
for i := 1 to length(s) do
Begin
symbolCorrect := false;
for j := 1 to alowedChars.Length do
if s[i] = alowedChars[j] then symbolCorrect := true;
if not symbolCorrect then stringCorrect := false;
end;
result := stringCorrect;
end;
//Inversed version of IsStringCorrect.
//Checks if all symbols in the string 's' are NOT in string 'alowedChars'
function IsStringCorrectInv(s:String; disalowedChars:String):Boolean;
var
i,j:Integer;
stringCorrect:Boolean;
symbolCorrect:Boolean;
Begin
If s.Length > 0 then stringCorrect := true
else stringCorrect := false;
for i := 1 to s.Length do
Begin
symbolCorrect := true;
for j := 1 to disalowedChars.Length do
if s[i] = disalowedChars[j] then symbolCorrect := false;
if not symbolCorrect then stringCorrect := false;
end;
result := stringCorrect;
end;
//Rounds "x" to the Nth digit after the point
function roundToN(x:Real; n:Integer):Real;
var
y : Integer;
Begin
y := trunc(power(10, n));
x := Round(x * y) / y;
result := x;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995-2002 Borland Software Corporation }
{ }
{*******************************************************}
unit ASDUnit;
interface
uses
Windows, Forms, Classes, SysUtils, AKlava,
DelphiProtected, Graphics, OpenGL, FormsGL;
type
TMessageType = (mtNone, mtSysTime, mtSysDataTime, mtProgTime, mtDir, mtLine);
TLogSystem = class(TObject)
private
FFileName: string;
FLog: TStringList;
FSec: TSecundomer;
procedure SetFileName(const Value: string);
protected
procedure AddText(const Format: string; const Args: array of const);
public
constructor Create(FileName: string);
destructor Destroy; override;
procedure AddLine(S: string; MessageType: TMessageType = mtNone);
property FileName: string read FFileName write SetFileName;
end;
TASDEngine = class(TObject)
private
FLog: TLogSystem;
FFormGL: TFormGL;
FEscToExit: Boolean;
procedure InitLog;
procedure SaveLog;
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
protected
procedure Error(Msg: string);
procedure AddLog(S: string; MessageType: TMessageType = mtNone);
public
constructor Create;
destructor Destroy; override;
procedure ScreenOptions(Width, Height, BPP, Refresh: Integer; FullScreen,
WaitVSync: Boolean);
procedure InitGL;
procedure Run;
property Log: TLogSystem read FLog;
property EscToExit: Boolean read FEscToExit write FEscToExit;
end;
var
ASDEngine: TASDEngine;
FormGL: TFormGL;
implementation
uses ASDConst;
{ TLogSystem }
procedure TLogSystem.AddLine(S: string; MessageType: TMessageType);
const
fsTime: string = '[%S] %S';
fsDataTime: string = '[%S|%S] %S';
fsDir: string = '--%S--';
Kof: Real = 1000 * 60 * 60 * 24;
begin
case MessageType of
mtNone:
FLog.Add(S);
mtSysTime:
AddText(fsTime, [TimeToStr(Time), S]);
mtSysDataTime:
AddText(fsDataTime, [DateToStr(Date), TimeToStr(Time), S]);
mtProgTime:
AddText(fsTime, [TimeToStr(FSec.Time / Kof), S]);
mtDir:
AddText(fsDir, [S]);
mtLine:
FLog.Add('----------------------');
end;
end;
constructor TLogSystem.Create(FileName: string);
begin
FFileName := FileName;
if FFileName = '' then
raise Exception.Create('File "' + FileName + '"not found');
FLog := TStringList.Create;
FSec := TSecundomer.Create;
FSec.Start;
end;
destructor TLogSystem.Destroy;
begin
FSec.Free;
FLog.SaveToFile(FFileName);
FLog.Free;
inherited;
end;
procedure TLogSystem.AddText(const Format: string;
const Args: array of const);
begin
FLog.Add(SysUtils.Format(Format, Args));
end;
procedure TLogSystem.SetFileName(const Value: string);
begin
if FFileName = '' then
raise Exception.Create('File "' + FileName + '" not found');
FFileName := Value;
end;
{ TASDEngine }
procedure TASDEngine.AddLog(S: string; MessageType: TMessageType);
begin
FLog.AddLine(S, MessageType);
end;
constructor TASDEngine.Create;
begin
InitLog;
Application.Initialize;
Application.CreateForm(TFormGL, FFormGL);
FFormGL.Color := clBlack;
FFormGL.Position := poScreenCenter;
FFormGL.OnKeyDown := FormKeyDown;
FormGL := FFormGL;
end;
procedure TASDEngine.FormKeyDown(Sender: TObject; var Key: Word; Shift:
TShiftState);
begin
if Key = VK_ESCAPE then
FFormGL.Close;
end;
destructor TASDEngine.Destroy;
begin
SaveLog;
inherited;
end;
procedure TASDEngine.SaveLog;
begin
with FLog do
begin
AddLog('Time Engine', mtProgTime);
AddLog('Engine Closed.', mtSysTime);
Free;
end;
end;
procedure TASDEngine.InitLog;
begin
FLog := TLogSystem.Create('ASDEngine.Log');
AddLog(cEngineName + ' ' + cEngineVERSION + ' Started...',
mtSysDataTime);
AddLog(cDirSysInfo, mtDir);
AddLog(cCPU + GetCPUVendor);
AddLog(GetCPUSpeed);
AddLog(GetCPUProductivity);
AddLog(GetAPIProductivity);
AddLog(GetMemProductivity);
AddLog('User : ' + GetUserNetName);
AddLog(cDirEndInfo, mtDir);
end;
procedure TASDEngine.ScreenOptions(Width, Height, BPP, Refresh: Integer;
FullScreen, WaitVSync: Boolean);
var
Temp: DEVMODE;
begin
if FullScreen then
begin
//FForm.WindowState := wsMaximized;
FFormGL.BorderStyle := bsNone;
FFormGL.Left := 0;
FFormGL.Top := 0;
AddLog(Format(cFullScreenMode, [Width, Height, BPP, Refresh]));
end
else
begin
FFormGL.BorderStyle := bsSingle;
FFormGL.Position := poScreenCenter;
end;
FFormGL.Width := Width;
FFormGL.Height := Height;
if not FullScreen then
Exit;
EnumDisplaySettings(nil, 0, Temp);
with Temp do
begin
dmSize := SizeOf(DEVMODE);
dmPelsWidth := Width;
dmPelsHeight := Height;
dmBitsPerPel := BPP;
dmDisplayFrequency := Refresh;
end;
if ChangeDisplaySettings(Temp, CDS_TEST or CDS_FULLSCREEN) <>
DISP_CHANGE_SUCCESSFUL then
begin
Error('Невозможно переключится в полноэкранный режим!');
end
else
ChangeDisplaySettings(Temp, CDS_FULLSCREEN);
{if WaitVSync and (wglGetSwapIntervalEXT <> 1) then
wglSwapIntervalEXT(1)
else
wglSwapIntervalEXT(0);}
end;
procedure TASDEngine.Run;
begin
Application.Run;
end;
procedure TASDEngine.Error(Msg: string);
begin
Exception.Create(Msg);
AddLog(Msg, mtSysTime);
end;
procedure TASDEngine.InitGL;
procedure InitSettings;
begin
glDisable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glShadeModel(GL_SMOOTH); // Enables Smooth Color Shading
glClearDepth(1.0); // Depth Buffer Setup
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glAlphaFunc(GL_GREATER, 0);
glEnable(GL_ALPHA_TEST);
glEnable(GL_BLEND);
end;
begin
InitSettings;
end;
initialization
ASDEngine := TASDEngine.Create;
finalization
ASDEngine.Free;
end.
|
// Materia: Introduccion a la Algoritmica y Programacion 2016
// Proyecto fin de año "Juego PasaPalabra".
// Comisión n°2 - Grupo n°7
// Integrantes:
// - Elena, Pablo.
// - Gremiger, Santiago.
// - Martinez, Christian.
// **********************
// Unit dedicada al manejo de las LSE.
unit unitLista;
Interface
uses
unitTipos;
{======================================================================================}
{Declaraciones de las acciones y funciones visibles para quienes utilizan esta unidad}
{Retorna un Puntero al primer elemento valido de la Lista, Fin(l) si esta vacia}
function Inicio( l : TLista ) : TPuntero;
{Retorna un Puntero al primer elemento no valido de la Lista}
function Fin ( l : TLista ) : TPuntero;
{Retorna un Puntero al ultimo elemento valido de la Lista, Fin(l) si esta vacia}
function Ultimo (l : TLista) : TPuntero;
{Retorna el puntero al siguiente elemento de un elemento valido}
{pre: pos <> nil}
function Siguiente(pos : TPuntero ) : TPuntero;
{Retorna True si la Lista esta vacia, falso en caso contrario}
function EsVacia( l : TLista ) : boolean;
{Retorna el valor del elemento que corresponde a un Puntero }
{pre: pos <> nil}
function Obtener( pos : TPuntero) : TInfo;
{Retorna la longitud de la Lista }
function Longitud( l : TLista ) : integer;
{Inicializa la Lista como vacia }
procedure Inicializar( var l : TLista );
{Modifica el elemento que esta en un Puntero }
{pre: pos <> nil}
procedure Modificar( e : TInfo; var pos : TPuntero);
{Inserta un elemento al principio de la Lista }
procedure InsertarAlInicio( e : TInfo; var l : TLista);
{Inserta un elemento al final de la Lista }
procedure InsertarAlFinal( e : TInfo; var l : TLista);
{Inserta un elemento en una posicion dada}
procedure InsertarEnPos(e: TInfo; var l: TLista; pos: integer);
{Elimina el primer elemento de la Lista}
{pre: Longitud(l) >= 1 }
procedure EliminarPrincipio(var l : TLista);
{Elimina el elemento que se encuentra en la posicion dada}
{pre: pos <= Loncitud(l)}
procedure EliminarEnPos(var l: TLista; pos: integer);
{Elimina el ultimo elemento de la Lista}
{pre: Longitud(l) >= 1 }
procedure EliminarFinal(var l : TLista);
{Controla si un elemento dado se encuentra en la lista}
function TieneElem(info: TInfo; l : TLista): boolean;
{Muestra los elementos de l}
procedure MostrarLista(l: TLista; todas: boolean);
{Verifica condiciones para que una accion/funcion funcione correctamente, de no ser asi, cierra el programa.}
procedure Verificar( cond : boolean; mensaje_error : string );
//Funciones para generar nivel(temporales)
{modifica el campo visible de un puntero de la lista}
procedure ocultar_letra(var l: TLista; pos: integer);
{Devuelve el caracter que se encuentra en la posicion dada}
function obtener_letra(var l: TLista; pos: integer):char;
{Retorna True si un caracter esta en una posicion determinada de la lista, falso de lo contrario}
function CheckEnPosCaracter(var l: TLista; pos: integer; car: char):boolean;
{Devuelve "true" si el campo ".visible" es true}
function CheckEnPosVisible(var l: TLista; pos: integer):boolean;
{======================================================================================}
{Implementación del Módulo}
Implementation
uses
crt;
{******************************************************************************************}
{********** Declaracion de Acciones y Funciones Auxiliares locales al módulo **************}
{******************************************************************************************}
{Incrementa en 1 el campo cant de la lista }
procedure IncrementarCantidadElementos(var l : TLista); forward;
{Decrementa en 1 el campo cant de la lista }
procedure DecrementarCantidadElementos(var l : TLista); forward;
{Crea un nuevo Nodo de la Lista y le setea la informacion recibida como parametro}
procedure CrearNuevoNodo( var nuevoNodo : TPuntero; e: TInfo); forward;
{******************************************************************************************}
{************************ Implementación de Acciones y Funciones Exportadas ***************}
{******************************************************************************************}
{Retorna un Puntero al primer elemento valido de la Lista, Fin(l) si esta vacia}
function Inicio( l : TLista ) : TPuntero;
begin
Inicio:= (l.pri^).next; //retorno el puntero que sigue al ficticio.
end;
{Retorna un Puntero al primer elemento no valido de la Lista}
function Fin ( l : TLista ) : TPuntero;
begin
Fin := nil;
end;
{Retorna un Puntero al ultimo elemento valido de la Lista, Fin(l) si esta vacia}
function Ultimo (l : TLista) : TPuntero;
var
pAux : TPuntero;
begin
pAux := l.pri;
while((pAux^).next <> nil)do begin
pAux := Siguiente(pAux);
end;
Ultimo := pAux;
end;
{Retorna el puntero al siguiente elemento de un elemento valido}
{pre: pos <> nil}
function Siguiente(pos : TPuntero ) : TPuntero;
begin
Verificar(pos <> nil,'No se puede obtener siguiente posicion. Puntero nulo.');
Siguiente:=(pos^).next;
end;
{Retorna True si la Lista esta vacia, falso en caso contrario}
function EsVacia( l : TLista ) : boolean;
begin
if l.cant=0 then
EsVacia:=true
else
EsVacia:=false;
end;
{Retorna el valor del elemento que corresponde a un Puntero }
{pre: pos <> nil}
function Obtener( pos : TPuntero) : TInfo;
begin
Verificar(pos <> nil,'No se puede obtener valor. Puntero nulo.');
Obtener := (pos^).info;
end;
{Retorna la longitud de la Lista.}
function Longitud( l : TLista ) : integer;
begin
longitud:=l.cant;
end;
{Inicializa la Lista como vacia.}
procedure Inicializar( var l : TLista );
begin
//Utilizacion elemento ficticio.
new(l.Pri);
(l.Pri^).next := nil;
l.Ult := l.Pri;
l.cant := 0;
end;
{Modifica el elemento que esta en un Puntero.}
{pre: pos <> nil}
procedure Modificar (e:TInfo; var pos : TPuntero);
begin
Verificar(pos <> nil,'No se puede modificar valor. Puntero nulo.');
(pos^).info := e;
end;
{Inserta un elemento al principio de la Lista.}
procedure InsertarAlInicio(e:TInfo; var l : TLista);
begin
InsertarEnPos(e,l,1);
end;
{Inserta un elemento en una posicion dada}
{pre: pos <= Longitud(l) && pos > 0}
procedure InsertarEnPos(e: TInfo; var l: TLista; pos: integer);
var
n,pAux: TPuntero;
i : integer;
begin
Verificar(((0 < pos) and (pos <= Longitud(l)+1)),'No se puede Insertar. Posicion fuera de rango.');
pAux:=l.pri; //Obtecion primer elemento.
i := 1;
while (i < pos) and (pAux <> nil) do begin
i := i + 1;
pAux := Siguiente(pAux);
end;
CrearNuevoNodo(n,e);
(n^).next := (pAux^).next;
(pAux^).next := n;
IncrementarCantidadElementos(l);
l.ult := Ultimo(l); //posiciona el puntero l.ult al ultimo elemento valido.
end;
{Inserta un elemento al final de la Lista }
procedure InsertarAlFinal(e:TInfo; var l : TLista);
begin
InsertarEnPos(e,l,l.cant+1);
end;
{ Elimina el primer elemento de la Lista}
{ pre: Longitud(l) >= 1 }
procedure EliminarPrincipio(var l : TLista);
begin
EliminarEnPos(l,1);
end;
{Elimina el elemento que se encuentra en la posición dada}
{pre: pos <= Longitud(l) && pos > 0}
procedure EliminarEnPos(var l: TLista; pos: integer);
var
pAux, pElim : TPuntero;
i: integer;
begin
Verificar(not(EsVacia(l)), 'La lista esta vacia no se puede Eliminar.');
Verificar(((0 < pos) and (pos <= Longitud(l))),'No se puede Eliminar. Posicion fuera de rango.');
pAux:=l.Pri; //Obtecion primer elemento.
i := 0;
while (i < pos-1) do begin
i := i + 1;
pAux := Siguiente(pAux);
end;
pElim := (pAux^).next;
(pAux^).next := (pElim^).next;
dispose(pElim);
DecrementarCantidadElementos(l);
l.ult := Ultimo(l); //posiciona el puntero l.ult al ultimo elemento valido.
end;
{Elimina el ultimo elemento de la Lista}
{ pre: Longitud(l) >= 1 }
procedure EliminarFinal(var l : TLista);
begin
EliminarEnPos(l,l.cant);
end;
{Controla si un elemento dado se encuentra en la lista}
function TieneElem(info: TInfo; l : TLista): boolean;
var
pAux: TPuntero;
encontrado : boolean;
begin
pAux := Inicio(l);
encontrado := false;
while ((pAux <> nil) and not(encontrado)) do begin
if (Obtener(pAux).caracter = info.caracter) then
encontrado := true
else
pAux := Siguiente(pAux);
end;
TieneElem := encontrado;
end;
{Muestra los elementos de l}
procedure MostrarLista(l: TLista; todas: boolean);
var
r: Tpuntero;
begin
Verificar(Not(EsVacia(l)), 'La lista esta vacia no se puede mostrar.');
r:=Inicio(l);
while r<>nil do begin
if (((Obtener(r)).visible) or (todas)) then
write(' ',upcase((Obtener(r)).caracter))
else
write(' _');
r:=Siguiente(r);
end;
end;
{Oculta el caracter de la posicion dada}
procedure ocultar_letra(var l: TLista; pos: integer);
var
pAux: TPuntero;
i: integer;
begin
Verificar((pos <= Longitud(l)+1)and(pos > 0),'La cantidad de elementos de la secuencia es menor a la posicion solicitada');
pAux:=Inicio(l);
i:=1;
while i<pos do begin
i:=i+1;
pAux:=Siguiente(pAux);
end;
(pAux^).info.visible:=false;
end;
{Devuelve el caracter que se encuentra en la posicion dada}
function obtener_letra(var l: TLista; pos: integer):char;
var
pAux: TPuntero;
i: integer;
begin
Verificar((pos <= Longitud(l)+1)and(pos > 0),'La cantidad de elementos de la secuencia es menor a la posicion solicitada');
pAux:=Inicio(l);
i:=1;
while i<pos do begin
i:=i+1;
pAux:=Siguiente(pAux);
end;
obtener_letra:=(pAux^).info.caracter;
end;
{Devuelve "true" si el caracter de la posicion dada es igual al de la palabra}
function CheckEnPosCaracter(var l: TLista; pos: integer; car: char):boolean;
var
pAux: TPuntero;
i: integer;
begin
Verificar((pos <= Longitud(l)+1)and(pos > 0),'La cantidad de elementos de la secuencia es menor a la posicion solicitada');
pAux:=Inicio(l);
i:=1;
while i<pos do begin
i:=i+1;
pAux:=Siguiente(pAux);
end;
CheckEnPosCaracter := (pAux^).info.caracter=car;
end;
{Devuelve "true" si el campo ".visible" es true}
function CheckEnPosVisible(var l: TLista; pos: integer):boolean;
var
s: TPuntero;
i: integer;
begin
Verificar((pos <= Longitud(l)+1)and(pos > 0),'La cantidad de elementos de la secuencia es menor a la posicion solicitada');
s:=Inicio(l);
i:=1;
while i<pos do begin
i:=i+1;
s:=Siguiente(s);
end;
CheckEnPosVisible := (s^).info.visible=true;
end;
{Verifica condiciones para que una accion/funcion funcione correctamente, de no ser asi, cierra el programa.}
procedure Verificar( cond : boolean; mensaje_error : string );
begin
if (not cond) then
begin
writeln('ERROR: ', mensaje_error);
halt;
end;
end;
{******************************************************************************************}
{********** Implementación de Acciones y Funciones Auxiliares locales al módulo ***********}
{******************************************************************************************}
//--------------------------------------------------------
procedure IncrementarCantidadElementos(var l : TLista);
begin
l.cant := l.cant + 1;
end;
//--------------------------------------------------------
procedure DecrementarCantidadElementos(var l : TLista);
begin
l.cant := l.cant - 1;
end;
//--------------------------------------------------------
procedure CrearNuevoNodo( var nuevoNodo : TPuntero; e: TInfo);
begin
new(nuevoNodo);
(nuevoNodo^).info := e;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.OBJ.Model;
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
System.SysUtils, System.Classes, System.Types, FMX.Types3D, FMX.Types,
FMX.Objects3D, System.Math, FMX.Import, System.UITypes;
type
TOBJMesh = class
private
FName: String;
FSubMeshes: TGEMeshDynArray;
function ReadUseMaterial(const ALine: String; const AVertexSource: TGEVertexSource): TGEMesh;
public
property SubMeshes: TGEMeshDynArray read FSubMeshes;
destructor Destroy(); override;
constructor Create();
end;
TOBJMeshDynArray = array of TOBJMesh;
TOBJModel = class(TCustomModel)
private
FMaterials: TGEMaterials;
FMeshes: TOBJMeshDynArray;
FVertexSource: TGEVertexSource;
FSmoothGroup: Integer;
function ReadMaterials(const ALine: String): String;
procedure ReadSources(const ALine: String);
function ReadGeometry(const ALine: String):TOBJMesh;
procedure ReadSmoothGroup(const ALine: String);
procedure ReadFaces(const AMesh: TGEMesh; const ALine: String);
public
property Materials: TGEMaterials read FMaterials;
property Meshes: TOBJMeshDynArray read FMeshes;
procedure LoadFromFile(const AFileName: String); override;
constructor Create();
destructor Destroy(); override;
end;
implementation
constructor TOBJMesh.Create();
begin
FSubMeshes := nil;
end;
constructor TOBJModel.Create();
begin
FVertexSource := TGEVertexSource.Create;
FMaterials := TGEMaterials.Create(True);
end;
destructor TOBJModel.Destroy();
var
i : Integer;
begin
FVertexSource.Free;
for i := 0 to High(FMeshes) do
FMeshes[i].Free;
FMaterials.Free;
end;
destructor TOBJMesh.Destroy();
var
i : Integer;
begin
inherited Destroy;
for i := 0 to High(FSubMeshes) do
FSubMeshes[i].Free;
end;
procedure TOBJModel.ReadFaces(const AMesh: TGEMesh; const ALine: String);
var
c: PChar;
LVid, LVal, i: Integer;
LVert: array of array [0..2] of String;
LVertex: TGEVertexID;
LPolygon: TGEPoligonID;
LSpace: Boolean;
procedure AddLetter();
begin
if LSpace = true then
begin
Inc(LVid);
SetLength(LVert, LVid + 1);
LVal := 0;
LVert[LVid][0] := '0';
LVert[LVid][1] := '0';
LVert[LVid][2] := '0';
LSpace := false;
end;
end;
begin
c := @ALine[2];
LVid := -1;
LVal := 0;
LVert := nil;
LSpace:= true;
// parse line like 'f 1/1/1 2/2/1 3/3/1'
while c^ <> #0 do
begin
case c^ of
'0'..'9':
begin
AddLetter();
LVert[LVid][LVal] := LVert[LVid][LVal] + c^;
end;
'/':
begin
AddLetter();
Inc(LVal);
end;
' ':
LSpace := true;
'f':
LSpace := true;
end;
Inc(c);
end;
// copy from LVert to LPolygon
SetLength(LPolygon, LVid+1);
for i := 0 to LVid do
begin
LVertex.SmoothGroup := FSmoothGroup;
LVertex.Position := StrToInt(LVert[i][0]) - 1;
LVertex.Texture0 := StrToInt(LVert[i][1]) - 1;
LVertex.Normal := StrToInt(LVert[i][2]) - 1;
LPolygon[i] := LVertex;
end;
AMesh.AddPoligon(LPolygon);
end;
function TOBJMesh.ReadUseMaterial(const ALine: String; const AVertexSource: TGEVertexSource): TGEMesh;
var
LName: String;
i: Integer;
begin
LName := Trim(Copy(ALine, Length('usemtl')+1, length(ALine)));
for i := 0 to High(FSubMeshes) do
begin
result := FSubMeshes[i];
if SameText(result.MaterialName, LName) then
exit;
end;
result := TGEMesh.Create(AVertexSource);
result.MaterialName := LName;
SetLength(FSubMeshes, Length(FSubMeshes) + 1 );
FSubMeshes[High(FSubMeshes)] := result;
end;
function TOBJModel.ReadMaterials(const ALine: String): String;
var
LName: TStringDynArray;
begin
LName := StringsToStringDynArray(ALine);
if not SameText(LName[0], 'mtllib') then exit;
result := LName[1];
end;
procedure TOBJModel.ReadSmoothGroup(const ALine: String);
begin
FSmoothGroup := StrToInt(Trim(Copy(ALine, 3, Length(ALine))));
end;
procedure TOBJModel.ReadSources(const ALine: String);
var
LSource: String;
begin
LSource := Trim(Copy(ALine, 3, Length(ALine)));
case ALine[2] of
' ' : FVertexSource.AddPositionSource(FloatStringsToSingleDynArray(LSource));
'n' : FVertexSource.AddNormalSource(FloatStringsToSingleDynArray(LSource));
't' : FVertexSource.AddTextue0Source(FloatStringsToSingleDynArray(LSource));
end;
end;
function TOBJModel.ReadGeometry(const ALine: String) : TOBJMesh;
var
LName: string;
i: Integer;
begin
LName := Trim(Copy(ALine, 2, length(ALine)));
for i := 0 to High(FMeshes) do
begin
result := FMeshes[i];
if SameText(result.FName, LName) then
exit;
end;
result := TOBJMesh.Create();
result.FName := LName;
SetLength(FMeshes, Length(FMeshes) + 1 );
FMeshes[High(FMeshes)] := result;
end;
function GetFormatColor(ax,ay,az: String):TVector3D;
var
LFormatSettings: TFormatSettings;
begin
{$IFDEF FPC}
LFormatSettings := DefaultFormatSettings;
{$ELSE}
LFormatSettings := TFormatSettings.Create;
{$ENDIF}
LFormatSettings.DecimalSeparator := '.';
if (pos(',', ax + ay + az ) > 0) then
LFormatSettings.DecimalSeparator := ',';
result := Vector3D(
StrToFloat(ax,LFormatSettings),
StrToFloat(ay,LFormatSettings),
StrToFloat(az,LFormatSettings));
end;
procedure TOBJModel.LoadFromFile(const AFileName: String);
var
LPos: Integer;
LFile : TextFile;
LLine : String;
LALine: AnsiString;
LMesh: TOBJMesh;
LSubMesh: TGEMesh;
LName: TStringDynArray;
LMaterial: TGEMaterial;
LMaterialsFile: String;
begin
AssignFile(LFile, AFileName);
Reset(LFile);
LSubMesh := nil;
LMesh := nil;
FSmoothGroup := 0;
while not(EOF(LFile)) do
begin
Readln(LFile, LALine);
LLine := String(LALine);
if (LLine <> '') and (LLine[1] <> '#') then
begin
case LLine[1] of
'm' : LMaterialsFile := ReadMaterials(LLine);
'v' : ReadSources(LLine);
'g' : LMesh := ReadGeometry(LLine);
'u' : LSubMesh := LMesh.ReadUseMaterial(LLine, FVertexSource);
's' : ReadSmoothGroup(LLine);
'f' :
begin
if (LMesh = nil) then
LMesh := ReadGeometry('g default');
if (LSubMesh = nil) then
LSubMesh := LMesh.ReadUseMaterial('usemtl Default', FVertexSource);
ReadFaces(LSubMesh, Trim(LLine));
end;
end;
end;
end;
if not FileExists(LMaterialsFile) then
LMaterialsFile := ChangeFileExt(AFileName, '.mtl');
// load material file
if FileExists(LMaterialsFile) then
begin
AssignFile(LFile, LMaterialsFile);
Reset(LFile);
LMaterial := nil;
while not(EOF(LFile)) do
begin
Readln(LFile, LALine);
LLine := String(LALine);
if (LLine <> '') and (LLine[1] <> '#') then
begin
LName := StringsToStringDynArray(LLine);
if SameText(LName[0], 'newmtl') then
begin
LMaterial := FMaterials.Add(TGEMaterial.Create);
LMaterial.FName := LName[1];
end else
if (Assigned(LMaterial)) then
begin
if SameText(LName[0], 'map_Kd') then
begin
{$IFDEF FPCCOMP}
LPos := Pos(WideString('map_Kd'), LLine) + Length(WideString('map_Kd'));
{$ELSE}
LPos := Pos('map_Kd', LLine) + Length('map_Kd');
{$ENDIF}
LMaterial.FDiffuseMap := Copy(LLine, LPos+1, Length(LLine)-LPos);
end
else if SameText(LName[0], 'Ka') then
LMaterial.FAmbient := GetFormatColor(LName[1],LName[2],LName[3])
else if SameText(LName[0], 'Ks') then
LMaterial.FSpecular := GetFormatColor(LName[1],LName[2],LName[3])
else if SameText(LName[0], 'Kd') then
LMaterial.FDiffuse := GetFormatColor(LName[1],LName[2],LName[3])
end;
end;
end;
Closefile(LFile);
end;
end;
end.
|
unit BaseProductsViewModel;
interface
uses
System.Classes, ProductsBaseQuery0, ProducersGroupUnit2, NotifyEvents,
FireDAC.Comp.Client;
type
TBaseProductsViewModel = class(TComponent)
private
FNotGroupClone: TFDMemTable;
FqProductsBase0: TQryProductsBase0;
class var
FProducersGroup: TProducersGroup2;
protected
class var
FInstanceCount: Integer;
function CreateProductsQuery: TQryProductsBase0; virtual;
function GetExportFileName: string; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property ExportFileName: string read GetExportFileName;
property NotGroupClone: TFDMemTable read FNotGroupClone;
class property ProducersGroup: TProducersGroup2 read FProducersGroup;
property qProductsBase0: TQryProductsBase0 read FqProductsBase0;
end;
implementation
uses
System.SysUtils;
constructor TBaseProductsViewModel.Create(AOwner: TComponent);
begin
inherited;
Inc(FInstanceCount);
if FProducersGroup = nil then
begin
FProducersGroup := TProducersGroup2.Create(Self);
FProducersGroup.ReOpen;
end;
FqProductsBase0 := CreateProductsQuery;
FNotGroupClone := FqProductsBase0.BPW.AddClone
(Format('%s = 0', [FqProductsBase0.BPW.IsGroup.FieldName]));
end;
destructor TBaseProductsViewModel.Destroy;
begin
Dec(FInstanceCount);
if (FInstanceCount = 0) and (FProducersGroup <> nil) then
begin
FreeAndNil(FProducersGroup);
end;
if FNotGroupClone <> nil then
qProductsBase0.BPW.DropClone(FNotGroupClone);
FNotGroupClone := nil;
inherited;
end;
function TBaseProductsViewModel.CreateProductsQuery: TQryProductsBase0;
begin
Result := TQryProductsBase0.Create(Self);
end;
function TBaseProductsViewModel.GetExportFileName: string;
begin
Result := 'file.xls';
end;
end.
|
{
Copyright (C) Alexey Torgashin, uvviewsoft.com
License: MPL 2.0 or LGPL
}
unit ATSynEdit_Cmp_HTML_Provider;
{$mode objfpc}{$H+}
interface
uses
SysUtils, Classes;
type
TATHtmlProvider = class abstract
public
procedure GetTags(L: TStringList); virtual; abstract;
procedure GetTagProps(const ATag: string; L: TStringList); virtual; abstract;
procedure GetTagPropValues(const ATag, AProp: string; L: TStringList); virtual; abstract;
end;
TATHtmlBasicProvider = class(TATHtmlProvider)
private
ListAll: TStringList;
ListGlobals: TStringList;
ListMediaTypes: TStringList;
public
constructor Create(const AFilenameList, AFilenameGlobals, AFilenameMediaTypes: string);
destructor Destroy; override;
procedure GetTags(L: TStringList); override;
procedure GetTagProps(const ATag: string; L: TStringList); override;
procedure GetTagPropValues(const ATag, AProp: string; L: TStringList); override;
end;
implementation
uses
ATStringProc,
ATStringProc_Separator;
function IsTagWithMimeType(const ATag: string): boolean;
begin
case ATag of
'a',
'embed',
'link',
'object',
'script',
'source',
'style':
Result:= true;
else
Result:= false;
end;
end;
procedure StripEmptyFromList(L: TStringList);
var
i: integer;
begin
for i:= L.Count-1 downto 0 do
if L[i]='' then
L.Delete(i);
end;
{ TATHtmlBasicProvider }
constructor TATHtmlBasicProvider.Create(const AFilenameList, AFilenameGlobals, AFilenameMediaTypes: string);
begin
ListAll:= TStringList.Create;
ListGlobals:= TStringList.Create;
ListMediaTypes:= TStringList.Create;
if FileExists(AFilenameList) then
begin
ListAll.LoadFromFile(AFilenameList);
StripEmptyFromList(ListAll);
end;
if FileExists(AFilenameGlobals) then
begin
ListGlobals.LoadFromFile(AFilenameGlobals);
StripEmptyFromList(ListGlobals);
end;
if FileExists(AFilenameMediaTypes) then
begin
ListMediaTypes.LoadFromFile(AFilenameMediaTypes);
StripEmptyFromList(ListMediaTypes);
end;
end;
destructor TATHtmlBasicProvider.Destroy;
begin
FreeAndNil(ListMediaTypes);
FreeAndNil(ListGlobals);
FreeAndNil(ListAll);
inherited Destroy;
end;
procedure TATHtmlBasicProvider.GetTags(L: TStringList);
var
S, SKey, SVal: string;
begin
L.Clear;
L.Sorted:= true;
for S in ListAll do
begin
SSplitByChar(S, '=', SKey, SVal);
L.Add(SKey);
end;
end;
procedure TATHtmlBasicProvider.GetTagProps(const ATag: string; L: TStringList);
var
S, SKey, SVal, SItem: string;
Sep: TATStringSeparator;
begin
L.Clear;
L.Sorted:= true;
for S in ListGlobals do
begin
SSplitByChar(S, '<', SKey, SVal);
L.Add(SKey);
end;
for S in ListAll do
begin
SSplitByChar(S, '=', SKey, SVal);
if SameText(SKey, ATag) then
begin
Sep.Init(SVal, '|');
while Sep.GetItemStr(SItem) do
begin
SItem:= SGetItem(SItem, '<');
L.Add(SItem);
end;
Break;
end;
end;
end;
procedure TATHtmlBasicProvider.GetTagPropValues(const ATag, AProp: string; L: TStringList);
//
function AddFromData(const AData: string): boolean;
var
SKey, SVal, SItem: string;
Sep: TATStringSeparator;
begin
Result:= false;
SSplitByChar(AData, '<', SKey, SVal);
if SameText(AProp, SKey) then
begin
Sep.Init(SVal, '?');
while Sep.GetItemStr(SItem) do
L.Add(SItem);
exit(true);
end;
end;
//
var
SRoot, SRootKey, SRootVal, SItem: string;
Sep: TATStringSeparator;
begin
L.Clear;
L.Sorted:= true;
if (AProp='type') and IsTagWithMimeType(ATag) then
begin
L.AddStrings(ListMediaTypes);
exit;
end;
for SItem in ListGlobals do
if AddFromData(SItem) then
exit;
for SRoot in ListAll do
begin
SSplitByChar(SRoot, '=', SRootKey, SRootVal);
if SameText(SRootKey, ATag) then
begin
Sep.Init(SRootVal, '|');
while Sep.GetItemStr(SItem) do
if AddFromData(SItem) then Break;
Break;
end;
end;
end;
end.
|
unit ExemptionsNotRecalculatedFormUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Grids, RPCanvas, RPrinter, RPDefine, RPBase, RPFiler, Buttons,
ComCtrls;
type
TExemptionsNotRecalculatedForm = class(TForm)
Label1: TLabel;
PrintButton: TBitBtn;
ReportFiler: TReportFiler;
ReportPrinter: TReportPrinter;
PrintDialog: TPrintDialog;
ExemptionsListView: TListView;
procedure ReportPrintHeader(Sender: TObject);
procedure ReportPrint(Sender: TObject);
procedure PrintButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
ExemptionsNotRecalculatedList : TStringList;
Procedure InitializeForm;
end;
var
ExemptionsNotRecalculatedForm: TExemptionsNotRecalculatedForm;
implementation
{$R *.DFM}
uses PASUtils, GlblCnst, Preview, WinUtils, PASTypes, Utilitys;
{=====================================================================}
Procedure TExemptionsNotRecalculatedForm.InitializeForm;
var
Index : Integer;
ParcelID, ExemptionCode : String;
begin
Index := 0;
while(Index < (ExemptionsNotRecalculatedList.Count - 1)) do
begin
ParcelID := ConvertSBLOnlyToDashDot(Copy(ExemptionsNotRecalculatedList[Index], 7, 20));
Inc(Index);
ExemptionCode := ExemptionsNotRecalculatedList[Index];
Inc(Index);
FillInListViewRow(ExemptionsListView, [ParcelID, ExemptionCode], False);
end; {while(Index < (ExemptionsNotRecalculatedList.Count - 1)) do}
end; {InitializeForm}
{========================================================}
Procedure TExemptionsNotRecalculatedForm.ReportPrintHeader(Sender: TObject);
begin
with Sender as TBaseReport do
begin
{Print the date and page number.}
SectionTop := 0.25;
SectionLeft := 0.5;
SectionRight := PageWidth - 0.5;
SetFont('Times New Roman',8);
PrintHeader('Page: ' + IntToStr(CurrentPage), pjRight);
PrintHeader('Date: ' + DateToStr(Date) +
' Time: ' + FormatDateTime(TimeFormat, Now), pjLeft);
SectionTop := 0.5;
SetFont('Arial',14);
Underline := True;
Home;
CRLF;
PrintCenter('Exemptions not Recalculated ', (PageWidth / 2));
SetFont('Times New Roman', 12);
CRLF;
CRLF;
Underline := False;
ClearTabs;
Bold := True;
SetTab(0.5, pjCenter, 1.5, 0, BoxLineBottom, 0); {Parcel 1}
SetTab(2.1, pjCenter, 0.5, 0, BoxLineBottom, 0); {Exemption Code}
SetTab(3.0, pjCenter, 1.5, 0, BoxLineBottom, 0); {Parcel 2}
SetTab(4.6, pjCenter, 0.5, 0, BoxLineBottom, 0); {Exemption Code}
SetTab(5.5, pjCenter, 1.5, 0, BoxLineBottom, 0); {Parcel 3}
SetTab(7.1, pjCenter, 0.5, 0, BoxLineBottom, 0); {Exemption Code}
Println(#9 + 'Parcel ID' +
#9 + 'Code' +
#9 + 'Parcel ID' +
#9 + 'Code' +
#9 + 'Parcel ID' +
#9 + 'Code');
Bold := False;
ClearTabs;
SetTab(0.5, pjLeft, 1.5, 0, BOXLINENONE, 0); {Parcel 1}
SetTab(2.1, pjLeft, 0.5, 0, BOXLINENONE, 0); {Exemption Code}
SetTab(3.0, pjLeft, 1.5, 0, BOXLINENONE, 0); {Parcel 2}
SetTab(4.6, pjLeft, 0.5, 0, BOXLINENONE, 0); {Exemption Code}
SetTab(5.5, pjLeft, 1.5, 0, BOXLINENONE, 0); {Parcel 3}
SetTab(7.1, pjLeft, 0.5, 0, BOXLINENONE, 0); {Exemption Code}
end; {with Sender as TBaseReport do}
end; {ReportPrintHeader}
{========================================================================}
Procedure TExemptionsNotRecalculatedForm.ReportPrint(Sender: TObject);
var
I, Index : Integer;
begin
Index := 0;
with Sender as TBaseReport do
while _Compare(Index, (ExemptionsNotRecalculatedList.Count - 1), coLessThan) do
begin
For I := 1 to 3 do
begin
If _Compare(Index, (ExemptionsNotRecalculatedList.Count - 1), coLessThan)
then
begin
Print(#9 + ConvertSBLOnlyToDashDot(Copy(ExemptionsNotRecalculatedList[Index], 7, 20)));
Inc(Index);
Print(#9 + ExemptionsNotRecalculatedList[Index]);
Inc(Index);
end; {If _Compare(Index, ...}
end; {For I := 1 to 3 do}
Println('');
If (LinesLeft < 5)
then NewPage;
end; {while _Compare(Index, (ExemptionsNotRecalculatedList.Count - 1), coLessThan) do}
end; {ReportPrint}
{=====================================================================}
Procedure TExemptionsNotRecalculatedForm.PrintButtonClick(Sender: TObject);
var
NewFileName : String;
Quit : Boolean;
begin
If PrintDialog.Execute
then
begin
AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptBoth], False, Quit);
If not Quit
then
begin
{If they want to preview the print (i.e. have it
go to the screen), then we need to come up with
a unique file name to tell the ReportFiler
component where to put the output.
Once we have done that, we will execute the
report filer which will print the report to
that file. Then we will create and show the
preview print form and give it the name of the
file. When we are done, we will delete the file
and make sure that we go back to the original
directory.}
If PrintDialog.PrintToFile
then
begin
NewFileName := GetPrintFileName(Self.Caption, True);
ReportFiler.FileName := NewFileName;
try
PreviewForm := TPreviewForm.Create(self);
PreviewForm.FilePrinter.FileName := NewFileName;
PreviewForm.FilePreview.FileName := NewFileName;
ReportFiler.Execute;
PreviewForm.ShowModal;
finally
PreviewForm.Free;
end; {If PrintRangeDlg.PreviewPrint}
end {They did not select preview, so we will go
right to the printer.}
else ReportPrinter.Execute;
end; {If not Quit}
ResetPrinter(ReportPrinter);
end; {If PrintDialog.Execute}
end; {PrintButtonClick}
end.
|
unit js_parser;
interface
uses js_lexer,fw_utils;
type
TJs_Parser=class(TJs_Lexer)
private
function s_IsValidSeparator:boolean;
function s_Error(s:string):boolean;
function s_ErrorN(s:string;p:p_node):boolean;
function s_ErrorP(s:string;p:p_node):pointer;
function s_node(p:p_node;k:cardinal):p_node;
function s_nodeP(p:p_node;k:cardinal):p_node;
function s_nodec(parent:cardinal;child:p_node):p_node;
function s_nodenc(parent:cardinal;child:p_node):p_node;
function s_expressionOrEmpty:p_node;
function s_name(s:string):string;
function s_identList(a:p_node;k:cardinal):boolean;
function s_ParamExpressionList(a:p_node):boolean;
function s_makelocal(p:p_node):boolean;
function Syntax_Statement:boolean;
function Syntax_TryStatement:boolean;
function Syntax_Statements(c:p_node):boolean;
function Syntax_GetterSetter(k:cardinal;r:p_node):p_node;
function Syntax_ObjectField(r:p_node):p_node;
function Syntax_IfStatement:boolean;
function Syntax_ForStatement:boolean;
function Syntax_ForEachStatement:boolean;
function Syntax_ForInStatement(v:boolean;p:p_node):boolean;
function Syntax_WhileStatement:boolean;
function Syntax_ThrowStatement:boolean;
function Syntax_Expression:p_node;
function Syntax_ExpressionGroup(p:p_node):p_node;
function Syntax_ExpressionGroupOn(p:p_node;k:longint):p_node;
function Syntax_BinExpression(op:longint):p_node;
function Syntax_TercExpression(op:longint;r:p_node):p_node;
function Syntax_VarStatement:boolean;
function Syntax_UnaryExpression:p_node;
function Syntax_Factor:p_node;
function Syntax_ObjectExpression:p_node;
function Syntax_ArrayExpression:p_node;
function Syntax_FunctionStatement:boolean;
function Syntax_BreakStatement:boolean;
function Syntax_ReturnStatement:boolean;
function Syntax_FunctionExpression(n_required:boolean):p_node;
public
root:p_node;
cur,vars,funcs:p_Node; // Nodos pivote
function s_nodeT(p:p_node;k:cardinal;s:string):p_node;
constructor Create;
destructor Destroy; override;
function Parse:boolean;
end;
var object_debug:longint=0;
implementation
uses js_tokens;
function TJs_Parser.s_identList(a:p_node;k:cardinal):boolean;
begin
repeat
result:=token=jst_ident;
if result then begin
if n_FindChildHash(a,hash)<>nil then result:=s_error('Duplicated symbol') else s_node(a,k).value:=n_ValuePP(a);
end else s_error('Expected ident');
until (result=false) or (lex_gtg(jst_Comma)<>1);
if result then result:=error='';
end;
function TJs_Parser.s_name(s:string):string;
var i:longint;
begin
i:=length(s);while (i>0) and (s[i]<>'#') do i:=i-1;
result:=copy(s,i+1,length(s));
end;
function TJs_Parser.s_nodeT(p:p_node;k:cardinal;s:string):p_node;
begin
result:=n_CreateT(p,k,s);
result.pos:=tpos-src;
result.len:=pos-tpos;
end;
function TJs_Parser.s_node(p:p_node;k:cardinal):p_node;
begin
result:=n_CreateT(p,k,lex_token);
result.pos:=tpos-src;
result.len:=pos-tpos;
end;
function TJs_Parser.s_nodeP(p:p_node;k:cardinal):p_node;
begin
result:=n_CreateT(p,k,lex_token);
result.pos:=tpos-src;
result.len:=pos-tpos;
result:=p;
end;
function TJs_Parser.s_nodenc(parent:cardinal;child:p_node):p_node;
begin
result:=n_Create(nil,parent);
result.pos:=tpos-src;
result.len:=0;
n_AddAsChild(result,child);
end;
function TJs_Parser.s_nodec(parent:cardinal;child:p_node):p_node;
begin
result:=s_node(nil,parent);n_AddAsChild(result,child);
end;
function TJs_Parser.s_ErrorN(s:string;p:p_node):boolean;
begin
result:=false;
if error='' then begin
error:=s;
if p<>nil then begin error:=error+' ('+js_token2str(p.kind)+') '+p.text;error:=error+CalcXY(src+p.pos);end;
end;
token:=jst_Error;
end;
function TJs_Parser.s_Error(s:string):boolean;
begin
result:=false;
if error='' then begin
error:=s+' ('+js_token2str(token)+':'+lex_token+')';
error:=error+CalcXY(tpos);
end;
token:=jst_Error;
end;
function TJs_Parser.s_ErrorP(s:string;p:p_node):pointer;
begin
s_error(s);if p<>nil then n_Free(p);
result:=nil;
end;
constructor TJs_Parser.Create;
begin
inherited Create;
cur:=nil;
root:=s_nodeT(nil,jst_root,'');
vars:=s_nodeT(root,jst_vars,'');
funcs:=s_nodeT(root,jst_functions,'');
end;
destructor TJs_Parser.Destroy;
begin
n_Free(root);
inherited Destroy;
end;
function TJs_Parser.Parse:boolean;
var p1,p2,p3:p_node;
begin
error:='';token:=jst_None;
result:=lex;
while result and (token<>jst_Eof) do begin
cur:=root;vars:=root.first;result:=Syntax_Statement;
end;
// Hacemos una pequeña limpieza y ponemos las definiciones de Codigo al final de la lista
if not result and (error='') then error:='UNDEFINED ERROR';
// Ponemos el codigo al final
if result then begin
p1:=n_Create(nil,0);
p2:=root.first;while p2<>nil do begin p3:=p2.next;if p2.kind=jst_CodeDef then n_AddAsChild(p1,n_RemoveFromParent(p2));p2:=p3;end;
p2:=p1.first; while p2<>nil do begin p3:=p2.next;n_AddAsChild(root,n_RemoveFromParent(p2));p2:=p3;end;
n_Free(p1);
end;
end;
// http://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion
// http://bclary.com/2004/11/07/#a-7.9.1
// http://inimino.org/~inimino/blog/javascript_semicolons
function TJs_Parser.s_IsValidSeparator:boolean;
var p1:pchar;
begin
p1:=spos;dec(p1);
if p1^='}' then begin result:=true;exit;end;
if p1^=#13 then begin result:=true;exit;end;
if p1^=#10 then begin result:=true;exit;end;
repeat result:=(p1^=#13) or (p1^=';');inc(p1); until result or (p1=tpos);
if not result then s_error('Expected [;] and have');
end;
function TJs_Parser.Syntax_Statement:boolean;
var p:pchar;
c1,c2:p_node;
begin
p:=pos;c1:=cur;c2:=vars;
case token of
jst_PComma: result:=lex;
jst_Break: result:=Syntax_BreakStatement;
jst_Function: result:=Syntax_FunctionStatement;
jst_If: result:=Syntax_IfStatement;
jst_While: result:=Syntax_WhileStatement;
jst_For: begin result:=lex;if result then if token=jst_Each then result:=Syntax_ForEachStatement else result:=Syntax_ForStatement;end;
jst_Try: result:=Syntax_TryStatement;
jst_Return: result:=Syntax_ReturnStatement;
jst_Throw: result:=Syntax_ThrowStatement;
jst_Var: result:=Syntax_VarStatement;
else result:=n_AddAsChild(cur,Syntax_ExpressionGroup(nil))<>nil; // Para el resto de casos hacemos una expresion
end;
if result then begin
if (token=jst_PComma) then result:=lex else
if token<>jst_end then result:=s_IsValidSeparator;
end;
cur:=c1;vars:=c2;
//if pc and result and (token=pPComma) then result:=lex;
if result and (p=pos) then result:=s_error('Endless loop');
end;
// Las prioridades de una expresion son las siguientes, de mas a menos
// FACTOR
// UNARIOS
// BINARIOS
// TERCIARIOS
// ASIGNACION
// COMA
function TJs_Parser.Syntax_ExpressionGroup(p:p_node):p_node;
begin
if p=nil then result:=Syntax_Expression else result:=p; // Si teniamos algun previo lo usamos, sino lo leemos
if (result<>nil) and (token=jst_Comma) then begin
result:=s_nodenc(jst_ExpGroup,result);
while (result<>nil) and (token=jst_Comma) do
if lex then begin if n_AddAsChild(result,Syntax_Expression)=nil then result:=n_Free(result);end
else result:=n_Free(result);
end;
end;
function TJs_Parser.Syntax_Expression:p_node;
begin
result:=Syntax_BinExpression(js_maxBinOp);
end;
function TJS_Parser.s_expressionOrEmpty:p_node;
begin
if (token=jst_PComma) or (token=jst_End) then result:=nil else result:=Syntax_Expression;
end;
function TJS_Parser.Syntax_VarStatement:boolean;
var p1,p2:p_node;
begin
repeat
result:=lex_ge(jst_ident);if not result then exit; // Consumimos var|, y esperamos encontrar un identificador
p1:=n_FindChildHash(vars,hash);if p1=nil then begin p1:=s_Node(vars,jst_Var);p1.value:=n_ValuePP(vars);end; // Localizamos o creamos el identificador en la lista de variables
case lex_gtg(jst_Assign) of
0: result:=False;
1: begin
p2:=s_nodeT(s_NodeT(cur,jst_assign,'='),jst_ident,p1.text);p2.data:=p1;;
p1:=n_AddAsChild(p2.parent,Syntax_Expression);result:=p1<>nil;
end;
end;
until (result=false) or (token<>jst_Comma);
end;
function TJS_Parser.Syntax_ReturnStatement:boolean;
begin
result:=lex;
// Atencion segun la gramatica despues de return NO podemos tener un linebreak o se auto-insertara un
// semicolon
if result then result:=n_AddAsChildP(s_NodeT(cur,jst_Return,'return'),s_expressionOrEmpty)<>nil;
end;
function TJS_Parser.Syntax_BreakStatement:boolean;
var p1:p_node;
begin
result:=lex;
if result then begin
p1:=cur; // Buscamos el loop
while (p1<>nil) and (js_tokenIsLoop(p1.kind)=false) do p1:=p1.parent;
if p1=nil then begin result:=s_Error('Break can only be used in loops');exit;end;
p1:=n_AddAfter(p1,s_node(nil,jst_BreakHelper));
p1.data:=s_NodeT(cur,jst_Break,'Break');
end;
end;
// Parsea un statement function name(){..some code .}
// Que en realidad quiere decir: name=CreateFunctionObject( ..some code....)
// Y nosotros lo traducimos como: #scope_name = { ..some code ..}
// name=CreateFunctionObject( #scope_name )
function TJS_Parser.Syntax_FunctionStatement:boolean;
var c1,c2:p_node;
begin
c1:=Syntax_FunctionExpression(true);result:=c1<>nil;if not result then exit;
c2:=n_FindChildText(vars,s_name(c1.data.text));
if c2=nil then begin c2:=s_nodeT(vars,jst_Var,s_name(c1.data.text));c2.value:=n_ValuePP(vars);end else n_ClearChildren(c2);
// Ahora generamos una expresion NEW_FUNCTION_OBJECT(CODE_INSTANCE);
n_AddAsChild(c2,c1);
end;
function TJS_Parser.s_makelocal(p:p_node):boolean;
var p1:p_node;
begin
if p.kind=jst_ExpGroup then begin p:=p.first;repeat result:=s_makelocal(p);p:=p.next;until (p=nil) or (result=false);exit;end;
if p.kind=jst_Assign then p:=p.first;
if p.kind<>jst_ident then begin result:=s_ErrorN('Expected IDENT',p);exit;end;
p1:=n_FindChildHash(vars,p.hash);
if p1=nil then begin p1:=s_NodeT(vars,jst_Var,p.text);p1.value:=n_ValuePP(vars);end;
p.data:=p1;
result:=true;
end;
// Entramos con function. Parsea el codigo de la funcion Como un CodeDef y defuelve un nodo jst_NewFunc
function TJS_Parser.Syntax_FunctionExpression(n_required:boolean):p_node;
var name:string;
c1,c2:p_node;
f_start:pchar;
begin
f_start:=tpos; // Donde empieza el nombre de la funcion
result:=nil;if not lex then exit; // Consumimos [function]
if (token<>jst_Ident) and n_required then begin s_error('Expected funcion name');exit;end; // Leemos el nombre de la funcion
if token=jst_Ident then begin name:=lex_token;if not lex then exit;end // o generamos uno si es anonima
else begin name:='!F'+s_i2s(root.value);n_ValuePP(root);end;
if not lex_eg(jst_OpenPar) then exit; // Consumimos (
c1:=cur;c2:=vars; // Guardamos cur y vars
name:=c1.text+'#'+name; // Este es el nombre cualificado de la funcion. El sufijo se utiliza para distinguir Getters y Setters. Internamente son funciones con distinto nombre
cur:=n_FindChildText(funcs,name);
if cur<>nil then n_ClearChildren(cur) else cur:=s_nodeT(funcs,jst_CodeDef,name); // Si esta repe eliminamos el contenido de la anterior, sino creamos una nueva
if n_required=false then cur.number:=1; // Si se trata de una function expression ponemos el campo number a 1
vars:=s_nodeT(cur,jst_Vars,'');vars.hash:=0; // Creamos el nodo con las variables locales. Utilizaremos los campos value, number y hash para contar variables definidas, capturadas y externas
if token<>jst_ClosePar then if not s_identList(vars,jst_Param) then exit; // Leemos los parametros
if not lex_eeg(jst_ClosePar,jst_Begin) then exit; // Consumimos )
while (token<>jst_End) and Syntax_Statement do begin end; // Hacemos los statements
if token<>jst_end then exit; // Salimos si no tenemos }, es decir hubo error
cur.pos:=f_start-src;cur.len:=tpos-f_start+1; // Guardamos donde empieza y donde acaba la funcion
if not lex then exit; // Consumimos el }
vars:=c2;cur.data:=c1; // La funcion se define en C1-VARS
while (cur.data<>root) and (cur.data.kind<>jst_CodeDef) do cur.data:=cur.data.parent; // Localizamos el scope donde se define la funcion
result:=s_nodeT(nil,jst_FuncDef,cur.text);result.data:=cur; // Definimos la funcion (que apunta al codigo)
cur:=c1; // Y restauramos cur
end;
function TJS_Parser.Syntax_ForEachStatement:boolean;
begin
result:=s_Error('Not implemented FOR EACH');
end;
// Si tenemos for (x in a,b) --> x in b
// Si tenemos for ( 'true' in
function TJS_Parser.Syntax_ForInStatement(v:boolean;p:p_node):boolean;
var c1,c:p_node;
begin
c1:=cur;
cur:=s_nodeT(cur,jst_ForIn,'FOR_IN');n_AddAsChild(cur,p);
if v then begin result:=s_MakeLocal(p.first);if not result then exit;end;
if token=jst_Comma then begin
c:=Syntax_ExpressionGroupOn(n_RemoveFromParent(p.first.next),jst_ClosePar);
result:=c<>nil;if not result then exit;
n_AddAsChild(p,c);
end;
result:=lex_eg(jst_ClosePar);if not result then exit;
if result then result:=Syntax_Statements(cur);
cur:=c1;
end;
function TJs_Parser.Syntax_ExpressionGroupOn(p:p_node;k:longint):p_node;
begin
// Si tenemos K salimos con p o none
if token=k then begin if p<>nil then result:=p else result:=s_nodeT(nil,jst_None,'');exit;end;
// Parseamos la expresion que tengamos
result:=Syntax_ExpressionGroup(p);
end;
function TJS_Parser.Syntax_ForStatement:boolean;
var c:p_node;
cvar:boolean;
begin
result:=lex_eg(jst_OpenPar);if not result then exit; // Esperamos un (
cvar:=token=jst_Var;if cvar then result:=lex;if not result then exit;
if token<>jst_PComma then begin
c:=Syntax_Expression;result:=c<>nil;if not result then exit;
if c.kind=jst_In then begin result:=Syntax_ForInStatement(cvar,c);exit;end;
c:=Syntax_ExpressionGroupOn(c,jst_PComma);result:=c<>nil;if not result then exit;
end else c:=s_nodeT(nil,jst_None,'');
// Si tenemos Var
if cvar then result:=s_MakeLocal(c);if not result then exit;
// Generamos el nodo FOR y la primera expresion
cur:=s_nodeT(cur,jst_for,'FOR');n_AddAsChild(cur,c);
result:=lex_eg(jst_PComma);if not result then exit;
// Ahora la segunda
c:=n_AddAsChild(cur,Syntax_ExpressionGroupOn(nil,jst_PComma));
result:=c<>nil;if not result then exit;
// Y la tercera
result:=lex_eg(jst_PComma);if not result then exit;
c:=n_AddAsChild(cur,Syntax_ExpressionGroupOn(nil,jst_ClosePar));
result:=c<>nil;if not result then exit;
result:=lex_eg(jst_ClosePar);if not result then exit;
if result then result:=Syntax_Statements(cur);
end;
function TJS_Parser.Syntax_Statements(c:p_node):boolean;
var c1:p_node;
begin
c1:=cur;cur:=c;
if token=jst_Begin then begin
result:=lex;cur:=s_nodeT(cur,jst_Begin,'');
while (token<>jst_End) and result do result:=Syntax_Statement;
if result then result:=lex_eg(jst_end);
end else result:=Syntax_Statement;
cur:=c1;
end;
function TJS_Parser.Syntax_ThrowStatement:boolean;
begin
cur:=s_node(cur,jst_throw);
result:=lex;
if result then result:=n_AddAsChild(cur,Syntax_Expression)<>nil;
end;
function TJS_Parser.Syntax_WhileStatement:boolean;
begin
cur:=s_node(cur,jst_while);
result:=lex_geg(jst_OpenPar);if not result then exit;
result:=n_AddAsChild(cur,Syntax_Expression)<>nil;if not result then exit;
result:=lex_eg(jst_ClosePar);if not result then exit;
result:=Syntax_Statements(cur);
end;
function TJS_Parser.Syntax_TryStatement:boolean;
var o,p:p_node;
begin
result:=lex_ge(jst_Begin);if not result then exit;
p:=s_node(cur,jst_Try);o:=p;
result:=Syntax_Statements(p);
if result then begin
result:=false;
if token=jst_catch then begin
result:=lex_gege(jst_OpenPar,jst_ident);
if result then p:=s_nodeP(s_node(p,jst_catch),token) else s_Error('Expected [Ident] in CATCH block');
if result then result:=lex_gege(jst_ClosePar,jst_Begin);
if result then result:=Syntax_Statements(p);
end;
if token=jst_finally then begin
if lex_ge(jst_Begin) then begin
n_RemoveFromParent(o);
o:=n_AddAsChildP(s_node(nil,jst_finally),o);
n_AddAsChild(cur,o);
result:=Syntax_Statements(o);
end;
end;
end;
if not result then result:=s_Error('Expected [CATCH or FINALLY] after TRY');
end;
function TJS_Parser.Syntax_IfStatement:boolean;
begin
cur:=s_nodeT(cur,jst_if,'IF');
result:=lex_geg(jst_OpenPar);if not result then exit;
result:=n_AddAsChild(cur,Syntax_Expression)<>nil;if not result then exit;
result:=lex_eg(jst_ClosePar);if not result then exit;
result:=Syntax_Statements(cur);if not result then exit;
if token<>jst_else then exit else result:=lex;
if result then result:=Syntax_Statements(cur);
end;
function TJs_Parser.Syntax_TercExpression(op:longint;r:p_node):p_node;
var a:p_node;
begin
result:=r;
if lex then begin
a:=n_AddAsChild(result,Syntax_Expression);
if (a<>nil) and lex_eg(jst_2Puntos) then n_AddAsChild(result,Syntax_Expression) else result:=n_Free(result);
end else result:=n_Free(result);
end;
function TJs_Parser.Syntax_BinExpression(op:longint):p_node;
var a:p_node;
begin
// Hacemos los operadores de mayor prioridad
if op<js_minBinOp then result:=Syntax_UnaryExpression else result:=Syntax_BinExpression(op-1);
if not js_tokenIsBinOp(token,op) then exit else result:=s_nodec(token,result);
// Si se trata del operador terciario ?:
if token=jst_CondIf then begin result:=Syntax_TercExpression(token,result);exit;end;
while (result<>nil) and js_tokenIsBinOp(token,op) do begin
if lex then begin
if op<js_minBinOp then a:=Syntax_UnaryExpression else a:=Syntax_BinExpression(op-1);
if a<>nil then n_AddAsChild(result,a) else result:=n_Free(result);
end else result:=n_Free(result);
end;
end;
function TJs_Parser.Syntax_UnaryExpression:p_node;
var p:p_node;
k:cardinal;
begin
result:=nil;k:=js_token2UnaryOp(token,true);
while (token<>jst_Error) and js_tokenIsUnaryPreOp(k) do begin result:=s_node(result,k);lex;k:=js_token2UnaryOp(token,true);end;
if token=jst_Error then begin result:=n_Free(n_top(result));exit;end;
p:=Syntax_Factor;
if p=nil then begin result:=n_Free(n_top(result));exit;end;
// Si tenemos postexpression y el post tiene mas prioridad que los operadores de pre !!
k:=js_token2UnaryOp(token,false);
while (token<>jst_Error) and js_tokenIsUnaryPostOp(k) and lex do begin
case k of
jst_fcall: begin p:=s_nodenc(k,p);s_ParamExpressionList(p);if n_kind(result)=jst_New then p.kind:=jst_Begin;end;
jst_index: begin if n_kind(result)<>jst_New then begin p:=s_nodenc(k,p);p.kind:=jst_Index;end
else begin p:=n_AddAsChildP(s_node(nil,k),n_AddAsChildP(result,p));result:=nil;end;
n_AddAsChild(p,Syntax_Expression);
lex_eg(jst_CloseB);
end;
jst_member: begin
if n_kind(result)<>jst_New then begin p:=s_nodenc(k,p);p.kind:=jst_member;end
else begin p:=n_AddAsChildP(s_node(nil,k),n_AddAsChildP(result,p));result:=nil;end;
s_node(p,jst_ident);
lex_eg(jst_ident);
end;
else p:=s_nodec(k,p);
end;
k:=js_token2UnaryOp(token,false);
end;
result:=n_top(n_AddAsChild(result,p)); // Subimos al nodo inicial
if token=jst_Error then result:=n_Free(result);
end;
function TJs_Parser.s_ParamExpressionList(a:p_node):boolean;
begin
if token=jst_ClosePar then begin result:=lex;exit;end;
repeat
result:=n_AddAsChild(a,Syntax_Expression)<>nil;
if result then begin
if (token<>jst_ClosePar) and (token<>jst_Comma) then result:=s_Error('Expected [comma]') else result:=lex_tg(jst_Comma)<>0;
end;
until (result=false) or (token=jst_ClosePar);
if result then result:=lex;
end;
function TJs_Parser.Syntax_Factor:p_node;
var next:boolean;
begin
next:=true;
case token of
jst_true: begin result:=s_nodeT(nil,jst_bool,'true');result.value:=1;end;
jst_false: begin result:=s_nodeT(nil,jst_bool,'false');result.value:=0;end;
jst_this,jst_null,jst_pchar,jst_ident,jst_integer,jst_float: begin result:=s_node(nil,token);end;
jst_OpenPar: if lex then begin result:=Syntax_ExpressionGroup(nil);if token<>jst_ClosePar then result:=n_Free(result);end;
jst_Function: begin result:=Syntax_FunctionExpression(false);next:=false;end;
jst_Begin: begin if lex then result:=Syntax_ObjectExpression else result:=nil;next:=false;end;
jst_OpenB: begin if lex then result:=Syntax_ArrayExpression else result:=nil;next:=false;end;
//pDiv: if lex_RegExpression then result:=s_lex(s_CreateT(nil,pRegExpDef,lex_token));
else result:=s_errorP('Expected factor',nil);
end;
if next and (result<>nil) then if not lex then result:=n_Free(result);
end;
function TJs_Parser.Syntax_GetterSetter(k:cardinal;r:p_node):p_node;
var c1,c2:p_node;
name:string;
begin
c1:=Syntax_FunctionExpression(true);if c1=nil then begin result:=n_free(result);exit;end; // Parseamos la funcion que sigue
c1.kind:=k;name:=s_name(c1.text); // Este es el nombre de la propiedad
c2:=n_FindChildText(r,name); // Buscamos la propiedad
if c2=nil then c2:=n_CreateT(r,jst_GetSet,name) // Si no existe la creamos
else if c2.kind<>jst_GetSet then begin result:=s_ErrorP('['+name+'] duplicated in Get/Set',c1);n_Free(result);exit;end; // Si existe debe de ser un Getter / Setter
if k=jst_Getter then name:='@G'+s_p2s(c2)+'_'+name else name:='@S'+s_p2s(c2)+'_'+name; // Le damos un nombre unico
n_Text(c1.data,name);n_Text(c1,name); // A la funcion y a la definicion
if n_FindChildText(c2,name)<>nil then begin result:=s_ErrorP('Duplicated ['+name+'] getter/setter',c1);n_Free(result);exit;end; // Si tenemos dos getters o dos setters damos error
n_AddAsChild(c2,c1); // Si no lo añadimos
result:=r; // Y devolvemos result
end;
function TJs_Parser.Syntax_ObjectField(r:p_node):p_node;
var c:p_node;
begin
if not (token in [jst_Ident,jst_pchar]) then begin result:=s_errorP('Expected field definition',r);exit;end;
c:=n_FindChildHash(r,hash);
if c=nil then c:=s_node(r,jst_Member) else n_ClearChildren(c); // Permitimos campos duplicados, pero en ese caso el segundo sobreescribe al primero
if not lex_geg(jst_2Puntos) then result:=n_Free(r) else
if n_AddAsChild(c,Syntax_Expression)=nil then result:=n_Free(r) else result:=r;
end;
// Entramos tras {
function TJs_Parser.Syntax_ObjectExpression:p_node;
begin
result:=s_NodeT(nil,jst_ObjectDef,'Object');
if token<>jst_End then begin
repeat
if lex_token='get' then result:=Syntax_GetterSetter(jst_Getter,result) else
if lex_token='set' then result:=Syntax_GetterSetter(jst_Setter,result) else
result:=Syntax_ObjectField(result);
until (result=nil) or (lex_tg(jst_Comma)<>1);
if result=nil then exit;
if token=jst_Error then begin result:=n_Free(result);exit;end;
end;
if not lex_eg(jst_End) then result:=n_Free(result);
end;
// Entramos tras [, usamos Syntax Sugar y se evalua como new Array(...)
function TJs_Parser.Syntax_ArrayExpression:p_node;
//var p:p_node;
begin
result:=s_node(nil,jst_ArrayDef);
if token<>jst_CloseB then begin
repeat
if n_AddAsChild(result,Syntax_Expression)=nil then begin result:=n_Free(result);exit;end;
until lex_tg(jst_Comma)<>1;
if token=jst_Error then begin result:=n_Free(result);exit;end;
end;
if not lex_eg(jst_CloseB) then result:=n_Free(result);
{
result:=s_nodeT(nil,jst_New,'NEW');
p:=s_node(result,jst_Begin);s_nodeT(p,jst_Ident,'Array');
if token<>jst_CloseB then begin
repeat
if n_AddAsChild(p,Syntax_Factor)=nil then begin result:=n_Free(result);exit;end;
until lex_tg(jst_Comma)<>1;
if token=jst_Error then begin result:=n_Free(result);exit;end;
end;
if not lex_eg(jst_CloseB) then result:=n_Free(result);
}
end;
end.
|
unit Serv_TLB;
{ This file contains pascal declarations imported from a type library.
This file will be written during each import or refresh of the type
library editor. Changes to this file will be discarded during the
refresh process. }
{ EmpservLib Library }
{ Version 1.0 }
interface
uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL;
const
LIBID_Serv: TGUID = '{53BC6560-5B3E-11D0-9FFC-00A0248E4B9A}';
const
{ Component class GUIDs }
Class_EmpServer: TGUID = '{53BC6562-5B3E-11D0-9FFC-00A0248E4B9A}';
type
{ Forward declarations }
{ Forward declarations: Interfaces }
IEmpServer = interface;
IEmpServerDisp = dispinterface;
{ Forward declarations: CoClasses }
EmpServer = IEmpServer;
{ Dispatch interface for EmpServer Object }
IEmpServer = interface(IDataBroker)
['{53BC6561-5B3E-11D0-9FFC-00A0248E4B9A}']
function Get_EmpQuery: IProvider; safecall;
property EmpQuery: IProvider read Get_EmpQuery;
end;
{ DispInterface declaration for Dual Interface IEmpServer }
IEmpServerDisp = dispinterface
['{53BC6561-5B3E-11D0-9FFC-00A0248E4B9A}']
function GetProviderNames: OleVariant; dispid 22929905;
property EmpQuery: IProvider readonly dispid 1;
end;
{ EmpServerObject }
CoEmpServer = class
class function Create: IEmpServer;
class function CreateRemote(const MachineName: string): IEmpServer;
end;
implementation
uses ComObj;
class function CoEmpServer.Create: IEmpServer;
begin
Result := CreateComObject(Class_EmpServer) as IEmpServer;
end;
class function CoEmpServer.CreateRemote(const MachineName: string): IEmpServer;
begin
Result := CreateRemoteComObject(MachineName, Class_EmpServer) as IEmpServer;
end;
end.
|
unit ufrmMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls, diocp.coder.tcpClient,
utils.safeLogger,
diocp.task, diocp.sockets, diocp.tcp.client;
type
TfrmMain = class(TForm)
mmoRecvMessage: TMemo;
btnConnect: TButton;
edtHost: TEdit;
edtPort: TEdit;
btnSendObject: TButton;
mmoData: TMemo;
Button1: TButton;
procedure btnConnectClick(Sender: TObject);
procedure btnSendObjectClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
FDiocpContext: TDiocpExRemoteContext;
FDiocpTcpClient: TDiocpTcpClient;
procedure OnDisconnected(pvContext: TDiocpCustomContext);
procedure OnRecvBuffer(pvContext: TDiocpCustomContext; buf: Pointer; len:
cardinal);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
frmMain: TfrmMain;
implementation
uses
utils.buffer;
{$R *.dfm}
{ TfrmMain }
constructor TfrmMain.Create(AOwner: TComponent);
var
s1, s2:AnsiString;
begin
inherited;
sfLogger.setAppender(TStringsAppender.Create(mmoRecvMessage.Lines));
sfLogger.AppendInMainThread := true;
TStringsAppender(sfLogger.Appender).MaxLines := 5000;
FDiocpTcpClient := TDiocpTcpClient.Create(Self);
FDiocpTcpClient.RegisterContextClass(TDiocpExRemoteContext);
FDiocpContext :=TDiocpExRemoteContext(FDiocpTcpClient.Add);
s1 := '#';
s2 := '!';
FDiocpContext.SetStart(PAnsiChar(s1), length(s1));
FDiocpContext.SetEnd(PAnsiChar(s2), length(s2));
FDiocpContext.OnBufferAction := OnRecvBuffer;
FDiocpTcpClient.OnContextDisconnected := OnDisconnected;
end;
destructor TfrmMain.Destroy;
begin
sfLogger.Enable := false;
FDiocpTcpClient.DisconnectAll;
FDiocpTcpClient.Free;
inherited Destroy;
end;
procedure TfrmMain.btnConnectClick(Sender: TObject);
begin
FDiocpTcpClient.open;
if FDiocpContext.Active then
begin
sfLogger.logMessage('already connected...');
Exit;
end;
FDiocpContext.Host := edtHost.Text;
FDiocpContext.Port := StrToInt(edtPort.Text);
FDiocpContext.Connect;
mmoRecvMessage.Clear;
mmoRecvMessage.Lines.Add('start to recv...');
end;
procedure TfrmMain.btnSendObjectClick(Sender: TObject);
var
s:AnsiString;
begin
s := mmoData.Lines.Text;
FDiocpContext.PostWSASendRequest(PAnsiChar(s), Length(s), True);
end;
procedure TfrmMain.Button1Click(Sender: TObject);
var
lvBuffer:TBufferLink;
s, s1, s2:AnsiString;
j:Integer;
begin
lvBuffer:=TBufferLink.Create;
s := mmoData.Lines.Text;
lvBuffer.AddBuffer(PAnsiChar(s), Length(s));
while lvBuffer.validCount > 0 do
begin
s1 := '#';
j := lvBuffer.SearchBuffer(PAnsiChar(s1), length(s1));
if j = -1 then
begin
sfLogger.logMessage('start is none...');
break;
end;
lvBuffer.Skip(j + length(s1));
s1 := '!';
j := lvBuffer.SearchBuffer(PAnsiChar(s1), length(s1));
if j = -1 then
begin
sfLogger.logMessage('end is none...');
break;
end;
setLength(s2, j);
lvBuffer.readBuffer(PAnsiChar(s2), j);
sfLogger.logMessage(s2);
lvBuffer.Skip(length(s1));
end;
lvBuffer.Free;
end;
procedure TfrmMain.OnDisconnected(pvContext: TDiocpCustomContext);
begin
if csDestroying in ComponentState then
begin
exit;
end;
sfLogger.logMessage('disconnected');
end;
procedure TfrmMain.OnRecvBuffer(pvContext: TDiocpCustomContext; buf: Pointer;
len: cardinal);
var
s:AnsiString;
begin
SetLength(s, len);
Move(buf^, pansichar(s)^, len);
sfLogger.logMessage(s);
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.ImageList;
interface
uses
System.Classes, System.Generics.Collections, System.UITypes, System.RTLConsts;
type
TImageLink = class;
/// <summary> The shared base class of lists of images (see <b>Vcl.ImgList.TCustomImageList</b>,
/// <b>FMX.ImgList.TCustomImageList</b>). This class contains only simple methods for notify changes to
/// <b>TImageLink</b></summary>
TBaseImageList = class(TComponent)
strict private
FUpdateCount: Integer;
FLinks: TList<TImageLink>;
FChanged: Boolean;
private
function GetLinkCount: Integer;
function GetLinks(const Index: Integer): TImageLink;
protected
/// <summary> Adding link into an array <b>Links</b> </summary>
procedure AddLink(Link: TImageLink);
/// <summary> Removing link from array <b>Links</b> </summary>
procedure DeleteLink(Link: TImageLink);
/// <summary>Number of elements in the array <b>Links</b></summary>
property LinkCount: Integer read GetLinkCount;
/// <summary> The array of references to instances of <b>TImageLink</b> for send notification of changes</summary>
property Links[const Index: Integer]: TImageLink read GetLinks;
/// <summary> Checks for the presence of the element in the <see cref="System.ImageList|TBaseImageList.Links">
/// Links</see> array </summary>
/// <param name="Link"> The desired element </param>
/// <param name="StartIndex"> Can be used to increase performance. At first the array element with this specified number is checked, then all other
/// elements in the array </param>
/// <returns> <c>True</c> if the <c>Link</c> element is in the array </returns>
function LinkContains(const Link: TImageLink; const StartIndex: Integer = -1): Boolean;
/// <summary> The method should perform several actions to reflect changes in the image list. Never call this
/// method yourself, but you can to use calling <b>Change</b></summary>
procedure DoChange; virtual; abstract;
/// <summary> The getter of property <b>Count</b>. This method must be overridden in heir </summary>
function GetCount: Integer; virtual; abstract;
procedure Updated; override;
procedure Loaded; override;
public
procedure BeforeDestruction; override;
/// <summary> This method must be called in case if there were some changes in the image list. It executes the
/// method <b>DoChange</b>. If the instance is in a state Loading, Destroying, Updating, then the method
/// <b>DoChange</b> won't be called immediately, but it will executes after end of updating and loading</summary>
procedure Change; virtual;
/// <summary> The first calling of this method sets the state <b>csUpdating</b>. Used when mass changes properties
/// for prevent multiple calling <b>DoChange</b> </summary>
procedure BeginUpdate;
/// <summary> The last calling of this method resets the state <b>csUpdating</b>. See also <b>BeginUpdate</b> </summary>
procedure EndUpdate;
/// <summary>The number of images in the list </summary>
property Count: Integer read GetCount;
end;
/// <summary> The base class that is used for notify some objects when TBaseImageList changed </summary>
TImageLink = class
private
[Weak] FImages: TBaseImageList;
FImageIndex: TImageIndex;
FIgnoreIndex: Boolean;
FOnChange: TNotifyEvent;
FIgnoreImages: Boolean;
procedure SetImageList(const Value: TBaseImageList);
procedure SetImageIndex(const Value: TImageIndex);
public
constructor Create; virtual;
destructor Destroy; override;
/// <summary> The virtual method that is called after change of properties <b>Images</b> and <b>ImageIndex</b>.
/// This takes into account the properties <b>IgnoreIndex</b>, <b>IgnoreImages</b>. This method call the event
/// <b>OnChange</b> </summary>
procedure Change; virtual;
/// <summary> Reference to list of images</summary>
property Images: TBaseImageList read FImages write SetImageList;
/// <summary> Ordinal number of image from <b>Images</b></summary>
property ImageIndex: TImageIndex read FImageIndex write SetImageIndex;
/// <summary> If this property is true then we won't call method <b>Change</b> when changing property
/// <b>ImageIndex</b> </summary>
property IgnoreIndex: Boolean read FIgnoreIndex write FIgnoreIndex;
/// <summary> If this property is true then we won't call method <b>Change</b> when changing property <b>Images</b>
/// </summary>
property IgnoreImages: Boolean read FIgnoreImages write FIgnoreImages;
/// <summary> The event handler that is happens after change of properties <b>Images</b> and <b>ImageIndex</b>.
/// This takes into account the properties <b>IgnoreIndex</b>, <b>IgnoreImages</b>.</summary>
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
implementation
{$REGION 'TBaseImageList'}
procedure TBaseImageList.BeforeDestruction;
var
I: Integer;
begin
if FLinks <> nil then
begin
for I := LinkCount - 1 downto 0 do
FLinks[I].Images := nil;
FLinks.DisposeOf;
FLinks := nil;
end;
inherited;
end;
procedure TBaseImageList.AddLink(Link: TImageLink);
begin
if Link <> nil then
begin
if FLinks = nil then
FLinks := TList<TImageLink>.Create;
if not FLinks.Contains(Link) then
FLinks.Add(Link);
Link.FImages := Self;
end;
end;
procedure TBaseImageList.DeleteLink(Link: TImageLink);
begin
if Link <> nil then
begin
if FLinks <> nil then
begin
FLinks.Remove(Link);
if FLinks.Count = 0 then
begin
FLinks.DisposeOf;
FLinks := nil;
end;
end;
Link.FImages := nil;
end;
end;
function TBaseImageList.GetLinkCount: Integer;
begin
if FLinks <> nil then
Result := FLinks.Count
else
Result := 0;
end;
function TBaseImageList.GetLinks(const Index: Integer): TImageLink;
begin
if (Index < 0) or (Index >= LinkCount) then
raise EListError.CreateFMT(sArgumentOutOfRange_Index, [Index, LinkCount]);
Result := FLinks[Index];
end;
procedure TBaseImageList.Change;
begin
FChanged := True;
if [csLoading, csDestroying, csUpdating] * ComponentState = [] then
begin
DoChange;
FChanged := False;
end;
end;
procedure TBaseImageList.Updated;
begin
inherited;
if FChanged then
Change;
end;
function TBaseImageList.LinkContains(const Link: TImageLink; const StartIndex: Integer = -1): Boolean;
begin
if (FLinks <> nil) and (FLinks.Count > 0) then
if (StartIndex >= 0) and (StartIndex < FLinks.Count) and (FLinks[StartIndex] = Link) then
Result := True
else
Result := FLinks.Contains(Link)
else
Result := False;
end;
procedure TBaseImageList.Loaded;
begin
inherited;
if FChanged then
Change;
end;
procedure TBaseImageList.BeginUpdate;
begin
if FUpdateCount = 0 then
Updating;
Inc(FUpdateCount);
end;
procedure TBaseImageList.EndUpdate;
begin
if FUpdateCount > 0 then
begin
Dec(FUpdateCount);
if FUpdateCount = 0 then
Updated;
end;
end;
{$ENDREGION}
{$REGION 'TImageLink'}
constructor TImageLink.Create;
begin
inherited;
FImageIndex := -1;
end;
destructor TImageLink.Destroy;
begin
if FImages <> nil then
FImages.DeleteLink(Self);
inherited;
end;
procedure TImageLink.SetImageIndex(const Value: TImageIndex);
begin
if FImageIndex <> Value then
begin
FImageIndex := Value;
if not IgnoreIndex then
Change;
end;
end;
procedure TImageLink.SetImageList(const Value: TBaseImageList);
begin
if Value <> FImages then
begin
if FImages <> nil then
FImages.DeleteLink(Self);
if Value <> nil then
Value.AddLink(Self);
if not IgnoreImages then
Change;
end;
end;
procedure TImageLink.Change;
begin
if Assigned(OnChange) then
OnChange(FImages);
end;
{$ENDREGION}
end.
|
unit AnnotatedImage;
interface
uses
Vcl.Graphics, System.Types, Generics.Collections,
Superobject, Annotation.Action;
type
TAnnotatedImage = class(TObject)
private
FBitmapImage: TBitmap;
FAnnotationActions: TList<IAnnotationAction>;
FName: string;
FIsChanged: boolean;
FCurrentAnnotationActionIndex: integer;
function GetCombinedBitmap: TBitmap;
function GetHeight: integer;
function GetWidth: integer;
function GetMaskBitmap: TBitmap;
function GetAnnotationActionsJSON: ISuperObject;
procedure PushAnnotationAction(const AnnotationAction: IAnnotationAction);
function GetBitmapImage: TBitmap;
public
constructor Create(const ImageBitmap: TBitmap; const Name: string); overload;
constructor Create(const ImageGraphic: TGraphic; const Name: string); overload;
destructor Destroy; override;
// properties
property ImageBitmap: TBitmap read GetBitmapImage;
property CombinedBitmap: TBitmap read GetCombinedBitmap;
property MaskBitmap: TBitmap read GetMaskBitmap;
property AnnotationActions: TList<IAnnotationAction> read FAnnotationActions;
property Width: integer read GetWidth;
property Height: integer read GetHeight;
property Name: string read FName;
property AnnotationActionsJSON: ISuperObject read GetAnnotationActionsJSON;
property IsChanged: boolean read FIsChanged;
property CurrentAnnotationActionIndex: integer read FCurrentAnnotationActionIndex;
// methods
procedure PutDotMarkerAt(const X, Y, ViewportWidth, ViewportHeight: integer);
procedure ClearAnnotationActions;
procedure OnSaved;
procedure SetAnnotationActionIndex(const Value: integer);
procedure LoadAnnotationsFromJSON(const AnnotationsArray: TSuperArray);
class function GetPatch(const X, Y, Width, Height,
ViewPortWidth, ViewPortHeight: integer;
const ZoomFactor: Byte;
SourceBitmap: TBitmap): TBitmap; // refactor this method
end;
implementation
uses
Annotation.Utils, SysUtils, Math, Settings;
{ TAnnotatedImage }
constructor TAnnotatedImage.Create(const ImageBitmap: TBitmap; const Name: string);
begin
FBitmapImage:= TBitmap.Create;
FBitmapImage.Assign(ImageBitmap);
FAnnotationActions:= Tlist<IAnnotationAction>.Create;
FName:= Name;
FCurrentAnnotationActionIndex:= -1;
PushAnnotationAction(TOriginalImageAction.Create);
FIsChanged:= False;
end;
procedure TAnnotatedImage.ClearAnnotationActions;
begin
//FAnnotationActions.Clear;
//FCurrentAnnotationActionIndex:= -1;
PushAnnotationAction(TAnnotationClear.Create);
end;
constructor TAnnotatedImage.Create(const ImageGraphic: TGraphic; const Name: string);
begin
FBitmapImage:= TBitmap.Create;
FBitmapImage.Assign(ImageGraphic);
FAnnotationActions:= TList<IAnnotationAction>.Create;
FName:= Name;
FCurrentAnnotationActionIndex:= -1;
PushAnnotationAction(TOriginalImageAction.Create);
FIsChanged:= False;
end;
destructor TAnnotatedImage.Destroy;
begin
FBitmapImage.Free;
FAnnotationActions.Free;
inherited;
end;
function TAnnotatedImage.GetCombinedBitmap: TBitmap;
var
i: integer;
AnnotationAction: IAnnotationAction;
BitmapAnnotationActions: TBitmap;
Settings: ISettings;
begin
Result:= TBitmap.Create;
Result.Assign(FBitmapImage);
BitmapAnnotationActions:= TBitmap.Create;
try
BitmapAnnotationActions.Assign(FBitmapImage);
BitmapAnnotationActions.Transparent:= true;
BitmapAnnotationActions.TransparentMode:= tmFixed;
BitmapAnnotationActions.TransparentColor:= clBlack;
BitmapAnnotationActions.Canvas.Brush.Color:= clBlack;
BitmapAnnotationActions.Canvas.Brush.Style:= bsSolid;
BitmapAnnotationActions.Canvas.FillRect(Rect(0, 0, BitmapAnnotationActions.Width, BitmapAnnotationActions.Height));
Settings:= TSettingsRegistry.Create('Software\ImageAnnotationTool\');
for i := 0 to FCurrentAnnotationActionIndex do
begin
AnnotationAction:= FAnnotationActions[i];
AnnotationAction.RenderOnView(BitmapAnnotationActions, Settings);
end;
Result.Canvas.Draw(0, 0, BitmapAnnotationActions);
finally
BitmapAnnotationActions.Free;
end;
end;
function TAnnotatedImage.GetHeight: integer;
begin
Result:= FBitmapImage.Width;
end;
function TAnnotatedImage.GetAnnotationActionsJSON: ISuperObject;
var
AnnotationAction: IAnnotationAction;
i: integer;
begin
Result:= SO;
Result.O['annotations']:= SA([]);
for i := 0 to FCurrentAnnotationActionIndex do
begin
AnnotationAction:= FAnnotationActions[i];
AnnotationAction.AddToJSONArray(Result, 'annotations');
//Result.A['annotations'].Add(AnnotationAction.ToJSON);
end;
end;
function TAnnotatedImage.GetBitmapImage: TBitmap;
begin
Result:= TBitmap.Create;
Result.Assign(FBitmapImage);
end;
function TAnnotatedImage.GetMaskBitmap: TBitmap;
var
AnnotationAction: IAnnotationAction;
i: integer;
begin
Result:= TBitmap.Create;
Result.PixelFormat:= pf1bit;
Result.Assign(FBitmapImage);
Result.Canvas.Brush.Color:= clBlack;
Result.Canvas.FillRect(Rect(0, 0, FBitmapImage.Width, FBitmapImage.Height));
for i := 0 to FCurrentAnnotationActionIndex do
begin
AnnotationAction:= FAnnotationActions[i];
AnnotationAction.RenderOnMask(Result);
end;
end;
class function TAnnotatedImage.GetPatch(const X, Y, Width, Height,
ViewPortWidth, ViewPortHeight: integer; const ZoomFactor: Byte;
SourceBitmap: TBitmap): TBitmap;
var
PointOnImage: TPoint;
DestRect, SourceRect: TRect;
XOffset, YOffset: integer;
CenterPoint: TPoint;
begin
Result:= TBitmap.Create;
Result.SetSize(Width, Height);
Result.Canvas.Brush.Color:= clBtnHighlight;
Result.Canvas.FillRect(Rect(0, 0, Width, Height));
if not IsOnImage(TPoint.Create(X, Y), ViewportWidth, ViewportHeight, SourceBitmap.Width, SourceBitmap.Height) then
exit;
PointOnImage:= ViewportToImage(TPoint.Create(X, Y),
ViewportWidth, ViewportHeight,
SourceBitmap.Width, SourceBitmap.Height);
XOffset:= Width div (2 * ZoomFactor);
YOffset:= Height div (2 * ZoomFactor);
DestRect:= TRect.Create(TPoint.Zero, TPoint.Create(Width, Height));
SourceRect:= TRect.Create(TPoint.Create(PointOnImage.X - XOffset,
PointOnImage.Y - YOffset),
TPoint.Create(PointOnImage.X + XOffset,
PointOnImage.Y + YOffset));
Result.Canvas.CopyRect(DestRect, SourceBitmap.Canvas, SourceRect);
CenterPoint:= TPoint.Zero;
CenterPoint.X:= Width div 2;
CenterPoint.Y:= Height div 2;
Result.Canvas.Pen.Color:= $0EF729;
Result.Canvas.Pen.Width:= 2;
Result.Canvas.MoveTo(CenterPoint.X, CenterPoint.Y - 15);
Result.Canvas.LineTo(CenterPoint.X, CenterPoint.Y + 15);
Result.Canvas.MoveTo(CenterPoint.X - 15, CenterPoint.Y);
Result.Canvas.LineTo(CenterPoint.X + 15, CenterPoint.Y);
end;
function TAnnotatedImage.GetWidth: integer;
begin
Result:= FBitmapImage.Height;
end;
procedure TAnnotatedImage.LoadAnnotationsFromJSON(
const AnnotationsArray: TSuperArray);
var
i: integer;
begin
FAnnotationActions.Clear;
FCurrentAnnotationActionIndex:= -1;
PushAnnotationAction(TOriginalImageAction.Create);
for i := 0 to AnnotationsArray.Length - 1 do
if CompareText(AnnotationsArray[i].S['type'], 'dot_marker') = 0 then
PushAnnotationAction(TDotMarker.Create(AnnotationsArray[i].I['x'], AnnotationsArray[i].I['y']));
end;
procedure TAnnotatedImage.OnSaved;
begin
FIsChanged:= False;
end;
procedure TAnnotatedImage.PushAnnotationAction(const AnnotationAction: IAnnotationAction);
begin
if FCurrentAnnotationActionIndex > -1 then
while FCurrentAnnotationActionIndex < (FAnnotationActions.Count - 1) do
FAnnotationActions.Delete(FAnnotationActions.Count - 1);
FAnnotationActions.Add(AnnotationAction);
Inc(FCurrentAnnotationActionIndex);
FIsChanged:= True;
end;
procedure TAnnotatedImage.PutDotMarkerAt(const X, Y, ViewportWidth,
ViewportHeight: integer);
var
PointOnImage: TPoint;
AnnotationAction: IAnnotationAction;
begin
if IsOnImage(TPoint.Create(X, Y), ViewportWidth, ViewportHeight, FBitmapImage.Width, FBitmapImage.Height) then
begin
PointOnImage:= ViewportToImage(TPoint.Create(X, Y),
ViewportWidth, ViewportHeight,
FBitmapImage.Width, FBitmapImage.Height);
AnnotationAction:= TDotMarker.Create(PointOnImage);
PushAnnotationAction(AnnotationAction);
end;
end;
procedure TAnnotatedImage.SetAnnotationActionIndex(const Value: integer);
begin
if (Value > -1) and (Value < FAnnotationActions.Count) then
begin
FCurrentAnnotationActionIndex:= Value;
FIsChanged:= FCurrentAnnotationActionIndex > 0;
end;
end;
end.
|
unit AChequesOO;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, Grids, CGrades, unDadosCR, unDados,
StdCtrls, Buttons, Mask, numericos, Localizacao, UnDadosLocaliza;
type
TRBDColunaGrade =(clCodBanco,clCodFormaPagamento,clNomFormaPagamento,clValCheque,clNomEmitente,clNumCheque,clDatVencimento,clNumContaCaixa,clNomContaCaixa,clDatEmissao,clCodCliente,clNomCliente, clNumConta, clNumAgencia);
TFChequesOO = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
Grade: TRBStringGridColor;
EFormaPagamento: TEditLocaliza;
Localiza: TConsultaPadrao;
EContaCaixa: TEditLocaliza;
PanelColor4: TPanelColor;
PanelColor2: TPanelColor;
BGravar: TBitBtn;
BCancelar: TBitBtn;
PanelColor3: TPanelColor;
Label1: TLabel;
Label2: TLabel;
EValParcela: Tnumerico;
EValCheques: Tnumerico;
EBanco: TRBEditLocaliza;
ECliente: TRBEditLocaliza;
EEmitente: TRBEditLocaliza;
CDuplicar: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BGravarClick(Sender: TObject);
procedure BCancelarClick(Sender: TObject);
procedure GradeCarregaItemGrade(Sender: TObject; VpaLinha: Integer);
procedure GradeDadosValidos(Sender: TObject; var VpaValidos: Boolean);
procedure GradeGetEditMask(Sender: TObject; ACol, ARow: Integer;
var Value: String);
procedure GradeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure GradeKeyPress(Sender: TObject; var Key: Char);
procedure GradeMudouLinha(Sender: TObject; VpaLinhaAtual,
VpaLinhaAnterior: Integer);
procedure GradeNovaLinha(Sender: TObject);
procedure EFormaPagamentoRetorno(Retorno1, Retorno2: String);
procedure GradeSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure GradeDepoisExclusao(Sender: TObject);
procedure EFormaPagamentoChange(Sender: TObject);
procedure EContaCaixaRetorno(Retorno1, Retorno2: String);
procedure EBancoRetorno(VpaColunas: TRBColunasLocaliza);
procedure EClienteRetorno(VpaColunas: TRBColunasLocaliza);
procedure EEmitenteRetorno(VpaColunas: TRBColunasLocaliza);
procedure EQtdParcelasKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
VprAcao,
VprCadastrandoChequeAvulso : Boolean;
VprNomCliente : String;
VprCodFormaPagamentoAnterior : Integer;
VprDBaixa : TRBDBaixaCR;
VprDCheque,
VprDChequeAnterior : TRBDCheque;
function ExisteFormaPagamento : Boolean;
function ExisteContaCorrente : Boolean;
procedure CarTitulosGrade;
procedure CarDChequeClasse;
procedure CarDChequeClasseDuplicado;
function RColunaGrade(VpaColuna : TRBDColunaGrade):Integer;
public
{ Public declarations }
function CadastraCheques(VpaDBaixa : TRBDBaixaCR) : boolean;
procedure ConsultaCheques(VpaCheques : TList);
function CadastraChequesAvulso : Boolean;
end;
var
FChequesOO: TFChequesOO;
implementation
uses APrincipal,Constantes, funData, funString,ConstMsg, unContasAReceber,
AFormasPagamento, unClientes;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFChequesOO.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
VprAcao := false;
VprCadastrandoChequeAvulso := false;
CarTitulosGrade;
VprDChequeAnterior := TRBDCheque.cria;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFChequesOO.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
function TFChequesOO.ExisteFormaPagamento : Boolean;
begin
result := false;
if Grade.Cells[rcolunagrade(clCodFormaPagamento),Grade.ALinha] <> '' then
begin
if StrToInt(Grade.Cells[RColunaGrade(clCodFormaPagamento),Grade.ALinha]) = VprCodFormaPagamentoAnterior then
result := true
else
begin
result := FunContasAReceber.ExisteFormaPagamento(StrToInt(Grade.Cells[RColunaGrade(clCodFormaPagamento),Grade.ALinha]));
if result then
begin
EFormaPagamento.Text := Grade.Cells[RColunaGrade(clCodFormaPagamento),Grade.ALinha];
EFormaPagamento.Atualiza;
end;
end;
end;
end;
{******************************************************************************}
function TFChequesOO.ExisteContaCorrente : Boolean;
begin
result := false;
if Grade.Cells[RColunaGrade(clNumContaCaixa),Grade.ALinha] <> '' then
begin
result := FunContasAReceber.ExisteContaCorrente(Grade.Cells[RColunaGrade(clNumContaCaixa),Grade.ALinha]);
if result then
begin
EContaCaixa.Text := Grade.Cells[RColunaGrade(clNumContaCaixa),Grade.ALinha];
EContaCaixa.Atualiza;
end;
end;
end;
{******************************************************************************}
procedure TFChequesOO.CarTitulosGrade;
begin
Grade.Cells[RColunaGrade(clCodBanco),0] := 'Banco';
Grade.Cells[RColunaGrade(clCodFormaPagamento),0] := 'Código';
Grade.Cells[RColunaGrade(clNomFormaPagamento),0] := 'Forma Pagamento';
Grade.Cells[RColunaGrade(clValCheque),0] := 'Valor';
Grade.Cells[RColunaGrade(clNomEmitente),0] := 'Emitente';
Grade.Cells[RColunaGrade(clNumCheque),0] := 'Nro Cheque';
Grade.Cells[RColunaGrade(clDatVencimento),0] := 'Vencimento';
Grade.Cells[RColunaGrade(clNumContaCaixa),0] := 'Conta Caixa';
Grade.Cells[RColunaGrade(clNomContaCaixa),0] := 'Descrição';
Grade.Cells[RColunaGrade(clDatEmissao),0] := 'Data Emissão';
Grade.Cells[RColunaGrade(clCodCliente),0] := 'Código';
Grade.Cells[RColunaGrade(clNomCliente),0] := 'Cliente';
Grade.Cells[RColunaGrade(clNumConta),0] := 'Nro Conta';
Grade.Cells[RColunaGrade(clNumAgencia),0] := 'Nro Agencia';
end;
{******************************************************************************}
procedure TFChequesOO.CarDChequeClasse;
begin
if Grade.Cells[RColunaGrade(clCodBanco),Grade.ALinha] <> '' then
VprDCheque.CodBanco := StrToInt(Grade.Cells[RColunaGrade(clCodBanco),Grade.ALinha])
else
VprDCheque.CodBanco := 0;
if Grade.Cells[RColunaGrade(clCodFormaPagamento),Grade.ALinha] <> '' then
VprDCheque.CodFormaPagamento := StrToInt(Grade.Cells[RColunaGrade(clCodFormaPagamento),Grade.ALinha])
else
VprDCheque.CodFormaPagamento := 0;
VprDCheque.ValCheque := StrToFloat(DeletaChars(Grade.Cells[RColunaGrade(clValCheque),Grade.ALinha],'.'));
VprDCheque.NomEmitente := UpperCase(Grade.Cells[RColunaGrade(clNomEmitente),Grade.alinha]);
if Grade.Cells[RColunaGrade(clNumCheque),Grade.ALinha] <> '' then
VprDCheque.NumCheque := StrToInt(Grade.Cells[RColunaGrade(clNumCheque),Grade.ALinha])
else
VprDCheque.NumCheque := 0;
try
VprDCheque.DatVencimento := StrToDate(Grade.Cells[RColunaGrade(clDatVencimento),Grade.ALinha])
except
VprDCheque.DatVencimento := MontaData(1,1,1900);
end;
VprDCheque.NumContaCaixa := Grade.Cells[RColunaGrade(clNumContaCaixa),Grade.ALinha];
if Grade.Cells[RColunaGrade(clCodCliente),Grade.ALinha] <> '' then
VprDCheque.CodCliente := StrToInt(Grade.Cells[RColunaGrade(clCodCliente),Grade.ALinha])
else
VprDCheque.CodCliente := 0;
VprDCheque.CodUsuario := varia.CodigoUsuario;
VprDCheque.DatCadastro := now;
try
VprDCheque.DatEmissao := StrToDate(Grade.Cells[RColunaGrade(clDatEmissao),Grade.ALinha])
except
VprDCheque.DatEmissao := MontaData(1,1,1900);
end;
if Grade.Cells[RColunaGrade(clNumConta),Grade.ALinha] <> '' then
VprDCheque.NumConta := StrToInt(Grade.Cells[RColunaGrade(clNumConta),Grade.ALinha])
else
VprDCheque.NumConta := 0;
if Grade.Cells[RColunaGrade(clNumAgencia),Grade.ALinha] <> '' then
VprDCheque.NumAgencia := StrToInt(Grade.Cells[RColunaGrade(clNumAgencia),Grade.ALinha])
else
VprDCheque.NumAgencia := 0;
FunContasAReceber.CopiaDCheque(VprDCheque,VprDChequeAnterior);
end;
{******************************************************************************}
procedure TFChequesOO.CarDChequeClasseDuplicado;
begin
if Grade.Cells[RColunaGrade(clCodBanco),Grade.ALinha-1] <> '' then
VprDCheque.CodBanco := StrToInt(Grade.Cells[RColunaGrade(clCodBanco),1])
else
VprDCheque.CodBanco := 0;
if Grade.Cells[RColunaGrade(clCodFormaPagamento),1] <> '' then
VprDCheque.CodFormaPagamento := StrToInt(Grade.Cells[RColunaGrade(clCodFormaPagamento),1])
else
VprDCheque.CodFormaPagamento := 0;
VprDCheque.NomFormaPagamento:= Grade.Cells[RColunaGrade(clNomFormaPagamento),1];
VprDCheque.ValCheque := StrToFloat(DeletaChars(Grade.Cells[RColunaGrade(clValCheque),1],'.'));
VprDCheque.NomEmitente := Grade.Cells[RColunaGrade(clNomEmitente),1];
if Grade.Cells[RColunaGrade(clNumCheque),1] <> '' then
VprDCheque.NumCheque := StrToInt(Grade.Cells[RColunaGrade(clNumCheque),1])
else
VprDCheque.NumCheque := 0;
try
VprDCheque.DatVencimento := StrToDate(Grade.Cells[RColunaGrade(clDatVencimento),1])
except
VprDCheque.DatVencimento := MontaData(1,1,1900);
end;
VprDCheque.NumContaCaixa := Grade.Cells[RColunaGrade(clNumContaCaixa),1];
VprDCheque.NomContaCaixa:= Grade.Cells[RColunaGrade(clNomContaCaixa),1];
if Grade.Cells[RColunaGrade(clCodCliente),1] <> '' then
VprDCheque.CodCliente := StrToInt(Grade.Cells[RColunaGrade(clCodCliente),1])
else
VprDCheque.CodCliente := 0;
VprDCheque.NomCliente:= Grade.Cells[RColunaGrade(clNomCliente),1];
VprDCheque.CodUsuario := varia.CodigoUsuario;
VprDCheque.DatCadastro := now;
try
VprDCheque.DatEmissao := StrToDate(Grade.Cells[RColunaGrade(clDatEmissao),1])
except
VprDCheque.DatEmissao := MontaData(1,1,1900);
end;
if Grade.Cells[RColunaGrade(clNumConta),1] <> '' then
VprDCheque.NumConta := StrToInt(Grade.Cells[RColunaGrade(clNumConta),1])
else
VprDCheque.NumConta := 0;
if Grade.Cells[RColunaGrade(clNumAgencia),1] <> '' then
VprDCheque.NumAgencia := StrToInt(Grade.Cells[RColunaGrade(clNumAgencia),1])
else
VprDCheque.NumAgencia := 0;
end;
{******************************************************************************}
function TFChequesOO.CadastraCheques(VpaDBaixa : TRBDBaixaCR) : boolean;
begin
VprDBaixa := VpaDBaixa;
VprDBaixa.Cheques := VpaDBaixa.Cheques;
Grade.ADados := VprDBaixa.Cheques;
Grade.CarregaGrade;
EValParcela.AValor := VpaDBaixa.ValorPago;
if VpaDBaixa.Parcelas.Count > 0 then
VprNomCliente := FunClientes.RNomCliente(InttoStr(TRBDParcelaBaixaCR(VpaDBaixa.Parcelas.Items[0]).CodCliente));
EValCheques.Avalor := FunContasAReceber.RValTotalCheques(VprDBaixa.Cheques);
showmodal;
result := VprAcao;
end;
{******************************************************************************}
procedure TFChequesOO.ConsultaCheques(VpaCheques : TList);
begin
VprDBaixa := TRBDBaixaCR.cria;
VprDBaixa.Cheques := VpaCheques;
Grade.ADados := VpaCheques;
Grade.CarregaGrade;
show;
end;
{******************************************************************************}
function TFChequesOO.CadastraChequesAvulso : Boolean;
begin
VprCadastrandoChequeAvulso := true;
VprDBaixa := TRBDBaixaCR.Cria;
Grade.ADados := VprDBaixa.Cheques;
Grade.CarregaGrade;
EValParcela.AValor := VprDBaixa.ValorPago;
EValCheques.Avalor := FunContasAReceber.RValTotalCheques(VprDBaixa.Cheques);
EFormaPagamento.ASelectValida.text := 'Select I_COD_FRM, C_NOM_FRM, C_FLA_TIP '+
' from CADFORMASPAGAMENTO ' +
' Where I_COD_FRM =@ '+
' AND C_FLA_TIP IN (''C'',''R'',''P'') ';
EFormaPagamento.ASelectLocaliza.text := 'Select I_COD_FRM, C_NOM_FRM, C_FLA_TIP '+
' from CADFORMASPAGAMENTO ' +
' Where C_NOM_FRM Like ''@%''' +
' AND C_FLA_TIP IN (''C'',''R'',''P'') '+
' order by C_NOM_FRM ';
showmodal;
FunContasAReceber.GravaDCheques(VprDBaixa.Cheques);
result := VprAcao;
end;
{******************************************************************************}
procedure TFChequesOO.BGravarClick(Sender: TObject);
var
VpfValoresOk : Boolean;
begin
VpfValoresOk := true;
if not VprCadastrandoChequeAvulso then
if EValParcela.AValor <> EValCheques.AValor then
VpfValoresOk := confirmacao('VALORES DIFERENTES!!!'#13'O Valor da parcela é diferente da somatória dos cheques. Tem certeza que deseja continuar?');
if VpfValoresOk then
begin
VprAcao := true;
Close;
end;
end;
{******************************************************************************}
procedure TFChequesOO.BCancelarClick(Sender: TObject);
begin
Close;
end;
{******************************************************************************}
procedure TFChequesOO.GradeCarregaItemGrade(Sender: TObject;
VpaLinha: Integer);
begin
VprDCheque := TRBDCheque(VprDBaixa.Cheques.Items[VpaLinha-1]);
if VprDCheque.CodBanco <> 0 then
Grade.Cells[RColunaGrade(clCodBanco),Grade.ALinha] := IntToStr(VprDCheque.CodBanco)
else
Grade.Cells[RColunaGrade(clCodBanco),Grade.ALinha] := '';
if VprDCheque.CodFormaPagamento <> 0 then
Grade.Cells[RColunaGrade(clCodFormaPagamento),Grade.ALinha] := IntToStr(VprDCheque.CodFormaPagamento)
else
Grade.Cells[RColunaGrade(clCodBanco),Grade.ALinha] := '';
Grade.Cells[RColunaGrade(clNomFormaPagamento),Grade.ALinha] := VprDCheque.NomFormaPagamento;
Grade.Cells[RColunaGrade(clValCheque),Grade.ALinha] := FormatFloat(varia.MascaraValor,VprDCheque.ValCheque);
Grade.Cells[RColunaGrade(clNomEmitente),Grade.ALinha] := VprDCheque.NomEmitente;
if VprDCheque.NumCheque <> 0 then
Grade.cells[RColunaGrade(clNumCheque),Grade.ALinha] := IntToStr(VprDCheque.NumCheque)
else
Grade.cells[RColunaGrade(clNumCheque),Grade.ALinha] := '';
if VprDCheque.DatVencimento > MontaData(1,1,1900) then
Grade.Cells[RColunaGrade(clDatVencimento),Grade.ALinha]:= FormatDateTime('DD/MM/YYYY',VprDCheque.DatVencimento)
else
Grade.Cells[RColunaGrade(clDatVencimento),Grade.ALinha] := '';
Grade.cells[RColunaGrade(clNumContaCaixa),Grade.ALinha] := VprDCheque.NumContaCaixa;
Grade.cells[RColunaGrade(clNomContaCaixa),Grade.ALinha] := VprDCheque.NomContaCaixa;
if VprDCheque.DatEmissao > MontaData(1,1,1900) then
Grade.Cells[RColunaGrade(clDatEmissao),Grade.ALinha]:= FormatDateTime('DD/MM/YYYY',VprDCheque.DatEmissao)
else
Grade.Cells[RColunaGrade(clDatEmissao),Grade.ALinha] := '';
if VprDCheque.CodCliente <> 0 then
Grade.Cells[RColunaGrade(clCodCliente),Grade.ALinha] := IntToStr(VprDCheque.CodCliente)
else
Grade.Cells[RColunaGrade(clCodCliente),Grade.ALinha] := '';
Grade.Cells[RColunaGrade(clNomCliente),Grade.ALinha] := VprDCheque.NomCliente;
Grade.Cells[RColunaGrade(clNumConta),Grade.ALinha] := IntToStr(VprDCheque.NumConta);
Grade.Cells[RColunaGrade(clNumAgencia),Grade.ALinha] := IntToStr(VprDCheque.NumAgencia);
end;
{******************************************************************************}
procedure TFChequesOO.GradeDadosValidos(Sender: TObject;
var VpaValidos: Boolean);
begin
VpaValidos := true;
if not ExisteFormaPagamento then
begin
aviso('FORMA DE PAGAMENTO INVÁLIDA!!!'#13'A forma de pagamento digitada não é valida ou não foi preechida.');
Vpavalidos := false;
Grade.Col := RColunaGrade(clCodFormaPagamento);
end
else
if Grade.Cells[4,Grade.ALinha] = '' then
begin
aviso('VALOR NÃO PREENCHIDO!!!'#13'É necessário preencher o valor.');
Vpavalidos := false;
Grade.Col := RColunaGrade(clValCheque);
end
else
if not ExisteContaCorrente then
begin
aviso('CONTA CAIXA INVALIDA!!!'#13'A conta caixa digitada não é válida ou não foi preenchida.');
Vpavalidos := false;
Grade.Col := RColunaGrade(clNumContaCaixa);
end
else
if not ECliente.AExisteCodigo(Grade.Cells[RColunaGrade(clCodCliente),Grade.ALinha]) then
begin
aviso('CLIENTE NÃO CADASTRADO!!!'#13'O cliente digitado não existe cadastrado.');
Grade.Col := RColunaGrade(clCodCliente);
end;
if VpaValidos then
begin
CarDChequeClasse;
if VprDCheque.DatVencimento <= MontaData(1,1,1900) then
begin
aviso('VENCIMENTO INVÁLIDO!!!'#13'A data de vencimento preenchida é inválida.');
Vpavalidos := false;
Grade.Col := RColunaGrade(clDatVencimento);
end
else
if VprDCheque.ValCheque = 0 then
begin
aviso('VALOR INVÁLIDO!!!'#13'O valor preenchido é inválido.');
Vpavalidos := false;
Grade.Col := RColunaGrade(clValCheque);
end
end;
if VpaValidos then
begin
if (VprDCheque.TipFormaPagamento in [fpCheque,fpChequeTerceiros])then //cheque, cheque de terceiro
begin
if VprDCheque.CodBanco = 0 then
begin
aviso('CÓDIGO DO BANCO NÃO PREENCHIDO!!!'#13'É necessário preencher o codigo do banco quando a forma de pagamento é cheque.');
Grade.Col := RColunaGrade(clCodBanco);
VpaValidos := false;
end
else
if VprDCheque.NomEmitente = '' then
begin
aviso('NOME DO EMITENTE NÃO PREENCHIDO!!!'#13'É necessário preencher o nome do emitente quando a forma de pagamento é cheque.');
Grade.Col := RColunaGrade(clNomEmitente);
VpaValidos := false;
end
else
if VprDCheque.NumCheque = 0 then
begin
aviso('NÚMERO DO CHEQUE NÃO PREENCHIDO!!!'#13'É necessário preencher o numero do cheque quando a forma de pagamento é cheque.');
Grade.Col := RColunaGrade(clNumCheque);
VpaValidos := false;
end
end;
end;
if VpaValidos then
EValCheques.Avalor := FunContasAReceber.RValTotalCheques(VprDBaixa.Cheques);
end;
{******************************************************************************}
procedure TFChequesOO.GradeGetEditMask(Sender: TObject; ACol, ARow: Integer;
var Value: String);
begin
if ACol = RColunaGrade(clCodBanco) then
Value := '000;0; '
else
if (ACol = RColunaGrade(clCodFormaPagamento)) or
(ACol = RColunaGrade(clCodCliente)) then
Value := '000000;0; '
else
if ACol = RColunaGrade(clNumCheque) then
Value := '000000000;0; '
else
if (ACol = RColunaGrade(clDatVencimento)) or
(ACol = RColunaGrade(clDatEmissao)) then
Value := FPrincipal.CorFoco.AMascaraData;
end;
{******************************************************************************}
procedure TFChequesOO.GradeKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
114 :
begin
if RColunaGrade(clCodBanco) = Grade.Col then
EBanco.AAbreLocalizacao
else
if RColunaGrade(clCodFormaPagamento) = Grade.Col then
EFormaPagamento.AAbreLocalizacao
else
if RColunaGrade(clNomEmitente) = Grade.Col then
EEmitente.AAbreLocalizacao
else
if RColunaGrade(clNumContaCaixa) = Grade.Col then
EContaCaixa.AAbreLocalizacao
else
if RColunaGrade(clCodCliente) = Grade.Col then
ECliente.AAbreLocalizacao
end;
end;
end;
{******************************************************************************}
procedure TFChequesOO.GradeKeyPress(Sender: TObject; var Key: Char);
begin
if (RColunaGrade(clNomFormaPagamento) = Grade.Col) or
(RColunaGrade(clNomCliente) = Grade.Col) or
(RColunaGrade(clNomContaCaixa) = Grade.Col) then
key := #0;
if (key = '.') and (RColunaGrade(clValCheque) = Grade.Col) then
key := DecimalSeparator;
end;
{******************************************************************************}
procedure TFChequesOO.GradeMudouLinha(Sender: TObject; VpaLinhaAtual,
VpaLinhaAnterior: Integer);
begin
if VprDBaixa.Cheques.Count > 0 then
begin
VprDCheque := TRBDCheque(VprDBaixa.Cheques.Items[VpaLinhaAtual -1]);
VprCodFormaPagamentoAnterior := VprDCheque.CodFormaPagamento;
end;
end;
{******************************************************************************}
procedure TFChequesOO.GradeNovaLinha(Sender: TObject);
begin
VprDCheque := VprDBaixa.AddCheque;
if VprDBaixa.Parcelas.Count > 0 then
begin
if VprDBaixa.IndContaOculta then
VprDCheque.IdeOrigem := 'S'
else
VprDCheque.IdeOrigem := 'N';
end
else
VprDCheque.IdeOrigem := 'A';
VprDCheque.TipCheque := 'C';
EContaCaixa.Text := VprDBaixa.NumContaCaixa;
EContaCaixa.Atualiza;
VprDCheque.CodFormaPagamento := VprDBaixa.CodFormaPAgamento;
EFormaPagamento.AInteiro := VprDBaixa.CodFormaPAgamento;
EFormaPagamento.Atualiza;
if not VprCadastrandoChequeAvulso then
VprDCheque.ValCheque := VprDBaixa.ValorPago - EValCheques.AValor;
VprDCheque.DatVencimento := VprDBaixa.DatPagamento;
EValCheques.Avalor := FunContasAReceber.RValTotalCheques(VprDBaixa.Cheques);
if CDuplicar.Checked then
begin
if VprDChequeAnterior.CodBanco <> 0 then
begin
FunContasAReceber.CopiaDCheque(VprDChequeAnterior,VprDCheque);
Grade.CarregaGrade(true);
Grade.Col := RColunaGrade(clNumCheque);
end;
end;
end;
{******************************************************************************}
procedure TFChequesOO.EFormaPagamentoRetorno(Retorno1, Retorno2: String);
begin
if Retorno1 <> '' then
begin
Grade.Cells[RColunaGrade(clCodFormaPagamento) ,Grade.ALinha] := EFormaPagamento.Text;
Grade.cells[RColunaGrade(clNomFormaPagamento),grade.ALinha] := Retorno1;
VprDCheque.TipFormaPagamento := FunContasAReceber.RTipoFormaPagamento(Retorno2);
VprDCheque.CodFormaPagamento := EFormaPagamento.AInteiro;
VprDCheque.NomFormaPagamento := Retorno1;
VprCodFormaPagamentoAnterior := VprDCheque.CodFormaPagamento;
if VprDCheque.TipFormaPagamento =fpCheque then
begin
VprDCheque.NomEmitente := VprNomCliente;
Grade.Cells[RColunaGrade(clNomEmitente),Grade.ALinha] := VprNomCliente;
end;
end
else
begin
Grade.Cells[RColunaGrade(clCodFormaPagamento),Grade.ALinha] := '';
Grade.Cells[RColunaGrade(clNomFormaPagamento),Grade.ALinha] := '';
VprDCheque.CodFormaPagamento :=0;
end;
end;
{******************************************************************************}
procedure TFChequesOO.EQtdParcelasKeyPress(Sender: TObject; var Key: Char);
begin
if (not (Key in [ '0'..'9',#8,#13])) then // somente permite digitar numeros
key := #0;
end;
{******************************************************************************}
procedure TFChequesOO.GradeSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
begin
if Grade.AEstadoGrade in [egInsercao,EgEdicao] then
if Grade.AColuna <> ACol then
begin
if RColunaGrade(clCodFormaPagamento) = Grade.AColuna then
begin
if not ExisteFormaPagamento then
begin
if not EFormaPagamento.AAbreLocalizacao then
begin
Grade.Cells[RColunaGrade(clCodFormaPagamento),Grade.ALinha] := '';
abort;
end;
end;
end
else
if RColunaGrade(clNumContaCaixa) = Grade.AColuna then
begin
if not ExisteContaCorrente then
begin
if not EContaCaixa.AAbreLocalizacao then
begin
Grade.Cells[RColunaGrade(clNumContaCaixa),Grade.ALinha]:='';
abort;
end;
end;
end
//cliente
else
if RColunaGrade(clCodCliente) = Grade.AColuna then
begin
if not ECliente.AExisteCodigo(Grade.Cells[RColunaGrade(clCodCliente),Grade.ALinha]) then
begin
if not ECliente.AAbreLocalizacao then
begin
Grade.Cells[RColunaGrade(clCodBanco),Grade.ALinha]:='';
abort;
end;
end;
end;
end;
end;
{******************************************************************************}
function TFChequesOO.RColunaGrade(VpaColuna: TRBDColunaGrade): Integer;
begin
case VpaColuna of
clCodBanco: result:=1;
clCodFormaPagamento: result:=2;
clNomFormaPagamento : result:=3;
clValCheque: result:=4;
clNomEmitente:result:=5;
clNumCheque: result:=6;
clDatVencimento: result:=7;
clNumContaCaixa: result:=8;
clNomContaCaixa: result:=9;
clDatEmissao: result:=10;
clCodCliente : result := 11;
clNomCliente : result := 12;
clNumConta : Result:=13;
clNumAgencia : Result:= 14;
end;
end;
{******************************************************************************}
procedure TFChequesOO.GradeDepoisExclusao(Sender: TObject);
begin
EValCheques.Avalor := FunContasAReceber.RValTotalCheques(VprDBaixa.Cheques);
end;
{******************************************************************************}
procedure TFChequesOO.EFormaPagamentoChange(Sender: TObject);
begin
FFormasPagamento := TFFormasPagamento.CriarSDI(self,'',FPrincipal.VerificaPermisao('FFormasPagamento'));
FFormasPagamento.BotaoCadastrar1.Click;
FFormasPagamento.showmodal;
FFormasPagamento.free;
Localiza.AtualizaConsulta;
end;
{******************************************************************************}
procedure TFChequesOO.EClienteRetorno(VpaColunas: TRBColunasLocaliza);
begin
Grade.Cells[RColunaGrade(clCodCliente),Grade.ALinha] := VpaColunas[0].AValorRetorno;
Grade.Cells[RColunaGrade(clNomCliente),Grade.ALinha] := VpaColunas[1].AValorRetorno;
if VpaColunas[0].AValorRetorno <> '' then
begin
VprDCheque.CodCliente := StrToInt(VpaColunas[0].AValorRetorno);
VprDCheque.NomCliente := VpaColunas[1].AValorRetorno;
end
else
begin
VprDCheque.CodCliente := 0;
VprDCheque.NomCliente := '';
end;
end;
{******************************************************************************}
procedure TFChequesOO.EContaCaixaRetorno(Retorno1, Retorno2: String);
begin
if Retorno1 <> '' then
begin
Grade.Cells[RColunaGrade(clNumContaCaixa),Grade.ALinha] := EContaCaixa.Text;
Grade.cells[RColunaGrade(clNomContaCaixa),grade.ALinha] := Retorno1;
VprDCheque.NumContaCaixa := EContaCaixa.Text;
VprDCheque.NomContaCaixa := Retorno1;
VprDCheque.TipContaCaixa := Retorno2;
end
else
begin
Grade.Cells[RColunaGrade(clNumContaCaixa),Grade.ALinha] := '';
Grade.Cells[RColunaGrade(clNomContaCaixa),Grade.ALinha] := '';
VprDCheque.NumContaCaixa :='';
end;
end;
procedure TFChequesOO.EEmitenteRetorno(VpaColunas: TRBColunasLocaliza);
begin
if EEmitente.AInteiro <> 0 then
begin
Grade.Cells[RColunaGrade(clNomEmitente),Grade.ALinha] := VpaColunas[1].AValorRetorno;
ECliente.Text := EEmitente.Text;
ECliente.Atualiza;
end
end;
{******************************************************************************}
procedure TFChequesOO.EBancoRetorno(VpaColunas: TRBColunasLocaliza);
begin
Grade.Cells[RColunaGrade(clCodBanco),Grade.ALinha] := VpaColunas[0].AValorRetorno;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFChequesOO]);
end.
|
unit TeeBIRegisterCreator;
interface
uses
ToolsAPI;
type
TGeneratedCreator=class(TInterfacedObject, IOTACreator, IOTAModuleCreator)
public
Code,
UnitName : String;
Constructor Create(const ACode,AUnitName:String);
// IOTACreator
function GetCreatorType: string;
function GetExisting: Boolean;
function GetFileSystem: string;
function GetOwner: IOTAModule;
function GetUnnamed: Boolean;
// IOTAModuleCreator
function GetAncestorName: string;
function GetImplFileName: string;
function GetIntfFileName: string;
function GetFormName: string;
function GetMainForm: Boolean;
function GetShowForm: Boolean;
function GetShowSource: Boolean;
function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
procedure FormCreated(const FormEditor: IOTAFormEditor);
end;
implementation
|
unit TestBufferInterpreter.ATA;
{
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, Device.SMART.List, SysUtils, BufferInterpreter.ATA,
BufferInterpreter;
type
// Test methods for class TATABufferInterpreter
TestTATABufferInterpreter = class(TTestCase)
strict private
FATABufferInterpreter: TATABufferInterpreter;
private
procedure CompareWithOriginalIdentify(
const ReturnValue: TIdentifyDeviceResult);
procedure CompareWithOriginalSMART(const ReturnValue: TSMARTValueList);
procedure CheckIDEquals(const Expected, Actual: TSMARTValueEntry;
const Msg: String);
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestBufferToIdentifyDeviceResult;
procedure TestBufferToSMARTValueList;
procedure TestLargeBufferToIdentifyDeviceResult;
procedure TestLargeBufferToSMARTValueList;
end;
const
CrucialM500IdentifyDevice: TSmallBuffer =
($40,$04,$FF,$3F,$37,$C8,$10,$00,$00,$00,$00,$00,$3F,$00,$00,$00,$00,$00,$00,$00
,$20,$20,$20,$20,$20,$20,$20,$20,$34,$31,$35,$31,$43,$30,$33,$31,$46,$41,$44,$38
,$00,$00,$00,$00,$00,$00,$55,$4D,$35,$30,$20,$20,$20,$20,$72,$43,$63,$75,$61,$69
,$5F,$6C,$54,$43,$32,$31,$4D,$30,$30,$35,$53,$30,$44,$53,$20,$31,$20,$20,$20,$20
,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$20,$10,$80,$01,$40,$00,$2F
,$01,$40,$00,$00,$00,$00,$00,$00,$FF,$3F,$10,$00,$3F,$00,$10,$FC,$FB,$00,$10,$B1
,$B0,$4B,$F9,$0D,$00,$00,$07,$00,$03,$00,$78,$00,$78,$00,$78,$00,$78,$00,$B0,$40
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$1F,$00,$0E,$F7,$C6,$00,$6C,$01,$CC,$00
,$F8,$03,$28,$00,$6B,$74,$09,$7D,$63,$61,$69,$74,$09,$BC,$63,$61,$7F,$40,$01,$00
,$01,$00,$FE,$00,$FE,$FF,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$B0,$4B,$F9,$0D,$00,$00,$00,$00,$00,$00,$08,$00,$08,$60,$00,$00,$0A,$50,$51,$07
,$13,$0C,$8D,$AF,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$1E,$40
,$1C,$40,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$29,$00,$55,$4D
,$35,$30,$30,$2E,$2E,$31,$30,$53,$00,$00,$00,$00,$00,$00,$34,$32,$34,$36,$20,$20
,$20,$20,$30,$30,$35,$43,$33,$32,$36,$31,$20,$20,$20,$20,$54,$4D,$44,$46,$41,$44
,$31,$4B,$30,$32,$41,$4D,$20,$56,$20,$00,$00,$00,$00,$00,$00,$00,$02,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$35,$00,$00,$00,$00,$00,$00,$40
,$00,$00,$00,$00,$00,$00,$01,$00,$00,$00,$00,$00,$00,$00,$01,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$7F,$10,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$01,$00,$FF,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$40,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$A5,$B8);
CrucialM500SMART: TSmallBuffer =
($10,$00,$01,$2F,$00,$64,$64,$00,$00,$00,$00,$00,$00,$00,$05,$33
,$00,$64,$64,$00,$00,$00,$00,$00,$00,$00,$09,$32,$00,$64,$64,$43
,$09,$00,$00,$00,$00,$00,$0C,$32,$00,$64,$64,$64,$04,$00,$00,$00
,$00,$00,$AB,$32,$00,$64,$64,$00,$00,$00,$00,$00,$00,$00,$AC,$32
,$00,$64,$64,$00,$00,$00,$00,$00,$00,$00,$AD,$32,$00,$64,$64,$09
,$00,$00,$00,$00,$00,$00,$AE,$32,$00,$64,$64,$C9,$00,$00,$00,$00
,$00,$00,$B4,$33,$00,$00,$00,$C6,$07,$00,$00,$00,$00,$00,$B7,$32
,$00,$64,$64,$00,$00,$00,$00,$00,$00,$00,$B8,$32,$00,$64,$64,$00
,$00,$00,$00,$00,$00,$00,$BB,$32,$00,$64,$64,$00,$00,$00,$00,$00
,$00,$00,$C2,$22,$00,$49,$31,$1B,$00,$00,$00,$33,$00,$00,$C4,$32
,$00,$64,$64,$00,$00,$00,$00,$00,$00,$00,$C5,$32,$00,$64,$64,$00
,$00,$00,$00,$00,$00,$00,$C6,$30,$00,$64,$64,$00,$00,$00,$00,$00
,$00,$00,$C7,$32,$00,$64,$64,$00,$00,$00,$00,$00,$00,$00,$CA,$31
,$00,$64,$64,$00,$00,$00,$00,$00,$00,$00,$CE,$0E,$00,$64,$64,$00
,$00,$00,$00,$00,$00,$00,$D2,$32,$00,$64,$64,$00,$00,$00,$00,$00
,$00,$00,$F6,$32,$00,$64,$64,$3D,$A3,$0C,$62,$00,$00,$00,$F7,$32
,$00,$64,$64,$44,$08,$12,$03,$00,$00,$00,$F8,$32,$00,$64,$64,$0A
,$1C,$17,$01,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$2B,$02,$00,$7B
,$03,$00,$01,$00,$02,$09,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00
,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$00,$AE);
implementation
procedure TestTATABufferInterpreter.SetUp;
begin
FATABufferInterpreter := TATABufferInterpreter.Create;
end;
procedure TestTATABufferInterpreter.TearDown;
begin
FATABufferInterpreter.Free;
FATABufferInterpreter := nil;
end;
procedure TestTATABufferInterpreter.TestBufferToIdentifyDeviceResult;
var
ReturnValue: TIdentifyDeviceResult;
Buffer: TSmallBuffer;
begin
Buffer := CrucialM500IdentifyDevice;
ReturnValue := FATABufferInterpreter.BufferToIdentifyDeviceResult(Buffer);
CompareWithOriginalIdentify(ReturnValue);
end;
procedure TestTATABufferInterpreter.CompareWithOriginalIdentify(
const ReturnValue: TIdentifyDeviceResult);
begin
CheckEquals('Crucial_CT120M500SSD1', ReturnValue.Model);
CheckEquals('MU05', ReturnValue.Firmware);
CheckEquals('14150C13AF8D', ReturnValue.Serial);
CheckEquals(117220824, ReturnValue.UserSizeInKB);
CheckTrue(TSATASpeed.SATA600 = ReturnValue.SATASpeed,
'TSATASpeed.SATA600 = ReturnValue.SATASpeed');
CheckEquals(512, ReturnValue.LBASize);
end;
procedure TestTATABufferInterpreter.TestBufferToSMARTValueList;
var
ReturnValue: TSMARTValueList;
Buffer: TSmallBuffer;
begin
Buffer := CrucialM500SMART;
ReturnValue := FATABufferInterpreter.BufferToSMARTValueList(Buffer);
CompareWithOriginalSMART(ReturnValue);
end;
procedure TestTATABufferInterpreter.CheckIDEquals(
const Expected, Actual: TSMARTValueEntry;
const Msg: String);
begin
CheckEquals(Expected.ID, Actual.ID, Msg);
CheckEquals(Expected.Current, Actual.Current, Msg);
CheckEquals(Expected.Worst, Actual.Worst, Msg);
CheckEquals(Expected.Threshold, Actual.Threshold, Msg);
CheckEquals(Expected.RAW, Actual.RAW, Msg);
end;
procedure TestTATABufferInterpreter.CompareWithOriginalSMART(
const ReturnValue: TSMARTValueList);
const
ID0: TSMARTValueEntry = (ID: 1; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID1: TSMARTValueEntry = (ID: 5; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID2: TSMARTValueEntry = (ID: 9; Current: 100; Worst: 100; Threshold: 0; RAW: 2371);
ID3: TSMARTValueEntry = (ID: 12; Current: 100; Worst: 100; Threshold: 0; RAW: 1124);
ID4: TSMARTValueEntry = (ID: 171; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID5: TSMARTValueEntry = (ID: 172; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID6: TSMARTValueEntry = (ID: 173; Current: 100; Worst: 100; Threshold: 0; RAW: 9);
ID7: TSMARTValueEntry = (ID: 174; Current: 100; Worst: 100; Threshold: 0; RAW: 201);
ID8: TSMARTValueEntry = (ID: 180; Current: 0; Worst: 0; Threshold: 0; RAW: 1990);
ID9: TSMARTValueEntry = (ID: 183; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID10: TSMARTValueEntry = (ID: 184; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID11: TSMARTValueEntry = (ID: 187; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID12: TSMARTValueEntry = (ID: 194; Current: 73; Worst: 49; Threshold: 0; RAW: 219043332123);
ID13: TSMARTValueEntry = (ID: 196; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID14: TSMARTValueEntry = (ID: 197; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID15: TSMARTValueEntry = (ID: 198; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID16: TSMARTValueEntry = (ID: 199; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID17: TSMARTValueEntry = (ID: 202; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID18: TSMARTValueEntry = (ID: 206; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID19: TSMARTValueEntry = (ID: 210; Current: 100; Worst: 100; Threshold: 0; RAW: 0);
ID20: TSMARTValueEntry = (ID: 246; Current: 100; Worst: 100; Threshold: 0; RAW: 1644995389);
ID21: TSMARTValueEntry = (ID: 247; Current: 100; Worst: 100; Threshold: 0; RAW: 51513412);
ID22: TSMARTValueEntry = (ID: 248; Current: 100; Worst: 100; Threshold: 0; RAW: 18291722);
begin
CheckEquals(23, ReturnValue.Count, 'ReturnValue.Count');
CheckIDEquals(ID0, ReturnValue[0], 'ReturnValue[0]');
CheckIDEquals(ID1, ReturnValue[1], 'ReturnValue[1]');
CheckIDEquals(ID2, ReturnValue[2], 'ReturnValue[2]');
CheckIDEquals(ID3, ReturnValue[3], 'ReturnValue[3]');
CheckIDEquals(ID4, ReturnValue[4], 'ReturnValue[4]');
CheckIDEquals(ID5, ReturnValue[5], 'ReturnValue[5]');
CheckIDEquals(ID6, ReturnValue[6], 'ReturnValue[6]');
CheckIDEquals(ID7, ReturnValue[7], 'ReturnValue[7]');
CheckIDEquals(ID8, ReturnValue[8], 'ReturnValue[8]');
CheckIDEquals(ID9, ReturnValue[9], 'ReturnValue[9]');
CheckIDEquals(ID10, ReturnValue[10], 'ReturnValue[10]');
CheckIDEquals(ID11, ReturnValue[11], 'ReturnValue[11]');
CheckIDEquals(ID12, ReturnValue[12], 'ReturnValue[12]');
CheckIDEquals(ID13, ReturnValue[13], 'ReturnValue[13]');
CheckIDEquals(ID14, ReturnValue[14], 'ReturnValue[14]');
CheckIDEquals(ID15, ReturnValue[15], 'ReturnValue[15]');
CheckIDEquals(ID16, ReturnValue[16], 'ReturnValue[16]');
CheckIDEquals(ID17, ReturnValue[17], 'ReturnValue[17]');
CheckIDEquals(ID18, ReturnValue[18], 'ReturnValue[18]');
CheckIDEquals(ID19, ReturnValue[19], 'ReturnValue[19]');
CheckIDEquals(ID20, ReturnValue[20], 'ReturnValue[20]');
CheckIDEquals(ID21, ReturnValue[21], 'ReturnValue[21]');
CheckIDEquals(ID22, ReturnValue[22], 'ReturnValue[22]');
end;
procedure TestTATABufferInterpreter.TestLargeBufferToIdentifyDeviceResult;
var
ReturnValue: TIdentifyDeviceResult;
Buffer: TLargeBuffer;
begin
FillChar(Buffer, SizeOf(Buffer), #0);
Move(CrucialM500IdentifyDevice, Buffer, SizeOf(CrucialM500IdentifyDevice));
ReturnValue :=
FATABufferInterpreter.LargeBufferToIdentifyDeviceResult(Buffer);
CompareWithOriginalIdentify(ReturnValue);
end;
procedure TestTATABufferInterpreter.TestLargeBufferToSMARTValueList;
var
ReturnValue: TSMARTValueList;
Buffer: TLargeBuffer;
begin
FillChar(Buffer, SizeOf(Buffer), #0);
Move(CrucialM500SMART, Buffer, SizeOf(CrucialM500SMART));
ReturnValue := FATABufferInterpreter.LargeBufferToSMARTValueList(Buffer);
CompareWithOriginalSMART(ReturnValue);
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTATABufferInterpreter.Suite);
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC DBX Migration Helpers }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$WARN SYMBOL_DEPRECATED OFF}
unit FireDAC.DBX.Migrate;
interface
uses
System.Classes, Data.DB,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Comp.Client;
type
TFDDBXProcParamList = TDataSet;
/// <summary>Emulates DBX TTransactionDesc.</summary>
TFDDBXTransactionDesc = record
TransactionID: LongWord;
GlobalID: LongWord;
IsolationLevel: TFDTxIsolation;
end;
/// <summary>Emulates DBX TDBXTransaction.</summary>
TFDDBXTransaction = class(TObject)
private
[Weak] FConnection: TFDCustomConnection;
FSerialID: LongWord;
public
property Connection: TFDCustomConnection read FConnection;
end;
/// <summary>TFDDBXConnectionAdminHelper is a helper class that emulates DBX
/// IConnectionAdmin.</summary>
TFDDBXConnectionAdminHelper = class helper for TFDCustomManager
/// <summary> The GetDriverParams method emulates DBX IConnectionAdmin.GetDriverParams.
/// Use IFDPhysDriverMetadata.GetConnParams instead. </summary>
function GetDriverParams(const DriverName: string; Params: TStrings): Integer;
deprecated 'Use IFDPhysDriverMetadata.GetConnParams instead';
/// <summary> The GetDriverLibNames method emulates DBX IConnectionAdmin.GetDriverLibNames.
/// Use TFDPhysXxxxDriverLink instead. </summary>
procedure GetDriverLibNames(const DriverName: string;
var LibraryName, VendorLibrary: string);
deprecated 'Use TFDPhysXxxxDriverLink instead';
end;
/// <summary>The TFDDBXConnectionHelper is a helper class that emulates DBX
/// TSQLConnection.</summary>
TFDDBXConnectionHelper = class helper for TFDCustomConnection
/// <summary> The GetFieldNames method emulates DBX TSQLConnection.GetFieldNames.
/// Use TFDConnection.GetFieldNames method instead. </summary>
procedure GetFieldNames(const TableName: string; List: TStrings); overload;
deprecated 'Use TFDConnection.GetFieldNames instead';
/// <summary> The GetFieldNames method emulates DBX TSQLConnection.GetFieldNames.
/// Use TFDConnection.GetFieldNames method instead. </summary>
procedure GetFieldNames(const TableName: string; SchemaName: string; List: TStrings); overload;
deprecated 'Use TFDConnection.GetFieldNames instead';
/// <summary> The GetIndexNames method emulates DBX TSQLConnection.GetIndexNames.
/// Use TFDConnection.GetIndexNames method instead. </summary>
procedure GetIndexNames(const TableName: string; List: TStrings); overload;
deprecated 'Use TFDConnection.GetIndexNames instead';
/// <summary> The GetIndexNames method emulates DBX TSQLConnection.GetIndexNames.
/// Use TFDConnection.GetIndexNames method instead. </summary>
procedure GetIndexNames(const TableName, SchemaName: string; List: TStrings); overload;
deprecated 'Use TFDConnection.GetIndexNames instead';
/// <summary> The GetProcedureNames method emulates DBX TSQLConnection.GetProcedureNames.
/// Use TFDConnection.GetStoredProcNames method instead. </summary>
procedure GetProcedureNames(List: TStrings); overload;
deprecated 'Use TFDConnection.GetStoredProcNames instead';
/// <summary> The GetProcedureNames method emulates DBX TSQLConnection.GetProcedureNames.
/// Use TFDConnection.GetStoredProcNames method instead. </summary>
procedure GetProcedureNames(const PackageName: string; List: TStrings); overload;
deprecated 'Use TFDConnection.GetStoredProcNames instead';
/// <summary> The GetProcedureNames method emulates DBX TSQLConnection.GetProcedureNames.
/// Use TFDConnection.GetStoredProcNames method instead. </summary>
procedure GetProcedureNames(const PackageName, SchemaName: string; List: TStrings); overload;
deprecated 'Use TFDConnection.GetStoredProcNames instead';
/// <summary> The GetPackageNames method emulates DBX TSQLConnection.GetPackageNames.
/// Use TFDConnection.GetPackageNames method instead. </summary>
procedure GetPackageNames(List: TStrings); overload;
deprecated 'Use TFDConnection.GetPackageNames instead';
/// <summary> The GetSchemaNames method emulates DBX TSQLConnection.GetSchemaNames.
/// Use TFDConnection.GetSchemaNames method instead. </summary>
procedure GetSchemaNames(List: TStrings); overload;
deprecated 'Use TFDConnection.GetSchemaNames instead';
/// <summary> The GetProcedureParams method emulates DBX TSQLConnection.GetProcedureParams.
/// Use TFDMetaInfoQuery with MetaInfoKind=mkProcArgs instead. </summary>
procedure GetProcedureParams(ProcedureName : string; List: TFDDBXProcParamList); overload;
deprecated 'Use TFDMetaInfoQuery with MetaInfoKind=mkProcArgs instead';
/// <summary> The GetProcedureParams method emulates DBX TSQLConnection.GetProcedureParams.
/// Use TFDMetaInfoQuery with MetaInfoKind=mkProcArgs instead. </summary>
procedure GetProcedureParams(ProcedureName, PackageName: string; List: TFDDBXProcParamList); overload;
deprecated 'Use TFDMetaInfoQuery with MetaInfoKind=mkProcArgs instead';
/// <summary> The GetProcedureParams method emulates DBX TSQLConnection.GetProcedureParams.
/// Use TFDMetaInfoQuery with MetaInfoKind=mkProcArgs instead. </summary>
procedure GetProcedureParams(ProcedureName, PackageName, SchemaName: string; List: TFDDBXProcParamList); overload;
deprecated 'Use TFDMetaInfoQuery with MetaInfoKind=mkProcArgs instead';
/// <summary> The GetTableNames method emulates DBX TSQLConnection.GetTableNames.
/// Use TFDConnection.GetTableNames method instead. </summary>
procedure GetTableNames(List: TStrings; SystemTables: Boolean = False); overload;
deprecated 'Use TFDConnection.GetTableNames instead';
/// <summary> The GetTableNames method emulates DBX TSQLConnection.GetTableNames.
/// Use TFDConnection.GetTableNames method instead. </summary>
procedure GetTableNames(List: TStrings; SchemaName: string; SystemTables: Boolean = False); overload;
deprecated 'Use TFDConnection.GetTableNames instead';
/// <summary> The GetLoginUsername method emulates DBX TSQLConnection.GetLoginUsername.
/// Use TFDConnection.CurrentSchema or TFDConnection.Params.UserName properties instead. </summary>
function GetLoginUsername: string;
deprecated 'Use TFDConnection.CurrentSchema or TFDConnection.Params.UserName instead';
{$IFNDEF NEXTGEN}
/// <summary> The StartTransaction method emulates DBX TSQLConnection.StartTransaction.
/// Use TFDConnection.StartTransaction method instead. </summary>
procedure StartTransaction(TransDesc: TFDDBXTransactionDesc); overload;
deprecated 'Use TFDConnection.StartTransaction instead';
{$ENDIF}
/// <summary> The BeginTransaction method emulates DBX TSQLConnection.BeginTransaction.
/// Use TFDConnection.StartTransaction method instead. </summary>
function BeginTransaction: TFDDBXTransaction; overload;
deprecated 'Use TFDConnection.StartTransaction instead';
/// <summary> The BeginTransaction method emulates DBX TSQLConnection.BeginTransaction.
/// Use TFDConnection.StartTransaction method instead. </summary>
function BeginTransaction(Isolation: TFDTxIsolation): TFDDBXTransaction; overload;
deprecated 'Use TFDConnection.StartTransaction instead';
/// <summary> The CommitFreeAndNil method emulates DBX TSQLConnection.CommitFreeAndNil.
/// Use TFDConnection.Commit method instead. </summary>
procedure CommitFreeAndNil(var Transaction: TFDDBXTransaction);
deprecated 'Use TFDConnection.Commit instead';
{$IFNDEF NEXTGEN}
/// <summary> The Commit method emulates DBX TSQLConnection.Commit.
/// Use TFDConnection.Commit method instead. </summary>
procedure Commit(TransDesc: TFDDBXTransactionDesc); overload;
deprecated 'Use TFDConnection.Commit instead';
{$ENDIF}
/// <summary> The RollbackFreeAndNil method emulates DBX TSQLConnection.RollbackFreeAndNil.
/// Use TFDConnection.Rollback method instead. </summary>
procedure RollbackFreeAndNil(var Transaction: TFDDBXTransaction);
deprecated 'Use TFDConnection.Rollback instead';
/// <summary> The RollbackIncompleteFreeAndNil method emulates DBX TSQLConnection.RollbackIncompleteFreeAndNil.
/// Use TFDConnection.Rollback method instead. </summary>
procedure RollbackIncompleteFreeAndNil(var Transaction: TFDDBXTransaction);
deprecated 'Use TFDConnection.Rollback instead';
{$IFNDEF NEXTGEN}
/// <summary> The Rollback method emulates DBX TSQLConnection.Rollback.
/// Use TFDConnection.Rollback method instead. </summary>
procedure Rollback(TransDesc: TFDDBXTransactionDesc); overload;
deprecated 'Use TFDConnection.Rollback instead';
{$ENDIF}
/// <summary> The HasTransaction method emulates DBX TSQLConnection.HasTransaction.
/// Use TFDConnection.InTransaction method instead. </summary>
function HasTransaction(Transaction: TFDDBXTransaction): Boolean;
deprecated 'Use TFDConnection.InTransaction instead';
end;
/// <summary>Emulates DBX TCustomSQLDataSet.</summary>
TFDDBXDataSetHelper = class helper for TFDRDBMSDataSet
private
function GetCommandText: string;
deprecated 'Use TFDQuery.SQL or TFDStoredProc.StoredProcName instead';
function GetCommandType: TSQLCommandType;
deprecated 'Use TFDQuery or TFDStoredProc instead';
function GetDbxCommandType: string;
deprecated 'Use TFDQuery or TFDStoredProc instead';
function GetNumericMapping: Boolean;
deprecated 'Use TFDQuery or TFDStoredProc FormatOptions instead';
procedure SetCommandText(const Value: string);
deprecated 'Use TFDQuery.SQL or TFDStoredProc.StoredProcName instead';
procedure SetCommandType(const Value: TSQLCommandType);
deprecated 'Use TFDQuery or TFDStoredProc instead';
procedure SetDbxCommandType(const Value: string);
deprecated 'Use TFDQuery or TFDStoredProc instead';
procedure SetNumericMapping(const Value: Boolean);
deprecated 'Use TFDQuery or TFDStoredProc FormatOptions instead';
public
/// <summary> The GetKeyFieldNames method emulates DBX TCustomSQLDataSet.GetKeyFieldNames.
/// Use TFDDataSet.IndexDefs or Indexes properties instead. </summary>
function GetKeyFieldNames(List: TStrings): Integer;
deprecated 'Use TFDDataSet.IndexDefs or Indexes instead';
/// <summary> The GetQuoteChar method emulates DBX TCustomSQLDataSet.GetQuoteChar.
/// Use TFDConnection.ConnectionMetaDataIntf.NameQuoteChar property instead. </summary>
function GetQuoteChar: string;
deprecated 'Use TFDConnection.ConnectionMetaDataIntf.NameQuoteChar instead';
/// <summary> The CommandType property emulates DBX TCustomSQLDataSet.CommandType.
/// Use TFDQuery or TFDStoredProc instead. </summary>
property CommandType: TSQLCommandType read GetCommandType write SetCommandType;
/// <summary> The DbxCommandType property emulates DBX TCustomSQLDataSet.DbxCommandType.
/// Use TFDQuery or TFDStoredProc instead. </summary>
property DbxCommandType: string read GetDbxCommandType write SetDbxCommandType;
/// <summary> The CommandText property emulates DBX TCustomSQLDataSet.CommandText.
/// Use TFDQuery.SQL or TFDStoredProc.StoredProcName properties instead. </summary>
property CommandText: string read GetCommandText write SetCommandText;
/// <summary> The NumericMapping property emulates DBX TCustomSQLDataSet.NumericMapping.
/// Use TFDQuery or TFDStoredProc FormatOptions property instead. </summary>
property NumericMapping: Boolean read GetNumericMapping write SetNumericMapping default False;
end;
implementation
uses
System.SysUtils,
FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Error, FireDAC.Stan.Intf,
FireDAC.DatS,
FireDAC.Phys.Intf;
{-------------------------------------------------------------------------------}
{ TFDDBXConnectionAdminHelper }
{-------------------------------------------------------------------------------}
function TFDDBXConnectionAdminHelper.GetDriverParams(const DriverName: string;
Params: TStrings): Integer;
var
oManMeta: IFDPhysManagerMetadata;
oDrvMeta: IFDPhysDriverMetadata;
oTab: TFDDatSTable;
i: Integer;
begin
FDPhysManager.CreateMetadata(oManMeta);
oManMeta.CreateDriverMetadata(DriverName, oDrvMeta);
oTab := oDrvMeta.GetConnParams(Params);
try
for i := 0 to oTab.Rows.Count - 1 do
Params.Add(oTab.Rows[i].GetData('Name') + '=' + oTab.Rows[i].GetData('DefVal'));
finally
FDFree(oTab);
end;
Result := Params.Count;
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionAdminHelper.GetDriverLibNames(
const DriverName: string; var LibraryName, VendorLibrary: string);
begin
end;
{-------------------------------------------------------------------------------}
{ TFDDBXConnectionHelper }
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetFieldNames(const TableName: string;
List: TStrings);
begin
GetFieldNames(TableName, '', List);
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetFieldNames(const TableName: string;
SchemaName: string; List: TStrings);
begin
GetFieldNames('', SchemaName, TableName, '', List);
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetIndexNames(const TableName: string;
List: TStrings);
begin
GetIndexNames(TableName, '', List);
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetIndexNames(const TableName,
SchemaName: string; List: TStrings);
begin
GetIndexNames('', SchemaName, TableName, '', List);
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetProcedureNames(List: TStrings);
begin
GetProcedureNames('', '', List);
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetProcedureNames(const PackageName: string;
List: TStrings);
begin
GetProcedureNames(PackageName, '', List);
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetProcedureNames(const PackageName,
SchemaName: string; List: TStrings);
begin
GetStoredProcNames('', SchemaName, PackageName, '', List, [osMy, osOther], True);
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetPackageNames(List: TStrings);
begin
GetPackageNames('', '', '', List, [osMy, osOther], True);
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetSchemaNames(List: TStrings);
begin
GetSchemaNames('', '', List);
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetProcedureParams(ProcedureName: string;
List: TFDDBXProcParamList);
begin
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetProcedureParams(ProcedureName, PackageName,
SchemaName: string; List: TFDDBXProcParamList);
begin
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetProcedureParams(ProcedureName,
PackageName: string; List: TFDDBXProcParamList);
begin
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetTableNames(List: TStrings;
SystemTables: Boolean);
begin
GetTableNames(List, '', SystemTables);
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.GetTableNames(List: TStrings;
SchemaName: string; SystemTables: Boolean);
var
eScopes: TFDPhysObjectScopes;
begin
eScopes := [osMy, osOther];
if SystemTables then
Include(eScopes, osSystem);
GetTableNames('', SchemaName, '', List, eScopes,
[tkSynonym, tkTable, tkView, tkTempTable, tkLocalTable], True);
end;
{-------------------------------------------------------------------------------}
function TFDDBXConnectionHelper.GetLoginUsername: string;
begin
Result := Params.UserName;
end;
{-------------------------------------------------------------------------------}
{$IFNDEF NEXTGEN}
procedure TFDDBXConnectionHelper.StartTransaction(
TransDesc: TFDDBXTransactionDesc);
begin
TxOptions.Isolation := TransDesc.IsolationLevel;
StartTransaction();
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
function TFDDBXConnectionHelper.BeginTransaction: TFDDBXTransaction;
begin
Result := BeginTransaction(xiReadCommitted);
end;
{-------------------------------------------------------------------------------}
function TFDDBXConnectionHelper.BeginTransaction(
Isolation: TFDTxIsolation): TFDDBXTransaction;
begin
TxOptions.Isolation := Isolation;
StartTransaction();
Result := TFDDBXTransaction.Create;
Result.FConnection := Self;
Result.FSerialID := ConnectionIntf.Transaction.SerialID;
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.CommitFreeAndNil(
var Transaction: TFDDBXTransaction);
begin
Commit;
FDFreeAndNil(Transaction);
end;
{-------------------------------------------------------------------------------}
{$IFNDEF NEXTGEN}
procedure TFDDBXConnectionHelper.Commit(TransDesc: TFDDBXTransactionDesc);
begin
Commit;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.RollbackFreeAndNil(
var Transaction: TFDDBXTransaction);
begin
Rollback;
FDFreeAndNil(Transaction);
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXConnectionHelper.RollbackIncompleteFreeAndNil(
var Transaction: TFDDBXTransaction);
begin
if HasTransaction(Transaction) then
RollbackFreeAndNil(Transaction);
Transaction := nil;
end;
{-------------------------------------------------------------------------------}
{$IFNDEF NEXTGEN}
procedure TFDDBXConnectionHelper.Rollback(TransDesc: TFDDBXTransactionDesc);
begin
Rollback;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
function TFDDBXConnectionHelper.HasTransaction(
Transaction: TFDDBXTransaction): Boolean;
begin
Result := InTransaction and
(ConnectionIntf.Transaction.TopSerialID <= Transaction.FSerialID) and
(ConnectionIntf.Transaction.SerialID >= Transaction.FSerialID);
end;
{-------------------------------------------------------------------------------}
{ TFDDBXDataSetHelper }
{-------------------------------------------------------------------------------}
const
DbxSQL = 'Dbx.SQL';
DbxStoredProcedure = 'Dbx.StoredProcedure';
DbxTable = 'Dbx.Table';
DSServerMethod = 'DataSnap.ServerMethod';
function TFDDBXDataSetHelper.GetCommandText: string;
begin
Result := PSGetCommandText;
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXDataSetHelper.SetCommandText(const Value: string);
begin
if Command <> nil then
Command.CommandText.Text := Value;
end;
{-------------------------------------------------------------------------------}
function TFDDBXDataSetHelper.GetCommandType: TSQLCommandType;
begin
Result := PSGetCommandType;
if Result = ctUnknown then
Result := ctQuery;
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXDataSetHelper.SetCommandType(const Value: TSQLCommandType);
begin
case Value of
ctQuery: Command.CommandKind := skUnknown;
ctTable: FDCapabilityNotSupported(Self, [S_FD_LComp, S_FD_LComp_PClnt]);
ctStoredProc: Command.CommandKind := skStoredProc;
ctServerMethod: Command.CommandKind := skStoredProc;
else Command.CommandKind := skUnknown;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDBXDataSetHelper.GetDbxCommandType: string;
begin
case GetCommandType of
ctQuery: Result := DbxSQL;
ctTable: Result := DbxTable;
ctStoredProc: Result := DbxStoredProcedure;
ctServerMethod: Result := DSServerMethod;
else Result := DbxSQL;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXDataSetHelper.SetDbxCommandType(const Value: string);
var
eType: TPSCommandType;
begin
if Value = DbxStoredProcedure then
eType := ctStoredProc
else if Value = DSServerMethod then
eType := ctServerMethod
else if Value = DbxTable then
eType := ctTable
else
eType := ctQuery;
CommandType := eType;
end;
{-------------------------------------------------------------------------------}
function TFDDBXDataSetHelper.GetNumericMapping: Boolean;
begin
Result := (FormatOptions.MaxBcdPrecision = 0) and (FormatOptions.MaxBcdScale = 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDDBXDataSetHelper.SetNumericMapping(const Value: Boolean);
begin
if Value then begin
FormatOptions.MaxBcdPrecision := 0;
FormatOptions.MaxBcdScale := 0;
FormatOptions.OwnMapRules := True;
FormatOptions.MapRules.Add(dtCurrency, dtFmtBCD);
end
else begin
FormatOptions.MaxBcdPrecision := 18;
FormatOptions.MaxBcdScale := 4;
FormatOptions.OwnMapRules := False;
FormatOptions.MapRules.Clear;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDBXDataSetHelper.GetKeyFieldNames(List: TStrings): Integer;
var
i: Integer;
begin
Result := IndexDefs.Count;
List.BeginUpdate;
try
List.Clear;
for i := 0 to Result - 1 do
List.Add(IndexDefs[i].Fields);
finally
List.EndUpdate;
end;
end;
{-------------------------------------------------------------------------------}
function TFDDBXDataSetHelper.GetQuoteChar: string;
begin
Result := PSGetQuoteChar;
end;
end.
|
unit frmNewPassword_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Buttons;
type
TfrmNewPasswordGenerator = class(TForm)
btnGenerate: TButton;
pnlPasswordOut: TPanel;
bmbClose: TBitBtn;
btnTextSave: TButton;
procedure btnGenerateClick(Sender: TObject);
procedure btnTextSaveClick(Sender: TObject);
private
{ Private declarations }
// variables used
sName, sSurname, sUsername, sNameCopy, sSurnameCopy, sYear,
sYearCopy: string;
iNum1, iNum2, iNum3: integer;
cChar1, cChar2: char;
sLetter1, sLetter2, sLetter3, sLetter4: string;
tDesktop: TextFile;
sTextName, sTextPassword, sPassword, sUsernamee, sTextUsername: string;
procedure Generation;
procedure SaveToDesktop;
public
{ Public declarations }
//constants for password generation
const
arrSpecial: array [1 .. 8] of char = ('@', '!', '#', '$', '%', '^', '&',
'*');
arrLetters: array [1 .. 26] of char = ('a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z');
end;
var
frmNewPasswordGenerator: TfrmNewPasswordGenerator;
implementation
{$R *.dfm}
procedure TfrmNewPasswordGenerator.btnGenerateClick(Sender: TObject);
begin
Randomize;
Generation;
// generation
sPassword := cChar1 + IntToStr(iNum1) + sLetter1 + IntToStr(iNum2)
+ cChar2 + sLetter2 + IntToStr(iNum3) + sLetter4 + sLetter3;
pnlPasswordOut.Caption := sPassword;
end;
procedure TfrmNewPasswordGenerator.btnTextSaveClick(Sender: TObject);
begin
Generation;
SaveToDesktop;
end;
procedure TfrmNewPasswordGenerator.Generation;
begin
// values
Randomize;
iNum1 := Random(35) + 1;
iNum2 := Random(35) + 1;
iNum3 := Random(35) + 1;
cChar1 := arrSpecial[Random(8) + 1];
cChar2 := arrSpecial[Random(8) + 1];
sLetter1 := arrLetters[Random(26) + 1];
sLetter2 := Uppercase(arrLetters[Random(26) + 1]);
sLetter3 := arrLetters[Random(26) + 1];
sLetter4 := Uppercase(arrLetters[Random(26) + 1]);
end;
procedure TfrmNewPasswordGenerator.SaveToDesktop;
begin
AssignFile(tDesktop, 'PASSWORDS GENERATED.txt');
Rewrite(tDesktop);
sTextPassword := 'Password:' + ' ' + sPassword;
Writeln(tDesktop,sTextPassword);
CloseFile(tDesktop);
end;
end.
|
unit IdAntiFreeze;
{
NOTE - This unit must NOT appear in any Indy uses clauses. This is a ONE way relationship
and is linked in IF the user uses this component. This is done to preserve the isolation from the
massive FORMS unit.
}
interface
uses
Classes,
IdAntiFreezeBase,
IdBaseComponent;
{Directive needed for C++Builder HPP and OBJ files for this that will force it
to be statically compiled into the code}
{$I IdCompilerDefines.inc}
{$IFDEF MSWINDOWS}
{$HPPEMIT '#pragma link "IdAntiFreeze.obj"'} {Do not Localize}
{$ENDIF}
{$IFDEF LINUX}
{$HPPEMIT '#pragma link "IdAntiFreeze.o"'} {Do not Localize}
{$ENDIF}
type
TIdAntiFreeze = class(TIdAntiFreezeBase)
public
procedure Process; override;
end;
implementation
uses
{$IFDEF LINUX}
QForms;
{$ENDIF}
{$IFDEF MSWINDOWS}
Forms,
Messages,
Windows;
{$ENDIF}
{$IFDEF LINUX}
procedure TIdAntiFreeze.Process;
begin
//TODO: Handle ApplicationHasPriority
Application.ProcessMessages;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
procedure TIdAntiFreeze.Process;
var
Msg: TMsg;
begin
if ApplicationHasPriority then begin
Application.ProcessMessages;
end else begin
// This guarantees it will not ever call Application.Idle
if PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE) then begin
Application.HandleMessage;
end;
end;
end;
{$ENDIF}
end.
|
unit contplug;
{ Contents of file contplug.pas }
interface
uses
Windows;
const
ftNoMoreFields = 0;
ftNumeric32 = 1;
ftNumeric64 = 2;
ftNumericFloating = 3;
ftDate = 4;
ft_Time = 5;
ft_Boolean = 6;
ft_MultipleChoice = 7;
ft_String = 8;
ft_Fulltext = 9;
ft_DateTime = 10;
ft_StringW = 11;
ft_fulltextw = 12;
ft_comparecontent = 100;
// for ContentGetValue
ft_NoSuchField = -1;
ft_FileError = -2;
ft_FieldEmpty = -3;
ft_OnDemand = -4;
ft_NotSupported = -5;
ft_SetCancel = -6;
ft_Delayed = 0;
ft_found = 1;
ft_notfound = -8;
// for ContentSetValue
ft_SetSuccess = 0; // setting of the attribute succeeded
// for ContentGetSupportedFieldFlags
contFlags_Edit = 1;
contFlags_SubstSize = 2;
contFlags_SubstDateTime = 4;
contFlags_SubstDate = 6;
contFlags_SubstTime = 8;
contFlags_SubstAttributes = 10;
contFlags_SubstAttributeStr = 12;
contFlags_PassThrough_Size_Float = 14;
contFlags_SubstMask = 14;
contFlags_FieldEdit = 16;
contflags_fieldsearch = 32;
contflags_searchpageonly = 64;
// for ContentSendStateInformation
contst_ReadNewDir = 1;
contst_RefreshPressed = 2;
contst_ShowHint = 4;
setflags_First_Attribute = 1; // First attribute of this file
setflags_Last_Attribute = 2; // Last attribute of this file
setflags_Only_Date = 4; // Only set the date of the datetime value!
CONTENT_DELAYIFSLOW = 1; // ContentGetValue called in foreground
CONTENT_PASSTHROUGH = 2; { If requested via contflags_passthrough_size_float: The size
is passed in as floating value, TC expects correct value
from the given units value, and optionally a text string}
type
PContentDefaultParamStruct = ^TContentDefaultParamStruct;
TContentDefaultParamStruct = record
Size,
PluginInterfaceVersionLow,
PluginInterfaceVersionHi: LongInt;
DefaultIniName: array[0..MAX_PATH-1] of char;
end;
PDateFormat = ^TDateFormat;
TDateFormat = record
wYear,
wMonth,
wDay: Word;
end;
PTimeFormat = ^TTimeFormat;
TTimeFormat = record
wHour,
wMinute,
wSecond : Word;
end;
PFileDetailsStruct = ^TFileDetailsStruct;
TFileDetailsStruct = record
FileSize1Lo,
FileSize1Hi: DWORD;
FileSize2Lo,
FileSize1Hi: DWORD;
FileTime1: TFileTime;
FileTime2: TFileTime;
Attr1,
Attr2: DWORD;
end;
type
TProgressCallbackProc = function(NextBlockData: integer): integer; stdcall;
implementation
{ Function prototypes: }
{
procedure ContentGetDetectString(DetectString: PAnsiChar; MaxLen: integer); stdcall;
function ContentGetSupportedField(FieldIndex: integer; FieldName, Units: PAnsiChar;
MaxLen: integer): integer; stdcall;
function ContentGetValue(FileName: PAnsiChar; FieldIndex, UnitIndex: integer; FieldValue: PByte;
MaxLen, Flags: integer): integer; stdcall;
function ContentGetValueW(FileName: PWideChar; FieldIndex, UnitIndex: integer; FieldValue: PByte;
MaxLen, Flags: integer): integer; stdcall;
procedure ContentSetDefaultParams(Dps: PContentDefaultParamStruct); stdcall;
procedure ContentPluginUnloading; stdcall;
procedure ContentStopGetValue(FileName: PAnsiChar); stdcall;
procedure ContentStopGetValueW(FileName: PWideChar); stdcall;
function ContentGetDefaultSortOrder(FieldIndex: integer): integer; stdcall;
function ContentGetSupportedFieldFlags(FieldIndex: integer): integer; stdcall;
function ContentSetValue(FileName: PAnsiChar; FieldIndex, UnitIndex, FieldType: integer;
FieldValue: PByte; Flags: integer): integer; stdcall;
function ContentSetValueW(FileName: PWideChar; FieldIndex, UnitIndex, FieldType: integer;
FieldValue: PByte; Flags: integer): integer; stdcall;
procedure ContentSendStateInformation(State: integer; Path: PAnsiChar); stdcall;
procedure ContentSendStateInformationW(State: integer; Path: PWideChar); stdcall;
function ContentEditValue(Handle: THandle; FieldIndex, UnitIndex, FieldType: integer;
FieldValue: PAnsiChar; MaxLen: integer; Flags: integer; LangIdentifier: PAnsiChar): integer; stdcall;
function ContentCompareFiles(ProgressCallback: TProgressCallbackProc; CompareIndex: integer;
FileName1, FileName2: PAnsiChar; FileDetails: PFileDetailsStruct): integer; stdcall;
function ContentCompareFilesW(ProgressCallback: TProgressCallbackProc; CompareIndex: integer;
FileName1, FileName2: PWideChar; FileDetails: PFileDetailsStruct): integer; stdcall;
}
function ContentFindValue(FileName: PAnsiChar;FieldIndex, UnitIndex, OperationIndex, FieldType,flags: integer; FieldValue: pbyte):integer; stdcall;
function ContentFindValueW(FileName: PWideChar;FieldIndex, UnitIndex, OperationIndex, FieldType,flags: integer; FieldValue: pbyte):integer; stdcall;
function ContentGetSupportedOperators(FieldIndex: integer; FieldOperators: pchar; maxlen: integer):integer; stdcall;
end.
|
unit IdGopher;
interface
uses
Classes,
IdEMailAddress, IdGlobal,
IdHeaderList, IdTCPClient;
type
TIdGopherMenuItem = class(TCollectionItem)
protected
FTitle: string;
FItemType: Char;
FSelector: string;
FServer: string;
FPort: Integer;
FGopherPlusItem: Boolean;
FGopherBlock: TIdHeaderList;
FViews: TStringlist;
FURL: string;
FAbstract: TStringList;
FAsk: TIdHeaderList;
fAdminEmail: TIdEMailAddressItem;
function GetLastModified: string;
function GetOrganization: string;
function GetLocation: string;
function GetGeog: string;
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
procedure DoneSettingInfoBlock; virtual;
property Title: string read FTitle write FTitle;
property ItemType: Char read FItemType write FItemType;
property Selector: string read FSelector write FSelector;
property Server: string read FServer write FServer;
property Port: Integer read FPort write FPort;
property GopherPlusItem: Boolean read FGopherPlusItem
write FGopherPlusItem;
property GopherBlock: TIdHeaderList read FGopherBlock;
property URL: string read FURL;
property Views: TStringList read FViews;
property AAbstract: TStringList read FAbstract;
property LastModified: string read GetLastModified;
property AdminEMail: TIdEMailAddressItem read fAdminEmail;
property Organization: string read GetOrganization;
property Location: string read GetLocation;
property Geog: string read GetGeog;
property Ask: TIdHeaderList read FAsk;
end;
TIdGopherMenu = class(TCollection)
protected
function GetItem(Index: Integer): TIdGopherMenuItem;
procedure SetItem(Index: Integer; const Value: TIdGopherMenuItem);
public
constructor Create; reintroduce;
function Add: TIdGopherMenuItem;
property Items[Index: Integer]: TIdGopherMenuItem read GetItem
write SetItem; default;
end;
TIdGopherMenuEvent = procedure(Sender: TObject;
MenuItem: TIdGopherMenuItem) of object;
TIdGopher = class(TIdTCPClient)
private
protected
FOnMenuItem: TIdGopherMenuEvent;
procedure DoMenu(MenuItem: TIdGopherMenuItem);
procedure ProcessGopherError;
function MenuItemFromString(stLine: string; Menu: TIdGopherMenu)
: TIdGopherMenuItem;
function ProcessDirectory(PreviousData: string = '';
const ExpectedLength: Integer = 0): TIdGopherMenu;
function LoadExtendedDirectory(PreviousData: string = '';
const ExpectedLength: Integer = 0): TIdGopherMenu;
procedure ProcessFile(ADestStream: TStream; APreviousData: string = '';
const ExpectedLength: Integer = 0);
procedure ProcessTextFile(ADestStream: TStream;
APreviousData: string = ''; const ExpectedLength: Integer = 0);
public
constructor Create(AOwner: TComponent); override;
function GetMenu(ASelector: string; IsGopherPlus: Boolean = False; AView:
string = ''):
TIdGopherMenu;
function Search(ASelector, AQuery: string): TIdGopherMenu;
procedure GetFile(ASelector: string; ADestStream: TStream; IsGopherPlus:
Boolean = False; AView: string = '');
procedure GetTextFile(ASelector: string; ADestStream: TStream; IsGopherPlus:
Boolean = False; AView: string = '');
function GetExtendedMenu(ASelector: string; AView: string = ''):
TIdGopherMenu;
published
property OnMenuItem: TIdGopherMenuEvent read FOnMenuItem write FOnMenuItem;
property Port default IdPORT_GOPHER;
end;
implementation
uses
IdComponent, IdException,
IdGopherConsts,
IdTCPConnection,
SysUtils;
procedure WriteToStream(AStream: TStream; AString: string);
begin
if Length(AString) > 0 then
AStream.Write(AString[1], Length(AString));
end;
constructor TIdGopher.Create(AOwner: TComponent);
begin
inherited;
Port := IdPORT_GOPHER;
end;
procedure TIdGopher.DoMenu(MenuItem: TIdGopherMenuItem);
begin
if Assigned(FOnMenuItem) then
FOnMenuItem(Self, MenuItem);
end;
procedure TIdGopher.ProcessGopherError;
var
ErrorNo: Integer;
ErrMsg: string;
begin
ErrMsg := AllData;
ErrorNo := StrToInt(Fetch(ErrMsg));
raise EIdProtocolReplyError.CreateError(ErrorNo, Copy(ErrMsg, 1, Length(ErrMsg)
- 5));
end;
function TIdGopher.MenuItemFromString(stLine: string;
Menu: TIdGopherMenu): TIdGopherMenuItem;
begin
stLine := Trim(stLine);
if Assigned(Menu) then
begin
Result := Menu.Add;
end
else
begin
Result := TIdGopherMenuItem.Create(nil);
end;
Result.Title := IdGlobal.Fetch(stLine, TAB);
if Length(Result.Title) > 0 then
begin
Result.ItemType := Result.Title[1];
end
else
begin
Result.ItemType := IdGopherItem_Error;
end;
Result.Title := Copy(Result.Title, 2, Length(Result.Title));
Result.Selector := Fetch(stLine, TAB);
Result.Server := Fetch(stLine, TAB);
Result.Port := StrToInt(Fetch(stLine, TAB));
stLine := Fetch(stLine, TAB);
Result.GopherPlusItem := ((Length(stLine) > 0) and
(stLine[1] = '+'));
end;
function TIdGopher.LoadExtendedDirectory(PreviousData: string = '';
const ExpectedLength: Integer = 0): TIdGopherMenu;
var
stLine: string;
gmnu: TIdGopherMenuItem;
begin
BeginWork(wmRead, ExpectedLength);
try
Result := TIdGopherMenu.Create;
gmnu := nil;
repeat
stLine := PreviousData + ReadLn;
PreviousData := '';
if (stLine <> '.') then
begin
if (Copy(stLine, 1, Length(IdGopherPlusInfo)) = IdGopherPlusInfo) then
begin
if (gmnu <> nil) then
begin
gmnu.DoneSettingInfoBlock;
DoMenu(gmnu);
end;
gmnu := MenuItemFromString(RightStr(stLine,
Length(stLine) - Length(IdGopherPlusInfo)), Result);
gmnu.GopherBlock.Add(stLine);
end
else
begin
if Assigned(gmnu) and (stLine <> '') then
begin
gmnu.GopherBlock.Add(stLine);
end;
end;
end
else
begin
if (gmnu <> nil) then
begin
DoMenu(gmnu);
end;
end;
until (stLine = '.') or not Connected;
finally EndWork(wmRead);
end;
end;
function TIdGopher.ProcessDirectory(PreviousData: string = '';
const ExpectedLength: Integer = 0): TIdGopherMenu;
var
stLine: string;
begin
BeginWork(wmRead, ExpectedLength);
try
Result := TIdGopherMenu.Create;
repeat
stLine := PreviousData + ReadLn;
PreviousData := '';
if (stLine <> '.') then
begin
DoMenu(MenuItemFromString(stLine, Result));
end;
until (stLine = '.') or not Connected;
finally
EndWork(wmRead);
end;
end;
procedure TIdGopher.ProcessTextFile(ADestStream: TStream; APreviousData: string =
'';
const ExpectedLength: Integer = 0);
begin
WriteToStream(ADestStream, APreviousData);
BeginWork(wmRead, ExpectedLength);
try
Capture(ADestStream, '.', True);
finally
EndWork(wmRead);
end;
end;
procedure TIdGopher.ProcessFile(ADestStream: TStream; APreviousData: string =
'';
const ExpectedLength: Integer = 0);
begin
BeginWork(wmRead, ExpectedLength);
try
WriteToStream(ADestStream, APreviousData);
ReadStream(ADestStream, -1, True);
ADestStream.Position := 0;
finally
EndWork(wmRead);
end;
end;
function TIdGopher.Search(ASelector, AQuery: string): TIdGopherMenu;
begin
Connect;
try
WriteLn(ASelector + TAB + AQuery);
Result := ProcessDirectory;
finally
Disconnect;
end;
end;
procedure TIdGopher.GetFile(ASelector: string; ADestStream: TStream;
IsGopherPlus: Boolean = False;
AView: string = '');
var
Reply: Char;
LengthBytes: Integer;
begin
Connect;
try
if not IsGopherPlus then
begin
WriteLn(ASelector);
ProcessFile(ADestStream);
end
else
begin
AView := Trim(Fetch(AView, ':'));
WriteLn(ASelector + TAB + '+' + AView);
ReadBuffer(Reply, 1);
case Reply of
'-':
begin
ReadLn;
ProcessGopherError;
end;
'+':
begin
LengthBytes := StrToInt(ReadLn);
case LengthBytes of
-1: ProcessTextFile(ADestStream);
-2: ProcessFile(ADestStream);
else
ProcessFile(ADestStream, '', LengthBytes);
end;
end;
else
begin
ProcessFile(ADestStream, Reply);
end;
end;
end;
finally
Disconnect;
end;
end;
function TIdGopher.GetMenu(ASelector: string; IsGopherPlus: Boolean = False;
AView: string = ''):
TIdGopherMenu;
var
Reply: Char;
LengthBytes: Integer;
begin
Result := nil;
Connect;
try
if not IsGopherPlus then
begin
WriteLn(ASelector);
Result := ProcessDirectory;
end
else
begin
WriteLn(ASelector + TAB + '+' + AView);
ReadBuffer(Reply, 1);
case Reply of
'-':
begin
ReadLn;
ProcessGopherError;
end;
'+':
begin
LengthBytes := StrToInt(ReadLn);
Result := ProcessDirectory('', LengthBytes);
end;
else
begin
Result := ProcessDirectory(Reply);
end;
end;
end;
finally
Disconnect;
end;
end;
function TIdGopher.GetExtendedMenu(ASelector, AView: string): TIdGopherMenu;
var
Reply: Char;
LengthBytes: Integer;
begin
Result := nil;
Connect;
try
WriteLn(ASelector + TAB + '$' + AView);
ReadBuffer(Reply, 1);
case Reply of
'-':
begin
ReadLn;
ProcessGopherError;
end;
'+':
begin
LengthBytes := StrToInt(ReadLn);
Result := LoadExtendedDirectory('', LengthBytes);
end;
else
Result := ProcessDirectory(Reply);
end;
finally
Disconnect;
end;
end;
procedure TIdGopher.GetTextFile(ASelector: string; ADestStream: TStream;
IsGopherPlus: Boolean; AView: string);
var
Reply: Char;
LengthBytes: Integer;
begin
Connect;
try
if not IsGopherPlus then
begin
WriteLn(ASelector);
ProcessTextFile(ADestStream);
end
else
begin
AView := Trim(Fetch(AView, ':'));
WriteLn(ASelector + TAB + '+' + AView);
ReadBuffer(Reply, 1);
case Reply of
'-':
begin
ReadLn;
ProcessGopherError;
end;
'+':
begin
LengthBytes := StrToInt(ReadLn);
case LengthBytes of
-1: ProcessTextFile(ADestStream);
-2: ProcessFile(ADestStream);
else
ProcessTextFile(ADestStream, '', LengthBytes);
end;
end;
else
begin
ProcessTextFile(ADestStream, Reply);
end;
end;
end;
finally
Disconnect;
end;
end;
function TIdGopherMenu.Add: TIdGopherMenuItem;
begin
Result := TIdGopherMenuItem(inherited Add);
end;
constructor TIdGopherMenu.Create;
begin
inherited Create(TIdGopherMenuItem);
end;
function TIdGopherMenu.GetItem(Index: Integer): TIdGopherMenuItem;
begin
result := TIdGopherMenuItem(inherited Items[index]);
end;
procedure TIdGopherMenu.SetItem(Index: Integer;
const Value: TIdGopherMenuItem);
begin
inherited SetItem(Index, Value);
end;
constructor TIdGopherMenuItem.Create(ACollection: TCollection);
begin
inherited;
FGopherBlock := TIdHeaderList.Create;
FGopherBlock.Sorted := False;
FGopherBlock.Duplicates := dupAccept;
FGopherBlock.UnfoldLines := False;
FGopherBlock.FoldLines := False;
FViews := TStringList.Create;
FAbstract := TStringList.Create;
FAsk := TIdHeaderList.Create;
fAdminEmail := TIdEMailAddressItem.Create(nil);
FAbstract.Sorted := False;
end;
destructor TIdGopherMenuItem.Destroy;
begin
FreeAndNil(fAdminEmail);
FreeAndNil(FAsk);
FreeAndNil(FAbstract);
FreeAndNil(FGopherBlock);
FreeAndNil(FViews);
inherited;
end;
procedure TIdGopherMenuItem.DoneSettingInfoBlock;
const
BlockTypes: array[1..3] of string = ('+VIEWS', '+ABSTRACT', '+ASK');
var
idx: Integer;
line: string;
procedure ParseBlock(Block: TStringList);
begin
Inc(idx);
while (idx < FGopherBlock.Count) and
(FGopherBlock[idx][1] = ' ') do
begin
Block.Add(TrimLeft(FGopherBlock[idx]));
Inc(idx);
end;
Dec(idx);
end;
begin
idx := 0;
while (idx < FGopherBlock.Count) do
begin
Line := FGopherBlock[idx];
Line := UpperCase(Fetch(Line, ':'));
case PosInStrArray(Line, BlockTypes) of
{+VIEWS:}
0: ParseBlock(FViews);
{+ABSTRACT:}
1: ParseBlock(FAbstract);
{+ASK:}
2: ParseBlock(FAsk);
end;
Inc(idx);
end;
fAdminEmail.Text := FGopherBlock.Values[' Admin'];
end;
function TIdGopherMenuItem.GetGeog: string;
begin
Result := FGopherBlock.Values[' Geog'];
end;
function TIdGopherMenuItem.GetLastModified: string;
begin
Result := FGopherBlock.Values[' Mod-Date'];
end;
function TIdGopherMenuItem.GetLocation: string;
begin
Result := FGopherBlock.Values[' Loc'];
end;
function TIdGopherMenuItem.GetOrganization: string;
begin
Result := FGopherBlock.Values[' Org'];
end;
end.
|
unit Ths.Erp.Database.Table.StokHareketi;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table,
Ths.Erp.Database.Table.AyarStokHareketTipi;
type
TStokHareketi = class(TTable)
private
FStokKodu: TFieldDB;
FMiktar: TFieldDB;
FTutar: TFieldDB;
FGirisCikisTipID: TFieldDB;
FGirisCikisTip: TFieldDB;
FTarih: TFieldDB;
protected
vStokHareketTipi: TAyarStokHareketTipi;
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property StokKodu: TFieldDB read FStokKodu write FStokKodu;
Property Miktar: TFieldDB read FMiktar write FMiktar;
Property Tutar: TFieldDB read FTutar write FTutar;
Property GirisCikisTipID: TFieldDB read FGirisCikisTipID write FGirisCikisTipID;
Property GirisCikisTip: TFieldDB read FGirisCikisTip write FGirisCikisTip;
Property Tarih: TFieldDB read FTarih write FTarih;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TStokHareketi.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'stok_hareketi';
SourceCode := '1000';
FStokKodu := TFieldDB.Create('stok_kodu', ftString, '', 0, False);
FMiktar := TFieldDB.Create('miktar', ftFloat, 0, 0, False);
FTutar := TFieldDB.Create('tutar', ftFloat, 0, 0, False);
FGirisCikisTipID := TFieldDB.Create('giris_cikis_tip_id', ftInteger, 0, 0, True, True);
FGirisCikisTip := TFieldDB.Create('giris_cikis_tip', ftString, 0, 0, False);
FTarih := TFieldDB.Create('tarih', ftDateTime, 0, 0, False);
end;
procedure TStokHareketi.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
vStokHareketTipi := TAyarStokHareketTipi.Create(Self.Database);
try
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FStokKodu.FieldName,
TableName + '.' + FMiktar.FieldName,
TableName + '.' + FTutar.FieldName,
TableName + '.' + FGirisCikisTipID.FieldName,
ColumnFromIDCol(vStokHareketTipi.Deger.FieldName, vStokHareketTipi.TableName, FGirisCikisTipID.FieldName, FGirisCikisTip.FieldName, TableName),
TableName + '.' + FTarih.FieldName+'::date'
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FStokKodu.FieldName).DisplayLabel := 'Stok Kodu';
Self.DataSource.DataSet.FindField(FMiktar.FieldName).DisplayLabel := 'Miktar';
Self.DataSource.DataSet.FindField(FTutar.FieldName).DisplayLabel := 'Tutar';
Self.DataSource.DataSet.FindField(FGirisCikisTipID.FieldName).DisplayLabel := 'Giriş Çıkış Tip ID';
Self.DataSource.DataSet.FindField(FGirisCikisTip.FieldName).DisplayLabel := 'Hareket Tipi';
Self.DataSource.DataSet.FindField(FTarih.FieldName).DisplayLabel := 'Tarih';
finally
vStokHareketTipi.Free;
end;
end;
end;
end;
procedure TStokHareketi.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
vStokHareketTipi := TAyarStokHareketTipi.Create(Self.Database);
try
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FStokKodu.FieldName,
TableName + '.' + FMiktar.FieldName,
TableName + '.' + FTutar.FieldName,
TableName + '.' + FGirisCikisTipID.FieldName,
ColumnFromIDCol(vStokHareketTipi.Deger.FieldName, vStokHareketTipi.TableName, FGirisCikisTipID.FieldName, FGirisCikisTip.FieldName, TableName),
TableName + '.' + FTarih.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FStokKodu.Value := FormatedVariantVal(FieldByName(FStokKodu.FieldName).DataType, FieldByName(FStokKodu.FieldName).Value);
FMiktar.Value := FormatedVariantVal(FieldByName(FMiktar.FieldName).DataType, FieldByName(FMiktar.FieldName).Value);
FTutar.Value := FormatedVariantVal(FieldByName(FTutar.FieldName).DataType, FieldByName(FTutar.FieldName).Value);
FGirisCikisTipID.Value := FormatedVariantVal(FieldByName(FGirisCikisTipID.FieldName).DataType, FieldByName(FGirisCikisTipID.FieldName).Value);
FTarih.Value := FormatedVariantVal(FieldByName(FTarih.FieldName).DataType, FieldByName(FTarih.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
finally
vStokHareketTipi.Free;
end;
end;
end;
end;
procedure TStokHareketi.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FStokKodu.FieldName,
FMiktar.FieldName,
FTutar.FieldName,
FGirisCikisTipID.FieldName,
FTarih.FieldName
]);
NewParamForQuery(QueryOfInsert, FStokKodu);
NewParamForQuery(QueryOfInsert, FMiktar);
NewParamForQuery(QueryOfInsert, FTutar);
NewParamForQuery(QueryOfInsert, FGirisCikisTipID);
NewParamForQuery(QueryOfInsert, FTarih);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TStokHareketi.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FStokKodu.FieldName,
FMiktar.FieldName,
FTutar.FieldName,
FGirisCikisTipID.FieldName,
FTarih.FieldName
]);
NewParamForQuery(QueryOfUpdate, FStokKodu);
NewParamForQuery(QueryOfUpdate, FMiktar);
NewParamForQuery(QueryOfUpdate, FTutar);
NewParamForQuery(QueryOfUpdate, FGirisCikisTipID);
NewParamForQuery(QueryOfUpdate, FTarih);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TStokHareketi.Clone():TTable;
begin
Result := TStokHareketi.Create(Database);
Self.Id.Clone(TStokHareketi(Result).Id);
FStokKodu.Clone(TStokHareketi(Result).FStokKodu);
FMiktar.Clone(TStokHareketi(Result).FMiktar);
FTutar.Clone(TStokHareketi(Result).FTutar);
FGirisCikisTipID.Clone(TStokHareketi(Result).FGirisCikisTipID);
FTarih.Clone(TStokHareketi(Result).FTarih);
end;
end.
|
unit ChilliSauce;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, URLMon, ShellApi, Vcl.Grids,
Vcl.StdCtrls, Vcl.ExtCtrls, IdHashMessageDigest, idHash;
type
TChilliSauceV1 = class( TForm )
StringGrid1 : TStringGrid;
Log : TMemo;
Timer1 : TTimer;
Button1 : TButton;
function DownloadFile( sourceURL, DestFile : string ) : Boolean;
procedure getFile( );
procedure FormCreate( Sender : TObject );
procedure Timer1Timer( Sender : TObject );
procedure loadFile( );
procedure readGrid( );
function addQuotes( s : String ) : String;
function MD5File( const FileName : string ) : string;
procedure HashItUp( );
function GetFileNames( Path : string ) : TStringList;
function isNew( hash : String ) : Boolean;
procedure Button1Click( Sender : TObject );
function addLog( msg : String ) : Boolean;
procedure deleteTempFiles( );
procedure FormClose( Sender : TObject; var Action : TCloseAction );
private
{ Private declarations }
public
{ Public declarations }
end;
const
CompletedTorsDir = 'D:\Movies\Completed .torrent files\';
ToAddTorsDir = 'D:\Movies\To download .torrent\';
var
ChilliSauceV1 : TChilliSauceV1;
LoadedFilesHash : TStringList;
implementation
{$R *.dfm}
function TChilliSauceV1.addLog( msg : String ) : Boolean;
var
I : Integer;
begin
// add log wraps add to memo and print time with the string in one function
Log.Lines.Add( '' );
msg := DateTimeToStr( Now ) + ' : ' + msg;
for I := 1 to msg.length do
Log.Lines[Log.Lines.Count - 1] := Log.Lines[Log.Lines.Count - 1] + msg[I];
end;
function TChilliSauceV1.addQuotes( s : String ) : String;
var
I : Integer;
temp : String;
begin
// add quotes before and after each value
// so the delimiter can be proccessed properly
// if a CSV doesn't have quotes, Delphi takes SPACE as a delimiter too.
temp := '';
for I := 1 to s.length do
if s[I] = ',' then
temp := temp + '","'
else
temp := temp + s[I];
temp := '"' + temp + '"';
Result := temp;
end;
procedure TChilliSauceV1.Button1Click( Sender : TObject );
begin
// force-refresh button, call the timer1 proc
Screen.Cursor := crHourGlass;
//Button1.Enabled := False;
Timer1Timer( Sender );
// Button1.Enabled := True;
Screen.Cursor := crDefault;
end;
procedure TChilliSauceV1.deleteTempFiles;
var
tempFiles : TStringList;
I : Integer;
begin
(*
generates a list of all files in the temp folder and deletes them
should be called while exiting
*)
tempFiles := TStringList.Create;
tempFiles := GetFileNames( GetCurrentDir + '\files\temp\' );
for I := 0 to tempFiles.Count - 1 do
DeleteFile( GetCurrentDir + '\files\temp\' + tempFiles[I] );
end;
function TChilliSauceV1.DownloadFile( sourceURL, DestFile : string ) : Boolean;
begin
// download the file from the sourceURL and save it to the DestFile
(*
the interesting thing about this function is it can directly be used in an if statement where
it will download a file and return a true if the download was succesful, preventing errors that can
occir if we try working with a file without downloading it
*)
try
Result := UrlDownloadToFile( nil, PChar( sourceURL ), PChar( DestFile ), 0,
nil ) = 0;
except
Result := False;
end;
end;
procedure TChilliSauceV1.FormClose( Sender : TObject;
var Action : TCloseAction );
begin
deleteTempFiles( );
end;
procedure TChilliSauceV1.FormCreate( Sender : TObject );
begin
Log.Text := '';
Timer1.Interval := 30 * 1000; // set refresh rate
LoadedFilesHash := TStringList.Create;
(* the following code checks for directories and files that should be in place.
if the 'files' directory which holds the CSV files for 'downloaded' and 'to download' files
doesn't exist, create it
if there is an error while creating it, ask for relaunch in ADMIN mode
also, tell the user what's going on in the Log Memo.
most other messages that are being printed to the log screen are self-explanatory
it also checks if the 'completed' torrents file (which contains hashes generated from .TORRENT files) exists
if that file is there, it is loaded into memory.
*)
if ( ( ( DirectoryExists( GetCurrentDir + '\files' ) ) AND
( DirectoryExists( GetCurrentDir + '\files\temp' ) ) ) ) then
begin
addLog( '"files" Directory exists, initilizing program.' );
addLog( 'loading files.' );
try
LoadedFilesHash.LoadFromFile( GetCurrentDir + '\files\completed.csv' );
except
addLog( 'Failed to load required files.' );
end;
end
else
begin
try
CreateDir( GetCurrentDir + '\files' );
CreateDir( GetCurrentDir + '\files\temp' );
addLog( '"files" Directory does not exist, creating directory' );
addLog( 'Directory created, initializing program.' )
except
ShowMessage( 'Please re-launch the program as administrator.' );
Exit;
end;
end;
// Timer1Timer( Sender );
end;
procedure TChilliSauceV1.getFile;
var
sURL, sFile : String;
begin
(* SourceURL and SaveFile :
URL from where the CSV is to be fetched and the location it is to be saved at
the DownloadFile function is explained in its implementation
*)
sURL := 'some-google-sheets-file-link';
// the Google Sheets file being used here should be published to Web. The queue takes about 3 minutes to refresh after that.
sFile := GetCurrentDir + '\files\Dloads.csv';
if DownloadFile( sURL, sFile ) then
begin
addLog( 'que Fetch succesful' );
end
else
addLog( 'Error fetching file, check internet connection ' );
end;
function TChilliSauceV1.GetFileNames( Path : string ) : TStringList;
var
SR : TSearchRec;
dest : TStringList;
begin
(* get a list of all files within the folder 'Path'.
'Path' must have a trailing BACK-SLASH '\' to indicate path is a directory and not a file.
the '*.*' filter can be replaced by any file type you want to search for.
since torrent files are usually marked as '*.torrent' i'm using that as a filter;
*)
dest := TStringList.Create;
if FindFirst( Path + '*.torrent', faAnyFile, SR ) = 0 then
repeat
dest.Add( SR.Name );
until FindNext( SR ) <> 0;
FindClose( SR );
Result := dest;
end;
procedure TChilliSauceV1.HashItUp;
var
fileNamesForHash : TStringList;
I : Integer;
begin
// initialize stringlists
fileNamesForHash := TStringList.Create;
// get a list of all files in the completed dir
fileNamesForHash := GetFileNames( CompletedTorsDir );
// add the complete address to the file
for I := 0 to fileNamesForHash.Count - 1 do
fileNamesForHash.Strings[I] := CompletedTorsDir +
fileNamesForHash.Strings[I];
Screen.Cursor := crHourGlass;
// hash up all the files ~ and show the hourglass/wheel style point while at it :P
for I := 2 to fileNamesForHash.Count - 1 do
LoadedFilesHash.Add( MD5File( fileNamesForHash[I] ) );
Screen.Cursor := crDefault;
// then save the hashes to a file for later use
LoadedFilesHash.SaveToFile( GetCurrentDir + '\files\completed.csv' );
addLog( 'Hash done' );
end;
function TChilliSauceV1.isNew( hash : String ) : Boolean;
var
I, tryPos : Integer;
res : Boolean;
begin
res := True;
// checks if a hash already exists in the generated list
for I := 0 to LoadedFilesHash.Count - 1 do
if hash = LoadedFilesHash.Strings[I] then
begin
res := False;
Result := res;
Exit;
end;
Result := res;
end;
procedure TChilliSauceV1.loadFile;
var
ldStr : TStringList;
I : Integer;
cTxt : String;
begin
// init strlist and load the file we just fetched from google sheets
ldStr := TStringList.Create;
ldStr.LoadFromFile( GetCurrentDir + '\files\DLoads.csv' );
StringGrid1.RowCount := ldStr.Count + 1;
// StringGrid1.ColCount := 10;
// load the string list to strGrid by adding quotes to the CSV
for I := 0 to ldStr.Count - 1 do
StringGrid1.Rows[I].CommaText := addQuotes( ldStr.Strings[I] );
addLog( 'File loaded.' );
end;
function TChilliSauceV1.MD5File( const FileName : string ) : string;
var
IdMD5 : TIdHashMessageDigest5;
FS : TFileStream;
begin
// Load file 'FileName'
// Hash the files, and return the hash
// free memory when done
IdMD5 := TIdHashMessageDigest5.Create;
FS := TFileStream.Create( FileName, fmOpenRead or fmShareDenyWrite );
try
Result := IdMD5.HashStreamAsHex( FS )
finally
FS.Free;
IdMD5.Free;
end;
end;
procedure TChilliSauceV1.readGrid;
var
currFileName : String;
I, J : Integer;
Empty : Boolean;
begin
// read the grid
for I := 1 to StringGrid1.RowCount - 1 do
begin
// if any of the four reqd. fields in a row are empty, do not consider that particular row
Empty := False;
for J := 0 to 4 do
if StringGrid1.Cells[J, I] = '' then
Empty := True;
if NOT ( Empty ) then
begin
// construct the full name for a torrent file ~ including the directories
currFileName := GetCurrentDir + '\files\temp\' + StringGrid1.Cells[0, I] +
'.' + StringGrid1.Cells[1, I] + '.' + StringGrid1.Cells[3, I] + '.' +
StringGrid1.Cells[4, I] + '.torrent';
// add hashes to the grid ~ JLT :P
(*
the following macro downloads the files listed on the strGrid in a temp. folder
the file is then used to create a hash ~ MD5 and check if the same file had recently been queued/downloaded
Namex is the full name of the file
*)
if NOT ( StringGrid1.Cells[5, I] = '' ) then
StringGrid1.Cells[5, I] := MD5File( currFileName );
if DownloadFile( StringGrid1.Cells[2, I], currFileName ) then
if isNew( MD5File( currFileName ) ) then
begin
LoadedFilesHash.Add( MD5File( currFileName ) );
StringGrid1.Cells[5, I] := MD5File( currFileName );
LoadedFilesHash.SaveToFile( GetCurrentDir + '\files\completed.csv' );
currFileName := StringGrid1.Cells[0, I] + '.' + StringGrid1.Cells
[1, I] + '.' + StringGrid1.Cells[3, I] + '.' + StringGrid1.Cells
[4, I] + '.torrent';
CopyFile( PChar( GetCurrentDir + '\files\temp\' + currFileName ),
PChar( ToAddTorsDir + currFileName ), False );
addLog( 'Added New Torrent' );
end;
end;
end;
addLog( 'Grid read.' );
end;
procedure TChilliSauceV1.Timer1Timer( Sender : TObject );
begin
// do all the functions
Screen.Cursor := crHourGlass;
// Button1.Enabled := True;
getFile( );
loadFile( );
HashItUp( );
readGrid( );
//Button1.Enabled := False;
Screen.Cursor := crDefault;
end;
end.
|
unit Bezier;
interface
uses SysUtils, Classes, Math, Points;
function CalculateBezierCurveSplines(initPoints: TList; curvePointStep: Real): TList;
implementation
function Factorial(n: Integer): Longint;
begin
if (n = 0) then
Result := 1
else
Result := n * Factorial(n - 1);
end;
function Permutations(n, i: Integer): Longint;
begin
Result := round(Factorial(n) / (Factorial(i) * Factorial(n - i)));
end;
function CalculateCurveLength(initPoints: TList; skip: Integer): Integer;
var left : Integer;
begin
left := initPoints.Count - skip;
if left < 4 then Result := left else Result := 4
end;
function CalculateBezierCurve(initPoints: TList; curvePointStep: Real): TList;
var
t,x,y, temp: Real;
n, i: Integer;
point : TPoint;
resultPoints: TList;
begin
resultPoints := TList.Create;
resultPoints.Clear;
n := initPoints.Count - 1;
t := 0;
while t <= 1 do
begin
x := 0;
y := 0;
for i := 0 to n do
begin
temp := Permutations(n, i) * power(t, i) * power(1-t, (n-i));
point := TPoint(initPoints[i]);
x := x + temp * point.X;
y := y + temp * point.Y;
end;
point := TPoint.Create(x, y, '');
resultPoints.Add(point);
t := t + 0.001;
end;
Result := resultPoints;
end;
function ProceedCurve(initPoints: TList; skip, prevCurveLength, currCurveLength, nextCurveLength: Integer): TList;
var
points : TList;
i, last : Integer;
x, y, l : Real;
begin
points := TList.Create;
points.Clear();
for i:= 0 to currCurveLength - 1 do points.Add(initPoints[skip + i]);
// if not first curve we replace first point and use prev point
if prevCurveLength <> 0 then
begin
l := prevCurveLength / currCurveLength;
x := (TPoint(points[0]).X + l * TPoint(points[1]).X) / (1 + l);
y := (TPoint(points[0]).Y + l * TPoint(points[1]).Y) / (1 + l);
// replace first point
points[0] := TPoint.Create(x, y, '');
end;
// if not last curve we replace last point
if nextCurveLength <> 0 then
begin
last := points.Count - 1;
l := currCurveLength / nextCurveLength;
x := (TPoint(points[last - 1]).X + l * TPoint(points[last]).X) / (1 + l);
y := (TPoint(points[last - 1]).Y + l * TPoint(points[last]).Y) / (1 + l);
// replace last point
points[last] := TPoint.Create(x, y, '');
end;
Result := CalculateBezierCurve(points, 0.001);
end;
function CalculateBezierCurveSplines(initPoints: TList; curvePointStep: Real): TList;
var
initPointsCount, skip, left, prevCurveLength, currCurveLength, nextCurveLength : Integer;
pointsList : TList;
curvesList: TList;
begin
pointsList := TList.Create;
pointsList.Clear;
curvesList := TList.Create;
curvesList.Clear;
skip := 0;
prevCurveLength := 0;
currCurveLength := 0;
nextCurveLength := 0;
initPointsCount := initPoints.Count;
while skip < initPointsCount do
begin
left := initPointsCount - skip;
currCurveLength := CalculateCurveLength(initPoints, skip);
// last curve
if currCurveLength >= left then
begin
pointsList := ProceedCurve(initPoints, skip, prevCurveLength, currCurveLength, 0);
curvesList.Add(pointsList);
break;
end else
begin
nextCurveLength := CalculateCurveLength(initPoints, skip + currCurveLength - 2);
pointsList := ProceedCurve(initPoints, skip, prevCurveLength, currCurveLength, nextCurveLength);
curvesList.Add(pointsList);
skip := skip + currCurveLength - 2;
prevCurveLength := currCurveLength;
end;
end;
Result := curvesList;
end;
end.
|
unit uMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ScktComp, StdCtrls, ExtCtrls;
type
TfrmMain = class(TForm)
grpButtons: TGroupBox;
spl1: TSplitter;
mmoLog: TMemo;
lb1: TLabel;
edtPort: TEdit;
btnGetState: TButton;
btnInit: TButton;
btnExeCommad: TButton;
btnGetResult: TButton;
lb2: TLabel;
edtMessage: TEdit;
btnConnect: TButton;
btnDisconnect: TButton;
clSock: TClientSocket;
procedure btnConnectClick(Sender: TObject);
procedure clSockConnect(Sender: TObject; Socket: TCustomWinSocket);
procedure btnDisconnectClick(Sender: TObject);
procedure btnGetStateClick(Sender: TObject);
procedure clSockDisconnect(Sender: TObject; Socket: TCustomWinSocket);
procedure clSockRead(Sender: TObject; Socket: TCustomWinSocket);
procedure clSockError(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
procedure btnInitClick(Sender: TObject);
procedure btnExeCommadClick(Sender: TObject);
procedure btnGetResultClick(Sender: TObject);
private
{ Private declarations }
procedure blockButtons(const state:boolean);
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
procedure TfrmMain.btnConnectClick(Sender: TObject);
begin
mmoLog.Lines.Clear;
try
clSock.Host:='127.0.0.1';
clSock.Port:=StrToIntDef(edtPort.Text,7777);
clSock.Active:=true;
mmoLog.Lines.add('Сервер подключен');
Application.ProcessMessages;
except
on e:Exception do
begin
mmoLog.Lines.add('Ошибка соединения - '+e.Message);
end;
end
end;
procedure TfrmMain.clSockConnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
btnGetState.Enabled:=true;
btnInit.Enabled:=true;
end;
procedure TfrmMain.btnDisconnectClick(Sender: TObject);
begin
clSock.Active:=False;
end;
procedure TfrmMain.btnGetStateClick(Sender: TObject);
begin
blockButtons(true);
mmoLog.Lines.Clear;
if clSock.Socket.Connected then
begin
mmoLog.Lines.add('Отправка команды GetState');
clSock.Socket.SendText('GetState');
end
else
mmoLog.Lines.add('Сервер отключен');
end;
procedure TfrmMain.clSockDisconnect(Sender: TObject;
Socket: TCustomWinSocket);
begin
mmoLog.Lines.add('Сервер отключен');
end;
procedure TfrmMain.clSockRead(Sender: TObject; Socket: TCustomWinSocket);
begin
blockButtons(false);
mmoLog.Lines.Clear;
mmoLog.Lines.add('Ответ сервера: '+ clSock.Socket.ReceiveText);
end;
procedure TfrmMain.clSockError(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
begin
mmoLog.Lines.Add('Ошибка связи: '+ inttostr(ErrorCode))
end;
procedure TfrmMain.btnInitClick(Sender: TObject);
begin
blockButtons(true);
mmoLog.Lines.Clear;
if clSock.Socket.Connected then
begin
mmoLog.Lines.add('Отправка команды Init');
clSock.Socket.SendText('Init');
end
else
mmoLog.Lines.add('Сервер отключен');
end;
procedure TfrmMain.btnExeCommadClick(Sender: TObject);
begin
blockButtons(true);
mmoLog.Lines.Clear;
if clSock.Socket.Connected then
begin
mmoLog.Lines.add('Отправка команды Run');
clSock.Socket.SendText('Run,'+edtMessage.Text);
end
else
mmoLog.Lines.add('Сервер отключен');
end;
procedure TfrmMain.btnGetResultClick(Sender: TObject);
begin
blockButtons(true);
mmoLog.Lines.Clear;
if clSock.Socket.Connected then
begin
mmoLog.Lines.add('Отправка команды GetMessage');
clSock.Socket.SendText('GetMessage');
end
else
mmoLog.Lines.add('Сервер отключен');
end;
procedure TfrmMain.blockButtons(const state: boolean);
begin
if state then
begin
btnGetState.Enabled:=false;
btnExeCommad.Enabled:=false;
btnInit.Enabled:=false;
btnGetResult.Enabled:=false;
btnConnect.Enabled:=false;
btnDisconnect.Enabled:=false;
end
else
begin
btnGetState.Enabled:=true;
btnExeCommad.Enabled:=true;
btnInit.Enabled:=true;
btnGetResult.Enabled:=true;
btnConnect.Enabled:=true;
btnDisconnect.Enabled:=true;
end;
end;
end.
|
unit AComandoFiscalFiltro;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, StdCtrls, Mask, numericos,
ComCtrls, Componentes1, Buttons, ExtCtrls, PainelGradiente, UnDados, UnECF;
type
TFComandoFiscalFiltro = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PPeriodo: TPanelColor;
PanelColor2: TPanelColor;
BOk: TBitBtn;
BCancelar: TBitBtn;
EDatInicio: TCalendario;
EDatFim: TCalendario;
Label1: TLabel;
Label2: TLabel;
PCRZ: TPanelColor;
ECRZInicial: Tnumerico;
ECRZFinal: Tnumerico;
Label3: TLabel;
Label4: TLabel;
PCOO: TPanelColor;
Label5: TLabel;
Label6: TLabel;
ECOOInicial: Tnumerico;
ECOOFinal: Tnumerico;
PTipoFiltro: TPanelColor;
Label7: TLabel;
CPeriodo: TRadioButton;
CCRZ: TRadioButton;
CCOO: TRadioButton;
PanelColor1: TPanelColor;
CGerarArquivo: TCheckBox;
PNumeroECF: TPanelColor;
Label8: TLabel;
ENumeroECF: TComboBoxColor;
PFormatoArquivo: TPanelColor;
CSintegra: TRadioButton;
CSped: TRadioButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BOkClick(Sender: TObject);
procedure BCancelarClick(Sender: TObject);
procedure CPeriodoClick(Sender: TObject);
private
{ Private declarations }
VprAcao : Boolean;
VprDFiltro : TRBDFiltroMenuFiscalECF;
FunECF :TRBFuncoesECF;
procedure ConfiguraTela;
procedure CarDClasse;
function DadosValidos : string;
public
{ Public declarations }
function FiltraMenuFiscal(VpaDFiltro : TRBDFiltroMenuFiscalECF):boolean;
end;
var
FComandoFiscalFiltro: TFComandoFiscalFiltro;
implementation
uses APrincipal, FunData, FunObjeto,ConstMsg;
{$R *.DFM}
{ **************************************************************************** }
procedure TFComandoFiscalFiltro.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
FunECF := TRBFuncoesECF.cria(nil,FPrincipal.BaseDados);
VprAcao := false;
EDatInicio.Date := PrimeiroDiaMes(date);
EDatFim.date := UltimoDiaMes(date);
end;
{ *************************************************************************** }
procedure TFComandoFiscalFiltro.BCancelarClick(Sender: TObject);
begin
close;
end;
{ *************************************************************************** }
procedure TFComandoFiscalFiltro.BOkClick(Sender: TObject);
Var
VpfResultado : String;
begin
VpfResultado := DadosValidos;
if VpfResultado <> '' then
begin
aviso(VpfResultado);
end
else
begin
VprAcao := true;
close;
end;
end;
{******************************************************************************}
procedure TFComandoFiscalFiltro.CarDClasse;
begin
VprDFiltro.DatInicio := EDatInicio.Date;
VprDFiltro.DatFim := EDatFim.Date;
VprDFiltro.NumIntervaloCRZInicio := ECRZInicial.AsInteger;
VprDFiltro.NumIntervaloCRZFim := ECRZFinal.AsInteger;
VprDFiltro.NumIntervaloCOOInicio := ECOOInicial.AsInteger;
VprDFiltro.NumIntervaloCOOFim := ECOOFinal.AsInteger;
VprDFiltro.IndGerarArquivo := CGerarArquivo.Checked;
end;
{******************************************************************************}
procedure TFComandoFiscalFiltro.ConfiguraTela;
begin
if VprDFiltro.IndMostrarNumECF then
begin
FunECF.CarNumerosECF(ENumeroECF.Items);
PNumeroECF.Visible := true;
PPeriodo.Visible := true;
PTipoFiltro.Visible := false;
end;
CPeriodo.Visible := VprDFiltro.IndMostrarPeriodo;
CCRZ.Visible := VprDFiltro.IndMostrarCRZ;
CCOO.Visible := VprDFiltro.IndMostrarCOO;
CGerarArquivo.Visible := VprDFiltro.IndMostrarGerarArquivo;
PFormatoArquivo.Visible := VprDFiltro.IndMostrarFormatoArquivo;
if PFormatoArquivo.Visible then
Self.Height := Self.Height + PFormatoArquivo.Height;
end;
{******************************************************************************}
procedure TFComandoFiscalFiltro.CPeriodoClick(Sender: TObject);
begin
AlterarVisibleDet([PPeriodo,PCRZ,PCOO],false);
case TCheckBox(Sender).Tag of
1 : PPeriodo.Visible := true;
2 : PCRZ.Visible := true;
3 : PCOO.Visible := true;
end;
Self.Height := PainelGradiente1.Top+ PainelGradiente1.Height++PCRZ.Height+PanelColor2.Height+PTipoFiltro.Height+PTipoFiltro.Height;
end;
{******************************************************************************}
function TFComandoFiscalFiltro.DadosValidos: string;
begin
result := '';
if VprDFiltro.IndMostrarNumECF then
begin
if ENumeroECF.ItemIndex = -1 then
result := 'NÚMERO DO ECF NÃO PREENCHIDO!!!'#13'É necessário preencher o numero de serie do equipamento ECF.';
end;
end;
{ *************************************************************************** }
function TFComandoFiscalFiltro.FiltraMenuFiscal(VpaDFiltro: TRBDFiltroMenuFiscalECF): boolean;
begin
VprDFiltro := VpaDFiltro;
CPeriodoClick(CPeriodo);
ConfiguraTela;
showmodal;
result := vprAcao;
if result then
begin
VpaDFiltro.DatInicio := EDatInicio.Date;
VpaDFiltro.DatFim := EDatFim.Date;
VpaDFiltro.NumIntervaloCRZInicio := ECRZInicial.AsInteger;
VpaDFiltro.NumIntervaloCRZFim := ECRZFinal.AsInteger;
VpaDFiltro.IndGerarArquivo:= CGerarArquivo.Checked;
VpaDFiltro.NumSerieECF := ENumeroECF.Text;
if CPeriodo.Checked then
VpaDFiltro.TipFiltro := tfPeriodo
else
if CCRZ.Checked then
VpaDFiltro.TipFiltro := tfCRZ
else
if CCOO.Checked then
VpaDFiltro.TipFiltro := tfCOO;
if CSintegra.Checked then
VpaDFiltro.TipFormatoArquivo := faSintegra
else
VpaDFiltro.TipFormatoArquivo := faSped;
end;
end;
{ *************************************************************************** }
procedure TFComandoFiscalFiltro.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
FunECF.Free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFComandoFiscalFiltro]);
end.
|
unit MasterMind.Evaluator;
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}
interface
uses
MasterMind.API;
type
TMasterMindGuessEvaluator = class(TInterfacedObject, IGuessEvaluator)
private
function ColorInCodeButWasNotAlreadyMarkedAsCorrectMatch(const Guess, CodeToBeGuessed: TMasterMindCode;
const GuessIndex: Integer): Boolean;
function GuessedColorIsAtCurrentPositionButIsNoCorrectMatch(const Guess, CodeToBeGuessed: TMasterMindCode;
const CurrentPosition, GuessPosition: Integer): Boolean;
function ColorCorrectAtPosition(const Guess, CodeToBeGuessed: TMasterMindCode; const Position: Integer): Boolean;
function ColorCorrectAtAnyPosition(const Guess, CodeToBeGuessed: TMasterMindCode; const Positions: array of Integer): Boolean;
procedure InitializeResultWithNoMatches(out EvaluationResult: TGuessEvaluationResult);
procedure SetCorrectMatchesInResult(var EvaluationResult: TGuessEvaluationResult; const CodeToBeGuessed, Guess: TMasterMindCode);
procedure SetWrongPlacesInResult(var EvaluationResult: TGuessEvaluationResult; const CodeToBeGuessed, Guess: TMasterMindCode);
procedure SortResult(var EvaluationResult: TGuessEvaluationResult);
function CountExactMatches(const EvaluationResult: TGuessEvaluationResult): Integer;
function CountWrongPlaces(const EvaluationResult: TGuessEvaluationResult): Integer;
function CountElements(const EvaluationResult: TGuessEvaluationResult; const HintType: TMasterMindHint): Integer;
procedure SetMatchesAndWrongPlaces(var EvaluationResult: TGuessEvaluationResult; const Matches, WrongPlaces: Integer);
public
function EvaluateGuess(const CodeToBeGuessed, Guess: TMasterMindCode): TGuessEvaluationResult;
end;
implementation
function TMasterMindGuessEvaluator.EvaluateGuess(const CodeToBeGuessed, Guess: TMasterMindCode): TGuessEvaluationResult;
begin
InitializeResultWithNoMatches(Result);
SetCorrectMatchesInResult(Result, CodeToBeGuessed, Guess);
SetWrongPlacesInResult(Result, CodeToBeGuessed, Guess);
SortResult(Result);
end;
procedure TMasterMindGuessEvaluator.InitializeResultWithNoMatches(out EvaluationResult: TGuessEvaluationResult);
var
I: Integer;
begin
for I := Low(TMasterMindCode) to High(TMasterMindCode) do
EvaluationResult[I] := mmhNoMatch;
end;
procedure TMasterMindGuessEvaluator.SetCorrectMatchesInResult(var EvaluationResult: TGuessEvaluationResult;
const CodeToBeGuessed, Guess: TMasterMindCode);
var
I: Integer;
begin
for I := Low(TMasterMindCode) to High(TMasterMindCode) do
if CodeToBeGuessed[I] = Guess[I] then
EvaluationResult[I] := mmhCorrect;
end;
procedure TMasterMindGuessEvaluator.SetWrongPlacesInResult(var EvaluationResult: TGuessEvaluationResult;
const CodeToBeGuessed, Guess: TMasterMindCode);
var
I: Integer;
begin
for I := Low(TMasterMindCode) to High(TMasterMindCode) do
if ColorInCodeButWasNotAlreadyMarkedAsCorrectMatch(Guess, CodeToBeGuessed, I) then
EvaluationResult[I] := mmhWrongPlace;
end;
function TMasterMindGuessEvaluator.ColorInCodeButWasNotAlreadyMarkedAsCorrectMatch(const Guess, CodeToBeGuessed: TMasterMindCode;
const GuessIndex: Integer): Boolean;
var
I: Integer;
begin
Result := False;
for I := Low(TMasterMindCode) to High(TMasterMindCode) do
if GuessedColorIsAtCurrentPositionButIsNoCorrectMatch(Guess, CodeToBeGuessed, I, GuessIndex) then
Exit(True);
end;
function TMasterMindGuessEvaluator.GuessedColorIsAtCurrentPositionButIsNoCorrectMatch(const Guess, CodeToBeGuessed: TMasterMindCode;
const CurrentPosition, GuessPosition: Integer): Boolean;
begin
Result := (CodeToBeGuessed[CurrentPosition] = Guess[GuessPosition])
and (not ColorCorrectAtAnyPosition(CodeToBeGuessed, Guess, [CurrentPosition, GuessPosition]));
end;
function TMasterMindGuessEvaluator.ColorCorrectAtAnyPosition(const Guess, CodeToBeGuessed: TMasterMindCode;
const Positions: array of Integer): Boolean;
var
Position: Integer;
begin
Result := False;
for Position in Positions do
if ColorCorrectAtPosition(Guess, CodeToBeGuessed, Position) then
Exit(True);
end;
function TMasterMindGuessEvaluator.ColorCorrectAtPosition(const Guess, CodeToBeGuessed: TMasterMindCode; const Position: Integer): Boolean;
begin
Result := CodeToBeGuessed[Position] = Guess[Position];
end;
procedure TMasterMindGuessEvaluator.SortResult(var EvaluationResult: TGuessEvaluationResult);
var
Matches, WrongPlaces: Integer;
begin
Matches := CountExactMatches(EvaluationResult);
WrongPlaces := CountWrongPlaces(EvaluationResult);
InitializeResultWithNoMatches(EvaluationResult);
SetMatchesAndWrongPlaces(EvaluationResult, Matches, WrongPlaces);
end;
procedure TMasterMindGuessEvaluator.SetMatchesAndWrongPlaces(var EvaluationResult: TGuessEvaluationResult; const Matches, WrongPlaces: Integer);
var
I: Integer;
begin
for I := 0 to Matches - 1 do
EvaluationResult[I] := mmhCorrect;
for I := 0 to WrongPlaces - 1 do
EvaluationResult[Matches + I] := mmhWrongPlace;
end;
function TMasterMindGuessEvaluator.CountExactMatches(const EvaluationResult: TGuessEvaluationResult): Integer;
begin
Result := CountElements(EvaluationResult, mmhCorrect);
end;
function TMasterMindGuessEvaluator.CountWrongPlaces(const EvaluationResult: TGuessEvaluationResult): Integer;
begin
Result := CountElements(EvaluationResult, mmhWrongPlace);
end;
function TMasterMindGuessEvaluator.CountElements(const EvaluationResult: TGuessEvaluationResult; const HintType: TMasterMindHint): Integer;
var
I: Integer;
begin
Result := 0;
for I := Low(EvaluationResult) to High(EvaluationResult) do
if EvaluationResult[I] = HintType then
Inc(Result);
end;
end. |
{*******************************************************}
{ }
{ FMXUI SVG图标支持单元 }
{ }
{ 版权所有 (C) 2016 YangYxd }
{ }
{*******************************************************}
unit UI.Utils.SVGImage;
interface
uses
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
Generics.Collections, System.Math.Vectors,
FMX.TextLayout,
FMX.Graphics, FMX.Surfaces, FMX.Types, FMX.Consts, System.UITypes,
Types, Classes, Sysutils, Math, Xml.VerySimple;
const
SSVGImageExtension = '.svg';
SVSVGImages = 'SVG Images';
const
DefaultSvgSize = 64;
type
TXMLDocument = class(TXmlVerySimple);
type
TSVGDecode = class(TObject)
private
FData: TXMLDocument;
FViewBox: TPointF;
[Weak] FSvg: TXmlNode;
function IsEmpty: Boolean;
function GetSize: TSize;
protected
procedure DecodeSVG(); virtual;
function ReadString(Node: TXmlNode; const Name: string): string;
function ReadFloat(Node: TXmlNode; const Name: string; const DefaultValue: Double = 0): Double; overload;
function ReadColor(Node: TXmlNode; const Name: string; const DefaultValue: TAlphaColor = 0): TAlphaColor; overload;
function ReadFontAnchor(Node: TXmlNode; DefaultValue: Integer = 0): Integer; overload;
function ReadFloat(const Value: string; const DefaultValue: Double = 0): Double; overload;
function ReadColor(const Value: string; const DefaultValue: TAlphaColor = 0): TAlphaColor; overload;
function ReadFontAnchor(const Value: string; DefaultValue: Integer = 0): Integer; overload;
public
destructor Destroy; override;
procedure LoadFormFile(const AFileName: string);
procedure LoadFormStream(const AStream: TStream); virtual;
procedure Parse(const S: string);
property SvgStyle: TXmlNode read FSvg;
property Data: TXMLDocument read FData;
property Empty: Boolean read IsEmpty;
property Size: TSize read GetSize;
property ViewBox: TPointF read FViewBox write FViewBox;
end;
type
TSVGImage = class(TPersistent)
private
FOnChange: TNotifyEvent;
FData: TSVGDecode;
FBitmap: TBitmap;
FLayout: TTextLayout;
FColor: TAlphaColor;
FLoss: Boolean;
function GetEmpty: Boolean;
function GetHeight: Integer;
function GetWidth: Integer;
procedure SetHeight(const Value: Integer);
procedure SetWidth(const Value: Integer);
procedure SetColor(const Value: TAlphaColor);
procedure SetLoss(const Value: Boolean);
protected
{ rtl }
procedure DefineProperties(Filer: TFiler); override;
procedure ReadData(Reader: TReader); virtual;
procedure WriteData(Writer: TWriter); virtual;
protected
procedure CreateDecode();
procedure InitBitmap();
procedure DrawSVG();
procedure DoChange();
procedure FillText(const Canvas: TCanvas; const ARect: TRectF; const AText: string;
const AColor: TAlphaColor; const AOpacity: Single;
const Flags: TFillTextFlags; const ATextAlign: TTextAlign;
const AVTextAlign: TTextAlign = TTextAlign.Center); overload;
procedure TextSize(const AText: string; var ASize: TSizeF; const SceneScale: Single;
const MaxWidth: Single = -1; AWordWrap: Boolean = False);
public
constructor Create;
destructor Destroy; override;
procedure LoadFormFile(const AFileName: string);
procedure LoadFormStream(const AStream: TStream);
procedure Parse(const S: string);
procedure Assign(Source: TPersistent); override;
procedure Clear;
procedure ReSize();
procedure Draw(Canvas: TCanvas; const X, Y: Single; const AOpacity: Single = 1; const HighSpeed: Boolean = False);
procedure SetSize(const Width, Height: Integer);
property Empty: Boolean read GetEmpty;
property Data: TSVGDecode read FData;
property Bitmap: TBitmap read FBitmap;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
published
property Width: Integer read GetWidth write SetWidth default 0;
property Height: Integer read GetHeight write SetHeight default 0;
property Color: TAlphaColor read FColor write SetColor default 0;
property Loss: Boolean read FLoss write SetLoss default True; // 矢量化
end;
implementation
uses
UI.Utils;
{ TSVGDecode }
procedure TSVGDecode.DecodeSVG;
var
S: string;
List: TStrings;
LSize: TPointF;
begin
if not Assigned(FData) then
raise Exception.Create('SVG not Initialization.');
FSvg := FData.ChildNodes.FindNode('svg');
if Assigned(FSvg) then begin
LSize := PointF(ReadFloat(FSvg, 'width', 0), ReadFloat(FSvg, 'height', 0));
S := ReadString(FSvg, 'viewBox');
if S = '' then
FViewBox := LSize
else begin
List := TStringList.Create;
try
List.DelimitedText := S;
if List.Count = 2 then
FViewBox := PointF(StrToFloatDef(List[0], LSize.X), StrToFloatDef(List[1], LSize.Y))
else if List.Count = 4 then
FViewBox := PointF(StrToFloatDef(List[2], LSize.X), StrToFloatDef(List[3], LSize.Y))
else
FViewBox := LSize;
finally
FreeAndNil(List);
end;
end;
end else begin
LSize := PointF(DefaultSvgSize, DefaultSvgSize);
FViewBox := LSize;
end;
end;
destructor TSVGDecode.Destroy;
begin
FreeAndNil(FData);
inherited;
end;
function TSVGDecode.GetSize: TSize;
begin
if Assigned(FSvg) then begin
Result.Width := Round(ReadFloat(FSvg, 'width', 0));
Result.Height := Round(ReadFloat(FSvg, 'height', 0));
end else begin
Result.Width := DefaultSvgSize;
Result.Height := DefaultSvgSize;
end;
end;
function TSVGDecode.IsEmpty: Boolean;
begin
Result := (FSvg = nil) or (FData = nil);
end;
procedure TSVGDecode.LoadFormFile(const AFileName: string);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(AFileName, fmOpenRead);
try
LoadFormStream(Stream);
finally
FreeAndNil(Stream);
end;
end;
procedure TSVGDecode.LoadFormStream(const AStream: TStream);
begin
if not Assigned(AStream) then
Exit;
if not Assigned(FData) then
FData := TXMLDocument.Create()
else
FData.Clear;
FSvg := nil;
FViewBox := TPoint.Zero;
try
FData.LoadFromStream(AStream);
DecodeSVG();
except
end;
end;
procedure TSVGDecode.Parse(const S: string);
begin
if S = '' then
Exit;
if not Assigned(FData) then
FData := TXMLDocument.Create()
else
FData.Clear;
FSvg := nil;
FViewBox := TPoint.Zero;
try
FData.Text := S;
DecodeSVG();
except
end;
end;
function TSVGDecode.ReadColor(Node: TXmlNode; const Name: string;
const DefaultValue: TAlphaColor): TAlphaColor;
begin
try
Result := HtmlColorToColor(ReadString(Node, Name), DefaultValue);
except
Result := DefaultValue;
end;
end;
function TSVGDecode.ReadFloat(Node: TXmlNode; const Name: string; const DefaultValue: Double): Double;
begin
Result := StrToFloatDef(ReadString(Node, Name), DefaultValue);
end;
function TSVGDecode.ReadFontAnchor(Node: TXmlNode; DefaultValue: Integer): Integer;
begin
Result := ReadFontAnchor(ReadString(Node, 'text-anchor'));
end;
function TSVGDecode.ReadString(Node: TXmlNode; const Name: string): string;
begin
Result := '';
if Assigned(Node) then
Result := Node.Attributes[Name];
end;
function TSVGDecode.ReadColor(const Value: string;
const DefaultValue: TAlphaColor): TAlphaColor;
begin
try
Result := HtmlColorToColor(Value, DefaultValue);
except
Result := DefaultValue;
end;
end;
function TSVGDecode.ReadFloat(const Value: string;
const DefaultValue: Double): Double;
begin
Result := StrToFloatDef(Value, DefaultValue);
end;
function TSVGDecode.ReadFontAnchor(const Value: string;
DefaultValue: Integer): Integer;
var
S: string;
begin
Result := DefaultValue;
S := LowerCase(Value);
if S = 'start' then
Result := 0
else if S = 'middle' then
Result := 1
else if S = 'end' then
Result := 2
else if S = 'inherit' then
Result := 3
end;
{ TSVGImage }
procedure TSVGImage.Assign(Source: TPersistent);
var
Stream: TMemoryStream;
begin
if Source is TSVGImage then begin
FColor := TSVGImage(Source).FColor;
if TSVGImage(Source).Empty then
Clear
else begin
CreateDecode();
Stream := TMemoryStream.Create;
try
TSVGImage(Source).FData.FData.SaveToStream(Stream);
Stream.Position := 0;
Self.FData.LoadFormStream(Stream);
if not Assigned(FBitmap) then
InitBitmap();
FBitmap.SetSize(FData.Size.Width, FData.Size.Height);
DrawSVG;
finally
Stream.Free;
end;
end;
DoChange();
end else
inherited;
end;
procedure TSVGImage.Clear;
begin
FreeAndNil(FData);
FreeAndNil(FBitmap);
DoChange();
end;
constructor TSVGImage.Create;
begin
FLoss := True;
end;
procedure TSVGImage.CreateDecode;
begin
if not Assigned(FData) then
FData := TSVGDecode.Create;
end;
procedure TSVGImage.DefineProperties(Filer: TFiler);
begin
inherited;
Filer.DefineProperty('SVGData', ReadData, WriteData, Assigned(FData));
end;
destructor TSVGImage.Destroy;
begin
FreeAndNil(FLayout);
FreeAndNil(FData);
FreeAndNil(FBitmap);
inherited;
end;
procedure TSVGImage.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TSVGImage.Draw(Canvas: TCanvas; const X, Y: Single; const AOpacity: Single; const HighSpeed: Boolean);
var
W, H: Single;
begin
if Assigned(FBitmap) then begin
W := FBitmap.Width;
H := FBitmap.Height;
Canvas.DrawBitmap(FBitmap, RectF(0, 0, W, H), RectF(X, Y, X + W, Y + H), AOpacity, HighSpeed);
end;
end;
procedure TSVGImage.DrawSVG;
var
FillOpacity, StrokeOpacity: Single; // 填充和边线透明度
SX, SY: Single; // X, Y 缩放
FontAnchor: Integer;
procedure ParserStyleItem(Canvas: TCanvas; const PS: PChar; const PN: Integer;
const PV: PChar; PL: Integer; const Flag: Integer);
var
P: PChar;
begin
//if (PL < 1) or (PN < 1) then Exit;
// 跳过尾部空格
P := PV + PL - 1;
while (P >= PV) and ((P^ = ' ') or (P^ = #13) or (P^ = #10)) do begin
Dec(PL);
Dec(P);
end;
if PL < 1 then Exit;
if (PN = 12) and (StrLComp(PS, 'stroke-width', PN) = 0) then begin
P := PV + PL;
while P > PV do begin
Dec(P);
if (P^ >= '0') and (P^ <= '9') then begin
Inc(P);
Break;
end;
end;
Canvas.Stroke.Thickness := PCharToFloatDef(PV, P - PV, 0) * SX;
end;
if Flag <> 0 then Exit;
if (PN = 4) and (FColor = 0) and (StrLComp(PS, 'fill', PN) = 0) then begin
Canvas.Fill.Color := HtmlColorToColor(PCharToStr(PV, PL), TAlphaColorRec.Black);
end else if (PN = 6) and (FColor = 0) and (StrLComp(PS, 'stroke', PN) = 0) then begin
Canvas.Stroke.Color := HtmlColorToColor(PCharToStr(PV, PL), TAlphaColorRec.Black);
end else if (PN = 12) and (StrLComp(PS, 'fill-opacity', PN) = 0) then begin
FillOpacity := StrToFloatDef(PCharToStr(PV, PL), 1);
end else if (PN = 14) and (StrLComp(PS, 'stroke-opacity', PN) = 0) then begin
StrokeOpacity := PCharToFloatDef(PV, PL, 1);
end else if (PN = 7) and (StrLComp(PS, 'opacity', PN) = 0) then begin
StrokeOpacity := PCharToFloatDef(PV, PL, 1);
FillOpacity := StrokeOpacity;
end else if (PN = 9) and (StrLComp(PS, 'font-size', PN) = 0) then begin
FLayout.Font.Size := PCharToFloatDef(PV, PL, FLayout.Font.Size);
end else if (PN = 11) and (StrLComp(PS, 'font-family', PN) = 0) then begin
FLayout.Font.Family := PCharToStr(PV, PL);
end;
end;
procedure ParserStyle(Canvas: TCanvas; const Data: string; Flag: Integer); overload;
var
P, PE, PS, PV: PChar;
PN: Integer;
begin
if Data = '' then Exit;
P := PChar(Data);
PE := P + Length(Data);
while (P < PE) and ((P^ = ' ') or (P^ = #13) or (P^ = #10)) do Inc(P);
PS := P;
PV := nil;
PN := 0;
while P < PE do begin
if (PV = nil) and (P^ = ':') then begin
PN := P - PS;
Inc(P);
while (P < PE) and ((P^ = ' ') or (P^ = #13) or (P^ = #10)) do Inc(P);
PV := P;
Continue;
end else if (P^ = ';') and (PV <> nil) then begin
if (PN > 0) and (P > PV) then
ParserStyleItem(Canvas, PS, PN, PV, P - PV, Flag);
PN := 0;
PV := nil;
Inc(P);
while (P < PE) and ((P^ = ' ') or (P^ = #13) or (P^ = #10)) do Inc(P);
PS := P;
end else
Inc(P);
end;
if (PV <> nil) and (P > PV) and (PN > 0) then
ParserStyleItem(Canvas, PS, PN, PV, P - PV, Flag);
end;
function TryGetAttr(Item: TXmlNode; var Value: string; const Key: string): Boolean;
var
Attr: TXmlAttribute;
begin
Attr := Item.AttributeList.Find(Key);
if Assigned(Attr) then begin
Value := Attr.Value;
Result := True;
end else
Result := False;
end;
procedure ParserStyle(Canvas: TCanvas; Item: TXmlNode; Flag: Integer = 0); overload;
var
Value: string;
begin
if (Flag = 0) and (FColor = 0) then
Canvas.Fill.Color := FData.ReadColor(Item, 'fill', Canvas.Fill.Color);
if (Flag = 0) and (FColor = 0) and TryGetAttr(Item, Value, 'stroke') then
Canvas.Stroke.Color := FData.ReadColor(Value, Canvas.Stroke.Color);
if TryGetAttr(Item, Value, 'stroke-width') then
Canvas.Stroke.Thickness := FData.ReadFloat(Value, Canvas.Stroke.Thickness) * SX;
if TryGetAttr(Item, Value, 'text-anchor') then
FontAnchor := FData.ReadFontAnchor(Value, FontAnchor);
if TryGetAttr(Item, Value, 'font-size') then
FLayout.Font.Size := FData.ReadFloat(Value, FLayout.Font.Size);
if TryGetAttr(Item, Value, 'font-family') then
FLayout.Font.Family := Value;
if TryGetAttr(Item, Value, 'style') then
ParserStyle(Canvas, Value, Flag);
end;
procedure ParserPoints(var LPoints: TPolygon; const Data: string; Offset: Single = 0);
var
List: TStrings;
I, J, P: Integer;
V, L: string;
begin
List := TStringList.Create;
J := 0;
try
List.Delimiter := ' ';
List.DelimitedText := Data;
if (Pos(',', Data) = 0) and (List.Count mod 2 = 0) then begin
SetLength(LPoints, List.Count div 2);
I := 0;
while I < List.Count do begin
LPoints[J] := PointF(StrToFloatDef(List[I], 0) + Offset, StrToFloatDef(List[I + 1], 0) + Offset);
Inc(I, 2);
Inc(J);
end;
end else begin
SetLength(LPoints, List.Count);
for I := 0 to List.Count - 1 do begin
V := Trim(List[I]);
if V = '' then Continue;
P := Pos(',', V);
if P = 0 then Continue;
L := Copy(V, 0, P - 1);
V := Copy(V, P + 1, Length(V) - P);
LPoints[J] := PointF(StrToFloatDef(L, 0) + Offset, StrToFloatDef(V, 0) + Offset);
Inc(J);
end;
end;
finally
List.Free;
SetLength(LPoints, J);
end;
end;
procedure ParserPointsSize(const Data: string; var W, H: Single; Offset: Single = 0);
var
List: TStrings;
I, P: Integer;
V, L: string;
begin
List := TStringList.Create;
try
List.Delimiter := ' ';
List.DelimitedText := Data;
W := 0;
H := 0;
for I := 0 to List.Count - 1 do begin
V := Trim(List[I]);
if V = '' then Continue;
P := Pos(',', V);
if P = 0 then Continue;
L := Copy(V, 0, P - 1);
V := Copy(V, P + 1, Length(V) - P);
W := Max(W, StrToFloatDef(L, 0) + Offset);
H := Max(H, StrToFloatDef(V, 0) + Offset);
end;
W := W + Offset;
H := H + Offset;
finally
List.Free;
end;
end;
procedure ParserPathSize(Path: TPathData; var W, H: Single);
var
I: Integer;
begin
W := 0;
H := 0;
for I := 0 to Path.Count - 1 do begin
with Path.Points[I] do begin
if Kind <> TPathPointKind.Close then begin
W := Max(Point.X, W);
H := Max(Point.Y, H);
end;
end;
end;
end;
procedure ParserNodesCaleSize(Canvas: TCanvas; Nodes: TXmlNodeList; Path: TPathData; var MW, MH: Single);
var
Item: TXmlNode;
I, DefFontAnchor: Integer;
W, H, X, Y, RX, RY, DefFontSize, DefStrokeSize: Single;
ASize: TSizeF;
LName, LData, DefFontName: string;
begin
DefStrokeSize := Canvas.Stroke.Thickness;
DefFontSize := FLayout.Font.Size;
DefFontName := FLayout.Font.Family;
DefFontAnchor := FontAnchor;
for I := 0 to Nodes.Count - 1 do begin
Item := Nodes.Items[I];
if Item = nil then Continue;
LName := LowerCase(Item.Name);
Canvas.Stroke.Thickness := DefStrokeSize;
if (LName = 'g') or (LName = 'a') then begin
// 扩展
Canvas.Font.Size := FData.ReadFloat(Item, 'font-size', 12);
Canvas.Font.Family := FData.ReadString(Item, 'font');
ParserStyle(Canvas, Item, 1);
if Item.ChildNodes.Count > 0 then
ParserNodesCaleSize(Canvas, Item.ChildNodes, Path, MW, MH);
FLayout.Font.Size := DefFontSize;
FLayout.Font.Family := DefFontName;
FontAnchor := DefFontAnchor;
end else if LName = 'path' then begin
ParserStyle(Canvas, Item, 1);
Path.Data := FData.ReadString(Item, 'd');
Path.Scale(SX, SY);
ParserPathSize(Path, W, H);
MW := Max(MW, W + Canvas.Stroke.Thickness * 0.5);
MH := Max(MH, H + Canvas.Stroke.Thickness * 0.5);
end else if LName = 'rect' then begin
ParserStyle(Canvas, Item, 1);
W := FData.ReadFloat(Item, 'width') * SX;
H := FData.ReadFloat(Item, 'height') * SY;
X := FData.ReadFloat(Item, 'x') * SX;
Y := FData.ReadFloat(Item, 'y') * SY;
MW := Max(MW, X + W + Canvas.Stroke.Thickness);
MH := Max(MH, Y + H + Canvas.Stroke.Thickness);
end else if LName = 'circle' then begin
ParserStyle(Canvas, Item, 1);
RX := FData.ReadFloat(Item, 'cx') * SX;
RY := FData.ReadFloat(Item, 'cy') * SY;
W := FData.ReadFloat(Item, 'r') * SX;
MW := Max(MW, RX + W + Canvas.Stroke.Thickness * 0.5);
MH := Max(MH, RY + W + Canvas.Stroke.Thickness * 0.5);
end else if LName = 'ellipse' then begin
ParserStyle(Canvas, Item, 1);
RX := FData.ReadFloat(Item, 'cx') * SX;
RY := FData.ReadFloat(Item, 'cy') * SY;
W := FData.ReadFloat(Item, 'rx') * SX;
H := FData.ReadFloat(Item, 'ry') * SX;
MW := Max(MW, RX + W + Canvas.Stroke.Thickness * 0.5);
MH := Max(MH, RY + H + Canvas.Stroke.Thickness * 0.5);
end else if LName = 'line' then begin
X := FData.ReadFloat(Item, 'x1') * SX;
Y := FData.ReadFloat(Item, 'y1') * SY;
RX := FData.ReadFloat(Item, 'x2') * SX;
RY := FData.ReadFloat(Item, 'y2') * SY;
MW := Max(MW, Max(X, RX));
MH := Max(MH, Max(Y, RY));
end else if LName = 'polygon' then begin
LData := FData.ReadString(Item, 'points');
ParserPointsSize(LData, W, H);
MW := Max(MW, W);
MH := Max(MH, H);
end else if LName = 'polyline' then begin
ParserStyle(Canvas, Item, 1);
LData := FData.ReadString(Item, 'points');
ParserPointsSize(LData, W, H, Canvas.Stroke.Thickness * 0.5);
MW := Max(MW, W);
MH := Max(MH, H);
end else if LName = 'text' then begin
// 文本
ParserStyle(Canvas, Item, 1);
X := FData.ReadFloat(Item, 'x') * SX;
Y := FData.ReadFloat(Item, 'y') * SY;
RX := FData.ReadFloat(Item, 'dx') * SX;
RY := FData.ReadFloat(Item, 'dy') * SX;
if Item.ChildNodes.Count = 0 then begin
TextSize(Item.Text, ASize, Canvas.Scale);
if FontAnchor = 3 then
FontAnchor := DefFontAnchor;
case FontAnchor of
1: // middle
W := X + ASize.Width * 0.5 + RX;
2: // end
W := X + RX;
else
W := X + ASize.Width + RX;
end;
MH := Max(MH, Y + RY);
MW := Max(MW, W);
end;
FLayout.Font.Size := DefFontSize;
FLayout.Font.Family := DefFontName;
FontAnchor := DefFontAnchor;
end;
end;
end;
procedure ParserNodes(Canvas: TCanvas; Nodes: TXmlNodeList; Path: TPathData);
var
LPoints: TPolygon;
Item: TXmlNode;
I, J, DefFontAnchor: Integer;
ASize: TSizeF;
W, H, X, Y, RX, RY, BX, BY, LD, DefStrokeSize, DefFontSize: Single;
DefStrokeColor, DefFillColor: TAlphaColor;
LName, LData, DefFontName: string;
begin
DefStrokeColor := Canvas.Stroke.Color;
DefFillColor := Canvas.Fill.Color;
DefStrokeSize := Canvas.Stroke.Thickness;
DefFontSize := FLayout.Font.Size;
DefFontName := FLayout.Font.Family;
DefFontAnchor := FontAnchor;
for I := 0 to Nodes.Count - 1 do begin
Item := Nodes.Items[I];
if Item = nil then Continue;
LName := LowerCase(Item.Name);
FillOpacity := 1;
StrokeOpacity := 1;
Canvas.Stroke.Color := DefStrokeColor;
Canvas.Fill.Color := DefFillColor;
Canvas.Stroke.Thickness := DefStrokeSize;
if (LName = 'g') or (LName = 'a') then begin
// 扩展
Canvas.Font.Size := FData.ReadFloat(Item, 'font-size', 12);
Canvas.Font.Family := FData.ReadString(Item, 'font');
ParserStyle(Canvas, Item);
if Item.ChildNodes.Count > 0 then
ParserNodes(Canvas, Item.ChildNodes, Path);
FLayout.Font.Size := DefFontSize;
FLayout.Font.Family := DefFontName;
FontAnchor := DefFontAnchor;
end else if LName = 'path' then begin
// 路径
LData := Item.Attributes['d'];
if LData <> '' then begin
Path.Data := LData;
if (SX <> 1) or (SY <> 1) then
Path.Scale(SX, SY);
ParserStyle(Canvas, Item);
if (Canvas.Fill.Color and $FF000000 <> 0) and (FillOpacity > 0) then
Canvas.FillPath(Path, FillOpacity);
if (Canvas.Stroke.Thickness > 0) and (StrokeOpacity > 0) then
Canvas.DrawPath(Path, StrokeOpacity);
end;
end else if LName = 'rect' then begin
// 矩形
ParserStyle(Canvas, Item);
W := FData.ReadFloat(Item, 'width') * SX;
H := FData.ReadFloat(Item, 'height') * SY;
if (W <= 0) or (H <= 0) then
Continue;
LD := Canvas.Stroke.Thickness;
X := FData.ReadFloat(Item, 'x') * SX;
Y := FData.ReadFloat(Item, 'y') * SY;
RX := FData.ReadFloat(Item, 'rx') * SX;
RY := FData.ReadFloat(Item, 'ry') * SY;
if RX > 0 then
BX := Max(0, RX - LD * 0.5)
else
BX := RX;
if RY > 0 then
BY := Max(0, RY - LD * 0.5)
else
BY := RY;
if (Canvas.Fill.Color and $FF000000 <> 0) and (FillOpacity > 0) then
Canvas.FillRect(RectF(X + LD * 0.5, Y + LD * 0.5, X + W - LD * 0.5, Y + H - LD * 0.5), BX, BY, AllCorners, FillOpacity);
if LD > 0 then begin
Canvas.DrawRect(RectF(X, Y, X + W, Y + H), RX, RY, AllCorners, StrokeOpacity);
end;
end else if LName = 'circle' then begin
// 圆
ParserStyle(Canvas, Item);
RX := FData.ReadFloat(Item, 'cx') * SX;
RY := FData.ReadFloat(Item, 'cy') * SY;
W := FData.ReadFloat(Item, 'r') * SX;
if W > 0 then begin
if (Canvas.Fill.Color and $FF000000 <> 0) and (FillOpacity > 0) then
Canvas.FillArc(PointF(RX, RY), PointF(W, W), 0, 360, FillOpacity);
if Canvas.Stroke.Thickness > 0 then
Canvas.DrawArc(PointF(RX, RY), PointF(W, W), 0, 360, StrokeOpacity);
end;
end else if LName = 'ellipse' then begin
// 椭圆
ParserStyle(Canvas, Item);
RX := FData.ReadFloat(Item, 'cx') * SX;
RY := FData.ReadFloat(Item, 'cy') * SY;
W := FData.ReadFloat(Item, 'rx') * SX;
H := FData.ReadFloat(Item, 'ry') * SX;
if (W > 0) or (H > 0) then begin
Canvas.FillArc(PointF(RX, RY), PointF(W, H), 0, 360, FillOpacity);
if Canvas.Stroke.Thickness > 0 then
Canvas.DrawArc(PointF(RX, RY), PointF(W, H), 0, 360, StrokeOpacity);
end;
end else if LName = 'line' then begin
// 线条
ParserStyle(Canvas, Item);
X := FData.ReadFloat(Item, 'x1') * SX;
Y := FData.ReadFloat(Item, 'y1') * SY;
RX := FData.ReadFloat(Item, 'x2') * SX;
RY := FData.ReadFloat(Item, 'y2') * SY;
Path.Clear;
Path.MoveTo(PointF(X, Y));
Path.LineTo(PointF(RX, RY));
if Canvas.Stroke.Thickness > 0 then
Canvas.DrawPath(Path, StrokeOpacity);
end else if LName = 'polygon' then begin
// 多边形
ParserStyle(Canvas, Item);
LData := FData.ReadString(Item, 'points');
if LData <> '' then begin
ParserPoints(LPoints, LData);
if Length(LPoints) = 0 then
Continue;
Canvas.FillPolygon(LPoints, FillOpacity);
if Canvas.Stroke.Thickness > 0 then
Canvas.DrawPolygon(LPoints, StrokeOpacity);
end;
end else if LName = 'polyline' then begin
// 折线
ParserStyle(Canvas, Item);
LData := FData.ReadString(Item, 'points');
if LData <> '' then begin
ParserPoints(LPoints, LData, Canvas.Stroke.Thickness * 0.5);
if (Length(LPoints) = 0) or (Canvas.Stroke.Thickness <= 0) then
Continue;
Path.Clear;
Path.MoveTo(LPoints[0]);
for J := 1 to High(LPoints) do
Path.LineTo(LPoints[J]);
Canvas.DrawPath(Path, StrokeOpacity);
end;
end else if LName = 'text' then begin
// 文本
ParserStyle(Canvas, Item);
X := FData.ReadFloat(Item, 'x') * SX;
Y := FData.ReadFloat(Item, 'y') * SY;
RX := FData.ReadFloat(Item, 'dx') * SX;
RY := FData.ReadFloat(Item, 'dy') * SX;
if Item.ChildNodes.Count = 0 then begin
LData := Item.Text;
TextSize(LData, ASize, Canvas.Scale);
if FontAnchor = 3 then
FontAnchor := DefFontAnchor;
case FontAnchor of
1: // middle
FillText(Canvas,
RectF(X - ASize.Width * 0.5 + RX, Y - ASize.Height + RY, X + ASize.Width * 0.5 + RX, Y + RY),
LData, Canvas.Fill.Color, FillOpacity, [],
TTextAlign.Leading, TTextAlign.Trailing);
2: // end
FillText(Canvas,
RectF(X - ASize.Width + RX, Y - ASize.Height + RY, X + RX, Y + RY),
LData, Canvas.Fill.Color, FillOpacity, [],
TTextAlign.Leading, TTextAlign.Trailing);
else // start
FillText(Canvas,
RectF(X + RX, Y - ASize.Height + RY, X + ASize.Width + RX, Y + RY),
LData, Canvas.Fill.Color, FillOpacity, [],
TTextAlign.Leading, TTextAlign.Trailing);
end;
end;
FLayout.Font.Size := DefFontSize;
FLayout.Font.Family := DefFontName;
FontAnchor := DefFontAnchor;
end;
end;
end;
var
Path: TPathData;
MW, MH: Single;
Canvas: TCanvas;
begin
if (FData = nil) or (Fdata.FData = nil) or (FData.FSvg = nil) then
Exit;
if FData.FViewBox.X = 0 then
SX := 1
else
SX := Width / FData.FViewBox.X;
if FData.FViewBox.Y = 0 then
SY := 1
else
SY := Height / FData.FViewBox.Y;
if not Assigned(FLayout) then begin
Canvas := FBitmap.Canvas;
FLayout := TTextLayoutManager.TextLayoutByCanvas(Canvas.ClassType).Create(Canvas);
end;
Path := TPathData.Create;
try
// 自动大小
if (FBitmap.Width = 0) and (FBitmap.Height = 0) then begin
MW := 0;
MH := 0;
FontAnchor := 0;
Canvas := FBitmap.Canvas;
Canvas.Stroke.Thickness := 0;
ParserNodesCaleSize(Canvas, FData.FSvg.ChildNodes, Path, MW, MH);
FData.ViewBox := PointF(MW, MH);
FBitmap.SetSize(Round(MW), Round(MH));
end;
if (FBitmap.Width = 0) or (FBitmap.Height = 0) then
Exit;
FBitmap.Clear(0);
Canvas := FBitmap.Canvas;
Canvas.BeginScene();
try
FontAnchor := 0;
Canvas.Stroke.Thickness := 0;
if FColor = 0 then begin
Canvas.Stroke.Color := TAlphaColorRec.Black;
Canvas.Fill.Color := TAlphaColorRec.Black;
end else begin
Canvas.Stroke.Color := FColor;
Canvas.Fill.Color := FColor;
end;
ParserNodes(Canvas, FData.FSvg.ChildNodes, Path);
finally
Canvas.EndScene;
end;
finally
FreeAndNil(Path);
end;
end;
procedure TSVGImage.FillText(const Canvas: TCanvas; const ARect: TRectF;
const AText: string; const AColor: TAlphaColor; const AOpacity: Single;
const Flags: TFillTextFlags; const ATextAlign, AVTextAlign: TTextAlign);
begin
with FLayout do begin
BeginUpdate;
TopLeft := ARect.TopLeft;
MaxSize := PointF(ARect.Width, ARect.Height);
Text := AText;
WordWrap := False;
Opacity := AOpacity;
HorizontalAlign := ATextAlign;
VerticalAlign := AVTextAlign;
Color := AColor;
Trimming := TTextTrimming.None;
RightToLeft := False;
EndUpdate;
RenderLayout(Canvas);
end;
end;
function TSVGImage.GetEmpty: Boolean;
begin
Result := (not Assigned(FData)) or (FData.Empty);
end;
function TSVGImage.GetHeight: Integer;
begin
if Assigned(FBitmap) then
Result := FBitmap.Height
else
Result := 0;
end;
function TSVGImage.GetWidth: Integer;
begin
if Assigned(FBitmap) then
Result := FBitmap.Width
else
Result := 0;
end;
procedure TSVGImage.InitBitmap;
begin
FBitmap := TBitmap.Create;
end;
procedure TSVGImage.LoadFormFile(const AFileName: string);
begin
CreateDecode();
FData.LoadFormFile(AFileName);
if Empty then begin
FreeAndNil(FBitmap);
Exit;
end;
if not Assigned(FBitmap) then
InitBitmap();
FBitmap.SetSize(FData.Size.Width, FData.Size.Height);
DrawSVG;
DoChange();
end;
procedure TSVGImage.LoadFormStream(const AStream: TStream);
begin
CreateDecode();
FData.LoadFormStream(AStream);
if Empty then begin
FreeAndNil(FBitmap);
Exit;
end;
if not Assigned(FBitmap) then
InitBitmap;
FBitmap.SetSize(FData.Size.Width, FData.Size.Height);
DrawSVG;
DoChange();
end;
procedure TSVGImage.Parse(const S: string);
begin
CreateDecode();
FData.Parse(S);
if Empty then begin
FreeAndNil(FBitmap);
Exit;
end;
if not Assigned(FBitmap) then
InitBitmap;
FBitmap.SetSize(FData.Size.Width, FData.Size.Height);
DrawSVG;
DoChange();
end;
procedure TSVGImage.ReadData(Reader: TReader);
var
Stream: TStringStream;
begin
try
Stream := TStringStream.Create;
try
Stream.WriteString(Reader.ReadString);
Stream.Position := 0;
Self.LoadFormStream(Stream);
finally
Stream.Free;
end;
except
end;
end;
procedure TSVGImage.ReSize;
var
LSize: TSizeF;
begin
if Assigned(FData) then begin
LSize := FData.GetSize;
SetSize(Round(LSize.Width), Round(LSize.Height));
end;
end;
procedure TSVGImage.SetColor(const Value: TAlphaColor);
begin
if FColor <> Value then begin
FColor := Value;
DrawSVG;
DoChange;
end;
end;
procedure TSVGImage.SetHeight(const Value: Integer);
begin
if Value <> Height then begin
SetSize(Width, Value);
DoChange;
end;
end;
procedure TSVGImage.SetLoss(const Value: Boolean);
begin
if FLoss <> Value then begin
FLoss := Value;
if (not Value) then
ReSize();
DoChange();
end;
end;
procedure TSVGImage.SetSize(const Width, Height: Integer);
begin
if Assigned(FBitmap) and ((Width <> FBitmap.Width) or (Height <> FBitmap.Height)) then begin
FBitmap.SetSize(Width, Height);
if (Width > 0) and (Height > 0) and (not Empty) then
DrawSVG();
end;
end;
procedure TSVGImage.SetWidth(const Value: Integer);
begin
if Value <> Width then begin
SetSize(Value, Height);
DoChange;
end;
end;
function RoundToScale(const Value, Scale: Single): Single;
begin
if Scale > 0 then
Result := Ceil(Value * Scale) / Scale
else
Result := Ceil(Value);
end;
procedure TSVGImage.TextSize(const AText: string; var ASize: TSizeF;
const SceneScale, MaxWidth: Single; AWordWrap: Boolean);
begin
with FLayout do begin
BeginUpdate;
TopLeft := TPointF.Zero;
if MaxWidth < 0 then
MaxSize := TTextLayout.MaxLayoutSize
else
MaxSize := PointF(MaxWidth, $FFFFFF);
Text := AText;
WordWrap := AWordWrap;
HorizontalAlign := TTextAlign.Leading;
VerticalAlign := TTextAlign.Leading;
RightToLeft := False;
EndUpdate;
ASize.Width := Width;
ASize.Height := Height;
//ASize.Width := RoundToScale(Width, SceneScale);
//ASize.Height := RoundToScale(Height, SceneScale);
end;
end;
procedure TSVGImage.WriteData(Writer: TWriter);
var
Stream: TStringStream;
begin
try
Stream := TStringStream.Create;
try
if Assigned(FData) and Assigned(FData.FData) then
FData.FData.SaveToStream(Stream);
finally
Writer.WriteString(Stream.DataString);
Stream.Free;
end;
except
end;
end;
initialization
end.
|
unit DragDropContext;
// -----------------------------------------------------------------------------
// Project: Drag and Drop Component Suite.
// Module: DragDropContext
// Description: Implements Context Menu Handler Shell Extensions.
// Version: 4.0
// Date: 18-MAY-2001
// Target: Win32, Delphi 5-6
// Authors: Anders Melander, anders@melander.dk, http://www.melander.dk
// Copyright © 1997-2001 Angus Johnson & Anders Melander
// -----------------------------------------------------------------------------
interface
uses
DragDrop,
DragDropComObj,
Menus,
ShlObj,
ActiveX,
Windows,
Classes;
{$include DragDrop.inc}
type
////////////////////////////////////////////////////////////////////////////////
//
// TDropContextMenu
//
////////////////////////////////////////////////////////////////////////////////
// Partially based on Borland's ShellExt demo.
////////////////////////////////////////////////////////////////////////////////
// A typical shell context menu handler session goes like this:
// 1. User selects one or more files and right clicks on them.
// The files must of a file type which has a context menu handler registered.
// 2. The shell loads the context menu handler module.
// 3. The shell instantiates the registered context menu handler object as an
// in-process COM server.
// 4. The IShellExtInit.Initialize method is called with a data object which
// contains the dragged data.
// 5. The IContextMenu.QueryContextMenu method is called to populate the popup
// menu.
// TDropContextMenu uses the PopupMenu property to populate the shell context
// menu.
// 6. If the user chooses one of the context menu menu items we have supplied,
// the IContextMenu.InvokeCommand method is called.
// TDropContextMenu locates the corresponding TMenuItem and fires the menu
// items OnClick event.
// 7. The shell unloads the context menu handler module (usually after a few
// seconds).
////////////////////////////////////////////////////////////////////////////////
TDropContextMenu = class(TInterfacedComponent, IShellExtInit, IContextMenu)
private
FContextMenu: TPopupMenu;
FMenuOffset: integer;
FDataObject: IDataObject;
FOnPopup: TNotifyEvent;
FFiles: TStrings;
procedure SetContextMenu(const Value: TPopupMenu);
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
{ IShellExtInit }
function Initialize(pidlFolder: PItemIDList; lpdobj: IDataObject;
hKeyProgID: HKEY): HResult; stdcall;
{ IContextMenu }
function QueryContextMenu(Menu: HMENU; indexMenu, idCmdFirst, idCmdLast,
uFlags: UINT): HResult; stdcall;
function InvokeCommand(var lpici: TCMInvokeCommandInfo): HResult; stdcall;
function GetCommandString(idCmd, uType: UINT; pwReserved: PUINT;
pszName: LPSTR; cchMax: UINT): HResult; stdcall;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property DataObject: IDataObject read FDataObject;
property Files: TStrings read FFiles;
published
property ContextMenu: TPopupMenu read FContextMenu write SetContextMenu;
property OnPopup: TNotifyEvent read FOnPopup write FOnPopup;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropContextMenuFactory
//
////////////////////////////////////////////////////////////////////////////////
// COM Class factory for TDropContextMenu.
////////////////////////////////////////////////////////////////////////////////
TDropContextMenuFactory = class(TShellExtFactory)
protected
function HandlerRegSubKey: string; virtual;
public
procedure UpdateRegistry(Register: Boolean); override;
end;
////////////////////////////////////////////////////////////////////////////////
//
// Component registration
//
////////////////////////////////////////////////////////////////////////////////
procedure Register;
////////////////////////////////////////////////////////////////////////////////
//
// Misc.
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
implementation
uses
DragDropFile,
DragDropPIDL,
Registry,
ComObj,
SysUtils;
////////////////////////////////////////////////////////////////////////////////
//
// Component registration
//
////////////////////////////////////////////////////////////////////////////////
procedure Register;
begin
RegisterComponents(DragDropComponentPalettePage, [TDropContextMenu]);
end;
////////////////////////////////////////////////////////////////////////////////
//
// Utilities
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// TDropContextMenu
//
////////////////////////////////////////////////////////////////////////////////
constructor TDropContextMenu.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFiles := TStringList.Create;
end;
destructor TDropContextMenu.Destroy;
begin
FFiles.Free;
inherited Destroy;
end;
function TDropContextMenu.GetCommandString(idCmd, uType: UINT;
pwReserved: PUINT; pszName: LPSTR; cchMax: UINT): HResult;
var
ItemIndex: integer;
begin
ItemIndex := integer(idCmd);
// Make sure we aren't being passed an invalid argument number
if (ItemIndex >= 0) and (ItemIndex < FContextMenu.Items.Count) then
begin
if (uType = GCS_HELPTEXT) then
// return help string for menu item.
StrLCopy(pszName, PChar(FContextMenu.Items[ItemIndex].Hint), cchMax);
Result := NOERROR;
end else
Result := E_INVALIDARG;
end;
function TDropContextMenu.InvokeCommand(var lpici: TCMInvokeCommandInfo): HResult;
var
ItemIndex: integer;
begin
Result := E_FAIL;
// Make sure we are not being called by an application
if (FContextMenu = nil) or (HiWord(Integer(lpici.lpVerb)) <> 0) then
Exit;
ItemIndex := LoWord(lpici.lpVerb);
// Make sure we aren't being passed an invalid argument number
if (ItemIndex < 0) or (ItemIndex >= FContextMenu.Items.Count) then
begin
Result := E_INVALIDARG;
Exit;
end;
// Execute the menu item specified by lpici.lpVerb.
try
try
FContextMenu.Items[ItemIndex].Click;
Result := NOERROR;
except
on E: Exception do
begin
Windows.MessageBox(0, PChar(E.Message), 'Error',
MB_OK or MB_ICONEXCLAMATION or MB_SYSTEMMODAL);
Result := E_UNEXPECTED;
end;
end;
finally
FDataObject := nil;
FFiles.Clear;
end;
end;
function TDropContextMenu.QueryContextMenu(Menu: HMENU; indexMenu, idCmdFirst,
idCmdLast, uFlags: UINT): HResult;
var
i: integer;
Last: integer;
Flags: UINT;
function IsLine(Item: TMenuItem): boolean;
begin
{$ifdef VER13_PLUS}
Result := Item.IsLine;
{$else}
Result := Item.Caption = '-';
{$endif}
end;
begin
Last := 0;
if (FContextMenu <> nil) and (((uFlags and $0000000F) = CMF_NORMAL) or
((uFlags and CMF_EXPLORE) <> 0)) then
begin
FMenuOffset := idCmdFirst;
for i := 0 to FContextMenu.Items.Count-1 do
if (FContextMenu.Items[i].Visible) then
begin
Flags := MF_STRING or MF_BYPOSITION;
if (not FContextMenu.Items[i].Enabled) then
Flags := Flags or MF_GRAYED;
if (IsLine(FContextMenu.Items[i])) then
Flags := Flags or MF_SEPARATOR;
// Add one menu item to context menu
InsertMenu(Menu, indexMenu, Flags, FMenuOffset+i,
PChar(FContextMenu.Items[i].Caption));
inc(indexMenu);
Last := i+1;
end;
end else
FMenuOffset := 0;
// Return number of menu items added
Result := MakeResult(SEVERITY_SUCCESS, FACILITY_NULL, Last)
end;
function TDropContextMenu.Initialize(pidlFolder: PItemIDList;
lpdobj: IDataObject; hKeyProgID: HKEY): HResult;
begin
FFiles.Clear;
if (lpdobj = nil) then
begin
Result := E_INVALIDARG;
Exit;
end;
// Save a reference to the source data object.
FDataObject := lpdobj;
// Extract source file names and store them in a string list.
with TFileDataFormat.Create(nil) do
try
if GetData(DataObject) then
FFiles.Assign(Files);
finally
Free;
end;
if (Assigned(FOnPopup)) then
FOnPopup(Self);
Result := NOERROR;
end;
procedure TDropContextMenu.SetContextMenu(const Value: TPopupMenu);
begin
if (Value <> FContextMenu) then
begin
if (FContextMenu <> nil) then
FContextMenu.RemoveFreeNotification(Self);
FContextMenu := Value;
if (Value <> nil) then
Value.FreeNotification(Self);
end;
end;
procedure TDropContextMenu.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) and (AComponent = FContextMenu) then
FContextMenu := nil;
inherited;
end;
////////////////////////////////////////////////////////////////////////////////
//
// TDropContextMenuFactory
//
////////////////////////////////////////////////////////////////////////////////
function TDropContextMenuFactory.HandlerRegSubKey: string;
begin
Result := 'ContextMenuHandlers';
end;
procedure TDropContextMenuFactory.UpdateRegistry(Register: Boolean);
var
ClassIDStr: string;
begin
ClassIDStr := GUIDToString(ClassID);
if Register then
begin
inherited UpdateRegistry(Register);
CreateRegKey(FileClass+'\shellex\'+HandlerRegSubKey+'\'+ClassName, '', ClassIDStr);
if (Win32Platform = VER_PLATFORM_WIN32_NT) then
with TRegistry.Create do
try
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions', True);
OpenKey('Approved', True);
WriteString(ClassIDStr, Description);
finally
Free;
end;
end else
begin
if (Win32Platform = VER_PLATFORM_WIN32_NT) then
with TRegistry.Create do
try
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions', True);
OpenKey('Approved', True);
DeleteKey(ClassIDStr);
finally
Free;
end;
DeleteRegKey(FileClass+'\shellex\'+HandlerRegSubKey+'\'+ClassName);
inherited UpdateRegistry(Register);
end;
end;
end.
|
unit testgq;
interface
uses Math, Sysutils, Ap, hblas, reflections, creflections, sblas, ablasf, ablas, ortfac, blas, rotations, hsschur, evd, gammafunc, gq;
function TestGQunit(Silent : Boolean):Boolean;
procedure BuildGaussHermiteQuadrature(n : AlglibInteger;
var x : TReal1DArray;
var w : TReal1DArray);
function testgq_test_silent():Boolean;
function testgq_test():Boolean;
implementation
function MapKind(K : AlglibInteger):Double;forward;
procedure BuildGaussLegendreQuadrature(n : AlglibInteger;
var x : TReal1DArray;
var w : TReal1DArray);forward;
procedure BuildGaussJacobiQuadrature(n : AlglibInteger;
Alpha : Double;
Beta : Double;
var x : TReal1DArray;
var w : TReal1DArray);forward;
procedure BuildGaussLaguerreQuadrature(n : AlglibInteger;
Alpha : Double;
var x : TReal1DArray;
var w : TReal1DArray);forward;
(*************************************************************************
Test
*************************************************************************)
function TestGQunit(Silent : Boolean):Boolean;
var
Alpha : TReal1DArray;
Beta : TReal1DArray;
X : TReal1DArray;
W : TReal1DArray;
X2 : TReal1DArray;
W2 : TReal1DArray;
Err : Double;
N : AlglibInteger;
I : AlglibInteger;
Info : AlglibInteger;
AKind : AlglibInteger;
BKind : AlglibInteger;
AlphaC : Double;
BetaC : Double;
ErrTol : Double;
NonStrictErrTol : Double;
StrictErrTol : Double;
RecErrors : Boolean;
SpecErrors : Boolean;
WasErrors : Boolean;
begin
RecErrors := False;
SpecErrors := False;
WasErrors := False;
ErrTol := 1.0E-12;
NonStrictErrTol := 1.0E-6;
StrictErrTol := 1000*MachineEpsilon;
//
// Three tests for rec-based Gauss quadratures with known weights/nodes:
// 1. Gauss-Legendre with N=2
// 2. Gauss-Legendre with N=5
// 3. Gauss-Chebyshev with N=1, 2, 4, 8, ..., 512
//
Err := 0;
SetLength(Alpha, 2);
SetLength(Beta, 2);
Alpha[0] := 0;
Alpha[1] := 0;
Beta[1] := AP_Double(1)/(4*1*1-1);
GQGenerateRec(Alpha, Beta, 2.0, 2, Info, X, W);
if Info>0 then
begin
Err := Max(Err, AbsReal(X[0]+Sqrt(3)/3));
Err := Max(Err, AbsReal(X[1]-Sqrt(3)/3));
Err := Max(Err, AbsReal(W[0]-1));
Err := Max(Err, AbsReal(W[1]-1));
I:=0;
while I<=0 do
begin
RecErrors := RecErrors or AP_FP_Greater_Eq(X[I],X[I+1]);
Inc(I);
end;
end
else
begin
RecErrors := True;
end;
SetLength(Alpha, 5);
SetLength(Beta, 5);
Alpha[0] := 0;
I:=1;
while I<=4 do
begin
Alpha[I] := 0;
Beta[I] := AP_Sqr(I)/(4*AP_Sqr(I)-1);
Inc(I);
end;
GQGenerateRec(Alpha, Beta, 2.0, 5, Info, X, W);
if Info>0 then
begin
Err := Max(Err, AbsReal(X[0]+Sqrt(245+14*Sqrt(70))/21));
Err := Max(Err, AbsReal(X[0]+X[4]));
Err := Max(Err, AbsReal(X[1]+Sqrt(245-14*Sqrt(70))/21));
Err := Max(Err, AbsReal(X[1]+X[3]));
Err := Max(Err, AbsReal(X[2]));
Err := Max(Err, AbsReal(W[0]-(322-13*Sqrt(70))/900));
Err := Max(Err, AbsReal(W[0]-W[4]));
Err := Max(Err, AbsReal(W[1]-(322+13*Sqrt(70))/900));
Err := Max(Err, AbsReal(W[1]-W[3]));
Err := Max(Err, AbsReal(W[2]-AP_Double(128)/225));
I:=0;
while I<=3 do
begin
RecErrors := RecErrors or AP_FP_Greater_Eq(X[I],X[I+1]);
Inc(I);
end;
end
else
begin
RecErrors := True;
end;
N := 1;
while N<=512 do
begin
SetLength(Alpha, N);
SetLength(Beta, N);
I:=0;
while I<=N-1 do
begin
Alpha[I] := 0;
if I=0 then
begin
Beta[I] := 0;
end;
if I=1 then
begin
Beta[I] := AP_Double(1)/2;
end;
if I>1 then
begin
Beta[I] := AP_Double(1)/4;
end;
Inc(I);
end;
GQGenerateRec(Alpha, Beta, Pi, N, Info, X, W);
if Info>0 then
begin
I:=0;
while I<=N-1 do
begin
Err := Max(Err, AbsReal(X[I]-Cos(Pi*(N-I-0.5)/N)));
Err := Max(Err, AbsReal(W[I]-Pi/N));
Inc(I);
end;
I:=0;
while I<=N-2 do
begin
RecErrors := RecErrors or AP_FP_Greater_Eq(X[I],X[I+1]);
Inc(I);
end;
end
else
begin
RecErrors := True;
end;
N := N*2;
end;
RecErrors := RecErrors or AP_FP_Greater(Err,ErrTol);
//
// Three tests for rec-based Gauss-Lobatto quadratures with known weights/nodes:
// 1. Gauss-Lobatto with N=3
// 2. Gauss-Lobatto with N=4
// 3. Gauss-Lobatto with N=6
//
Err := 0;
SetLength(Alpha, 2);
SetLength(Beta, 2);
Alpha[0] := 0;
Alpha[1] := 0;
Beta[0] := 0;
Beta[1] := AP_Double(1*1)/(4*1*1-1);
GQGenerateGaussLobattoRec(Alpha, Beta, 2.0, -1, +1, 3, Info, X, W);
if Info>0 then
begin
Err := Max(Err, AbsReal(X[0]+1));
Err := Max(Err, AbsReal(X[1]));
Err := Max(Err, AbsReal(X[2]-1));
Err := Max(Err, AbsReal(W[0]-AP_Double(1)/3));
Err := Max(Err, AbsReal(W[1]-AP_Double(4)/3));
Err := Max(Err, AbsReal(W[2]-AP_Double(1)/3));
I:=0;
while I<=1 do
begin
RecErrors := RecErrors or AP_FP_Greater_Eq(X[I],X[I+1]);
Inc(I);
end;
end
else
begin
RecErrors := True;
end;
SetLength(Alpha, 3);
SetLength(Beta, 3);
Alpha[0] := 0;
Alpha[1] := 0;
Alpha[2] := 0;
Beta[0] := 0;
Beta[1] := AP_Double(1*1)/(4*1*1-1);
Beta[2] := AP_Double(2*2)/(4*2*2-1);
GQGenerateGaussLobattoRec(Alpha, Beta, 2.0, -1, +1, 4, Info, X, W);
if Info>0 then
begin
Err := Max(Err, AbsReal(X[0]+1));
Err := Max(Err, AbsReal(X[1]+Sqrt(5)/5));
Err := Max(Err, AbsReal(X[2]-Sqrt(5)/5));
Err := Max(Err, AbsReal(X[3]-1));
Err := Max(Err, AbsReal(W[0]-AP_Double(1)/6));
Err := Max(Err, AbsReal(W[1]-AP_Double(5)/6));
Err := Max(Err, AbsReal(W[2]-AP_Double(5)/6));
Err := Max(Err, AbsReal(W[3]-AP_Double(1)/6));
I:=0;
while I<=2 do
begin
RecErrors := RecErrors or AP_FP_Greater_Eq(X[I],X[I+1]);
Inc(I);
end;
end
else
begin
RecErrors := True;
end;
SetLength(Alpha, 5);
SetLength(Beta, 5);
Alpha[0] := 0;
Alpha[1] := 0;
Alpha[2] := 0;
Alpha[3] := 0;
Alpha[4] := 0;
Beta[0] := 0;
Beta[1] := AP_Double(1*1)/(4*1*1-1);
Beta[2] := AP_Double(2*2)/(4*2*2-1);
Beta[3] := AP_Double(3*3)/(4*3*3-1);
Beta[4] := AP_Double(4*4)/(4*4*4-1);
GQGenerateGaussLobattoRec(Alpha, Beta, 2.0, -1, +1, 6, Info, X, W);
if Info>0 then
begin
Err := Max(Err, AbsReal(X[0]+1));
Err := Max(Err, AbsReal(X[1]+Sqrt((7+2*Sqrt(7))/21)));
Err := Max(Err, AbsReal(X[2]+Sqrt((7-2*Sqrt(7))/21)));
Err := Max(Err, AbsReal(X[3]-Sqrt((7-2*Sqrt(7))/21)));
Err := Max(Err, AbsReal(X[4]-Sqrt((7+2*Sqrt(7))/21)));
Err := Max(Err, AbsReal(X[5]-1));
Err := Max(Err, AbsReal(W[0]-AP_Double(1)/15));
Err := Max(Err, AbsReal(W[1]-(14-Sqrt(7))/30));
Err := Max(Err, AbsReal(W[2]-(14+Sqrt(7))/30));
Err := Max(Err, AbsReal(W[3]-(14+Sqrt(7))/30));
Err := Max(Err, AbsReal(W[4]-(14-Sqrt(7))/30));
Err := Max(Err, AbsReal(W[5]-AP_Double(1)/15));
I:=0;
while I<=4 do
begin
RecErrors := RecErrors or AP_FP_Greater_Eq(X[I],X[I+1]);
Inc(I);
end;
end
else
begin
RecErrors := True;
end;
RecErrors := RecErrors or AP_FP_Greater(Err,ErrTol);
//
// Three tests for rec-based Gauss-Radau quadratures with known weights/nodes:
// 1. Gauss-Radau with N=2
// 2. Gauss-Radau with N=3
// 3. Gauss-Radau with N=3 (another case)
//
Err := 0;
SetLength(Alpha, 1);
SetLength(Beta, 2);
Alpha[0] := 0;
Beta[0] := 0;
Beta[1] := AP_Double(1*1)/(4*1*1-1);
GQGenerateGaussRadauRec(Alpha, Beta, 2.0, -1, 2, Info, X, W);
if Info>0 then
begin
Err := Max(Err, AbsReal(X[0]+1));
Err := Max(Err, AbsReal(X[1]-AP_Double(1)/3));
Err := Max(Err, AbsReal(W[0]-0.5));
Err := Max(Err, AbsReal(W[1]-1.5));
I:=0;
while I<=0 do
begin
RecErrors := RecErrors or AP_FP_Greater_Eq(X[I],X[I+1]);
Inc(I);
end;
end
else
begin
RecErrors := True;
end;
SetLength(Alpha, 2);
SetLength(Beta, 3);
Alpha[0] := 0;
Alpha[1] := 0;
I:=0;
while I<=2 do
begin
Beta[I] := AP_Sqr(I)/(4*AP_Sqr(I)-1);
Inc(I);
end;
GQGenerateGaussRadauRec(Alpha, Beta, 2.0, -1, 3, Info, X, W);
if Info>0 then
begin
Err := Max(Err, AbsReal(X[0]+1));
Err := Max(Err, AbsReal(X[1]-(1-Sqrt(6))/5));
Err := Max(Err, AbsReal(X[2]-(1+Sqrt(6))/5));
Err := Max(Err, AbsReal(W[0]-AP_Double(2)/9));
Err := Max(Err, AbsReal(W[1]-(16+Sqrt(6))/18));
Err := Max(Err, AbsReal(W[2]-(16-Sqrt(6))/18));
I:=0;
while I<=1 do
begin
RecErrors := RecErrors or AP_FP_Greater_Eq(X[I],X[I+1]);
Inc(I);
end;
end
else
begin
RecErrors := True;
end;
SetLength(Alpha, 2);
SetLength(Beta, 3);
Alpha[0] := 0;
Alpha[1] := 0;
I:=0;
while I<=2 do
begin
Beta[I] := AP_Sqr(I)/(4*AP_Sqr(I)-1);
Inc(I);
end;
GQGenerateGaussRadauRec(Alpha, Beta, 2.0, +1, 3, Info, X, W);
if Info>0 then
begin
Err := Max(Err, AbsReal(X[2]-1));
Err := Max(Err, AbsReal(X[1]+(1-Sqrt(6))/5));
Err := Max(Err, AbsReal(X[0]+(1+Sqrt(6))/5));
Err := Max(Err, AbsReal(W[2]-AP_Double(2)/9));
Err := Max(Err, AbsReal(W[1]-(16+Sqrt(6))/18));
Err := Max(Err, AbsReal(W[0]-(16-Sqrt(6))/18));
I:=0;
while I<=1 do
begin
RecErrors := RecErrors or AP_FP_Greater_Eq(X[I],X[I+1]);
Inc(I);
end;
end
else
begin
RecErrors := True;
end;
RecErrors := RecErrors or AP_FP_Greater(Err,ErrTol);
//
// test recurrence-based special cases (Legendre, Jacobi, Hermite, ...)
// against another implementation (polynomial root-finder)
//
N:=1;
while N<=20 do
begin
//
// test gauss-legendre
//
Err := 0;
GQGenerateGaussLegendre(N, Info, X, W);
if Info>0 then
begin
BuildGaussLegendreQuadrature(N, X2, W2);
I:=0;
while I<=N-1 do
begin
Err := Max(Err, AbsReal(X[I]-X2[I]));
Err := Max(Err, AbsReal(W[I]-W2[I]));
Inc(I);
end;
end
else
begin
SpecErrors := True;
end;
SpecErrors := SpecErrors or AP_FP_Greater(Err,ErrTol);
//
// Test Gauss-Jacobi.
// Since task is much more difficult we will use less strict
// threshold.
//
Err := 0;
AKind:=0;
while AKind<=9 do
begin
BKind:=0;
while BKind<=9 do
begin
AlphaC := MapKind(AKind);
BetaC := MapKind(BKind);
GQGenerateGaussJacobi(N, AlphaC, BetaC, Info, X, W);
if Info>0 then
begin
BuildGaussJacobiQuadrature(N, AlphaC, BetaC, X2, W2);
I:=0;
while I<=N-1 do
begin
Err := Max(Err, AbsReal(X[I]-X2[I]));
Err := Max(Err, AbsReal(W[I]-W2[I]));
Inc(I);
end;
end
else
begin
SpecErrors := True;
end;
Inc(BKind);
end;
Inc(AKind);
end;
SpecErrors := SpecErrors or AP_FP_Greater(Err,NonStrictErrTol);
//
// special test for Gauss-Jacobi (Chebyshev weight
// function with analytically known nodes/weights)
//
Err := 0;
GQGenerateGaussJacobi(N, -0.5, -0.5, Info, X, W);
if Info>0 then
begin
I:=0;
while I<=N-1 do
begin
Err := Max(Err, AbsReal(X[I]+Cos(Pi*(I+0.5)/N)));
Err := Max(Err, AbsReal(W[I]-Pi/N));
Inc(I);
end;
end
else
begin
SpecErrors := True;
end;
SpecErrors := SpecErrors or AP_FP_Greater(Err,StrictErrTol);
//
// Test Gauss-Laguerre
//
Err := 0;
AKind:=0;
while AKind<=9 do
begin
AlphaC := MapKind(AKind);
GQGenerateGaussLaguerre(N, AlphaC, Info, X, W);
if Info>0 then
begin
BuildGaussLaguerreQuadrature(N, AlphaC, X2, W2);
I:=0;
while I<=N-1 do
begin
Err := Max(Err, AbsReal(X[I]-X2[I]));
Err := Max(Err, AbsReal(W[I]-W2[I]));
Inc(I);
end;
end
else
begin
SpecErrors := True;
end;
Inc(AKind);
end;
SpecErrors := SpecErrors or AP_FP_Greater(Err,NonStrictErrTol);
//
// Test Gauss-Hermite
//
Err := 0;
GQGenerateGaussHermite(N, Info, X, W);
if Info>0 then
begin
BuildGaussHermiteQuadrature(N, X2, W2);
I:=0;
while I<=N-1 do
begin
Err := Max(Err, AbsReal(X[I]-X2[I]));
Err := Max(Err, AbsReal(W[I]-W2[I]));
Inc(I);
end;
end
else
begin
SpecErrors := True;
end;
SpecErrors := SpecErrors or AP_FP_Greater(Err,NonStrictErrTol);
Inc(N);
end;
//
// end
//
WasErrors := RecErrors or SpecErrors;
if not Silent then
begin
Write(Format('TESTING GAUSS QUADRATURES'#13#10'',[]));
Write(Format('FINAL RESULT: ',[]));
if WasErrors then
begin
Write(Format('FAILED'#13#10'',[]));
end
else
begin
Write(Format('OK'#13#10'',[]));
end;
Write(Format('* SPECIAL CASES (LEGENDRE/JACOBI/..) ',[]));
if SpecErrors then
begin
Write(Format('FAILED'#13#10'',[]));
end
else
begin
Write(Format('OK'#13#10'',[]));
end;
Write(Format('* RECURRENCE-BASED: ',[]));
if RecErrors then
begin
Write(Format('FAILED'#13#10'',[]));
end
else
begin
Write(Format('OK'#13#10'',[]));
end;
if WasErrors then
begin
Write(Format('TEST FAILED'#13#10'',[]));
end
else
begin
Write(Format('TEST PASSED'#13#10'',[]));
end;
Write(Format(''#13#10''#13#10'',[]));
end;
Result := not WasErrors;
end;
(*************************************************************************
Gauss-Hermite, another variant
*************************************************************************)
procedure BuildGaussHermiteQuadrature(n : AlglibInteger;
var x : TReal1DArray;
var w : TReal1DArray);
var
i : AlglibInteger;
j : AlglibInteger;
r : Double;
r1 : Double;
p1 : Double;
p2 : Double;
p3 : Double;
dp3 : Double;
pipm4 : Double;
tmp : Double;
begin
SetLength(x, n-1+1);
SetLength(w, n-1+1);
pipm4 := Power(Pi, -0.25);
i:=0;
while i<=(n+1) div 2-1 do
begin
if i=0 then
begin
r := Sqrt(2*n+1)-1.85575*Power(2*n+1, -AP_Double(1)/6);
end
else
begin
if i=1 then
begin
r := r-1.14*Power(n, 0.426)/r;
end
else
begin
if i=2 then
begin
r := 1.86*r-0.86*x[0];
end
else
begin
if i=3 then
begin
r := 1.91*r-0.91*x[1];
end
else
begin
r := 2*r-x[i-2];
end;
end;
end;
end;
repeat
p2 := 0;
p3 := pipm4;
j:=0;
while j<=n-1 do
begin
p1 := p2;
p2 := p3;
p3 := p2*r*Sqrt(AP_Double(2)/(j+1))-p1*Sqrt(AP_Double(j)/(j+1));
Inc(j);
end;
dp3 := Sqrt(2*j)*p2;
r1 := r;
r := r-p3/dp3;
until AP_FP_Less(AbsReal(r-r1),MachineEpsilon*(1+AbsReal(r))*100);
x[i] := r;
w[i] := 2/(dp3*dp3);
x[n-1-i] := -x[i];
w[n-1-i] := w[i];
Inc(i);
end;
i:=0;
while i<=N-1 do
begin
j:=0;
while j<=n-2-i do
begin
if AP_FP_Greater_Eq(x[j],x[j+1]) then
begin
Tmp := x[j];
x[j] := x[j+1];
x[j+1] := Tmp;
Tmp := w[j];
w[j] := w[j+1];
w[j+1] := Tmp;
end;
Inc(j);
end;
Inc(i);
end;
end;
(*************************************************************************
Maps:
0 => -0.9
1 => -0.5
2 => -0.1
3 => 0.0
4 => +0.1
5 => +0.5
6 => +0.9
7 => +1.0
8 => +1.5
9 => +2.0
*************************************************************************)
function MapKind(K : AlglibInteger):Double;
begin
Result := 0;
if K=0 then
begin
Result := -0.9;
end;
if K=1 then
begin
Result := -0.5;
end;
if K=2 then
begin
Result := -0.1;
end;
if K=3 then
begin
Result := 0.0;
end;
if K=4 then
begin
Result := +0.1;
end;
if K=5 then
begin
Result := +0.5;
end;
if K=6 then
begin
Result := +0.9;
end;
if K=7 then
begin
Result := +1.0;
end;
if K=8 then
begin
Result := +1.5;
end;
if K=9 then
begin
Result := +2.0;
end;
end;
(*************************************************************************
Gauss-Legendre, another variant
*************************************************************************)
procedure BuildGaussLegendreQuadrature(n : AlglibInteger;
var x : TReal1DArray;
var w : TReal1DArray);
var
i : AlglibInteger;
j : AlglibInteger;
r : Double;
r1 : Double;
p1 : Double;
p2 : Double;
p3 : Double;
dp3 : Double;
Tmp : Double;
begin
SetLength(x, n-1+1);
SetLength(w, n-1+1);
i:=0;
while i<=(n+1) div 2-1 do
begin
r := cos(Pi*(4*i+3)/(4*n+2));
repeat
p2 := 0;
p3 := 1;
j:=0;
while j<=n-1 do
begin
p1 := p2;
p2 := p3;
p3 := ((2*j+1)*r*p2-j*p1)/(j+1);
Inc(j);
end;
dp3 := n*(r*p3-p2)/(r*r-1);
r1 := r;
r := r-p3/dp3;
until AP_FP_Less(AbsReal(r-r1),MachineEpsilon*(1+AbsReal(r))*100);
x[i] := r;
x[n-1-i] := -r;
w[i] := 2/((1-r*r)*dp3*dp3);
w[n-1-i] := 2/((1-r*r)*dp3*dp3);
Inc(i);
end;
i:=0;
while i<=N-1 do
begin
j:=0;
while j<=n-2-i do
begin
if AP_FP_Greater_Eq(x[j],x[j+1]) then
begin
Tmp := x[j];
x[j] := x[j+1];
x[j+1] := Tmp;
Tmp := w[j];
w[j] := w[j+1];
w[j+1] := Tmp;
end;
Inc(j);
end;
Inc(i);
end;
end;
(*************************************************************************
Gauss-Jacobi, another variant
*************************************************************************)
procedure BuildGaussJacobiQuadrature(n : AlglibInteger;
Alpha : Double;
Beta : Double;
var x : TReal1DArray;
var w : TReal1DArray);
var
i : AlglibInteger;
j : AlglibInteger;
r : Double;
r1 : Double;
t1 : Double;
t2 : Double;
t3 : Double;
p1 : Double;
p2 : Double;
p3 : Double;
pp : Double;
an : Double;
bn : Double;
a : Double;
b : Double;
c : Double;
tmpsgn : Double;
Tmp : Double;
alfbet : Double;
temp : Double;
its : AlglibInteger;
begin
SetLength(x, n-1+1);
SetLength(w, n-1+1);
i:=0;
while i<=n-1 do
begin
if i=0 then
begin
an := alpha/n;
bn := beta/n;
t1 := (1+alpha)*(2.78/(4+n*n)+0.768*an/n);
t2 := 1+1.48*an+0.96*bn+0.452*an*an+0.83*an*bn;
r := (t2-t1)/t2;
end
else
begin
if i=1 then
begin
t1 := (4.1+alpha)/((1+alpha)*(1+0.156*alpha));
t2 := 1+0.06*(n-8)*(1+0.12*alpha)/n;
t3 := 1+0.012*beta*(1+0.25*AbsReal(alpha))/n;
r := r-t1*t2*t3*(1-r);
end
else
begin
if i=2 then
begin
t1 := (1.67+0.28*alpha)/(1+0.37*alpha);
t2 := 1+0.22*(n-8)/n;
t3 := 1+8*beta/((6.28+beta)*n*n);
r := r-t1*t2*t3*(x[0]-r);
end
else
begin
if i<n-2 then
begin
r := 3*x[i-1]-3*x[i-2]+x[i-3];
end
else
begin
if i=n-2 then
begin
t1 := (1+0.235*beta)/(0.766+0.119*beta);
t2 := 1/(1+0.639*(n-4)/(1+0.71*(n-4)));
t3 := 1/(1+20*alpha/((7.5+alpha)*n*n));
r := r+t1*t2*t3*(r-x[i-2]);
end
else
begin
if i=n-1 then
begin
t1 := (1+0.37*beta)/(1.67+0.28*beta);
t2 := 1/(1+0.22*(n-8)/n);
t3 := 1/(1+8*alpha/((6.28+alpha)*n*n));
r := r+t1*t2*t3*(r-x[i-2]);
end;
end;
end;
end;
end;
end;
alfbet := alpha+beta;
repeat
temp := 2+alfbet;
p1 := (alpha-beta+temp*r)*0.5;
p2 := 1;
j:=2;
while j<=n do
begin
p3 := p2;
p2 := p1;
temp := 2*j+alfbet;
a := 2*j*(j+alfbet)*(temp-2);
b := (temp-1)*(alpha*alpha-beta*beta+temp*(temp-2)*r);
c := 2*(j-1+alpha)*(j-1+beta)*temp;
p1 := (b*p2-c*p3)/a;
Inc(j);
end;
pp := (n*(alpha-beta-temp*r)*p1+2*(n+alpha)*(n+beta)*p2)/(temp*(1-r*r));
r1 := r;
r := r1-p1/pp;
until AP_FP_Less(AbsReal(r-r1),MachineEpsilon*(1+AbsReal(r))*100);
x[i] := r;
w[i] := exp(LnGamma(alpha+n, tmpsgn)+LnGamma(beta+n, tmpsgn)-LnGamma(n+1, tmpsgn)-LnGamma(n+alfbet+1, tmpsgn))*temp*Power(2, alfbet)/(pp*p2);
Inc(i);
end;
i:=0;
while i<=N-1 do
begin
j:=0;
while j<=n-2-i do
begin
if AP_FP_Greater_Eq(x[j],x[j+1]) then
begin
Tmp := x[j];
x[j] := x[j+1];
x[j+1] := Tmp;
Tmp := w[j];
w[j] := w[j+1];
w[j+1] := Tmp;
end;
Inc(j);
end;
Inc(i);
end;
end;
(*************************************************************************
Gauss-Laguerre, another variant
*************************************************************************)
procedure BuildGaussLaguerreQuadrature(n : AlglibInteger;
Alpha : Double;
var x : TReal1DArray;
var w : TReal1DArray);
var
i : AlglibInteger;
j : AlglibInteger;
r : Double;
r1 : Double;
p1 : Double;
p2 : Double;
p3 : Double;
dp3 : Double;
tsg : Double;
tmp : Double;
begin
SetLength(x, n-1+1);
SetLength(w, n-1+1);
i:=0;
while i<=n-1 do
begin
if i=0 then
begin
r := (1+Alpha)*(3+0.92*Alpha)/(1+2.4*n+1.8*Alpha);
end
else
begin
if i=1 then
begin
r := r+(15+6.25*Alpha)/(1+0.9*Alpha+2.5*n);
end
else
begin
r := r+((1+2.55*(i-1))/(1.9*(i-1))+1.26*(i-1)*Alpha/(1+3.5*(i-1)))/(1+0.3*Alpha)*(r-x[i-2]);
end;
end;
repeat
p2 := 0;
p3 := 1;
j:=0;
while j<=n-1 do
begin
p1 := p2;
p2 := p3;
p3 := ((-r+2*j+alpha+1)*p2-(j+Alpha)*p1)/(j+1);
Inc(j);
end;
dp3 := (n*p3-(n+Alpha)*p2)/r;
r1 := r;
r := r-p3/dp3;
until AP_FP_Less(AbsReal(r-r1),MachineEpsilon*(1+AbsReal(r))*100);
x[i] := r;
w[i] := -Exp(LnGamma(Alpha+n, tsg)-LnGamma(n, tsg))/(dp3*n*p2);
Inc(i);
end;
i:=0;
while i<=N-1 do
begin
j:=0;
while j<=n-2-i do
begin
if AP_FP_Greater_Eq(x[j],x[j+1]) then
begin
Tmp := x[j];
x[j] := x[j+1];
x[j+1] := Tmp;
Tmp := w[j];
w[j] := w[j+1];
w[j+1] := Tmp;
end;
Inc(j);
end;
Inc(i);
end;
end;
(*************************************************************************
Silent unit test
*************************************************************************)
function testgq_test_silent():Boolean;
begin
Result := TestGQunit(True);
end;
(*************************************************************************
Unit test
*************************************************************************)
function testgq_test():Boolean;
begin
Result := TestGQunit(False);
end;
end. |
unit stack;
interface
uses SysUtils, Classes;
const
T_NIL = 0; // external types
T_BOOLEAN = 1;
T_POINTER = 2;
T_NUMBER = 3;
T_STRING = 4;
type
TStack = class(TObject)
private
Marker : Cardinal;
DT : TList; // element type
DA : TList; // element content or address
function GetIndex(Index : Integer; out Res : Integer) : LongBool;
public
constructor Create;
procedure Free;
function GetTop : Integer;
function GetType(Index : Integer) : Integer;
procedure Insert(Index : Integer);
procedure PushNil;
procedure PushBoolean(Value : LongBool);
procedure PushPointer(Value : Pointer);
procedure PushPtrOrNil(Value : Pointer);
procedure PushInteger(Value : Integer);
procedure PushDouble(Value : Double);
procedure PushStrRef(Value : PAnsiChar);
procedure PushStrVal(Value : PAnsiChar);
procedure PushLStrRef(Value : PAnsiChar; Len : Integer);
procedure PushLStrVal(Value : PAnsiChar; Len : Integer);
procedure PushValue(Index : Integer);
function GetBoolean(Index : Integer) : LongBool;
function GetPointer(Index : Integer) : Pointer;
function GetInteger(Index : Integer) : Integer;
function GetDouble(Index : Integer) : Double;
function GetString(Index : Integer) : PAnsiChar;
function GetLString(Index : Integer; out Len : Integer) : PAnsiChar;
procedure Remove(Index : Integer);
procedure SetTop(Index : Integer);
procedure Mark;
procedure Clean;
procedure MoveTo(Target : TStack; Index,Cnt : Integer);
end;
implementation
////////////////////////////////////////////////////////////////////////////////
type
TLStr = record // This type is used to hold S_LSTRREF and S_LSTRVAL.
L : Integer; // In the latter case, the actual string is stored
P : Pointer; // beginning at P, so the structure requires >8 bytes.
end;
PLStr = ^TLStr;
const
S_NIL = 0; // internal types, stored in DT
S_BOOLEAN = 1;
S_POINTER = 2;
S_INTEGER = 3;
S_DOUBLE = 4;
S_STRREF = 5;
S_LSTRREF = 6;
S_LSTRVAL = 7;
////////////////////////////////////////////////////////////////////////////////
constructor TStack.Create;
begin
inherited Create;
DT:=TList.Create;
DA:=TList.Create;
Marker:=0;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.Free;
begin
SetTop(0);
DT.Free;
DA.Free;
inherited Free;
end;
////////////////////////////////////////////////////////////////////////////////
function TStack.GetIndex(Index : Integer; out Res : Integer) : LongBool;
// converts logical index (may be negative) to actual index (zero-based)
begin
if Index>=0 then Res:=Index-1
else Res:=DT.Count+Index;
Result:=(Res>=0)and(Res<DT.Count); // return false if index out of bounds
end;
////////////////////////////////////////////////////////////////////////////////
function TStack.GetTop : Integer;
// returns logical index of last item on stack (= number of items)
begin
Result:=DT.Count;
end;
////////////////////////////////////////////////////////////////////////////////
function TStack.GetType(Index : Integer) : Integer;
// converts internal to external type
var
i : Integer;
begin
Result:=T_NIL; // default is nil
if GetIndex(Index,i) then
case Cardinal(DT[i]) of
S_BOOLEAN : Result:=T_BOOLEAN;
S_POINTER : Result:=T_POINTER;
S_INTEGER,S_DOUBLE : Result:=T_NUMBER;
S_STRREF,S_LSTRREF,
S_LSTRVAL : Result:=T_STRING;
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.Insert(Index : Integer);
// insert top item at specified index (actually moves item)
var
i,t : Integer;
begin
if not GetIndex(Index,i) then Exit; // target index must be valid
t:=DT.Count-1;
DT.Insert(i,DT[t]);
DA.Insert(i,DA[t]);
DT.Delete(t+1);
DA.Delete(t+1);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.PushNil;
// push NIL to top of stack
begin
DT.Add(Pointer(S_NIL));
DA.Add(nil);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.PushBoolean(Value : LongBool);
// push boolean to top of stack
begin
DT.Add(Pointer(S_BOOLEAN));
DA.Add(Pointer(Value));
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.PushPointer(Value : Pointer);
// push pointer to top of stack
begin
DT.Add(Pointer(S_POINTER));
DA.Add(Value);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.PushPtrOrNil(Value : Pointer);
// push pointer to top of stack, replace with NIL if pointer is zero
begin
if Value=nil then PushNil
else PushPointer(Value);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.PushInteger(Value : Integer);
// push integer to top of stack
begin
DT.Add(Pointer(S_INTEGER));
DA.Add(Pointer(Value));
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.PushDouble(Value : Double);
// push double to top of stack
var
P : ^Double;
begin
New(P); // reserve 8 bytes
P^:=Value;
DT.Add(Pointer(S_DOUBLE));
DA.Add(P);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.PushStrRef(Value : PAnsiChar);
// push string reference to top of stack
begin
DT.Add(Pointer(S_STRREF));
DA.Add(Value);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.PushStrVal(Value : PAnsiChar);
// push string value to top of stack
begin
PushLStrVal(Value,Length(Value)); // store internally as length-string
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.PushLStrRef(Value : PAnsiChar; Len : Integer);
// push length-string reference to top of stack
var
Buf : PLStr;
begin
New(Buf); // reserve 8 bytes
Buf^.L:=Len;
Buf^.P:=Value;
DT.Add(Pointer(S_LSTRREF));
DA.Add(Buf);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.PushLStrVal(Value : PAnsiChar; Len : Integer);
// push length-string value to top of stack
var
Buf : PLStr;
begin
GetMem(Buf,Len+5); // reserve space (>8 bytes!)
Buf^.L:=Len;
Move(Value^,Buf^.P,Len); // overwrite memory starting at P
PAnsiChar(Buf)[Len+5]:=#0; // make sure string is zero-terminated
DT.Add(Pointer(S_LSTRVAL));
DA.Add(Buf);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.PushValue(Index : Integer);
// push/duplicate item at specified index to top of stack
var
i : Integer;
begin
if GetIndex(Index,i) then
case Cardinal(DT[i]) of
S_DOUBLE : PushDouble(Double(DA[i]^));
S_LSTRREF : with PLStr(DA[i])^ do PushLStrRef(P,L);
S_LSTRVAL : with PLStr(DA[i])^ do PushLStrVal(@P,L);
else begin
DT.Add(DT[i]);
DA.Add(DA[i]);
end;
end;
end;
////////////////////////////////////////////////////////////////////////////////
function TStack.GetBoolean(Index : Integer) : LongBool;
// return boolean at index
var
i : Integer;
begin
Result:=False; // default is false
if GetIndex(Index,i) then
if Cardinal(DT[i])=S_BOOLEAN then
Result:=LongBool(DA[i]);
end;
////////////////////////////////////////////////////////////////////////////////
function TStack.GetPointer(Index : Integer) : Pointer;
// return pointer at index
var
i : Integer;
begin
Result:=nil; // default is nil
if GetIndex(Index,i) then
if Cardinal(DT[i])=S_POINTER then
Result:=DA[i];
end;
////////////////////////////////////////////////////////////////////////////////
function TStack.GetInteger(Index : Integer) : Integer;
// return integer at index
var
i : Integer;
begin
Result:=0; // default is 0
if GetIndex(Index,i) then
case Cardinal(DT[i]) of
S_INTEGER : Result:=Integer(DA[i]);
S_DOUBLE : Result:=Trunc(Double(DA[i]^));
end;
end;
////////////////////////////////////////////////////////////////////////////////
function TStack.GetDouble(Index : Integer) : Double;
// return double at index
var
i : Integer;
begin
Result:=0; // default is 0
if GetIndex(Index,i) then
case Cardinal(DT[i]) of
S_INTEGER : Result:=Integer(DA[i]);
S_DOUBLE : Result:=Double(DA[i]^);
end;
end;
////////////////////////////////////////////////////////////////////////////////
function TStack.GetString(Index : Integer) : PAnsiChar;
// return string at index
var
i : Integer;
begin
Result:=''; // default is ''
if GetIndex(Index,i) then
case Cardinal(DT[i]) of
S_STRREF : Result:=DA[i];
S_LSTRREF : with PLStr(DA[i])^ do Result:=P;
S_LSTRVAL : with PLStr(DA[i])^ do Result:=@P;
end;
end;
////////////////////////////////////////////////////////////////////////////////
function TStack.GetLString(Index : Integer; out Len : Integer) : PAnsiChar;
// return length-string at index
var
i : Integer;
begin
Len:=0; // set defaults
Result:=PAnsiChar('');
if GetIndex(Index,i) then
case Cardinal(DT[i]) of
S_STRREF : begin
Result:=DA[i];
Len:=Length(Result);
end;
S_LSTRREF : with PLStr(DA[i])^ do
begin
Result:=P;
Len:=L;
end;
S_LSTRVAL : with PLStr(DA[i])^ do
begin
Result:=@P;
Len:=L;
end;
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.Remove(Index : Integer);
// remove item at index
var
i : Integer;
begin
if not GetIndex(Index,i) then Exit;
case Cardinal(DT[i]) of // release memory
S_DOUBLE : Dispose(PDouble(DA[i]));
S_LSTRREF : Dispose(PLStr(DA[i]));
S_LSTRVAL : FreeMem(DA[i]);
end;
DT.Delete(i);
DA.Delete(i);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.SetTop(Index : Integer);
// grow or shrink stack to specified index
var
i : Integer;
begin
GetIndex(Index,i); // ignore result (allow invalid index)
if i<-1 then i:=-1;
while DT.Count-1<i do
PushNil;
while DT.Count-1>i do
Remove(-1);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.Mark;
// mark/remember current top index
begin
Marker:=GetTop;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.Clean;
// remove all elements up to marked
var
i : Integer;
begin
for i:=1 to Marker do
Remove(1);
Marker:=0;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TStack.MoveTo(Target : TStack; Index,Cnt : Integer);
// move items to another stack
var
i,j : Integer;
begin
if not GetIndex(Index,i) then Exit;
for j:=1 to Cnt do
begin
if i>=DT.Count then Break; // check cnt
Target.DT.Add(DT[i]);
Target.DA.Add(DA[i]);
DT.Delete(i);
DA.Delete(i);
end;
end;
////////////////////////////////////////////////////////////////////////////////
end.
|
unit Testthds;
{$mode objfpc}{$H+}
interface
uses
Classes,
Graphics, ExtCtrls, Forms,
PythonEngine;
type
{ TTestThread }
TTestThread = class(TPythonThread)
private
FScript: TStrings;
running : Boolean;
protected
procedure ExecuteWithPython; override;
public
constructor Create( AThreadExecMode: TThreadExecMode; script: TStrings);
procedure Stop;
end;
implementation
{ TTestThread }
constructor TTestThread.Create( AThreadExecMode: TThreadExecMode; script: TStrings);
begin
fScript := script;
FreeOnTerminate := True;
ThreadExecMode := AThreadExecMode;
inherited Create(False);
end;
procedure TTestThread.ExecuteWithPython;
begin
running := true;
try
with GetPythonEngine do
begin
if Assigned(fScript) then
ExecStrings(fScript);
end;
finally
running := false;
end;
end;
procedure TTestThread.Stop;
begin
with GetPythonEngine do
begin
if running then
begin
PyEval_AcquireThread(self.ThreadState);
PyErr_SetString(PyExc_KeyboardInterrupt^, 'Terminated');
PyEval_ReleaseThread(self.ThreadState);
end;
end;
end;
end.
|
unit ueverettrandom;
{ Random integer generation via beam-splitter quantum event generator
Code copyright (C)2019 minesadorada@charcodelvalle.com
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.
================================================================================
Description and purpose
=======================
The Everett interpretation of quantum mechanics ("Many Worlds") is that when
an interaction is made with an elementary wave function (such as an electron or
photon etc) the universe bifurcates.
ref: https://en.wikipedia.org/wiki/Many-worlds_interpretation
This happens naturally of course (just via radioactive decays in atoms of your
body there are about 5000 bifucations per second) but this component brings into
the mix "Free Will". By requesting a random number from the online source, which
is a beam-splitter based in Austrailia you are bifurcating the Universe deliberately
- that is, based on your Free Will.
You may or may not find that interesting, but nevertheless this component gives
you this ability (to "play God" with the Universe)
The random numbers returned are truly random (i.e. not pseudorandom via algorithm)
Details of the online resource below:
================================================================================
webpage: https://qrng.anu.edu.au/
To get a set of numbers generated online by a quantum number generator:
Post to: https://qrng.anu.edu.au/API/jsonI.php?length=[array length]&type=[data type]&size=[block size]
If the request is successful, the random numbers are returned in a JSON encoded array named 'data'
(Note: block size parameter is only needed for data type=hex16)
The random numbers are generated in real-time in our lab by measuring the quantum fluctuations of the vacuum
Example to get 10 numbers of range 0-255 is
https://qrng.anu.edu.au/API/jsonI.php?length=10&type=uint8
JSON returned:
{"type":"uint8","length":10,"data":[241,83,235,48,81,154,222,4,77,120],"success":true}
Example to get 10 numbers of range 0–65535 is
https://qrng.anu.edu.au/API/jsonI.php?length=10&type=uint16
JSON returned:
{"type":"uint16","length":10,"data":[50546,25450,24289,44825,10457,49509,48848,30970,33829,47807],"success":true}
Example to get 10 hexadecimal numbers of range 00–FF is
https://qrng.anu.edu.au/API/jsonI.php?length=10&type=hex16
JSON returned:
{"type":"string","length":10,"size":1,"data":["5d","f9","aa","bf","5e","02","3c","55","6e","9e"],"success":true}
Example to get 10 hexadecimal numbers of range 0000–FFFF (blocksize=2) is
https://qrng.anu.edu.au/API/jsonI.php?length=10&type=hex16&size=2
JSON returned:
{"type":"string","length":10,"size":2,"data":["2138","592e","0643","8cdf","b955","e42f","eda6","c62a","2c66","f009"],"success":true}
Example to get 10 hexadecimal numbers of range 000000–FFFFFF (blocksize=3) is
https://qrng.anu.edu.au/API/jsonI.php?length=10&type=hex16&size=3
JSON returned:
{"type":"string","length":10,"size":3,"data":["add825","ac3530","79b708","ee8d42","683647","b6bb25","a92571","a8ae6a","963131","f62ec2"],"success":true}
Javascript:
var json = eval('('+ ajaxobject.responseText +')'); /* JSON is here*/
document.getElementById('json_success').innerHTML = json.success;
document.getElementById('dataHere').innerHTML = ajaxobject.responseText;
================================================================================
Version History:
V0.1.2.0 - initial commit
V0.1.3.0 - cleanup
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Dialogs, Controls, Forms, StdCtrls, Variants,
everett_httpclient, open_ssl, fpjson, fpjsonrtti;
const
C_QUANTUMSERVERLIMIT = 1024;
C_URL = 'https://qrng.anu.edu.au/API/jsonI.php?length=%d&type=%s&size=%d';
resourcestring
rsSSLLibraries = 'SSL libraries unavailable and/or unable to be downloaded '
+ 'on this system. Please fix.';
rsFailedTooMan = 'Failed - Too many requests to the Quantum server%s%s';
rsFailedQuantu = 'Failed - Quantum server refused with code %d';
rsQuantumServe = 'Quantum server did not deliver a valid array';
rsFailedQuantu2 = 'Failed - Quantum server refused with code %s';
rsPleaseWaitCo = 'Please wait. Contacting Quantum Server';
type
TQuantumNumberType = (uint8, uint16, hex16);
TQuantumNumberDataObject = class; // Forward declaration
// This is a persistent class with an owner
{ TEverett }
TEverett = class(TComponent)
private
fHttpClient: TFPHTTPClient;
fQuantumNumberType: TQuantumNumberType;
fQuantumNumberDataObject: TQuantumNumberDataObject;
fShowWaitDialog: boolean;
fWaitDialogCaption: string;
fArraySize,fHexSize:Integer;
procedure SetArraySize(AValue:Integer);
protected
// Main worker function
function FetchQuantumRandomNumbers(AQuantumNumberType: TQuantumNumberType;
Alength: integer; ABlocksize: integer = 1): boolean; virtual;
// Object that contains array results
property QuantumNumberDataObject: TQuantumNumberDataObject
read fQuantumNumberDataObject;
public
// (Dynamic) Array results
IntegerArray: array of integer;
HexArray: array of string;
// TEverett should have an owner so that cleanup is easy
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// Fetch a single random number
function GetSingle8Bit: integer;
function GetSingle16Bit: integer;
function GetSingleHex: String;
// Array functions will put results into:
// (uint8, uint16) IntegerArray[0..Pred(ArraySize)]
// (hex16) HexArray[0..Pred(ArraySize)]
function GetInteger8BitArray:Boolean;
function GetInteger16BitArray:Boolean;
function GetHexArray:Boolean;
published
property NumberType: TQuantumNumberType read fQuantumNumberType
write fQuantumNumberType default uint8;
property ShowWaitDialog: boolean
read fShowWaitDialog write fShowWaitDialog default True;
property WaitDialogCaption: string read fWaitDialogCaption write fWaitDialogCaption;
property ArraySize:Integer read fArraySize write SetArraySize default 1;
property HexSize:Integer read fHexSize write fHexSize default 1;
end;
// DeStreamer.JSONToObject populates all the properties
// Do not change any of the properties
TQuantumNumberDataObject = class(TObject)
private
fNumberType: string;
fNumberLength: integer;
fNumbersize: integer;
fNumberData: variant;
fNumberSuccess: string;
public
published
// Prefix property name with & to avoid using a reserved pascal word
// Note: This bugs out the JEDI code formatter
property &type: string read fNumberType write fNumberType;
property length: integer read fNumberLength write fNumberLength;
property size: integer read fNumbersize write fNumbersize;
// Note: property "data" must be lowercase. JEDI changes it to "Data"
property data: variant read fNumberData write fNumberData;
property success: string read fNumberSuccess write fNumberSuccess;
end;
implementation
procedure TEverett.SetArraySize(AValue: Integer);
// Property setter
begin
if Avalue <=C_QUANTUMSERVERLIMIT then
fArraySize:=AValue
else
fArraySize:=1;
end;
// This is the core function.
// If successful, it populates either IntegerArray or HexArray
// Parameters:
// AQuantumNumberType can be uint8, uint16 or hex16
// ALength is the size of the returned array
// ABlocksize is only relavent if AQuantumNumberType=hex16
// it is the size of the hex number in HexArray (1=FF, 2=FFFF, 3=FFFFFF etc)
function TEverett.FetchQuantumRandomNumbers(AQuantumNumberType: TQuantumNumberType;
Alength: integer; ABlocksize: integer): boolean;
var
szURL: string;
JSON: TJSONStringType;
DeStreamer: TJSONDeStreamer;
ct: integer;
frmWaitDlg: TForm;
lbl_WaitDialog: TLabel;
begin
Result := False; // assume failure
// Reset arrays
SetLength(IntegerArray, 0);
SetLength(HexArray, 0);
// Parameter checks
if Alength > C_QUANTUMSERVERLIMIT then
Exit;
if ABlocksize > C_QUANTUMSERVERLIMIT then
Exit;
// Is SSL installed? If not, download it.
// If this fails then just early return FALSE;
if not CheckForOpenSSL then
begin
ShowMessage(rsSSLLibraries);
exit;
end;
// Make up the Quantum Server URL query
case AQuantumNumberType of
uint8:
szURL := Format(C_URL, [Alength, 'uint8', ABlocksize]);
uint16:
szURL := Format(C_URL, [Alength, 'uint16', ABlocksize]);
hex16:
szURL := Format(C_URL, [Alength, 'hex16', ABlocksize]);
else
exit;
end;
try
// Create the Wait Dialog
frmWaitDlg := TForm.CreateNew(nil);
with frmWaitDlg do
begin
// Set Dialog properties
Height := 100;
Width := 200;
position := poOwnerFormCenter;
borderstyle := bsNone;
Caption := '';
formstyle := fsSystemStayOnTop;
lbl_WaitDialog := TLabel.Create(frmWaitDlg);
with lbl_WaitDialog do
begin
align := alClient;
alignment := tacenter;
Caption := fWaitDialogCaption;
ParentFont := True;
Cursor := crHourGlass;
parent := frmWaitDlg;
end;
Autosize := True;
// Show it or not
if fShowWaitDialog then
Show;
Application.ProcessMessages;
end;
with fhttpclient do
begin
// Set up the JSON destramer
DeStreamer := TJSONDeStreamer.Create(nil);
DeStreamer.Options := [jdoIgnorePropertyErrors];
// Set up the http client
ResponseHeaders.NameValueSeparator := ':';
AddHeader('Accept', 'application/json;charset=UTF-8');
//DEBUG:ShowMessage(szURL);
// Go get the data!
JSON := Get(szURL);
// DEBUG: ShowMessageFmt('Response code = %d',[ResponseStatusCode]);
// Any response other than 200 is bad news
if (ResponseStatusCode <> 200) then
case ResponseStatusCode of
429:
begin
ShowMessageFmt(rsFailedTooMan,
[LineEnding, JSON]);
Exit(False);
end;
else
begin
ShowMessageFmt(rsFailedQuantu,
[ResponseStatusCode]);
Exit(False);
end;
end;
try
// Stream it to the object list
DeStreamer.JSONToObject(JSON, fQuantumNumberDataObject);
// Populate IntegerArray/Hexarray
if VarIsArray(QuantumNumberDataObject.Data) then
begin
case AQuantumNumberType of
uint8, uint16:
begin
SetLength(IntegerArray,
fQuantumNumberDataObject.fNumberLength);
for ct := 0 to Pred(fQuantumNumberDataObject.fNumberLength) do
IntegerArray[ct] :=
StrToInt(fQuantumNumberDataObject.Data[ct]);
end;
hex16:
begin
SetLength(HexArray,
fQuantumNumberDataObject.fNumberLength);
for ct := 0 to Pred(fQuantumNumberDataObject.fNumberLength) do
HexArray[ct] :=
fQuantumNumberDataObject.Data[ct];
end;
end;
end
else
begin
ShowMessage(rsQuantumServe);
Exit;
end;
except
On E: Exception do
showmessagefmt(rsFailedQuantu2, [E.Message]);
On E: Exception do
Result := False;
end;
end;
finally
// No matter what - free memory
DeStreamer.Free;
frmWaitDlg.Free;
end;
Result := True; //SUCCESS!
// DEBUG ShowMessage(fQuantumNumberDataObject.fNumberSuccess);
end;
constructor TEverett.Create(AOwner: TComponent);
begin
inherited;
fQuantumNumberType := uint8; // default is 8-bit (byte)
fShowWaitDialog := True; // Show dialog whilst fetching data online
fWaitDialogCaption := rsPleaseWaitCo;
fHttpClient := TFPHTTPClient.Create(Self);
fQuantumNumberDataObject := TQuantumNumberDataObject.Create;
fArraySize:=1; // default
fHexSize:=1; // default
SetLength(IntegerArray, 0);
SetLength(HexArray, 0);
end;
destructor TEverett.Destroy;
begin
FreeAndNil(fQuantumNumberDataObject);
FreeAndNil(fHttpClient);
inherited;
end;
function TEverett.GetSingle8Bit: integer;
begin
Result := 0;
if FetchQuantumRandomNumbers(uint8, 1, 1) then
Result := IntegerArray[0];
end;
function TEverett.GetSingle16Bit: integer;
begin
Result := 0;
if FetchQuantumRandomNumbers(uint16, 1, 1) then
Result := IntegerArray[0];
end;
function TEverett.GetSingleHex: String;
begin
Result:='00';
if FetchQuantumRandomNumbers(hex16, 1, 1) then
Result := HexArray[0];
end;
function TEverett.GetInteger8BitArray: Boolean;
// Populates IntegerArray
begin
Result:=FetchQuantumRandomNumbers(uint8, fArraySize, 1);
end;
function TEverett.GetInteger16BitArray: Boolean;
// Populates IntegerArray
begin
Result:=FetchQuantumRandomNumbers(uint16, fArraySize, 1);
end;
function TEverett.GetHexArray: Boolean;
// Populates HexArray
begin
Result:=FetchQuantumRandomNumbers(hex16, fArraySize, fHexSize);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXDb2MetaDataReader;
interface
uses
Data.DBXCommonTable,
Data.DBXMetaDataReader,
Data.DBXPlatform;
type
TDBXDb2MetaDataReader = class(TDBXBaseMetaDataReader)
public
function FetchCatalogs: TDBXTable; override;
function FetchColumnConstraints(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable; override;
function FetchPackages(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable; override;
function FetchPackageProcedures(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ProcedureType: string): TDBXTable; override;
function FetchPackageProcedureParameters(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ParameterName: string): TDBXTable; override;
function FetchPackageSources(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable; override;
function FetchUsers: TDBXTable; override;
protected
function AreSchemasSupported: Boolean; override;
function GetProductName: string; override;
function GetTableType: string; override;
function GetViewType: string; override;
function GetSystemTableType: string; override;
function GetSqlProcedureQuoteChar: string; override;
function IsSetRowSizeSupported: Boolean; override;
function IsParameterMetadataSupported: Boolean; override;
function GetSqlForSchemas: string; override;
function GetSqlForTables: string; override;
function GetSqlForViews: string; override;
function GetSqlForColumns: string; override;
function GetSqlForIndexes: string; override;
function GetSqlForIndexColumns: string; override;
function GetSqlForForeignKeys: string; override;
function GetSqlForForeignKeyColumns: string; override;
function GetSqlForSynonyms: string; override;
function GetSqlForProcedures: string; override;
function GetSqlForProcedureSources: string; override;
function GetSqlForProcedureParameters: string; override;
function GetSqlForRoles: string; override;
function GetVersion: string; override;
function GetDataTypeDescriptions: TDBXDataTypeDescriptionArray; override;
function GetReservedWords: TDBXStringArray; override;
end;
implementation
uses
Data.DBXCommon,
Data.DBXMetaDataNames;
function TDBXDb2MetaDataReader.AreSchemasSupported: Boolean;
begin
Result := True;
end;
function TDBXDb2MetaDataReader.GetProductName: string;
begin
Result := 'Db2';
end;
function TDBXDb2MetaDataReader.GetTableType: string;
begin
Result := 'T';
end;
function TDBXDb2MetaDataReader.GetViewType: string;
begin
Result := 'V';
end;
function TDBXDb2MetaDataReader.GetSystemTableType: string;
begin
Result := 'T';
end;
function TDBXDb2MetaDataReader.GetSqlProcedureQuoteChar: string;
begin
Result := '';
end;
function TDBXDb2MetaDataReader.IsSetRowSizeSupported: Boolean;
begin
Result := True;
end;
function TDBXDb2MetaDataReader.IsParameterMetadataSupported: Boolean;
begin
Result := True;
end;
function TDBXDb2MetaDataReader.FetchCatalogs: TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateCatalogsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Catalogs, Columns);
end;
function TDBXDb2MetaDataReader.GetSqlForSchemas: string;
begin
Result := 'SELECT CAST(NULL AS VARCHAR(1)), SCHEMANAME FROM SYSCAT.SCHEMATA ORDER BY 1';
end;
function TDBXDb2MetaDataReader.GetSqlForTables: string;
begin
Result := 'SELECT CAST(NULL AS VARCHAR(1)), TABSCHEMA, TABNAME, CASE WHEN TABSCHEMA IN (''SYSIBM'',''SYSCAT'',''SYSSTAT'') THEN ''SYSTEM '' ELSE '''' END || CASE TYPE WHEN ''T'' THEN ''TABLE'' ELSE ''VIEW'' END ' +
'FROM SYSCAT.TABLES ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(TABSCHEMA) = LOWER(CAST(:SCHEMA_NAME AS VARCHAR(128))) OR (:SCHEMA_NAME IS NULL)) AND (TABNAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
' AND (TYPE IN (''T'',''V'')) ' +
' AND (TYPE=CASE WHEN TABSCHEMA IN (''SYSIBM'',''SYSCAT'',''SYSSTAT'') THEN CAST(:SYSTEM_TABLES AS VARCHAR(12)) ELSE CAST(:TABLES AS VARCHAR(12)) END OR TYPE=CASE WHEN TABSCHEMA IN (''SYSIBM'',''SYSCAT'',''SYSSTAT'') THEN CAST(:SYSTEM_VIEWS AS VARCHAR(12)) ELSE CAST(:' + 'VIEWS AS VARCHAR(12)) END) ' +
'ORDER BY 2,3';
end;
function TDBXDb2MetaDataReader.GetSqlForViews: string;
begin
Result := 'SELECT CAST(NULL AS VARCHAR(1)), VIEWSCHEMA, VIEWNAME, TEXT ' +
'FROM SYSCAT.VIEWS ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (VIEWSCHEMA = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (VIEWNAME = :VIEW_NAME OR (:VIEW_NAME IS NULL)) ' +
'ORDER BY 2,3';
end;
function TDBXDb2MetaDataReader.GetSqlForColumns: string;
begin
Result := 'SELECT CAST(NULL AS VARCHAR(1)), TABSCHEMA, TABNAME, COLNAME, TYPENAME, LENGTH, SCALE, COLNO+1, DEFAULT, CASE WHEN NULLS=''Y'' THEN 1 ELSE 0 END, CASE WHEN IDENTITY=''Y'' THEN 1 ELSE 0 END, CAST(NULL AS INTEGER) ' +
'FROM SYSCAT.COLUMNS ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(TABSCHEMA) = LOWER(CAST(:SCHEMA_NAME AS VARCHAR(128))) OR (:SCHEMA_NAME IS NULL)) AND (TABNAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 2, 3, COLNO';
end;
function TDBXDb2MetaDataReader.FetchColumnConstraints(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateColumnConstraintsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ColumnConstraints, Columns);
end;
function TDBXDb2MetaDataReader.GetSqlForIndexes: string;
begin
Result := 'SELECT CAST(NULL AS VARCHAR(1)), TABSCHEMA, TABNAME, INDNAME, CASE WHEN USER_DEFINED=1 THEN CAST(NULL AS VARCHAR(1)) ELSE INDNAME END, CASE WHEN UNIQUERULE=''P'' THEN 1 ELSE 0 END, CASE WHEN UNIQUERULE=''D'' THEN 0 ELSE 1 END, 1 ' +
'FROM SYSCAT.INDEXES ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(TABSCHEMA) = LOWER(CAST(:SCHEMA_NAME AS VARCHAR(128))) OR (:SCHEMA_NAME IS NULL)) AND (TABNAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 2, 3, 4';
end;
function TDBXDb2MetaDataReader.GetSqlForIndexColumns: string;
begin
Result := 'SELECT CAST(NULL AS VARCHAR(1)), I.TABSCHEMA, I.TABNAME, I.INDNAME, C.COLNAME, C.COLSEQ, CASE WHEN COLORDER=''A'' THEN 1 WHEN COLORDER=''D'' THEN 0 ELSE CAST (NULL AS INTEGER) END ' +
'FROM SYSCAT.INDEXES I, SYSCAT.INDEXCOLUSE C ' +
'WHERE I.INDSCHEMA = C.INDSCHEMA AND I.INDNAME = C.INDNAME ' +
' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(I.TABSCHEMA) = LOWER(CAST(:SCHEMA_NAME AS VARCHAR(128))) OR (:SCHEMA_NAME IS NULL)) AND (I.TABNAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (I.INDNAME = :INDEX_NAME OR (:INDEX_NAME IS NULL)) ' +
'ORDER BY 2, 3, 4, 6';
end;
function TDBXDb2MetaDataReader.GetSqlForForeignKeys: string;
begin
Result := 'SELECT CAST(NULL AS VARCHAR(1)), TABSCHEMA, TABNAME, CONSTNAME ' +
'FROM SYSCAT.REFERENCES ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(TABSCHEMA) = LOWER(CAST(:SCHEMA_NAME AS VARCHAR(128))) OR (:SCHEMA_NAME IS NULL)) AND (TABNAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 2,3,4';
end;
function TDBXDb2MetaDataReader.GetSqlForForeignKeyColumns: string;
begin
Result := 'SELECT CAST(NULL AS VARCHAR(1)), FK.TABSCHEMA, FK.TABNAME, FK.CONSTNAME, FC.COLNAME, CAST(NULL AS VARCHAR(1)), FK.REFTABSCHEMA, FK.REFTABNAME, FK.REFKEYNAME, PC.COLNAME, FC.COLSEQ ' +
'FROM SYSCAT.REFERENCES FK, SYSCAT.KEYCOLUSE FC, SYSCAT.KEYCOLUSE PC ' +
'WHERE FK.TABSCHEMA = FC.TABSCHEMA ' +
' AND FK.TABNAME = FC.TABNAME ' +
' AND FK.CONSTNAME = FC.CONSTNAME ' +
' AND FK.REFTABSCHEMA = PC.TABSCHEMA ' +
' AND FK.REFTABNAME = PC.TABNAME ' +
' AND FK.REFKEYNAME = PC.CONSTNAME ' +
' AND FC.COLSEQ = PC.COLSEQ ' +
' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(FK.TABSCHEMA) = LOWER(CAST(:SCHEMA_NAME AS VARCHAR(128))) OR (:SCHEMA_NAME IS NULL)) AND (FK.TABNAME = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (FK.CONSTNAME = :FOREIGN_KEY_NAME OR (:FOREIGN_KEY_NAME IS NU' + 'LL)) ' +
' AND (1<2 OR (:PRIMARY_CATALOG_NAME IS NULL)) AND (LOWER(FK.REFTABSCHEMA) = LOWER(CAST(:PRIMARY_SCHEMA_NAME AS VARCHAR(128))) OR (:PRIMARY_SCHEMA_NAME IS NULL)) AND (FK.REFTABNAME = :PRIMARY_TABLE_NAME OR (:PRIMARY_TABLE_NAME IS NULL)) AND (FK.REFKEYNAME ' + '= :PRIMARY_KEY_NAME OR (:PRIMARY_KEY_NAME IS NULL)) ' +
'ORDER BY 2,3,4,FC.COLSEQ';
end;
function TDBXDb2MetaDataReader.GetSqlForSynonyms: string;
begin
Result := 'SELECT CAST(NULL AS VARCHAR(1)), TABSCHEMA, TABNAME, CAST(NULL AS VARCHAR(1)), BASE_TABSCHEMA, BASE_TABNAME ' +
'FROM SYSCAT.TABLES ' +
'WHERE TYPE = ''A'' ' +
' AND (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(TABSCHEMA) = LOWER(CAST(:SCHEMA_NAME AS VARCHAR(128))) OR (:SCHEMA_NAME IS NULL)) AND (TABNAME = :SYNONYM_NAME OR (:SYNONYM_NAME IS NULL)) ' +
'ORDER BY 2,3';
end;
function TDBXDb2MetaDataReader.GetSqlForProcedures: string;
begin
Result := 'SELECT CAST(NULL AS VARCHAR(1)), ROUTINESCHEMA, ROUTINENAME, CASE WHEN ROUTINETYPE=''P'' THEN ''PROCEDURE'' ELSE ''FUNCTION'' END ' +
'FROM SYSCAT.ROUTINES ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(ROUTINESCHEMA) = LOWER(CAST(:SCHEMA_NAME AS VARCHAR(128))) OR (:SCHEMA_NAME IS NULL)) AND (ROUTINENAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND ((CASE WHEN ROUTINETYPE=''P'' THEN ''PROCEDURE'' ELSE ' + '''METHOD'' END) = :PROCEDURE_TYPE OR (:PROCEDURE_TYPE IS NULL)) ' +
'ORDER BY 2,3';
end;
function TDBXDb2MetaDataReader.GetSqlForProcedureSources: string;
begin
Result := 'SELECT CAST(NULL AS VARCHAR(1)), ROUTINESCHEMA, ROUTINENAME, CASE WHEN ROUTINETYPE=''P'' THEN ''PROCEDURE'' ELSE ''FUNCTION'' END, TEXT, CAST(NULL AS VARCHAR(1)) ' +
'FROM SYSCAT.ROUTINES ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(ROUTINESCHEMA) = LOWER(CAST(:SCHEMA_NAME AS VARCHAR(128))) OR (:SCHEMA_NAME IS NULL)) AND (ROUTINENAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) ' +
'ORDER BY 2,3';
end;
function TDBXDb2MetaDataReader.GetSqlForProcedureParameters: string;
begin
Result := 'SELECT CAST(NULL AS VARCHAR(1)), ROUTINESCHEMA, ROUTINENAME, PARMNAME, CASE WHEN ROWTYPE=''P'' THEN ''IN'' WHEN ROWTYPE=''O'' THEN ''OUT'' WHEN ROWTYPE=''B'' THEN ''INOUT'' ELSE ''RESULT'' END, TYPENAME, LENGTH, SCALE, ORDINAL, 1 ' +
'FROM SYSCAT.ROUTINEPARMS ' +
'WHERE (1<2 OR (:CATALOG_NAME IS NULL)) AND (LOWER(ROUTINESCHEMA) = LOWER(CAST(:SCHEMA_NAME AS VARCHAR(128))) OR (:SCHEMA_NAME IS NULL)) AND (ROUTINENAME = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (PARMNAME = :PARAMETER_NAME OR (:PARAMETER_NAME IS' + ' NULL)) ' +
'ORDER BY 2,3,ORDINAL';
end;
function TDBXDb2MetaDataReader.FetchPackages(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackagesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Packages, Columns);
end;
function TDBXDb2MetaDataReader.FetchPackageProcedures(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ProcedureType: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageProceduresColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedures, Columns);
end;
function TDBXDb2MetaDataReader.FetchPackageProcedureParameters(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ParameterName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageProcedureParametersColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedureParameters, Columns);
end;
function TDBXDb2MetaDataReader.FetchPackageSources(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageSourcesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageSources, Columns);
end;
function TDBXDb2MetaDataReader.FetchUsers: TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateUsersColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Users, Columns);
end;
function TDBXDb2MetaDataReader.GetSqlForRoles: string;
begin
Result := 'SELECT NGNAME FROM SYSCAT.NODEGROUPS';
end;
function TDBXDb2MetaDataReader.GetVersion: string;
begin
Result := 'SELECT FIRST 1 DBINFO(''version'',''major'')||''.''||DBINFO(''version'',''minor'')||''.''||DBINFO(''version'',''level'') FROM SYSTABLES';
end;
function TDBXDb2MetaDataReader.GetDataTypeDescriptions: TDBXDataTypeDescriptionArray;
var
Types: TDBXDataTypeDescriptionArray;
begin
SetLength(Types,14);
Types[0] := TDBXDataTypeDescription.Create('SMALLINT', TDBXDataTypes.Int16Type, 5, 'SMALLINT', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[1] := TDBXDataTypeDescription.Create('INTEGER', TDBXDataTypes.Int32Type, 10, 'INTEGER', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[2] := TDBXDataTypeDescription.Create('BIGINT', TDBXDataTypes.Int64Type, 19, 'BIGINT', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[3] := TDBXDataTypeDescription.Create('REAL', TDBXDataTypes.SingleType, 7, 'REAL', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[4] := TDBXDataTypeDescription.Create('DOUBLE', TDBXDataTypes.DoubleType, 53, 'DOUBLE', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[5] := TDBXDataTypeDescription.Create('DECIMAL', TDBXDataTypes.BcdType, 38, 'DECIMAL({0}, {1})', 'Precision, Scale', 38, 0, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[6] := TDBXDataTypeDescription.Create('CHARACTER', TDBXDataTypes.AnsiStringType, 4000, 'CHARACTER({0})', 'Precision', -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[7] := TDBXDataTypeDescription.Create('VARCHAR', TDBXDataTypes.AnsiStringType, 4000, 'VARCHAR({0})', 'Precision', -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[8] := TDBXDataTypeDescription.Create('LONG VARCHAR', TDBXDataTypes.AnsiStringType, 32700, 'LONG VARCHAR', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[9] := TDBXDataTypeDescription.Create('BLOB', TDBXDataTypes.BlobType, 2147483647, 'BLOB', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[10] := TDBXDataTypeDescription.Create('CLOB', TDBXDataTypes.BlobType, 2147483647, 'CLOB', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.StringOption);
Types[11] := TDBXDataTypeDescription.Create('DATE', TDBXDataTypes.DateType, 4, 'DATE', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[12] := TDBXDataTypeDescription.Create('TIME', TDBXDataTypes.TimeType, 3, 'TIME', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[13] := TDBXDataTypeDescription.Create('TIMESTAMP', TDBXDataTypes.TimeStampType, 10, 'TIMESTAMP', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.BestMatch or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Result := Types;
end;
function TDBXDb2MetaDataReader.GetReservedWords: TDBXStringArray;
var
Words: TDBXStringArray;
begin
SetLength(Words,310);
Words[0] := 'ADD';
Words[1] := 'AFTER';
Words[2] := 'ALIAS';
Words[3] := 'ALL';
Words[4] := 'ALLOCATE';
Words[5] := 'ALLOW';
Words[6] := 'ALTER';
Words[7] := 'AND';
Words[8] := 'ANY';
Words[9] := 'APPLICATION';
Words[10] := 'AS';
Words[11] := 'ASSOCIATE';
Words[12] := 'ASUTIME';
Words[13] := 'AUDIT';
Words[14] := 'AUTHORIZATION';
Words[15] := 'AUX';
Words[16] := 'AUXILIARY';
Words[17] := 'BEFORE';
Words[18] := 'BEGIN';
Words[19] := 'BETWEEN';
Words[20] := 'BINARY';
Words[21] := 'BUFFERPOOL';
Words[22] := 'BY';
Words[23] := 'CACHE';
Words[24] := 'CALL';
Words[25] := 'CALLED';
Words[26] := 'CAPTURE';
Words[27] := 'CARDINALITY';
Words[28] := 'CASCADED';
Words[29] := 'CASE';
Words[30] := 'CAST';
Words[31] := 'CCSID';
Words[32] := 'CHAR';
Words[33] := 'CHARACTER';
Words[34] := 'CHECK';
Words[35] := 'CLOSE';
Words[36] := 'CLUSTER';
Words[37] := 'COLLECTION';
Words[38] := 'COLLID';
Words[39] := 'COLUMN';
Words[40] := 'COMMENT';
Words[41] := 'COMMIT';
Words[42] := 'CONCAT';
Words[43] := 'CONDITION';
Words[44] := 'CONNECT';
Words[45] := 'CONNECTION';
Words[46] := 'CONSTRAINT';
Words[47] := 'CONTAINS';
Words[48] := 'CONTINUE';
Words[49] := 'COUNT';
Words[50] := 'COUNT_BIG';
Words[51] := 'CREATE';
Words[52] := 'CROSS';
Words[53] := 'CURRENT';
Words[54] := 'CURRENT_DATE';
Words[55] := 'CURRENT_LC_CTYPE';
Words[56] := 'CURRENT_PATH';
Words[57] := 'CURRENT_SERVER';
Words[58] := 'CURRENT_TIME';
Words[59] := 'CURRENT_TIMESTAMP';
Words[60] := 'CURRENT_TIMEZONE';
Words[61] := 'CURRENT_USER';
Words[62] := 'CURSOR';
Words[63] := 'CYCLE';
Words[64] := 'DATA';
Words[65] := 'DATABASE';
Words[66] := 'DAY';
Words[67] := 'DAYS';
Words[68] := 'DB2GENERAL';
Words[69] := 'DB2GENRL';
Words[70] := 'DB2SQL';
Words[71] := 'DBINFO';
Words[72] := 'DECLARE';
Words[73] := 'DEFAULT';
Words[74] := 'DEFAULTS';
Words[75] := 'DEFINITION';
Words[76] := 'DELETE';
Words[77] := 'DESCRIPTOR';
Words[78] := 'DETERMINISTIC';
Words[79] := 'DISALLOW';
Words[80] := 'DISCONNECT';
Words[81] := 'DISTINCT';
Words[82] := 'DO';
Words[83] := 'DOUBLE';
Words[84] := 'DROP';
Words[85] := 'DSNHATTR';
Words[86] := 'DSSIZE';
Words[87] := 'DYNAMIC';
Words[88] := 'EACH';
Words[89] := 'EDITPROC';
Words[90] := 'ELSE';
Words[91] := 'ELSEIF';
Words[92] := 'ENCODING';
Words[93] := 'END-EXEC';
Words[94] := 'END-EXEC1';
Words[95] := 'END';
Words[96] := 'ERASE';
Words[97] := 'ESCAPE';
Words[98] := 'EXCEPT';
Words[99] := 'EXCEPTION';
Words[100] := 'EXCLUDING';
Words[101] := 'EXECUTE';
Words[102] := 'EXISTS';
Words[103] := 'EXIT';
Words[104] := 'EXTERNAL';
Words[105] := 'FENCED';
Words[106] := 'FETCH';
Words[107] := 'FIELDPROC';
Words[108] := 'FILE';
Words[109] := 'FINAL';
Words[110] := 'FOR';
Words[111] := 'FOREIGN';
Words[112] := 'FREE';
Words[113] := 'FROM';
Words[114] := 'FULL';
Words[115] := 'FUNCTION';
Words[116] := 'GENERAL';
Words[117] := 'GENERATED';
Words[118] := 'GET';
Words[119] := 'GLOBAL';
Words[120] := 'GO';
Words[121] := 'GOTO';
Words[122] := 'GRANT';
Words[123] := 'GRAPHIC';
Words[124] := 'GROUP';
Words[125] := 'HANDLER';
Words[126] := 'HAVING';
Words[127] := 'HOLD';
Words[128] := 'HOUR';
Words[129] := 'HOURS';
Words[130] := 'IDENTITY';
Words[131] := 'IF';
Words[132] := 'IMMEDIATE';
Words[133] := 'IN';
Words[134] := 'INCLUDING';
Words[135] := 'INCREMENT';
Words[136] := 'INDEX';
Words[137] := 'INDICATOR';
Words[138] := 'INHERIT';
Words[139] := 'INNER';
Words[140] := 'INOUT';
Words[141] := 'INSENSITIVE';
Words[142] := 'INSERT';
Words[143] := 'INTEGRITY';
Words[144] := 'INTO';
Words[145] := 'IS';
Words[146] := 'ISOBID';
Words[147] := 'ISOLATION';
Words[148] := 'ITERATE';
Words[149] := 'JAR';
Words[150] := 'JAVA';
Words[151] := 'JOIN';
Words[152] := 'KEY';
Words[153] := 'LABEL';
Words[154] := 'LANGUAGE';
Words[155] := 'LC_CTYPE';
Words[156] := 'LEAVE';
Words[157] := 'LEFT';
Words[158] := 'LIKE';
Words[159] := 'LINKTYPE';
Words[160] := 'LOCAL';
Words[161] := 'LOCALE';
Words[162] := 'LOCATOR';
Words[163] := 'LOCATORS';
Words[164] := 'LOCK';
Words[165] := 'LOCKMAX';
Words[166] := 'LOCKSIZE';
Words[167] := 'LONG';
Words[168] := 'LOOP';
Words[169] := 'MAXVALUE';
Words[170] := 'MICROSECOND';
Words[171] := 'MICROSECONDS';
Words[172] := 'MINUTE';
Words[173] := 'MINUTES';
Words[174] := 'MINVALUE';
Words[175] := 'MODE';
Words[176] := 'MODIFIES';
Words[177] := 'MONTH';
Words[178] := 'MONTHS';
Words[179] := 'NEW';
Words[180] := 'NEW_TABLE';
Words[181] := 'NO';
Words[182] := 'NOCACHE';
Words[183] := 'NOCYCLE';
Words[184] := 'NODENAME';
Words[185] := 'NODENUMBER';
Words[186] := 'NOMAXVALUE';
Words[187] := 'NOMINVALUE';
Words[188] := 'NOORDER';
Words[189] := 'NOT';
Words[190] := 'NULL';
Words[191] := 'NULLS';
Words[192] := 'NUMPARTS';
Words[193] := 'OBID';
Words[194] := 'OF';
Words[195] := 'OLD';
Words[196] := 'OLD_TABLE';
Words[197] := 'ON';
Words[198] := 'OPEN';
Words[199] := 'OPTIMIZATION';
Words[200] := 'OPTIMIZE';
Words[201] := 'OPTION';
Words[202] := 'OR';
Words[203] := 'ORDER';
Words[204] := 'OUT';
Words[205] := 'OUTER';
Words[206] := 'OVERRIDING';
Words[207] := 'PACKAGE';
Words[208] := 'PARAMETER';
Words[209] := 'PART';
Words[210] := 'PARTITION';
Words[211] := 'PATH';
Words[212] := 'PIECESIZE';
Words[213] := 'PLAN';
Words[214] := 'POSITION';
Words[215] := 'PRECISION';
Words[216] := 'PREPARE';
Words[217] := 'PRIMARY';
Words[218] := 'PRIQTY';
Words[219] := 'PRIVILEGES';
Words[220] := 'PROCEDURE';
Words[221] := 'PROGRAM';
Words[222] := 'PSID';
Words[223] := 'QUERYNO';
Words[224] := 'READ';
Words[225] := 'READS';
Words[226] := 'RECOVERY';
Words[227] := 'REFERENCES';
Words[228] := 'REFERENCING';
Words[229] := 'RELEASE';
Words[230] := 'RENAME';
Words[231] := 'REPEAT';
Words[232] := 'RESET';
Words[233] := 'RESIGNAL';
Words[234] := 'RESTART';
Words[235] := 'RESTRICT';
Words[236] := 'RESULT';
Words[237] := 'RESULT_SET_LOCATOR';
Words[238] := 'RETURN';
Words[239] := 'RETURNS';
Words[240] := 'REVOKE';
Words[241] := 'RIGHT';
Words[242] := 'ROLLBACK';
Words[243] := 'ROUTINE';
Words[244] := 'ROW';
Words[245] := 'ROWS';
Words[246] := 'RRN';
Words[247] := 'RUN';
Words[248] := 'SAVEPOINT';
Words[249] := 'SCHEMA';
Words[250] := 'SCRATCHPAD';
Words[251] := 'SECOND';
Words[252] := 'SECONDS';
Words[253] := 'SECQTY';
Words[254] := 'SECURITY';
Words[255] := 'SELECT';
Words[256] := 'SENSITIVE';
Words[257] := 'SET';
Words[258] := 'SIGNAL';
Words[259] := 'SIMPLE';
Words[260] := 'SOME';
Words[261] := 'SOURCE';
Words[262] := 'SPECIFIC';
Words[263] := 'SQL';
Words[264] := 'SQLID';
Words[265] := 'STANDARD';
Words[266] := 'START';
Words[267] := 'STATIC';
Words[268] := 'STAY';
Words[269] := 'STOGROUP';
Words[270] := 'STORES';
Words[271] := 'STYLE';
Words[272] := 'SUBPAGES';
Words[273] := 'SUBSTRING';
Words[274] := 'SYNONYM';
Words[275] := 'SYSFUN';
Words[276] := 'SYSIBM';
Words[277] := 'SYSPROC';
Words[278] := 'SYSTEM';
Words[279] := 'TABLE';
Words[280] := 'TABLESPACE';
Words[281] := 'THEN';
Words[282] := 'TO';
Words[283] := 'TRANSACTION';
Words[284] := 'TRIGGER';
Words[285] := 'TRIM';
Words[286] := 'TYPE';
Words[287] := 'UNDO';
Words[288] := 'UNION';
Words[289] := 'UNIQUE';
Words[290] := 'UNTIL';
Words[291] := 'UPDATE';
Words[292] := 'USAGE';
Words[293] := 'USER';
Words[294] := 'USING';
Words[295] := 'VALIDPROC';
Words[296] := 'VALUES';
Words[297] := 'VARIABLE';
Words[298] := 'VARIANT';
Words[299] := 'VCAT';
Words[300] := 'VIEW';
Words[301] := 'VOLUMES';
Words[302] := 'WHEN';
Words[303] := 'WHERE';
Words[304] := 'WHILE';
Words[305] := 'WITH';
Words[306] := 'WLM';
Words[307] := 'WRITE';
Words[308] := 'YEAR';
Words[309] := 'YEARS';
Result := Words;
end;
end.
|
unit NotesU;
interface
uses
System.Generics.Collections, FMX.Graphics, FMX.Objects;
type
TUneNote = class
strict private
FClientNom: string;
FClientID: integer;
FNoteDate: TDateTime;
FPhoto: TBitmap;
FDescription: string;
FisNewNote: boolean;
FID: Int64;
procedure SetClientID(const Value: integer);
procedure SetClientNom(const Value: string);
procedure SetDescription(const Value: string);
procedure SetNoteDate(const Value: TDateTime);
procedure SetPhoto(const Value: TBitmap);
public
constructor Create(isNewNote: boolean);
destructor Destroy; override;
property Description: string read FDescription write SetDescription;
property NoteDate: TDateTime read FNoteDate write SetNoteDate;
property Photo: TBitmap read FPhoto write SetPhoto;
property ClientID: integer read FClientID write SetClientID;
Property ClientNom: string read FClientNom write SetClientNom;
function isNewNote: boolean;
property ID: Int64 read FID write FID;
end;
TNoteColl = class(TObjectList<TUneNote>)
public
constructor Create;
destructor Destroy; override;
end;
// constructor Create;
// destructor Destroy; overload;
implementation
uses System.SysUtils;
{ TUneNote }
constructor TUneNote.Create(isNewNote: boolean);
begin
inherited Create;
FisNewNote := isNewNote;
FDescription := '';
FNoteDate := now;
FClientNom := '';
FClientID := -1;
// FPhoto := nil
FPhoto:= TBitmap.Create(0,0);
end;
destructor TUneNote.Destroy;
begin
end;
function TUneNote.isNewNote: boolean;
begin
result := FisNewNote;
end;
procedure TUneNote.SetClientID(const Value: integer);
begin
FClientID := Value;
end;
procedure TUneNote.SetClientNom(const Value: string);
begin
FClientNom := Value;
end;
procedure TUneNote.SetDescription(const Value: string);
begin
FDescription := Value;
end;
procedure TUneNote.SetNoteDate(const Value: TDateTime);
begin
FNoteDate := Value;
end;
procedure TUneNote.SetPhoto(const Value: TBitmap);
begin
FPhoto := Value;
end;
{ TNoteColl }
constructor TNoteColl.Create;
begin
inherited Create(true);
end;
destructor TNoteColl.Destroy;
begin
inherited;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit FMX.Design.Path;
interface
uses
System.SysUtils, System.Types, System.Classes, FMX.Types, FMX.Controls, FMX.Forms, FMX.StdCtrls,
FMX.Dialogs, FMX.Layouts, FMX.Objects, FMX.Memo, FmxDesignWindows;
type
TPathDataDesigner = class(TFmxDesignWindow)
previewLayout: TLayout;
Label1: TLabel;
PreviewPath: TPath;
Layout2: TLayout;
Button1: TButton;
Button2: TButton;
Button3: TButton;
LabelMemo: TLabel;
PathData: TMemo;
procedure PathDataChange(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
PathDataDesigner: TPathDataDesigner;
implementation
uses System.UITypes;
{$R *.fmx}
procedure TPathDataDesigner.Button1Click(Sender: TObject);
begin
pathData.SelectAll;
pathData.DeleteSelection;
pathData.PasteFromClipboard;
end;
procedure TPathDataDesigner.Button2Click(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TPathDataDesigner.Button3Click(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TPathDataDesigner.PathDataChange(Sender: TObject);
begin
if previewLayout.Visible then
previewPath.Data.Data:= PathData.Text;
end;
end.
|
{: Build mesh objects.
How often do you miss a BuildSphereMesh function for testing or editors?
Well this unit is intended to solve that problem. We want fast,
flexible functions with lots of options...
Original Author: Joen Joensen.
Contributed to the GLScene community.
Features: BuildCube, BuildCylinder.
<b>History : </b><font size=-1><ul>
<li>22/01/10 - Yar - Added GLVectorTypes to uses
<li>29/11/03 - JAJ - Created and Submitted to GLScene.
<li>21/07/03 - JAJ - Added BuildCylinder2 submitted by Gorka?
</ul></font>
}
unit GLMeshBuilder;
interface
Uses
SysUtils, Classes, GLScene, GLVectorFileObjects,
GLVectorTypes, GLVectorGeometry, GLVectorLists;
Procedure BuildCube(Mesh : TMeshObject; Position, Scale : TAffineVector);
Procedure BuildCylinder(Mesh : TMeshObject; Position, Scale : TAffineVector; Slices : Integer);
Procedure BuildCylinder2(Mesh : TMeshObject; Position, Scale : TAffineVector; TopRadius,BottomRadius,Height: single; Slices : Integer);
implementation
Function VectorCombineWeighted(Position,Scale : TAffineVector; X, Y, Z : Single) : TAffineVector;
Begin
Result.V[0]:= position.V[0]+Scale.V[0]*X;
Result.V[1]:= position.V[1]+Scale.V[1]*Y;
Result.V[2]:= position.V[2]+Scale.V[2]*Z;
End;
Procedure BuildCube(Mesh : TMeshObject; Position, Scale : TAffineVector);
Var
FGR : TFGVertexNormalTexIndexList;
VertexOffset : Integer;
NormalOffset : Integer;
TextureOffset : Integer;
Begin
// Vertexes
VertexOffset :=
Mesh.Vertices.Add(VectorCombineWeighted(Position,Scale,0.5,0.5,0.5));
Mesh.Vertices.Add(VectorCombineWeighted(Position,Scale,-0.5,0.5,0.5));
Mesh.Vertices.Add(VectorCombineWeighted(Position,Scale,0.5,-0.5,0.5));
Mesh.Vertices.Add(VectorCombineWeighted(Position,Scale,-0.5,-0.5,0.5));
Mesh.Vertices.Add(VectorCombineWeighted(Position,Scale,0.5,0.5,-0.5));
Mesh.Vertices.Add(VectorCombineWeighted(Position,Scale,-0.5,0.5,-0.5));
Mesh.Vertices.Add(VectorCombineWeighted(Position,Scale,0.5,-0.5,-0.5));
Mesh.Vertices.Add(VectorCombineWeighted(Position,Scale,-0.5,-0.5,-0.5));
// Normals
NormalOffset :=
Mesh.Normals.add(AffineVectorMake(0,0,1));
Mesh.Normals.add(AffineVectorMake(0,0,-1));
Mesh.Normals.add(AffineVectorMake(1,0,0));
Mesh.Normals.add(AffineVectorMake(-1,0,0));
Mesh.Normals.add(AffineVectorMake(0,1,0));
Mesh.Normals.add(AffineVectorMake(0,-1,0));
// Texture Coordinates
TextureOffset :=
Mesh.TexCoords.add(AffineVectorMake(1,1,1));
Mesh.TexCoords.add(AffineVectorMake(0,1,1));
Mesh.TexCoords.add(AffineVectorMake(1,0,1));
Mesh.TexCoords.add(AffineVectorMake(0,0,1));
Mesh.TexCoords.add(AffineVectorMake(1,1,0));
Mesh.TexCoords.add(AffineVectorMake(0,1,0));
Mesh.TexCoords.add(AffineVectorMake(1,0,0));
Mesh.TexCoords.add(AffineVectorMake(0,0,0));
FGR := TFGVertexNormalTexIndexList.CreateOwned(Mesh.FaceGroups);
FGR.Mode := fgmmTriangles;
// front
FGR.VertexIndices.Add(VertexOffset+0,VertexOffset+1,VertexOffset+3);
FGR.VertexIndices.Add(VertexOffset+0,VertexOffset+3,VertexOffset+2);
FGR.NormalIndices.Add(NormalOffset+0,NormalOffset+0,NormalOffset+0);
FGR.NormalIndices.Add(NormalOffset+0,NormalOffset+0,NormalOffset+0);
FGR.TexCoordIndices.Add(TextureOffset+0,TextureOffset+1,TextureOffset+3);
FGR.TexCoordIndices.Add(TextureOffset+0,TextureOffset+3,TextureOffset+2);
// back
FGR.VertexIndices.Add(VertexOffset+4,VertexOffset+6,VertexOffset+7);
FGR.VertexIndices.Add(VertexOffset+4,VertexOffset+7,VertexOffset+5);
FGR.NormalIndices.Add(NormalOffset+1,NormalOffset+1,NormalOffset+1);
FGR.NormalIndices.Add(NormalOffset+1,NormalOffset+1,NormalOffset+1);
FGR.TexCoordIndices.Add(TextureOffset+4,TextureOffset+6,TextureOffset+7);
FGR.TexCoordIndices.Add(TextureOffset+4,TextureOffset+7,TextureOffset+5);
// right
FGR.VertexIndices.Add(VertexOffset+0,VertexOffset+2,VertexOffset+6);
FGR.VertexIndices.Add(VertexOffset+0,VertexOffset+6,VertexOffset+4);
FGR.NormalIndices.Add(NormalOffset+2,NormalOffset+2,NormalOffset+2);
FGR.NormalIndices.Add(NormalOffset+2,NormalOffset+2,NormalOffset+2);
FGR.TexCoordIndices.Add(TextureOffset+0,TextureOffset+2,TextureOffset+6);
FGR.TexCoordIndices.Add(TextureOffset+0,TextureOffset+6,TextureOffset+4);
// left
FGR.VertexIndices.Add(VertexOffset+1,VertexOffset+5,VertexOffset+7);
FGR.VertexIndices.Add(VertexOffset+1,VertexOffset+7,VertexOffset+3);
FGR.NormalIndices.Add(NormalOffset+3,NormalOffset+3,NormalOffset+3);
FGR.NormalIndices.Add(NormalOffset+3,NormalOffset+3,NormalOffset+3);
FGR.TexCoordIndices.Add(TextureOffset+1,TextureOffset+5,TextureOffset+7);
FGR.TexCoordIndices.Add(TextureOffset+1,TextureOffset+7,TextureOffset+3);
// top
FGR.VertexIndices.Add(VertexOffset+0,VertexOffset+4,VertexOffset+5);
FGR.VertexIndices.Add(VertexOffset+0,VertexOffset+5,VertexOffset+1);
FGR.NormalIndices.Add(NormalOffset+4,NormalOffset+4,NormalOffset+4);
FGR.NormalIndices.Add(NormalOffset+4,NormalOffset+4,NormalOffset+4);
FGR.TexCoordIndices.Add(TextureOffset+0,TextureOffset+4,TextureOffset+5);
FGR.TexCoordIndices.Add(TextureOffset+0,TextureOffset+5,TextureOffset+1);
// bottom
FGR.VertexIndices.Add(VertexOffset+2,VertexOffset+3,VertexOffset+7);
FGR.VertexIndices.Add(VertexOffset+2,VertexOffset+7,VertexOffset+6);
FGR.NormalIndices.Add(NormalOffset+5,NormalOffset+5,NormalOffset+5);
FGR.NormalIndices.Add(NormalOffset+5,NormalOffset+5,NormalOffset+5);
FGR.TexCoordIndices.Add(TextureOffset+2,TextureOffset+3,TextureOffset+7);
FGR.TexCoordIndices.Add(TextureOffset+2,TextureOffset+7,TextureOffset+6);
End;
Procedure BuildCylinder(Mesh : TMeshObject; Position, Scale : TAffineVector; Slices : Integer);
Var
FGR : TFGVertexNormalTexIndexList;
VertexOffset : Integer;
NormalOffset : Integer;
TextureOffset : Integer;
Cosine,Sine : Array of Single;
xc,yc : Integer;
Begin
If Slices < 3 then Exit;
SetLength(Sine,Slices+1);
SetLength(Cosine,Slices+1);
PrepareSinCosCache(Sine,Cosine,0,360);
VertexOffset := Mesh.Vertices.Count;
NormalOffset := Mesh.Normals.Count;
TextureOffset := Mesh.TexCoords.Count;
For xc := 0 to Slices-1 do
Begin
Mesh.Vertices.Add(VectorCombineWeighted(Position,Scale,0.5*cosine[xc],0.5*sine[xc],0.5));
Mesh.Vertices.Add(VectorCombineWeighted(Position,Scale,0.5*cosine[xc],0.5*sine[xc],-0.5));
// Normals
Mesh.Normals.add(AffineVectorMake(cosine[xc],sine[xc],0));
// Texture Coordinates
Mesh.TexCoords.add(VectorCombineWeighted(Position,XYZVector,0.5*cosine[xc],0.5*sine[xc],0.5));
Mesh.TexCoords.add(VectorCombineWeighted(Position,XYZVector,0.5*cosine[xc],0.5*sine[xc],-0.5));
End;
Mesh.Normals.add(AffineVectorMake(0,0,1));
Mesh.Normals.add(AffineVectorMake(0,0,-1));
FGR := TFGVertexNormalTexIndexList.CreateOwned(Mesh.FaceGroups);
FGR.Mode := fgmmTriangles;
For xc := 0 to Slices-1 do
Begin
yc := xc+1;
If yc = slices then yc := 0;
FGR.VertexIndices.Add(VertexOffset+xc*2,VertexOffset+xc*2+1,VertexOffset+yc*2+1);
FGR.VertexIndices.Add(VertexOffset+xc*2,VertexOffset+yc*2+1,VertexOffset+yc*2);
FGR.NormalIndices.Add(NormalOffset+xc,NormalOffset+xc,NormalOffset+yc);
FGR.NormalIndices.Add(NormalOffset+xc,NormalOffset+yc,NormalOffset+yc);
FGR.TexCoordIndices.Add(TextureOffset+xc*2,TextureOffset+xc*2+1,TextureOffset+yc*2+1);
FGR.TexCoordIndices.Add(TextureOffset+xc*2,TextureOffset+yc*2+1,TextureOffset+yc*2);
End;
For xc := 1 to Slices-2 do
Begin
yc := xc+1;
FGR.VertexIndices.Add(VertexOffset,VertexOffset+xc*2,VertexOffset+yc*2);
FGR.VertexIndices.Add(VertexOffset+1,VertexOffset+yc*2+1,VertexOffset+xc*2+1);
FGR.NormalIndices.Add(NormalOffset+Slices,NormalOffset+Slices,NormalOffset+Slices);
FGR.NormalIndices.Add(NormalOffset+Slices+1,NormalOffset+Slices+1,NormalOffset+Slices+1);
FGR.TexCoordIndices.Add(TextureOffset,TextureOffset+xc*2,TextureOffset+yc*2);
FGR.TexCoordIndices.Add(TextureOffset+1,TextureOffset+yc*2+1,TextureOffset+xc*2+1);
End;
End;
Procedure BuildCylinder2(Mesh : TMeshObject; Position, Scale : TAffineVector; TopRadius,BottomRadius,Height: single; Slices : Integer);
Var
FGR : TFGVertexNormalTexIndexList;
VertexOffset : Integer;
NormalOffset : Integer;
TextureOffset : Integer;
Cosine,Sine : Array of Single;
xc,yc : Integer;
Begin
If Slices < 3 then Exit;
SetLength(Sine,Slices+1);
SetLength(Cosine,Slices+1);
PrepareSinCosCache(Sine,Cosine,0,360);
VertexOffset := Mesh.Vertices.Count;
NormalOffset := Mesh.Normals.Count;
TextureOffset := Mesh.TexCoords.Count;
For xc := 0 to Slices-1 do
Begin
Mesh.Vertices.Add(VectorCombineWeighted(Position,Scale,TopRadius*0.5*cosine[xc],TopRadius*0.5*sine[xc],Height/2));
Mesh.Vertices.Add(VectorCombineWeighted(Position,Scale,BottomRadius*0.5*cosine[xc],BottomRadius*0.5*sine[xc],-Height/2));
// Normals
Mesh.Normals.add(AffineVectorMake(cosine[xc],sine[xc],0));
// Texture Coordinates
Mesh.TexCoords.add(VectorCombineWeighted(Position,XYZVector,TopRadius*0.5*cosine[xc],TopRadius*0.5*sine[xc],Height/2));
Mesh.TexCoords.add(VectorCombineWeighted(Position,XYZVector,BottomRadius*0.5*cosine[xc],BottomRadius*0.5*sine[xc],-Height/2));
End;
Mesh.Normals.add(AffineVectorMake(0,0,1));
Mesh.Normals.add(AffineVectorMake(0,0,-1));
FGR := TFGVertexNormalTexIndexList.CreateOwned(Mesh.FaceGroups);
FGR.Mode := fgmmTriangles;
For xc := 0 to Slices-1 do
Begin
yc := xc+1;
If yc = slices then yc := 0;
FGR.VertexIndices.Add(VertexOffset+xc*2,VertexOffset+xc*2+1,VertexOffset+yc*2+1);
FGR.VertexIndices.Add(VertexOffset+xc*2,VertexOffset+yc*2+1,VertexOffset+yc*2);
FGR.NormalIndices.Add(NormalOffset+xc,NormalOffset+xc,NormalOffset+yc);
FGR.NormalIndices.Add(NormalOffset+xc,NormalOffset+yc,NormalOffset+yc);
FGR.TexCoordIndices.Add(TextureOffset+xc*2,TextureOffset+xc*2+1,TextureOffset+yc*2+1);
FGR.TexCoordIndices.Add(TextureOffset+xc*2,TextureOffset+yc*2+1,TextureOffset+yc*2);
End;
For xc := 1 to Slices-2 do
Begin
yc := xc+1;
FGR.VertexIndices.Add(VertexOffset,VertexOffset+xc*2,VertexOffset+yc*2);
FGR.VertexIndices.Add(VertexOffset+1,VertexOffset+yc*2+1,VertexOffset+xc*2+1);
FGR.NormalIndices.Add(NormalOffset+Slices,NormalOffset+Slices,NormalOffset+Slices);
FGR.NormalIndices.Add(NormalOffset+Slices+1,NormalOffset+Slices+1,NormalOffset+Slices+1);
FGR.TexCoordIndices.Add(TextureOffset,TextureOffset+xc*2,TextureOffset+yc*2);
FGR.TexCoordIndices.Add(TextureOffset+1,TextureOffset+yc*2+1,TextureOffset+xc*2+1);
End;
End;
end.
|
unit xml;
{$MODE Delphi}
interface
uses Classes, Contnrs, SysUtils;
type
TXMLNode = class;
TXMLNodeEnum = class
private
FList: TObjectList;
function GetCount: Integer;
function GetItem(Index: Integer): TXMLNode;
constructor Create(AList: TObjectList);
public
destructor Destroy; override;
property Count: Integer read GetCount;
property Item[Index: Integer]: TXMLNode read GetItem; default;
end;
TXMLNode = class
private
FName: String;
FAttributes: TStringList;
FChildren: TObjectList;
function GetAttribute(const AttrName: String): String;
procedure SetAttribute(const AttrName: String; const Value: String);
procedure Add(Child: TXMLNode);
public
constructor Create;
destructor Destroy; override;
function AddChild: TXMLNode;
function GetNodesByName(const str: String): TXMLNodeEnum;
property Name: String read FName write FName;
property Attributes[const AttrName: String]: String
read GetAttribute write SetAttribute;
end;
TXMLWriter = class
private
FStream: TStream;
procedure Write(const str: String); overload;
procedure WriteLn(const str: String);
public
constructor Create(Stream: TStream);
procedure Write(node: TXMLNode); overload;
end;
TXMLReader = class
private
FStream: TStream;
FLastChar: Char;
procedure ReadChar;
procedure SkipSpace;
function ReadName: String;
function ReadValue: String;
function IsNameCharacter: Boolean;
function IsNameStartingCharacter: Boolean;
function EOF: Boolean;
public
constructor Create(Stream: TStream);
function Read: TXMLNode;
end;
implementation
function EncodeXML(const str: String): String;
begin
Result := str;
Result := StringReplace(Result, '&', '&', [rfReplaceAll]);
Result := StringReplace(Result, '<', '<', [rfReplaceAll]);
Result := StringReplace(Result, '>', '>', [rfReplaceAll]);
end;
function DecodeXML(const str: String): String;
begin
Result := str;
Result := StringReplace(Result, '>', '>', [rfReplaceAll]);
Result := StringReplace(Result, '<', '<', [rfReplaceAll]);
Result := StringReplace(Result, '&', '&', [rfReplaceAll]);
end;
function TXMLNodeEnum.GetCount: Integer;
begin
Result := FList.Count;
end;
function TXMLNodeEnum.GetItem(Index: Integer): TXMLNode;
begin
Result := FList[Index] as TXMLNode;
end;
constructor TXMLNodeEnum.Create(AList: TObjectList);
begin
FList := AList;
end;
destructor TXMLNodeEnum.Destroy;
begin
FList.Free;
inherited Destroy;
end;
constructor TXMLNode.Create;
begin
FAttributes := TStringList.Create;
FChildren := TObjectList.Create;
end;
destructor TXMLNode.Destroy;
begin
FChildren.Free;
FAttributes.Free;
inherited Destroy;
end;
procedure TXMLNode.Add(Child: TXMLNode);
begin
if Child <> nil then
FChildren.Add(Child);
end;
function TXMLNode.AddChild: TXMLNode;
begin
Result := TXMLNode.Create;
FChildren.Add(Result);
end;
function TXMLNode.GetAttribute(const AttrName: String): String;
begin
Result := FAttributes.Values[AttrName];
end;
procedure TXMLNode.SetAttribute(const AttrName: String; const Value: String);
begin
FAttributes.Values[AttrName] := Value;
end;
function TXMLNode.GetNodesByName(const str: String): TXMLNodeEnum;
var
list: TObjectList;
i: Integer;
begin
list := TObjectList.Create(False);
for i := 0 to Self.FChildren.Count - 1 do
begin
if str = (FChildren[i] as TXMLNode).Name then
list.Add(FChildren[i]);
end;
Result := TXMLNodeEnum.Create(list);
end;
constructor TXMLWriter.Create(Stream: TStream);
begin
FStream := Stream;
end;
procedure TXMLWriter.Write(const str: String);
begin
FStream.Write(str[1], Length(str));
end;
procedure TXMLWriter.WriteLn(const str: String);
begin
Write(str + #13#10);
end;
procedure TXMLWriter.Write(Node: TXMLNode);
var
i: Integer;
strName, strValue: String;
begin
Write('<' + Node.Name);
for i := 0 to Node.FAttributes.Count - 1 do
begin
strName := Node.FAttributes.Names[i];
strValue := Node.Attributes[strName];
Write(' ' + strName + '="' + EncodeXML(strValue) + '"');
end;
if Node.FChildren.Count > 0 then
begin
WriteLn('>');
for i := 0 to Node.FChildren.Count - 1 do
Write(Node.FChildren[i] as TXMLNode);
Write('</' + Node.Name + '>');
end
else
WriteLn(' />');
end;
constructor TXMLReader.Create(Stream: TStream);
begin
FStream := Stream;
FLastChar := ' ';
end;
function TXMLReader.EOF: Boolean;
begin
Result := FLastChar = Chr(26);
end;
procedure TXMLReader.ReadChar;
begin
if FStream.Read(FLastChar, SizeOf(Char)) < SizeOf(Char) then
begin
FLastChar := Chr(26);
end;
end;
procedure TXMLReader.SkipSpace;
begin
while (not EOF) and (FLastChar <= ' ') do
ReadChar;
end;
function TXMLReader.ReadName: String;
begin
if not IsNameStartingCharacter then
raise Exception.Create('Expected latin letter');
Result := '';
while (not EOF) and IsNameCharacter do
begin
Result := Result + FLastChar;
ReadChar;
end;
end;
function TXMLReader.ReadValue: String;
begin
Result := '';
while (not EOF) and (FLastChar <> '"') do
begin
Result := Result + FLastChar;
ReadChar;
end;
Result := DecodeXML(Result);
end;
function TXMLReader.IsNameStartingCharacter: Boolean;
begin
Result := ((FLastChar >= 'a') and (FLastChar <= 'z')) or
((FLastChar >= 'A') and (FLastChar <= 'Z'));
end;
function TXMLReader.IsNameCharacter: Boolean;
begin
Result := (FLastChar in ['a'..'z']) or (FLastChar in ['A'..'Z']) or
(FLastChar in ['0'..'9']) or (FLastChar in ['_', '-']);
end;
function TXMLReader.Read: TXMLNode;
var
strAttrName, strAttrValue: String;
closedTag: Boolean;
begin
SkipSpace;
if EOF then
begin
Result := nil;
Exit;
end;
if FLastChar <> '<' then
raise Exception.Create('Character < expected');
ReadChar; // skip '<'
Result := TXMLNode.Create;
Result.Name := ReadName;
SkipSpace;
while (IsNameStartingCharacter) do
begin
strAttrName := ReadName;
SkipSpace;
if (FLastChar <> '=') then
raise Exception.Create('Character = expected');
ReadChar;
SkipSpace;
if (FLastChar <> '"') then
raise Exception.Create('Character " expected');
ReadChar;
strAttrValue := ReadValue;
if (FLastChar <> '"') then
raise Exception.Create('Character " expected');
ReadChar;
Result.Attributes[strAttrName] := strAttrValue;
if (EOF) then
raise Exception.Create('Premature end of file during attribute parsing');
SkipSpace;
end;
if (EOF) then
raise Exception.Create('Premature end of file - expecting close tag');
if (FLastChar = '/') then
begin
ReadChar;
if (FLastChar <> '>') then
raise Exception.Create('Expecting > character');
ReadChar;
{ no children, and we succeeded!!! }
end
else if (FLastChar = '>') then
begin
ReadChar;
closedTag := False;
repeat
{ try to find children and then lookup for a matching </ }
SkipSpace;
if FLastChar <> '<' then
raise Exception.Create('Expecting <');
ReadChar;
if IsNameStartingCharacter then
begin
// go 1 chars back
FStream.Seek(-1, soFromCurrent);
// set FLastChar
FLastChar := '<';
// read recursive
Result.Add(Self.Read);
end
else if FLastChar = '/' then
begin
ReadChar;
if Result.Name <> ReadName then
raise Exception.Create('Start tag does not match close tag');
if FLastChar <> '>' then
raise Exception.Create('Expecting >');
ReadChar;
closedTag := True;
end
else
raise Exception.Create('Expecting tag name or /');
until closedTag;
end
else
raise Exception.Create('Expecting / or > but found ' + FLastChar);
end;
end.
|
unit frm_xplappslauncher;
{==============================================================================
UnitName = frm_xplappslauncher
UnitDesc = Standard xPL apps launching box
UnitCopyright = GPL by Clinique / xPL Project
==============================================================================
1.0 : Added code to avoid presenting myself in the list of applications to launch
}
{$mode objfpc}{$H+}
{$r *.lfm}
interface
uses Classes, SysUtils, LSControls, LResources, Forms, Controls, Graphics,
ComCtrls, ActnList, Buttons, ExtCtrls, dlg_template;
type // TfrmAppLauncher =======================================================
TfrmAppLauncher = class(TDlgTemplate)
FrmAcLaunch: TAction;
DlgTbLaunch: TLSBitBtn;
lvApps: TListView;
procedure DlgTbLaunchClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
end;
procedure ShowFrmAppLauncher;
implementation //==============================================================
uses Process
, FileUtil
, Dialogs
, u_xpl_application
, u_xpl_collection
, u_xpl_settings
, u_xpl_gui_resource
;
var frmAppLauncher: TfrmAppLauncher;
// ============================================================================
procedure ShowFrmAppLauncher;
begin
if not Assigned(frmAppLauncher) then
Application.CreateForm(TFrmAppLauncher, frmAppLauncher);
frmAppLauncher.ShowModal;
end;
// Form procedures ============================================================
procedure TfrmAppLauncher.FormCreate(Sender: TObject);
begin
inherited;
SetButtonImage(DlgTbLaunch,FrmAcLaunch,K_IMG_MENU_RUN);
end;
procedure TfrmAppLauncher.FormShow(Sender: TObject);
var sl : TxPLCustomCollection;
path, version, nicename : string;
i : integer;
begin
inherited;
lvApps.Items.Clear;
with TxPLRegistrySettings(xPLApplication.Settings) do begin
sl := GetxPLAppList;
for i := 0 to sl.Count -1 do begin
GetAppDetail(sl.Items[i].Value,sl.Items[i].DisplayName,path,version, nicename);
if path <> Application.ExeName then with lvApps.Items.Add do begin // Avoid presenting myself in the app list
if NiceName<>'' then Caption := NiceName
else Caption := sl[i].DisplayName;
SubItems.DelimitedText:= Sl[i].Value + ',' + version + ',' + path;
end;
end;
sl.Free;
end;
end;
procedure TfrmAppLauncher.DlgTbLaunchClick(Sender: TObject);
var filename : string;
begin
if lvApps.Selected = nil then exit;
filename := lvApps.Selected.SubItems[2];
if FileExists(filename) then
with TProcess.Create(nil) do try
Executable := filename;
Execute;
finally
Free;
DlgTbClose.Click;
end
else
ShowMessage('File not found : ' + FileName);
end;
end.
|
unit ClassBSTree;
interface
type TBSTree = class;
TBSTreeChildren = array of TBSTree;
TBSTree = class
public
C : char;
IsWord : boolean;
Children : TBSTreeChildren;
constructor Create( Value : char; Word : boolean );
destructor Destroy; override;
end;
implementation
//==============================================================================
// Constructor / destructor
//==============================================================================
constructor TBSTree.Create( Value : char; Word : boolean );
begin
inherited Create;
C := Value;
IsWord := Word;
SetLength( Children , 0 );
end;
destructor TBSTree.Destroy;
var I : integer;
begin
for I := Low( Children ) to High( Children ) do
Children[I].Free;
SetLength( Children , 0 );
inherited;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
Edit1: TEdit;
Label2: TLabel;
Button1: TButton;
Label3: TLabel;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{
Function for detecting whether a string is a palindrome
}
function isPalindrome(number: string): boolean;
var
sNumber: string;
lengthNumber, halfLengthNumber: integer;
i: integer;
flag: boolean;
begin
flag := true;
// sNumber := intToStr(number);
sNumber := number;
// quantity digits in number
lengthNumber := length(sNumber);
// half length of number for checking process
halfLengthNumber := lengthNumber div 2;
for i := 1 to halfLengthNumber do
begin
if (sNumber[i] <> sNumber[lengthNumber - i + 1]) then
begin
flag := false;
break;
end;
end;
isPalindrome := flag;
end;
{
Function for resersing string
}
function reverse(number: string): string;
var
sNumber: string;
temp: char;
lengthNumber, halfLengthNumber: integer;
i: integer;
begin
// sNumber := intToStr(number);
sNumber := number;
// quantity digits in number
lengthNumber := length(sNumber);
halfLengthNumber := lengthNumber div 2;
temp := '0';
// swapping symbols in string
for i := 1 to halfLengthNumber do
begin
temp := sNumber[i];
sNumber[i] := sNumber[lengthNumber - i + 1];
sNumber[lengthNumber - i + 1] := temp;
end;
reverse := sNumber;
end;
{
Function for summation long numbers
}
function longPlus(longA: string; longB: string):string;
var
len, c, i: longint;
a, b: array[1..100] of longint;
res: string;
begin
c := 0;
// split symbols of strings to arrays
len := length(LongA);
for i := 1 to len do
a[len - i + 1] := Ord(LongA[i])-48;
len := length(longB);
for i := 1 to len do
b[len - i + 1] := Ord(longB[i])-48;
// search number for max length
if (length(longA) > length(longB)) then
len := length(longA)
else
len := length(longB);
// summation and transfer of tens
for i := 1 to len do
begin
c := c + a[i] + b[i];
a[i] := c mod 10;
c := c div 10;
end;
// checking for the need to add to the descharge
if (c > 0) then
begin
len := len + 1;
a[len] := c;
end;
// write result number to string
res := '';
for i := len downto 1 do
res := res + IntToStr(a[i]);
longPlus := res;
end;
{
Version for simple summation
Is not work for some numbers(for exemple 573)
}
function simpleVersion(n: longint): string;
const
// minimum necessary quantity operations
OPS = 100;
var
operations: longint;
number: string;
begin
operations := 0;
// if "n" is not palindrom and program not yet perform OPS operations
while (not isPalindrome(intToStr(n))) do
begin
if (operations = OPS) then
begin
operations := -1;
break;
end;
n := n + strToInt(reverse(intToStr(n)));
inc(operations);
end;
simpleVersion := intToStr(operations);
end;
{
Versia that works across the all range from 10 to 10000
}
function longVersion(n: longint): string;
const
// minimum necessary quantity operations
OPS = 100;
var
operations: longint;
sNumber: string;
begin
sNumber := intToStr(n);
operations := 0;
// if "n" is not palindrom and program not yet perform OPS operations
while (not isPalindrome(sNumber)) do
begin
if (operations = OPS) then
begin
operations := -1;
break;
end;
sNumber := longPlus(sNumber,reverse(sNumber));
inc(operations);
end;
longVersion := intToStr(operations);
end;
{
main programm
}
procedure TForm1.Button1Click(Sender: TObject);
var
n: longint;
operations, number: string;
begin
number := Form1.Edit1.Text;
if ((number <> '')) then
begin
if (length(number) <= 5) then
begin
n := strToInt(Form1.Edit1.Text);
// operations := simpleVersion(n);
operations := longVersion(n);
Form1.Label3.Caption := 'Ответ: ' + operations;
end else ShowMessage('Вы ввели слишком большое число!');
end else ShowMessage('Введите в поле число!');
end;
end.
|
{ *******************************************************************************
Title: T2Ti ERP
Description: Funções e procedimentos do PAF;
The MIT License
Copyright: Copyright (C) 2010 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</p>
@author Albert Eije (T2Ti.COM)
@version 1.0
******************************************************************************* }
unit UPAF;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Dbtables, Inifiles, Generics.Collections, Biblioteca, ProdutoController,
ACBrPAF, ACBrPAF_D, ACBrPAF_E, ACBrPAF_P, ACBrPAF_R, ACBrPAF_T,
ACBrPAFRegistros, Math;
procedure PreencherHeader(Header: TRegistroX1);
procedure GeraTabelaProdutos;
procedure GeraArquivoEstoque;
procedure GeraMovimentoECF;
procedure DAVEmitidos(DataIni: String; DataFim:String);
implementation
uses
R02VO, R03VO, R04VO, R05VO, R06VO, R07VO, RegistroRController,
EmpresaController, EmpresaVO, UDataModule, ProdutoVO, ImpressoraController,
ImpressoraVO, TotalTipoPagamentoController, MeiosPagamentoVO, SintegraController,
Sintegra60MVO, Sintegra60AVO, DAVController, DAVVO;
procedure PreencherHeader(Header: TRegistroX1);
var
EmpresaControl: TEmpresaController;
Empresa: TEmpresaVO;
begin
EmpresaControl := TEmpresaController.Create;
Empresa := EmpresaControl.PegaEmpresa(StrToInt(FDataModule.IdEmpresa));
Header.UF := Empresa.UF;
Header.CNPJ := Empresa.CNPJ;
Header.IE := Empresa.InscricaoEstadual;
Header.IM := Empresa.InscricaoMunicipal;
Header.RAZAOSOCIAL := Empresa.RAZAOSOCIAL;
end;
procedure GeraTabelaProdutos;
var
P2: TRegistroP2;
i: integer;
ListaProduto: TObjectList<TProdutoVO>;
ProdutoControl: TProdutoController;
begin
ListaProduto := ProdutoControl.TabelaProduto;
if Assigned(ListaProduto) then
begin
// registro P1
PreencherHeader(FDataModule.ACBrPAF.PAF_P.RegistroP1);
// preencher header do arquivo
// registro P2
FDataModule.ACBrPAF.PAF_P.RegistroP2.Clear;
for i := 0 to ListaProduto.Count - 1 do
begin
P2 := FDataModule.ACBrPAF.PAF_P.RegistroP2.New;
P2.COD_MERC_SERV := TProdutoVO(ListaProduto.Items[i]).GTIN;
P2.DESC_MERC_SERV := TProdutoVO(ListaProduto.Items[i]).DescricaoPDV;
P2.UN_MED := TProdutoVO(ListaProduto.Items[i]).UnidadeProduto;
P2.IAT := TProdutoVO(ListaProduto.Items[i]).IAT;
P2.IPPT := TProdutoVO(ListaProduto.Items[i]).IPPT;
P2.ST := TProdutoVO(ListaProduto.Items[i]).SituacaoTributaria;
P2.ALIQ := StrToFloat(TProdutoVO(ListaProduto.Items[i]).ECFICMS);
P2.VL_UNIT := TProdutoVO(ListaProduto.Items[i]).ValorVenda;
end;
FDataModule.ACBrPAF.SaveFileTXT_P('PAF_P.txt');
end
else
Application.MessageBox('Não existem produtos na tabela.',
'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
end;
procedure GeraArquivoEstoque;
var
E2: TRegistroE2;
i: integer;
ListaProduto: TObjectList<TProdutoVO>;
ProdutoControl: TProdutoController;
begin
ListaProduto := ProdutoControl.TabelaProduto;
if Assigned(ListaProduto) then
begin
// registro E1
PreencherHeader(FDataModule.ACBrPAF.PAF_E.RegistroE1);
// preencher header do arquivo
// registro E2
FDataModule.ACBrPAF.PAF_E.RegistroE2.Clear;
for i := 0 to ListaProduto.Count - 1 do
begin
E2 := FDataModule.ACBrPAF.PAF_E.RegistroE2.New;
E2.COD_MERC := TProdutoVO(ListaProduto.Items[i]).GTIN;
E2.DESC_MERC := TProdutoVO(ListaProduto.Items[i]).DescricaoPDV;
E2.UN_MED := TProdutoVO(ListaProduto.Items[i]).UnidadeProduto;
E2.QTDE_EST := TProdutoVO(ListaProduto.Items[i]).QtdeEstoque;
E2.DT_EST := Date;
end;
FDataModule.ACBrPAF.SaveFileTXT_E('PAF_E.txt');
end
else
Application.MessageBox('Não existem produtos na tabela.',
'Informação do Sistema', MB_OK + MB_ICONINFORMATION);
end;
procedure GeraMovimentoECF;
var
i, j: integer;
ImpressoraControl: TImpressoraController;
Impressora: TImpressoraVO;
EmpresaControl: TEmpresaController;
Empresa: TEmpresaVO;
ListaR02: TObjectList<TR02VO>;
ListaR03: TObjectList<TR03VO>;
ListaR04: TObjectList<TR04VO>;
ListaR05: TObjectList<TR05VO>;
ListaR06: TObjectList<TR06VO>;
ListaR07: TObjectList<TR07VO>;
RegistroRContol: TRegistroRController;
begin
RegistroRContol := TRegistroRController.Create;
// dados da impressora
ImpressoraControl := TImpressoraController.Create;
Impressora := ImpressoraControl.PegaImpressora
(StrToInt(FDataModule.IdImpressora));
// dados da empresa
EmpresaControl := TEmpresaController.Create;
Empresa := EmpresaControl.PegaEmpresa(StrToInt(FDataModule.IdEmpresa));
// Registro R1
with FDataModule.ACBrPAF.PAF_R.RegistroR01 do
begin
NUM_FAB := Impressora.Serie;
MF_ADICIONAL := Impressora.MFD;
TIPO_ECF := Impressora.Tipo;
MARCA_ECF := Impressora.Marca;
MODELO_ECF := Impressora.Modelo;
VERSAO_SB := FDataModule.ACBrECF.NumVersao;
DT_INST_SB := FDataModule.ACBrECF.DataHoraSB;
HR_INST_SB := FDataModule.ACBrECF.DataHoraSB;
NUM_SEQ_ECF := Impressora.Id;
CNPJ := Empresa.CNPJ;
IE := Empresa.InscricaoEstadual;
{ TODO : Onde vamos armazenar os dados da Software House? No BD? Arquivo INI? }
CNPJ_SH := '10793118000178';
IE_SH := 'ISENTO';
IM_SH := 'ISENTO';
NOME_SH := 'T2TI.COM';
NOME_PAF := 'T2Ti PDV';
VER_PAF := '0100';
COD_MD5 := '9e107d9d372bb6826bd81d3542a419d6';
DT_INI := Date;
DT_FIN := Date;
ER_PAF_ECF := '0105';
end;
// Registro R02 e R03
ListaR02 := RegistroRContol.TabelaR02;
for i := 0 to ListaR02.Count - 1 do
begin
with FDataModule.ACBrPAF.PAF_R.RegistroR02.New do
begin
NUM_USU := TR02VO(ListaR02.Items[i]).IdOperador;
CRZ := TR02VO(ListaR02.Items[i]).CRZ;
COO := TR02VO(ListaR02.Items[i]).COO;
CRO := TR02VO(ListaR02.Items[i]).CRO;
DT_MOV := StrToDateTime(TR02VO(ListaR02.Items[i]).DataMovimento);
DT_EMI := StrToDateTime(TR02VO(ListaR02.Items[i]).DataEmissao);
HR_EMI := StrToDateTime(TR02VO(ListaR02.Items[i]).HoraEmissao);
VL_VBD := TR02VO(ListaR02.Items[i]).VendaBruta;
PAR_ECF := '';
// Registro R03 - FILHO
ListaR03 := RegistroRContol.TabelaR03(TR02VO(ListaR02.Items[i]).Id);
if Assigned(ListaR03) then
begin
for j := 0 to ListaR03.Count - 1 do
begin
with RegistroR03.New do
begin
TOT_PARCIAL := TR03VO(ListaR03.Items[j]).TotalizadorParcial;
VL_ACUM := TR03VO(ListaR03.Items[j]).ValorAcumulado;
end;
end;
end;
end;
end;
// Registro R04 e R05
ListaR04 := RegistroRContol.TabelaR04;
for i := 0 to ListaR04.Count - 1 do
begin
with FDataModule.ACBrPAF.PAF_R.RegistroR04.New do
begin
NUM_USU := TR04VO(ListaR04.Items[i]).IdOperador;
NUM_CONT := TR04VO(ListaR04.Items[i]).CCF;
COO := TR04VO(ListaR04.Items[i]).COO;
DT_INI := StrToDateTime(TR04VO(ListaR04.Items[i]).DataEmissao);
SUB_DOCTO := TR04VO(ListaR04.Items[i]).SubTotal;
SUB_DESCTO := TR04VO(ListaR04.Items[i]).Desconto;
TP_DESCTO := TR04VO(ListaR04.Items[i]).IndicadorDesconto;
SUB_ACRES := TR04VO(ListaR04.Items[i]).Acrescimo;
TP_ACRES := TR04VO(ListaR04.Items[i]).IndicadorAcrescimo;
VL_TOT := TR04VO(ListaR04.Items[i]).ValorLiquido;
CANC := TR04VO(ListaR04.Items[i]).Cancelado;
VL_CA := TR04VO(ListaR04.Items[i]).CancelamentoAcrescimo;
ORDEM_DA := TR04VO(ListaR04.Items[i]).OrdemDescontoAcrescimo;
NOME_CLI := TR04VO(ListaR04.Items[i]).Cliente;
CNPJ_CPF := TR04VO(ListaR04.Items[i]).CPFCNPJ;
// Registro R05 - FILHO
ListaR05 := RegistroRContol.TabelaR05(TR04VO(ListaR04.Items[i]).Id);
if Assigned(ListaR05) then
begin
for j := 0 to ListaR05.Count - 1 do
begin
with RegistroR05.New do
begin
NUM_ITEM := TR05VO(ListaR05.Items[j]).Item;
COD_ITEM := TR05VO(ListaR05.Items[j]).GTIN;
DESC_ITEM := TR05VO(ListaR05.Items[j]).DescricaoPDV;
QTDE_ITEM := TR05VO(ListaR05.Items[j]).Quantidade;
UN_MED := TR05VO(ListaR05.Items[j]).SiglaUnidade;
VL_UNIT := TR05VO(ListaR05.Items[j]).ValorUnitario;
DESCTO_ITEM := TR05VO(ListaR05.Items[j]).Desconto;
ACRES_ITEM := TR05VO(ListaR05.Items[j]).Acrescimo;
VL_TOT_ITEM := TR05VO(ListaR05.Items[j]).TotalItem;
COD_TOT_PARC := TR05VO(ListaR05.Items[j]).TotalizadorParcial;
IND_CANC := TR05VO(ListaR05.Items[j]).IndicadorCancelamento;
QTDE_CANC := TR05VO(ListaR05.Items[j]).QuantidadeCancelada;
VL_CANC := TR05VO(ListaR05.Items[j]).ValorCancelado;
VL_CANC_ACRES := TR05VO(ListaR05.Items[j]).CancelamentoAcrescimo;
IAT := TR05VO(ListaR05.Items[j]).IAT;
IPPT := TR05VO(ListaR05.Items[j]).IPPT;
QTDE_DECIMAL := TR05VO(ListaR05.Items[j]).CasasDecimaisQuantidade;
VL_DECIMAL := TR05VO(ListaR05.Items[j]).CasasDecimaisValor;
end;
end;
end;
end;
end;
// Registro R06 e R07
ListaR06 := RegistroRContol.TabelaR06;
for i := 0 to ListaR06.Count - 1 do
begin
with FDataModule.ACBrPAF.PAF_R.RegistroR06.New do
begin
NUM_USU := TR06VO(ListaR06.Items[i]).IdOperador;
COO := TR06VO(ListaR06.Items[i]).COO;
GNF := TR06VO(ListaR06.Items[i]).GNF;
GRG := TR06VO(ListaR06.Items[i]).GRG;
CDC := TR06VO(ListaR06.Items[i]).CDC;
DENOM := TR06VO(ListaR06.Items[i]).Denominacao;
DT_FIN := StrToDateTime(TR06VO(ListaR06.Items[i]).DataEmissao);
HR_FIN := StrToDateTime(TR06VO(ListaR06.Items[i]).HoraEmissao);
// Registro R07 - FILHO
ListaR07 := RegistroRContol.TabelaR07(TR06VO(ListaR06.Items[i]).Id);
if Assigned(ListaR07) then
begin
for j := 0 to ListaR07.Count - 1 do
begin
with RegistroR07.New do
begin
CCF := TR07VO(ListaR07.Items[j]).CCF;
MP := TR07VO(ListaR07.Items[j]).MeioPagamento;
VL_PAGTO := TR07VO(ListaR07.Items[j]).ValorPagamento;
IND_EST := TR07VO(ListaR07.Items[j]).IndicadorEstorno;
VL_EST := TR07VO(ListaR07.Items[j]).ValorEstorno;
end;
end;
end;
end;
end;
FDataModule.ACBrPAF.SaveFileTXT_R('PAF_R.txt');
end;
procedure DAVEmitidos(DataIni: String; DataFim:String);
var
ListaDAV: TObjectList<TDAVVO>;
DAVControl: TDAVController;
ImpressoraControl: TImpressoraController;
Impressora: TImpressoraVO;
D2: TRegistroD2;
i:integer;
begin
ListaDAV := DavControl.ListaDAVPeriodo(DataIni,DataFim);
if Assigned(ListaDAV) then
begin
// registro D1
UPAF.PreencherHeader(FDataModule.ACBrPAF.PAF_D.RegistroD1); // preencher header do arquivo
// registro D2
FDataModule.ACBrPAF.PAF_D.RegistroD2.Clear;
//dados da impressora
ImpressoraControl := TImpressoraController.Create;
Impressora := ImpressoraControl.PegaImpressora(StrToInt(FDataModule.IdImpressora));
for i := 0 to ListaDAV.Count - 1 do
begin
D2 := FDataModule.ACBrPAF.PAF_D.RegistroD2.New;
D2.NUM_FAB := Impressora.Serie;
D2.MF_ADICIONAL := Impressora.MFD;
D2.TIPO_ECF := Impressora.Tipo;
D2.MARCA_ECF := Impressora.Marca;
D2.MODELO_ECF := Impressora.Modelo;
D2.COO := IntToStr(TDAVVO(ListaDAV.Items[i]).COO);
D2.NUM_DAV := StringOfChar('0',10-Length(IntToStr(TDAVVO(ListaDAV.Items[i]).Id))) + IntToStr(TDAVVO(ListaDAV.Items[i]).Id);
D2.DT_DAV := StrToDateTime(TDAVVO(ListaDAV.Items[i]).DataHoraEmissao);
{ TODO : Devemos configurar o titulo de cada DAV? Ou pelo menos deixar em aberto a configuração do titulo dos DAV (orçamento/pedido/etc)? }
D2.TIT_DAV := 'ORÇAMENTO';
D2.VLT_DAV := TDAVVO(ListaDAV.Items[i]).Valor;
end;
{ TODO : Devemos configurar o caminho para salvar os arquivos ou salvamos na propria pasta da aplicação? }
FDataModule.ACBrPAF.SaveFileTXT_D('PAF_D.txt');
end;
end;
end.
|
unit CRT;
{$A+,B-,C-,D+,E-,F-,G+,H+,I-,J+,K-,L+,M-,N+,O+,P-,Q-,R-,S-,T-,U-,V-,W-,X+,Y+}
{BP7 compatible CRT unit for Win32/64 Delphi}
interface
{$IFDEF CONDITIONALEXPRESSIONS}
{$IF CompilerVersion >= 23.0} {D16(XE2)+}
{$DEFINE UNIT_SCOPE}
{$IFEND}
{$IF CompilerVersion >= 23.0}
{$DEFINE TXTREC_CP}
{$IFEND}
{$ENDIF}
uses
{$ifdef UNIT_SCOPE}
winapi.windows;
{$else}
Windows;
{$endif}
(*************************************************************************
DESCRIPTION : BP7 compatible CRT unit for Win32/64 Delphi
REQUIREMENTS : D2-D7/D9-D10/D12/D17
EXTERNAL DATA :
MEMORY USAGE :
DISPLAY MODE : text
REMARKS : The unit is tested with D17 (XE3) but NOT with D14-D16.
The symbols UNIT_SCOPE and TXTREC_CP are defined for D16+,
for UNIT_SCOPE this is consistent with official Delphi
documents; please report any problems.
REFERENCES : [1] Will DeWitt's Delphi 2+ CRT unit from Code central
http://cc.embarcadero.com/Item.aspx?id=19810
[2] Phoenix Technical Reference Series: System BIOS for
IBM PC/XT/AT Computers and Compatibles
[3] Background info: CRT source codes from BP7, VP 2.1, FP 2.0
[4] Rudy Velthuis' freeware http://rvelthuis.de/programs/console.html
Version Date Author Modification
------- -------- ------- ------------------------------------------
1.00 W. deWitt Initial version
1.10 WdW Delphi 2 compatibility and other
1.11 WdW Delphi 7 separation etc
1.12 WdW Bug fixes
1.20 21.03.04 WdW Some additional extended Crt functionality
1.21 23.09.05 W.Ehrhardt Removed sysutils,
1.30.00 10.10.06 we Routines from Rudy Velthuis' console.pas:
TranslateKey, Readkey, Keypressed
1.30.01 10.10.06 we Keypressed with INPUT_RECORD
1.30.02 11.10.06 we Removed NOCRTEXTENSIONS
1.30.03 11.10.06 we Delay with DWORD
1.30.04 11.10.06 we RV Convertkey removed
1.30.05 11.10.06 we RV Keypressed D3 compatible
1.30.06 11.10.06 we Removed "deprecated"
1.30.07 11.10.06 we mask ENHANCED_KEY in readkey
1.30.08 11.10.06 we Removed unused consts
1.30.09 11.10.06 we (VPC:) Removed register, bug fix first 2 entries of RV CKeys (trailing ';')
1.30.10 11.10.06 we WindMin/WindMax longint
1.31.00 11.10.06 we removed crt.ini
1.31.01 12.10.06 we Hardware sound for Win9x, MessageBeep(0) for NT+, Hz now word
1.31.02 12.10.06 we Fixed LastMode vs. LASTMODE confusion, const _LASTMODE=-1;
LastMode and Actual_Mode integer
1.31.03 13.10.06 we Map modes with Font8x8 to C4350
1.31.04 14.10.06 we Removed RV routines (buggy Enhanced keys, no Alt+[A-Z] etc
Complete rewrite of keypressed/readkey
1.31.05 14.10.06 we Fix: NumPad-5, Numpad-/, Ctrl-PrtScr
1.31.06 15.10.06 we Fix: Crtl-2, Crtl-6
1.31.07 15.10.06 we Esc, ^A,^D,^F,^S,^Z, Num-Enter in CrtInput
1.31.08 15.10.06 we BP types in GotoXY, Sound, TextBackground, TextColor
1.31.09 15.10.06 we BP modes, textmode call clrscr; WhereX/Y: byte
1.31.10 16.10.06 we Window parameters bytes, WindMin/WindMax words,
1.31.11 16.10.06 we Normalize cursor, BufMax instead of f.BufPos in CrtInput
1.31.12 17.10.06 we Code clean up and comments
1.31.13 17.10.06 we More comments/references
1.31.14 17.10.06 we Bugfix scroll: byte -> smallint
1.31.15 18.10.06 we Last cosmetic changes in comment
1.31.16 05.11.06 we Keep only INPUT_RECORD as non pre-D4 type
1.31.17 05.11.06 we GetCursorPosXY
1.31.18 07.11.06 we CHAR_INFO etc reintroduced for Delphi2
1.32.00 18.07.09 we Delphi 2009 (D12) adjustments
1.32.01 29.07.09 we Updated URL for [1]
1.32.02 02.06.10 we CRTFix_01 for ^
1.33.00 23.12.12 we D17 (aka XE3) adjustments
**************************************************************************)
(*-------------------------------------------------------------------------
Portions Copyright (c) 1988-2003 Borland Software Corporation
Portions Copyright (c) 2006-2012 W.Ehrhardt
Disclaimer:
===========
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
If you use this code, please credit me and keep the references to the other
authors and sources.
Description:
============
This unit is a light version of Will DeWitt's code with several bug fixes
(especially readkey, extended key codes etc). Will's 'unit was based heavily
off of the Borland CBuilder 5 RTL'. Because of the unclear licence status of
Will's unit, my CRT source is not under zlib license.
Anyway, in this unit the code from Will/Borland is radically rewritten and
rearranged. The guiding requirement was to make it almost BP7 compatible.
The basic idea for separate hardware/software sound support is from Rudy
Velthuis' freeware console, but the implementation is different.
The supported keys for line editing are from BP7 (^A, ^H, ^D, ^F, ^M, ^S,
^Z), the paradigm shift from readkey to keypressed for doing the dirty work
is from FP. The key codes / translations / functionalities were taken from
the Phoenix BIOS book and a test program compiled with BP7.
There is still work to be done for some rare special extended keys, but this
work is delayed to bugfixes or problem reports.
-------------------------------------------------------------------------*)
const
{ CRT modes }
BW40 = 0; { 40x25 B/W on Color Adapter }
CO40 = 1; { 40x25 Color on Color Adapter }
BW80 = 2; { 80x25 B/W on Color Adapter }
CO80 = 3; { 80x25 Color on Color Adapter }
Mono = 7; { 80x25 on Monochrome Adapter }
Font8x8 = 256; { Add-in for ROM font }
{ Delphi extension modes }
Last_Mode = -1; { Use LastMode}
Init_Mode = -2; { Mode at initialization}
C40 = CO40; { Mode constants for 3.0 compatibility }
C80 = CO80;
Black = 0; { Foreground and background color constants }
Blue = 1;
Green = 2;
Cyan = 3;
Red = 4;
Magenta = 5;
Brown = 6;
LightGray = 7;
DarkGray = 8; { Foreground color constants }
LightBlue = 9;
LightGreen = 10;
LightCyan = 11;
LightRed = 12;
LightMagenta = 13;
Yellow = 14;
White = 15;
Blink = 128; { Mask for blinking, does not work in Win32,}
{ turns on high intensity background colors.}
var
CheckBreak : boolean = true; { Enable Ctrl-Break }
CheckSnow : boolean; { Enable snow filtering }
DirectVideo: boolean; { Enable direct video addressing }
LastMode : integer; { Current text mode }
TextAttr : byte; { Current text attribute }
CheckEOF : boolean = false; { Enable Ctrl-Z }
WindMin : word; { Window upper left coordinates }
WindMax : word; { Window lower right coordinates }
procedure AssignCrt(var f: text);
{-Associate the console with text file f}
procedure ClrEol;
{-Clears all the chars from the cursor position to the end of the line}
procedure ClrScr;
{-Clear the current window, screen if no window set}
procedure Delay(MS: word);
{-Delay/Sleep for MS milliseconds}
procedure DelLine;
{-Delete the line containing the cursor}
procedure GotoXY(X, Y: byte);
{-Move cursor to col X, row Y (window relative)}
procedure HighVideo;
{-Set high intensity forground}
procedure InsLine;
{-Insert new line at cursor position}
function KeyPressed: boolean;
{-Return true if a character producing key has been pressed}
procedure LowVideo;
{-Set low intensity forground}
procedure NormVideo;
{-Set initial text attribute}
procedure NoSound;
{-Sound off, hardware for Win9x, dummy for NT+}
function ReadKey: AnsiChar;
{-Read a character from the keyboard, sleep until keypressed}
procedure Sound(Hz: word);
{-Sound on, hardware for Win9x / MesseageBeep(0) for NT+}
procedure TextBackground(Color: byte);
{-Set background color part if text attribute}
procedure TextColor(Color: byte);
{-Set foreground color part if text attribute}
procedure TextMode(Mode: integer);
{-Set new text mode / NormalAttr and clrscr}
function WhereX: byte;
{-Return current column of cursor (window relative)}
function WhereY: byte;
{-Return current row of cursor (window relative)}
procedure Window(X1, Y1, X2, Y2: byte);
{-Define screen area as net text window}
{$ifdef VER90}
procedure InitCRT;
{-Interfaced for Delphi 2 to overcome IsConsole quirk, see initialization}
{$endif}
implementation
{Will deWitt lists the following line in his source code:}
{Copyright (c) 1988-2003 Borland Software Corporation}
{$ifdef FPC}
Error('Not for Free Pascal');
{$endif}
{$ifdef VirtualPascal}
Error('Not for VirtualPascal');
{$endif}
{$ifndef WIN32}
{$ifndef WIN64}
Error('At least Delphi 2');
{$endif}
{$endif}
{$ifdef VER120} {D4}
{$define D4PLUS}
{$endif}
{$ifdef VER125} {BCB4}
{$define D4PLUS}
{$endif}
{$ifdef VER130} {D5}
{$define D4PLUS}
{$endif}
{$ifdef VER140} {D6}
{$define D4PLUS}
{$define D6PLUS}
{$endif}
{$ifdef CONDITIONALEXPRESSIONS} {D6+}
{$ifndef D4PLUS}
{$define D4PLUS}
{$endif}
{$ifndef D6PLUS}
{$define D6PLUS}
{$endif}
{$endif}
{$ifndef D6PLUS}
{Directly use Delphi 2-5 definitions to avoid sysutils overhead}
const
{File mode magic numbers}
fmClosed = $D7B0;
fmInput = $D7B1;
fmOutput = $D7B2;
fmInOut = $D7B3;
type
{Text file record structure used for text files}
PTextBuf = ^TTextBuf;
TTextBuf = array[0..127] of AnsiChar;
TTextRec = packed record
Handle : integer;
Mode : integer;
BufSize : Cardinal;
BufPos : Cardinal;
BufEnd : Cardinal;
BufPtr : PAnsiChar;
OpenFunc : pointer;
InOutFunc: pointer;
FlushFunc: pointer;
CloseFunc: pointer;
UserData : array[1..32] of byte;
Name : array[0..259] of AnsiChar;
Buffer : TTextBuf;
end;
{$endif}
{$ifndef D4PLUS}
{ Types that are either incorrectly defined in Windows.pas in pre-Delphi 4,
or that aren't defined at all. }
type
CONSOLE_SCREEN_BUFFER_INFO = TConsoleScreenBufferInfo;
CONSOLE_CURSOR_INFO = TConsoleCursorInfo;
COORD = TCoord;
SMALL_RECT = TSmallRect;
CHAR_INFO = record
case integer of
0: (UnicodeChar: WCHAR; Attributes: word);
1: (AsciiChar: AnsiChar);
end;
KEY_EVENT_RECORD = packed record
bKeyDown: BOOL;
wRepeatCount: word;
wVirtualKeyCode: word;
wVirtualScanCode: word;
case integer of
0: (UnicodeChar: WCHAR; dwControlKeyState: DWORD);
1: (AsciiChar: AnsiChar);
end;
TKeyEventRecord = KEY_EVENT_RECORD;
INPUT_RECORD = record
EventType: word;
Reserved: word;
Event: record case integer of
0: (KeyEvent: TKeyEventRecord);
1: (MouseEvent: TMouseEventRecord);
2: (WindowBufferSizeEvent: TWindowBufferSizeRecord);
3: (MenuEvent: TMenuEventRecord);
4: (FocusEvent: TFocusEventRecord);
end;
end;
function ReadConsoleInputA(hConsoleInput: THandle; var lpBuffer: INPUT_RECORD; nLength: DWORD; var lpNumberOfEventsRead: DWORD): BOOL; stdcall;
external 'kernel32.dll' name 'ReadConsoleInputA';
function ScrollConsoleScreenBufferA(hConsoleOutput: THandle; const lpScrollRectangle: TSmallRect; lpClipRectangle: PSmallRect; dwDestinationOrigin: TCoord; var lpFill: CHAR_INFO): BOOL; stdcall;
external 'kernel32.dll' name 'ScrollConsoleScreenBufferA';
{$endif}
type
T2Bytes = packed record
X,Y: byte;
end;
type
TScrollDir = (UP, DOWN); {Enum type for scroll directions}
type
TStringInfo = record
X, Y: integer;
SStart, SEnd: PAnsiChar;
end;
var
IsWinNT : boolean = true; {Default: use Win32 functions, hardware if Win9x detected}
var
ScreenWidth : integer = 0; {current width of screen}
ScreenHeight: integer = 0; {current height of screen}
NormalAttr : byte = $07; {attribute for NormVideo}
Orig_C : COORD; {original screen size}
MaxLines : integer = 50; {Number of lines for Font8x8}
var
InputHandle : THandle = INVALID_HANDLE_VALUE; {handle for CRT input}
OutputHandle: THandle = INVALID_HANDLE_VALUE; {handle for CRT output}
var
WMax : T2Bytes absolute WindMax;
WMin : T2Bytes absolute WindMin;
{---------------------------------------------------------------------------}
procedure NormalizeCursor;
{-Set cursor info, work around for a randomly disappearing }
{ cursor after mode set / clear screen}
var
Info: CONSOLE_CURSOR_INFO;
begin
SetConsoleCursorInfo(OutputHandle, Info);
if Info.dwSize=0 then Info.dwSize := 25
else if Info.dwSize<15 then Info.dwSize := 15
else if Info.dwSize>99 then Info.dwSize := 99;
Info.bVisible := True;
SetConsoleCursorInfo(OutputHandle, Info);
end;
{---------------------------------------------------------------------------}
procedure SetNewMode(NewMode: integer);
{-Set new text mode}
var
C: COORD;
R: SMALL_RECT;
begin
if NewMode=Init_Mode then C := Orig_C
else begin
if NewMode=Last_Mode then NewMode := LastMode;
if NewMode and Font8x8 <> 0 then C.Y := MaxLines else C.Y := 25;
if (NewMode and $FF) in [CO40, BW40] then C.X :=40 else C.X := 80;
end;
R.Left := 0;
R.Top := 0;
R.Right := C.X - 1;
R.Bottom := C.Y - 1;
{Double SetConsoleScreenBufferSize seems sometimes necessary!}
SetConsoleScreenBufferSize(OutputHandle, C);
if not SetConsoleWindowInfo(OutputHandle, true, R) then exit;
if SetConsoleScreenBufferSize(OutputHandle, C) then begin
ScreenWidth := C.X;
ScreenHeight := C.Y;
WMin.X := 0;
WMin.Y := 0;
WMax.X := ScreenWidth - 1;
WMax.Y := ScreenHeight - 1;
LastMode := NewMode;
end;
end;
{---------------------------------------------------------------------------}
function CtrlHandlerRoutine(dwCtrlType: DWORD): BOOL; stdcall;
{-Console CTRL+C / CTRL+BREAK handler routine}
begin
Result := false;
case dwCtrlType of
CTRL_CLOSE_EVENT,
CTRL_BREAK_EVENT,
CTRL_C_EVENT: begin
Result := true;
if IsConsole and CheckBreak then halt;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure InitVideo;
{-Get console buffer/window info; initialize internal variables for current mode}
var
Info: CONSOLE_SCREEN_BUFFER_INFO;
C: COORD;
begin
{Get initial screen info}
if GetConsoleScreenBufferInfo(OutputHandle, Info) then begin
{save original screen size}
Orig_C := info.dwSize;
NormalAttr := Info.wAttributes;
TextAttr := Info.wAttributes;
ScreenWidth := Info.dwSize.X;
ScreenHeight := Info.dwSize.Y;
end;
{Get number of lines for Font8x8}
C := GetLargestConsoleWindowSize(OutputHandle);
if C.Y <= 43 then MaxLines := 43 else MaxLines := 50;
{Always assume color modes for Win32}
if ScreenWidth<=40 then LastMode := CO40 else LastMode := CO80;
if ScreenHeight>25 then LastMode := LastMode or Font8x8;
{Set legacy variables}
CheckSnow := false;
DirectVideo := true;
{Set WindMin/Windmax}
WMin.X := 0;
WMin.Y := 0;
WMax.X := ScreenWidth - 1;
WMax.Y := ScreenHeight - 1;
if (ScreenWidth>255) or (ScreenHeight>255) then begin
{Paranoia: Make sure screen dimensions fit into bytes}
SetNewMode(LastMode);
end;
end;
{---------------------------------------------------------------------------}
procedure MoveCursor(X, Y: word);
{-Move cursor to X/Y position (internal)}
var
C: COORD;
begin
C.X := X;
C.Y := Y;
SetConsoleCursorPosition(OutputHandle, C);
end;
{---------------------------------------------------------------------------}
procedure Scroll(Dir: TScrollDir; X1, Y1, X2, Y2, NumLines: smallint);
{-Scroll a given area by NumLines, clear if NumLines=0}
var
Fill: CHAR_INFO;
R: SMALL_RECT;
C: COORD;
begin
Fill.AsciiChar := ' ';
Fill.Attributes := TextAttr;
if NumLines=0 then NumLines := Y2 - Y1 + 1;
R.Left := X1;
R.Top := Y1;
R.Right := X2;
R.Bottom := Y2;
C.X := X1;
if Dir=UP then C.Y := Y1 - NumLines
else C.Y := Y1 + NumLines;
ScrollConsoleScreenBufferA(OutputHandle, R, @R, C, Fill);
end;
{---------------------------------------------------------------------------}
procedure GetCursorPosXY(var cx,cy: integer);
{-get cursor X/Y positions (internal)}
var
Info: CONSOLE_SCREEN_BUFFER_INFO;
begin
if GetConsoleScreenBufferInfo(OutputHandle, Info) then begin
cx := Info.dwCursorPosition.X;
cy := Info.dwCursorPosition.Y;
end
else begin
cx := 0;
cy := 0;
end
end;
{---------------------------------------------------------------------------}
function CursorPosX: integer;
{-get cursor X position (internal)}
var
dummy: integer;
begin
GetCursorPosXY(Result, dummy);
end;
{---------------------------------------------------------------------------}
function CursorPosY: integer;
{-get cursor Y position (internal)}
var
dummy: integer;
begin
GetCursorPosXY(dummy, Result);
end;
{---------------------------------------------------------------------------}
function CrtClose(var f: TTextRec): integer;
{Close input/output, ie remove association of f with CRT}
begin
CloseHandle(f.Handle);
fillchar(f, sizeof(f), 0);
f.Handle := integer(INVALID_HANDLE_VALUE);
f.Mode := fmClosed;
Result := 0;
end;
{---------------------------------------------------------------------------}
function CrtInput(var f: TTextRec): integer;
{-CRT line input. read up to f.BufSize characters into f.BufPtr^}
var
BufMax: cardinal;
ch: AnsiChar;
{---------------------------------------------------}
procedure DoBackSpace;
{-Do one Backspace and replace with space}
begin
if f.BufEnd > 0 then begin
write(#8' '#8);
dec(f.BufEnd);
end;
end;
{---------------------------------------------------}
procedure DoEnter;
{-Perform Enter function, insert additional LineFeed}
begin
f.BufPtr[f.BufEnd] := #13;
inc(f.BufEnd);
if f.BufEnd + 1 < f.BufSize then begin
f.BufPtr[f.BufEnd] := #10;
inc(f.BufEnd);
end;
write(#13#10);
end;
{---------------------------------------------------}
procedure DoRecover;
{-"Recover" a previously erased char}
begin
if f.BufEnd < BufMax then begin
write(f.BufPtr[f.BufEnd]);
inc(f.BufEnd);
end;
end;
begin
{CrtInput reads up to BufSize characters into BufPtr^, and returns the number}
{of characters read in BufEnd. In addition, it stores zero in BufPos. If the}
{CrtInput function returns zero in BufEnd as a result of an input request, Eof}
{becomes true for the file.}
f.BufPos := 0;
f.BufEnd := 0;
BufMax := 0;
while f.BufEnd < f.BufSize do begin
ch := readkey;
case ch of
#0: begin
if ReadKey=#28 then begin
{Numpad Enter}
f.BufPtr[f.BufEnd] := #13;
DoEnter;
break;
end;
end;
#1..#31: begin
{ASCII ctrl chars}
case ch of
#27,
^A: while f.BufEnd > 0 do DoBackSpace;
^H: DoBackSpace;
^D: DoRecover;
^F: while f.BufEnd < BufMax do DoRecover;
^M: begin
DoEnter;
break;
end;
^S: DoBackSpace;
^Z: if CheckEOF then begin
inc(f.BufEnd);
break;
end;
else {drop!}
end;
end;
else begin
f.BufPtr[f.BufEnd] := ch;
write(ch);
inc(f.BufEnd);
{Update max. BufMax}
if f.BufEnd>BufMax then BufMax := f.BufEnd;
end;
end;
end;
Result := 0;
end;
{---------------------------------------------------------------------------}
function CrtInFlush(var f: TTextRec): integer;
{-called at the end of each Read, Readln}
begin
Result := 0;
end;
{ Internal Output Functions }
{---------------------------------------------------------------------------}
function CrtOutput(var f: TTextRec): integer;
{-write BufPos characters from BufPtr^,}
var
S: TStringInfo;
Hidden: boolean;
const
MAX_CELLS = 64; { C++ RTL defined this as 32}
procedure Flush(var S: TStringInfo);
{-Flush a string of characters to screen}
var
i, Len: integer;
Size, C: COORD;
Region: SMALL_RECT;
Cells: packed array[0..MAX_CELLS-1] of CHAR_INFO;
begin
Len := S.SEnd - S.SStart;
if Len=0 then exit;
for i:=0 to Len-1 do begin
Cells[i].AsciiChar := S.SStart[i];
Cells[i].Attributes := TextAttr;
end;
Size.X := Len;
Size.Y := 1;
C.X := 0;
C.Y := 0;
Region.Left := S.X - Len;
Region.Right := S.X - 1;
Region.Top := S.Y;
Region.Bottom := Region.Top;
WriteConsoleOutputA(OutputHandle, @Cells[0], Size, C, Region);
S.SStart := S.SEnd;
end;
begin
GetCursorPosXY(S.X, S.Y);
S.SStart := f.BufPtr;
S.SEnd := f.BufPtr;
{write BufPos characters from BufPtr^, and return zero in BufPos}
while f.BufPos > 0 do begin
dec(f.BufPos);
Hidden := true;
case S.SEnd[0] of
#7: begin
Flush(S);
MessageBeep(0);
end;
#8: begin
Flush(S);
if S.X > WMin.X then dec(S.X);
end;
#10: begin
Flush(S);
inc(S.Y);
end;
#13: begin
Flush(S);
S.X := WMin.X;
end;
else begin
Hidden := false;
inc(S.X);
end;
end;
inc(S.SEnd);
if Hidden then S.SStart := S.SEnd;
if S.SEnd-S.SStart >= MAX_CELLS then Flush(S);
if S.X > WMax.X then begin
Flush(S);
S.X := WMin.X;
inc(S.Y);
end;
if S.Y > WMax.Y then begin
Flush(S);
Scroll(UP, WMin.X, WMin.Y, WMax.X, WMax.Y, 1);
dec(S.Y);
end;
end;
Flush(S);
MoveCursor(S.X, S.Y);
Result := 0;
end;
{---------------------------------------------------------------------------}
function CrtOpen(var f: TTextRec): integer;
{-Prepare f for input or output according to the f.Mode value}
var
Info: CONSOLE_SCREEN_BUFFER_INFO;
begin
Result := 0;
{The CreateFile function enables a process to get a handle of its console's}
{input buffer and active screen buffer, even if STDIN and STDOUT have been}
{redirected. To open a handle of a console's input buffer, specify the CONIN$}
{value in a call to CreateFile. Specify the CONOUT$ value in a call to}
{CreateFile to open a handle of a console's active screen buffer.}
case f.Mode of
fmInput: begin
InputHandle := CreateFile('CONIN$', GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0);
f.Handle := InputHandle;
f.Mode := fmInput;
if f.BufPtr=nil then begin
f.BufPtr := @f.Buffer;
f.BufSize := sizeof(f.Buffer)
end;
SetConsoleMode(f.Handle, 0);
SetConsoleCtrlHandler(@CtrlHandlerRoutine, true);
f.InOutFunc := @CrtInput;
f.FlushFunc := @CrtInFlush;
f.CloseFunc := @CrtClose;
{$ifdef TXTREC_CP}
if f.CodePage = 0 then begin
if GetFileType(f.Handle)=FILE_TYPE_CHAR then begin
{f.Mode=fmInput}
f.CodePage := GetConsoleCP
end
else f.CodePage := DefaultSystemCodePage;
end;
f.MBCSLength := 0;
f.MBCSBufPos := 0;
{$endif}
end;
fmInOut,
fmOutput: begin
OutputHandle := CreateFile('CONOUT$', GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, 0, 0);
{$ifdef D6PLUS}
{Delphi 6 and above default to LF-only line breaks}
f.Mode := fmClosed;
SetLineBreakStyle(text(f), tlbsCRLF);
{$endif}
f.Handle := OutputHandle;
f.Mode := fmOutput;
if f.BufPtr=nil then begin
f.BufPtr := @f.Buffer;
f.BufSize := sizeof(f.Buffer)
end;
InitVideo;
if (GetConsoleScreenBufferInfo(f.Handle, Info)) then begin
SetConsoleMode(f.Handle, 0);
f.InOutFunc := @CrtOutput;
f.FlushFunc := @CrtOutput;
f.CloseFunc := @CrtClose;
{$ifdef TXTREC_CP}
if f.CodePage = 0 then begin
if GetFileType(f.Handle) = FILE_TYPE_CHAR then begin
{f.Mode=fmOutput}
f.CodePage := GetConsoleOutputCP
end
else f.CodePage := DefaultSystemCodePage;
end;
f.MBCSLength := 0;
f.MBCSBufPos := 0;
{$endif}
end
else begin
Result := GetLastError;
end;
end;
end; {case}
end;
{---------------------------------------------------------------------------}
procedure AssignCrt(var f: text);
{-Associate the console with text file f}
begin
with TTextRec(f) do begin
Mode := fmClosed;
BufSize := sizeof(Buffer);
BufPtr := @Buffer;
OpenFunc := @CrtOpen;
InOutFunc := nil;
FlushFunc := nil;
CloseFunc := nil;
fillchar(Name, sizeof(Name), 0);
end;
end;
{---------------------------------------------------------------------------}
procedure ClrEol;
{-Clears all the chars from the cursor position to the end of the line}
var
C: COORD;
CX, CY: integer;
Len, NumWritten: DWORD;
begin
GetCursorPosXY(CX, CY);
if WMax.X > CX then begin
C.X := CX;
C.Y := CY;
Len := WMax.X - C.X + 1;
FillConsoleOutputCharacter(OutputHandle, ' ', Len, C, NumWritten);
FillConsoleOutputAttribute(OutputHandle, TextAttr, Len, C, NumWritten);
end;
end;
{---------------------------------------------------------------------------}
procedure ClrScr;
{-Clear the current window, screen if no window set}
var
C: COORD;
i: integer;
Len, NumWritten: DWORD;
begin
if (WMin.X=0) and (WMin.Y=0) and (WMax.X=ScreenWidth-1) and (WMax.Y=ScreenHeight-1) then begin
Len := ScreenWidth * ScreenHeight;
C.X := 0;
C.Y := 0;
FillConsoleOutputCharacter(OutputHandle, ' ', Len, C, NumWritten);
FillConsoleOutputAttribute(OutputHandle, TextAttr, Len, C, NumWritten);
end
else begin
Len := WMax.X - WMin.X + 1;
C.X := WMin.X;
for i:=WMin.Y to WMax.Y do begin
C.Y := i;
FillConsoleOutputCharacter(OutputHandle, ' ', Len, C, NumWritten);
FillConsoleOutputAttribute(OutputHandle, TextAttr, Len, C, NumWritten);
end;
end;
GotoXY(1, 1);
NormalizeCursor;
end;
{---------------------------------------------------------------------------}
procedure Delay(MS: word);
{-Delay/Sleep for MS milliseconds}
begin
Sleep(MS);
end;
{---------------------------------------------------------------------------}
procedure DelLine;
{-Return true if a character producing key has been pressed}
begin
Scroll(UP, WMin.X, CursorPosY, WMax.X, WMax.Y, 1);
end;
{---------------------------------------------------------------------------}
procedure GotoXY(X, Y: byte);
{-Move cursor to col X, row Y (window relative)}
var
R, C: integer;
begin
R := integer(Y)-1 + WMin.Y;
C := integer(X)-1 + WMin.X;
if (R<WMin.Y) or (R>WMax.Y) or (C<WMin.X) or (C>WMax.X) then exit;
MoveCursor(C, R);
end;
{---------------------------------------------------------------------------}
procedure HighVideo;
{-Set high intensity forground}
begin
TextAttr := TextAttr or $08;
end;
{---------------------------------------------------------------------------}
procedure InsLine;
{-Insert new line at cursor position}
begin
Scroll(DOWN, WMin.X, CursorPosY, WMax.X, WMax.Y, 1);
end;
{---------------------------------------------------------------------------}
procedure LowVideo;
{-Set low intensity forground}
begin
TextAttr := TextAttr and $77;
end;
{---------------------------------------------------------------------------}
procedure NormVideo;
{-Set initial text attribute}
begin
TextAttr := NormalAttr;
end;
{---------------------------------------------------------------------------}
procedure TextBackground(Color: byte);
{-Set background color part if text attribute}
begin
TextAttr := (TextAttr and $8F) or ((Color shl 4) and $7F);
end;
{---------------------------------------------------------------------------}
procedure TextColor(Color: byte);
{-Set foreground color part if text attribute}
begin
TextAttr := (TextAttr and $70) or (Color and $8F);
end;
{---------------------------------------------------------------------------}
procedure TextMode(Mode: integer);
{-Set new text mode / NormalAttr and clrscr}
begin
SetNewMode(Mode);
TextAttr := NormalAttr;
ClrScr;
end;
{---------------------------------------------------------------------------}
function WhereX: byte;
{-Return current column of cursor (window relative)}
var
diff: integer;
begin
diff := CursorPosX - WMin.X + 1;
if diff<0 then diff := 0;
if diff>255 then diff := 255;
Result := byte(diff);
end;
{---------------------------------------------------------------------------}
function WhereY: byte;
{-Return current row of cursor (window relative)}
var
diff: integer;
begin
diff := CursorPosY - WMin.Y + 1;
if diff<0 then diff := 0;
if diff>255 then diff := 255;
Result := byte(diff);
end;
{---------------------------------------------------------------------------}
procedure Window(X1, Y1, X2, Y2: byte);
{-Define screen area as net text window}
begin
if (X1<1) or (X2>ScreenWidth) or (Y1<1) or (Y2>ScreenHeight) or (X2<=X1) or (Y2<=Y1) then exit;
WMin.X := X1-1;
WMax.X := X2-1;
WMin.Y := Y1-1;
WMax.Y := Y2-1;
MoveCursor(WMin.X, WMin.Y);
end;
{---------------------------------------------------------------------------}
procedure InitCRT;
{-initialize Input/Output for CRT, see Delphi 2 notes in initialization}
var
OSVersionInfo: TOSVersionInfo;
begin
OSVersionInfo.dwOSVersionInfoSize := sizeof(OSVersionInfo);
{Get OS Version used for hardware sound if not NT+}
if GetVersionEx(OSVersionInfo) then IsWinNT := OSVersionInfo.dwPlatformId = VER_PLATFORM_WIN32_NT;
{Paranoia: detect version / alignment conflicts}
if sizeof(TTextRec)=sizeof(text) then begin
AssignCrt(Input);
reset(Input);
AssignCrt(Output);
rewrite(Output);
end
else CheckBreak := false;
end;
{---------------------------------------------------------------------------}
{----------------------------- Sound ---------------------------------------}
{---------------------------------------------------------------------------}
{---------------------------------------------------------------------------}
procedure Sound(Hz: word);
{-Sound on, hardware for Win9x / MesseageBeep(0) for NT+}
begin
{$ifdef WIN32}
if IsWinNT then begin
{Because Beep(. , .) acts synchronous and waits there is no}
{simple compatible Sound procedure, use lame MessageBeep(0)}
MessageBeep(0);
end
else asm
mov cx,[Hz]
cmp cx,37
jb @2
mov ax,$34dd
mov dx,$0012
div cx
mov cx,ax
in al,$61
test al,$03
jnz @1
or al,03
out $61,al
mov al,$b6
out $43,al
@1: mov al,cl
out $42,al
mov al,ch
out $42,al
@2:
end;
{$else}
{$ifdef WIN64}
MessageBeep(0);
{$endif}
{$endif}
end;
{---------------------------------------------------------------------------}
procedure NoSound;
{-Sound off, hardware for Win9x, dummy for NT+}
begin
{$ifdef WIN32}
if IsWinNT then {nothing because Sound uses MessageBeep(0)}
else asm
in al,$61
and al,$fc
out $61,al
end;
{$endif}
end;
{---------------------------------------------------------------------------}
{----------------------- Readkey / Keypressed ----------------------------}
{---------------------------------------------------------------------------}
var
ScanCode : byte; {Current code for keypressed}
ExtSCode : boolean; {Current key press produced extended code}
InAltNum : boolean; {In Alt+Numpad entry mode}
AltNumVal: byte; {Accumulated Alt+Numpad code}
{---------------------------------------------------------------------------}
function KeyPressed : boolean;
{-Return true if a character producing key is pressed}
var
NumEvents,NumRead : dword;
InputRec : INPUT_RECORD;
IsAlt, IsCtrl, IsShift: boolean;
nc: integer;
const
No_Keys = [VK_SHIFT, VK_MENU {=Alt}, VK_CONTROL, VK_CAPITAL{=Caps}, VK_NUMLOCK, VK_SCROLL];
NumNum : array[$47..$53] of byte = (7,8,9,$FF,4,5,6,$FF,1,2,3,0,$FF);
CtrlNum: array[$47..$53] of byte = ($77, $8D, $84, $8E, $73, $8F, $74, $4E, $75, $91, $76, $92, $93);
begin
if ScanCode<>0 then begin
Result := true;
exit;
end;
Result := false;
repeat
GetNumberOfConsoleInputEvents(InputHandle,NumEvents);
if NumEvents=0 then break;
ReadConsoleInputA(InputHandle,InputRec,1,NumRead);
if (NumRead>0) and (InputRec.EventType=KEY_EVENT) then with InputRec.Event.KeyEvent do begin
if bKeyDown then begin
IsAlt := dwControlKeyState and (RIGHT_ALT_PRESSED or LEFT_ALT_PRESSED) <> 0;
IsCtrl := dwControlKeyState and (RIGHT_CTRL_PRESSED or LEFT_CTRL_PRESSED) <> 0;
IsShift := dwControlKeyState and SHIFT_PRESSED <> 0;
{Consider potential character producing keys}
if not (wVirtualKeyCode in No_Keys) then begin
Result:=true;
//writeln(wVirtualScanCode:5, wVirtualKeyCode:5, ord(AsciiChar):5);
if (AsciiChar=#0) or (dwControlKeyState and (LEFT_ALT_PRESSED or ENHANCED_KEY) <> 0) then begin
{Real extended keys or Alt/Cursor block}
ExtSCode := true;
if (wVirtualScanCode=$37) and (dwControlKeyState and ENHANCED_KEY <> 0) then begin
{Ctrl-PrtScr}
if wVirtualScanCode=$37 then ScanCode := 114;
end
else begin
if wVirtualScanCode in [1,2,4,5,6,8,9,10,11,13] then begin
{Only Ctrl+2 (VSC=3) and Ctrl+6 (VSC=7) generate key codes}
Result := false;
ExtSCode := false;
ScanCode := 0;
end
else begin
{-Convert VirtualScanCode to CRT Scancode}
Scancode := wVirtualScanCode;
if IsAlt then begin
case ScanCode of
$02..$0D: inc(ScanCode, $76); {Digits .. BS}
$1C: Scancode := $A6; {Enter}
$35: Scancode := $A4; {/}
$3B..$44: inc(Scancode, $2D); {F1 - F10}
$47..$49,
$4B, $4D,
$4F..$53: inc(Scancode, $50); {Extended cursor block keys}
$57..$58: inc(Scancode, $34); {F11, F12}
end
end
else if IsCtrl then begin
case Scancode of
$07: ScanCode := $1E;
$0C: ScanCode := $1F;
$0F: Scancode := $94; {Tab}
$35: Scancode := $95; {Keypad \}
$37: Scancode := $96; {Keypad *}
$3B..$44: inc(Scancode, $23); {F1 - F10}
$47..$53: Scancode := CtrlNum[Scancode]; {Keypad num keys}
$57..$58: inc(Scancode, $32); {F1 - F10}
end
end
else if IsShift then begin
case Scancode of
$3B..$44: inc(Scancode, $19); {F1 - F10}
$57..$58: inc(Scancode, $30); {F1 - F10}
end
end
else begin
case Scancode of
$57..$58: inc(Scancode, $2E); {F1 - F10}
{$ifdef CRTFix_01}
$29: begin
{Some Windows/keyboards declare ^ as Extended}
ExtSCode := false;
AsciiChar:= '^';
ScanCode := byte(AsciiChar);
end;
{$endif}
end;
end;
if (AsciiChar='/') and (not IsAlt) then begin
{Windows declares Numpad-/ as Extended}
ScanCode := 47;
ExtSCode := false;
end;
end;
end;
end
else begin
{redeclare some of the keys as extended}
if (AsciiChar=#9) and IsShift then begin
{shift-tab }
ExtSCode := true;
ScanCode := 15;
end
else if (AsciiChar=#240) and (dwControlKeyState=0) then begin
{Numpad 5}
ExtSCode := true;
ScanCode := 76;
end
else begin
ExtSCode := false;
ScanCode := byte(AsciiChar);
end;
end;
if IsAlt and (dwControlKeyState and ENHANCED_KEY = 0) then begin
{Alt pressed and no ENHANCED_KEY, gather AltNum code}
if wVirtualScanCode in [$47..$52] then begin
nc := NumNum[wVirtualScanCode];
if nc>9 then break
else begin
InAltNum := true;
AltNumVal := (10*AltNumVal + nc) and $FF;
Result := false;
ExtSCode := false;
ScanCode := 0;
end;
end
else exit;
end
else exit;
end;
end
else begin
{Process Key UP: finish AltNum entry if ALT=VK_Menu is released}
if (wVirtualKeyCode=VK_MENU) and InAltNum and (AltNumVal>0) then begin
ScanCode := AltNumVal;
Result := true;
InAltNum := false;
AltNumVal := 0;
exit;
end;
end;
end;
if Result then exit;
until false;
end;
{---------------------------------------------------------------------------}
function ReadKey: AnsiChar;
{-Read a character from the keyboard, sleep until keypressed}
begin
while not KeyPressed do sleep(1);
if ExtSCode then begin
{Extended code: first return #0 and (with a second call) the char code}
Result := #0;
ExtSCode := false;
end
else begin
Result := AnsiChar(ScanCode);
ScanCode := 0;
end;
end;
begin
{ This initialization code does not work as expected in Delphi 2. In D2,
IsConsole appears to be always false even if $APPTYPE is set to CONSOLE in
the main project file. }
{*we: IsConsole is true after begin in main program, so InitCrt}
{ should be called again in the main program}
{$ifdef VER90}
InitCRT;
{$endif}
if IsConsole then InitCRT;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus, ExtCtrls, ComCtrls, ToolWin, StdCtrls, Buttons;
type
TForm1 = class(TForm)
MainMenu1: TMainMenu;
Game1: TMenuItem;
New1: TMenuItem;
Giveup1: TMenuItem;
Done1: TMenuItem;
N1: TMenuItem;
Exit1: TMenuItem;
Setings1: TMenuItem;
Size1: TMenuItem;
Balls1: TMenuItem;
N8x81: TMenuItem;
N10x101: TMenuItem;
N12x121: TMenuItem;
N41: TMenuItem;
N61: TMenuItem;
N81: TMenuItem;
Board: TImage;
N2: TMenuItem;
Tutorial1: TMenuItem;
BitBtn1: TBitBtn;
Label1: TLabel;
Label2: TLabel;
BitBtn2: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure OptLabels;
procedure LoadImages;
procedure NewGame(FieldSize,PBalls:integer;Tutorial:boolean);
procedure Exit1Click(Sender: TObject);
function Skonci:boolean;
function GetPosit(px,py:integer):integer;
function IsBall(bx,by:integer):boolean;
procedure Skontroluj;
procedure ShowBalls;
procedure Svetlo(lx,ly,sx,sy:integer);
procedure New1Click(Sender: TObject);
procedure Tutorial1Click(Sender: TObject);
procedure N8x81Click(Sender: TObject);
procedure N10x101Click(Sender: TObject);
procedure N12x121Click(Sender: TObject);
procedure N41Click(Sender: TObject);
procedure N61Click(Sender: TObject);
procedure N81Click(Sender: TObject);
procedure BoardMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure BoardMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure BitBtn1Click(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
procedure Done1Click(Sender: TObject);
procedure Giveup1Click(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
Imag:array[1..11] of TBitmap;
mx,my:integer;
Posit:integer;
protected
field: array[0..13,0..13] of integer;
ball: array[1..8] of record
x,y:integer;
end;
PlacedBalls,Score: integer;
Counter:integer;
public
tut: boolean;
size: integer;
balls: integer;
endgame: boolean;
end;
const
names:array[1..11] of string=
('blank.bmp' ,'empty.bmp' ,
'ball_tmp.bmp','ball_err.bmp','ball_tut.bmp',
'light_up.bmp','light_dn.bmp',
'face_def.bmp','face_clk.bmp','face_suc.bmp','face_err.bmp');
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.LoadImages;
var i:integer;
begin
for i:=1 to 11 do
begin
Imag[i]:=TBitmap.Create;
Imag[i].LoadFromFile(names[i]);
end;
end;
procedure TForm1.OptLabels;
begin
Label1.Width:=49;
Label1.Height:=33;
Label2.Width:=49;
Label2.Height:=33;
end;
procedure TForm1.NewGame(FieldSize,PBalls:integer;Tutorial:boolean);
var a,b:integer;
j:array[1..8] of word;
procedure GameSize(NSize:integer);
var farba : TColor;
begin
Width:=321+(NSize-8)*24;
Height:=369+(NSize-8)*24;
BitBtn1.Left:=136+(NSize-8)*12;
Label2.Left:=200+(NSize-8)*24;
with Board do
begin
Width:=NSize*24+48;
Height:=NSize*24+48;
Canvas.Brush.Color := clWhite;
Canvas.FillRect( Board.ClientRect );
end;
end;
function ine(Coun:integer):boolean;
var Vpor:boolean;
i:integer;
begin
Vpor:=true;
for i:=1 to Coun-1 do
if j[i]=j[Coun] then
Vpor:=false;
ine:=Vpor;
end;
procedure NewBalls(NBalls:integer);
var i:integer;
begin
j[1]:=random(FieldSize*FieldSize);
for i:=2 to NBalls do
repeat
j[i]:=random(FieldSize*FieldSize);
until ine(i);
for i:=1 to NBalls do
begin
ball[i].x:=j[i] mod FieldSize+1;
ball[i].y:=j[i] div FieldSize+1;
end;
end;
begin
if FieldSize<>size then GameSize(FieldSize);
NewBalls(PBalls);
for a:=1 to FieldSize do
for b:=1 to FieldSize do
Board.Canvas.Draw(a*24,b*24,Imag[2]);
for a:=1 to FieldSize do
begin
Board.Canvas.Draw(a*24,0,Imag[6]);
Board.Canvas.Draw(a*24,FieldSize*24+24,Imag[6]);
end;
for a:=1 to FieldSize do
begin
Board.Canvas.Draw(0 ,a*24,Imag[6]);
Board.Canvas.Draw(FieldSize*24+24,a*24,Imag[6]);
end;
Board.Canvas.Draw(0 ,0 ,Imag[1]);
Board.Canvas.Draw(FieldSize*24+24,0 ,Imag[1]);
Board.Canvas.Draw(0 ,FieldSize*24+24,Imag[1]);
Board.Canvas.Draw(FieldSize*24+24,FieldSize*24+24,Imag[1]);
if Tutorial then
for a:=1 to PBalls do
Board.Canvas.Draw(Ball[a].x*24,Ball[a].y*24,Imag[5]);
for a:=0 to FieldSize+1 do
for b:=0 to FieldSize+1 do
field[a,b]:=0;
PlacedBalls:=0;
Score:=0;
size:=FieldSize;
Balls:=PBalls;
Counter:=1;
tut:=Tutorial;
endgame:=false;
BitBtn2.Enabled:=true;
Done1.Enabled:=true;
Giveup1.Enabled:=true;
Label1.Caption:='0';
Label2.Caption:='0/'+inttostr(Balls);
OptLabels;
end;
procedure TForm1.Skontroluj;
var i:integer;
spravne:boolean;
begin
spravne:=true;
for i:=1 to balls do
if Field[ball[i].x,ball[i].y]=0 then
spravne:=false;
if spravne then
messagedlg('Puzzle solved! Your final score is: '+inttostr(score),
mtInformation,[MbOK],0)
else
messagedlg('The balls were not placed correctly.',
mtInformation,[MbOK],0);
endgame:=true;
BitBtn2.Enabled:=false;
Done1.Enabled:=false;
Giveup1.Enabled:=false;
ShowBalls;
end;
procedure TForm1.ShowBalls;
var a,b:integer;
begin
for a:=1 to Balls do
if Field[ball[a].x,ball[a].y]=0 then
Board.Canvas.Draw(ball[a].x*24,ball[a].y*24,Imag[5])
else Field[ball[a].x,ball[a].y]:=2;
for a:=1 to Size do
for b:=1 to Size do
if Field[a,b]=1 then
Board.Canvas.Draw(a*24,b*24,Imag[4]);
end;
procedure TForm1.Svetlo(lx,ly,sx,sy:integer);
var h,pol:integer;
koniec:boolean;
procedure napis;
var s:string;
begin
case h of
-1:s:='R';
0:s:='H';
1:begin
s:=inttostr(Counter);
inc(Counter);
Board.Canvas.TextOut(lx*24+2,ly*24+2,s);
Field[lx,ly]:=1;
end;
end;
Board.Canvas.TextOut(mx*24+2,my*24+2,s);
Field[mx,my]:=1;
end;
begin
h:=10;
if isball(lx+sx,ly+sy) then
h:=0
else
case abs(sx) of
0:if (isball(lx+1,ly+sy)) or (isball(lx-1,ly+sy)) then
h:=-1;
1:if (isball(lx+sx,ly+1)) or (isball(lx+sx,ly-1)) then
h:=-1;
end;
koniec:=false; pol:=2;
if h>0 then
begin
h:=1;
while not koniec do
case abs(sx) of
0:begin
if (ly+sy*pol=0) or (ly+sy*pol=size+1) then
begin
ly:=ly+sy*pol;
if (lx=mx) and (ly=my) then
h:=-1;
koniec:=true;
end
else
if isball(lx,ly+sy*pol) then
begin
h:=0;
koniec:=true;
end
else
if isball(lx-1,ly+sy*pol) then
begin
ly:=ly+sy*(pol-1);
sx:=1;
sy:=0;
pol:=0;
end
else
if isball(lx+1,ly+sy*pol) then
begin
ly:=ly+sy*(pol-1);
sx:=-1;
sy:=0;
pol:=0;
end;
inc(pol);
end;
1:begin
if (lx+sx*pol=0) or (lx+sx*pol=size+1) then
begin
lx:=lx+sx*pol;
if (lx=mx) and (ly=my) then
h:=-1;
koniec:=true;
end
else
if isball(lx+sx*pol,ly) then
begin
h:=0;
koniec:=true;
end
else
if isball(lx+sx*pol,ly-1) then
begin
lx:=lx+sx*(pol-1);
sx:=0;
sy:=1;
pol:=0;
end
else
if isball(lx+sx*pol,ly+1) then
begin
lx:=lx+sx*(pol-1);
sx:=0;
sy:=-1;
pol:=0;
end;
inc(pol);
end;
end;
end;
Napis;
inc(Score);
Label1.Caption:=inttostr(Score);
OptLabels;
end;
function TForm1.Skonci:boolean;
var i:integer;
w:word;
ds:boolean;
begin
w:=messagedlg('Quit?',mtConfirmation,[mbYes,mbNo],0);
if w=mrYes then
begin
for i:=1 to 11 do
Imag[i].Destroy;
ds:=true;
end
else
ds:=false;
Skonci:=ds;
end;
procedure TForm1.FormCreate(Sender: TObject);
var i,j:integer;
begin
size:=0;
for i:=0 to 13 do
for j:=0 to 13 do
field[i,j]:=0;
LoadImages;
Board.Canvas.Font.Color:=clBtnText;
NewGame(8,4,false);
end;
procedure TForm1.Exit1Click(Sender: TObject);
begin
close;
end;
procedure TForm1.New1Click(Sender: TObject);
begin
NewGame(Size,Balls,Tut);
end;
procedure TForm1.Tutorial1Click(Sender: TObject);
begin
if tut then
Tutorial1.Checked:=false
else
Tutorial1.Checked:=true;
NewGame(Size,Balls,not tut);
end;
procedure TForm1.N8x81Click(Sender: TObject);
begin
if Size<>8 then
begin
N8x81.Checked:=true;
N10x101.Checked:=false;
N12x121.Checked:=false;
NewGame(8,Balls,tut);
end;
end;
procedure TForm1.N10x101Click(Sender: TObject);
begin
if Size<>10 then
begin
N8x81.Checked:=false;
N10x101.Checked:=true;
N12x121.Checked:=false;
NewGame(10,Balls,tut);
end;
end;
procedure TForm1.N12x121Click(Sender: TObject);
begin
if Size<>12 then
begin
N8x81.Checked:=false;
N10x101.Checked:=false;
N12x121.Checked:=true;
NewGame(12,Balls,tut);
end;
end;
procedure TForm1.N41Click(Sender: TObject);
begin
if Balls<>4 then
begin
N41.Checked:=true;
N61.Checked:=false;
N81.Checked:=false;
NewGame(Size,4,tut);
end;
end;
procedure TForm1.N61Click(Sender: TObject);
begin
if Balls<>6 then
begin
N41.Checked:=false;
N61.Checked:=true;
N81.Checked:=false;
NewGame(Size,6,tut);
end;
end;
procedure TForm1.N81Click(Sender: TObject);
begin
if Balls<>8 then
begin
N41.Checked:=false;
N61.Checked:=false;
N81.Checked:=true;
NewGame(Size,8,tut);
end;
end;
function TForm1.GetPosit(px,py:integer):integer;
var pom:integer;
begin
pom:=maxint;
if (px>0) and (px<Size+1) and (py<1) then
pom:=1;
if (px>0) and (px<Size+1) and (py>Size) then
pom:=3;
if (py>0) and (py<Size+1) and (px<1) then
pom:=4;
if (py>0) and (py<Size+1) and (px>Size) then
pom:=2;
if (px>0) and (px<Size+1) and (py>0) and (py<Size+1) then
pom:=5;
getposit:=pom;
end;
function TForm1.IsBall(bx,by:integer):boolean;
var i:integer;
pb:boolean;
begin
pb:=false;
for i:=1 to balls do
if (ball[i].x=bx) and (ball[i].y=by) then
pb:=true;
IsBall:=pb;
end;
procedure TForm1.BoardMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if not endgame then
begin
mx:=(x+1) div 24;
my:=(y+1) div 24;
posit:=getposit(mx,my);
if posit<5 then
if Field[mx,my]=0 then
Board.Canvas.Draw(mx*24,my*24,Imag[7]);
if posit=5 then
if field[mx,my]=0 then
Board.Canvas.Draw(mx*24,my*24,Imag[3])
else
if (tut) and (isball(mx,my)) then
Board.Canvas.Draw(mx*24,my*24,Imag[5])
else
Board.Canvas.Draw(mx*24,my*24,Imag[2]);
end;
end;
procedure TForm1.BoardMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if not endgame then
begin
if posit<5 then
if Field[mx,my]=0 then
begin
Board.Canvas.Draw(mx*24,my*24,Imag[6]);
if ((x+1) div 24=mx) and ((y+1) div 24=my) then
svetlo(mx,my,abs(posit-2)-1,abs(posit-3)-1);
end;
if posit=5 then
if Field[mx,my]=0 then
begin
Field[mx,my]:=1;
inc(PlacedBalls);
end
else
begin
Field[mx,my]:=0;
dec(PlacedBalls);
end;
Label2.Caption:=inttostr(PlacedBalls)+'/'+inttostr(Balls);
OptLabels;
end;
end;
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
NewGame(Size,Balls,tut);
end;
procedure TForm1.BitBtn2Click(Sender: TObject);
begin
if PlacedBalls=Balls then Skontroluj
else
messagedlg(inttostr(balls)+' balls are reqiured to place.',
mtInformation,[mbOk],0);
end;
procedure TForm1.Done1Click(Sender: TObject);
begin
if PlacedBalls=Balls then Skontroluj
else
messagedlg(inttostr(balls)+' balls are reqiured to place.',
mtInformation,[mbOk],0);
end;
procedure TForm1.Giveup1Click(Sender: TObject);
var w:word;
begin
w:=messagedlg('Realy want to end this game?',mtConfirmation,
[mbYes,mbNo],0);
if w=mrYes then
begin
endgame:=true;
BitBtn2.Enabled:=false;
Done1.Enabled:=false;
Giveup1.Enabled:=false;
ShowBalls;
end;
end;
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if Skonci then
CanClose:=true
else
CanClose:=false;
end;
end.
|
unit ncnxServerPlugin;
interface
{$I NEX.INC}
uses
Classes,
Windows,
ExtCtrls,
nxptBasePooledTransport,
nxllTypes,
nxllList,
nxllComponent,
nxllTransport,
nxllPluginBase,
nxllSync,
ncNetMsg,
ncClassesBase;
type
TncnxServerPlugin = class(TnxBasePluginEngine)
private
FNexServ : TncServidorBase;
FTransp : TnxBaseTransport;
procedure SetNexServ(const Value: TncServidorBase);
protected
class function bpeIsRemote: Boolean; override;
procedure OnEnviaEvento(aMsg: Integer; aDados: Pointer);
public
constructor Create( aOwner: TComponent ); override;
procedure BroadcastKeepAlive;
function spRemoveSession( aSessionId: TnxSessionId ): TnxResult;
function scShowUpTime: Boolean; override;
property Transp: TnxBaseTransport read FTransp write FTransp;
published
property NexServ: TncServidorBase
read FNexServ write SetNexServ;
end;
{
This is the plugin command handler that translates messages from the
remote interface into method calls of the actual plugin engine.
}
TncnxCmdHandler = class(TnxBasePluginCommandHandler)
private
function ServUnlock: TList;
procedure ServLock(aSessionID: TnxSessionID);
procedure SendReply(aEventos : TList;
aMsgID : TnxMsgID;
aErrorCode : TnxResult;
aReplyData : Pointer;
aReplyDataLen : TnxWord32);
protected
function GetPluginEngine: TncnxServerPlugin;
procedure SetPluginEngine( aEngine: TncnxServerPlugin );
procedure bpchRemoveSession( aTransport: TnxBaseTransport;
aSessionId: TnxSessionID); override;
procedure bpchSessionFailed(aTransport : TnxBaseTransport;
aSessionID : TnxSessionID); override;
function Serv: TncServidorBase;
procedure nmLogin (var aMsg: TnxDataMessage);
procedure nmLogout (var aMsg: TnxDataMessage);
procedure nmNovoObj (var aMsg: TnxDataMessage);
procedure nmAlteraObj (var aMsg: TnxDataMessage);
procedure nmApagaObj (var aMsg: TnxDataMessage);
procedure nmObtemLista (var aMsg: TnxDataMessage);
procedure nmDownloadArq (var aMsg: TnxDataMessage);
{
procedure nmDownloadArqInterno (var aMsg: TnxDataMessage);
}
procedure nmUploadArq (var aMsg: TnxDataMessage);
procedure nmObtemStreamConfig (var aMsg: TnxDataMessage);
procedure nmObtemPastaServ (var aMsg: TnxDataMessage);
procedure nmSalvaCredito (var aMsg: TnxDataMessage);
procedure nmCancelaTran (var aMsg: TnxDataMessage);
procedure nmSalvaMovEst (var aMsg: TnxDataMessage);
procedure nmSalvaDebito (var aMsg: TnxDataMessage);
procedure nmAbreCaixa (var aMsg: TnxDataMessage);
procedure nmFechaCaixa (var aMsg: TnxDataMessage);
procedure nmSalvaLancExtra (var aMsg: TnxDataMessage);
procedure nmCorrigeDataCaixa (var aMsg: TnxDataMessage);
procedure nmSalvaLic (var aMsg: TnxDataMessage);
procedure nmAjustaPontosFid (var aMsg: TnxDataMessage);
procedure nmKeepAlive (var aMsg: TnxDataMessage);
procedure nmGetLoginData (var aMsg: TnxDataMessage);
procedure nmZerarEstoque (var aMsg: TnxDataMessage);
procedure nmSalvaApp (var aMsg: TnxDataMessage);
procedure nmGetCertificados (var aMsg: TnxDataMessage);
procedure nmReemitirNFCe (var aMsg: TnxDataMessage);
procedure nmInstalaNFCeDepend (var aMsg: TnxDataMessage);
procedure nmInstalaNFeDepend (var aMsg: TnxDataMessage);
procedure nmTableUpdated (var aMsg: TnxDataMessage);
procedure nmGeraXMLProt (var aMsg: TnxDataMessage);
procedure nmConsultarSAT (var aMsg: TnxDataMessage);
procedure nmInutilizarNFCE (var aMsg: TnxDataMessage);
procedure _bpchProcess( aMsg: PnxDataMessage;
var aHandled: Boolean);
public
procedure bpchProcess( aMsg: PnxDataMessage;
var aHandled: Boolean); override;
published
property PluginEngine: TncnxServerPlugin
read GetPluginEngine
write SetPluginEngine;
end;
procedure Register;
implementation
uses SysUtils,
ncServAtualizaLic_Indy,
nxllMemoryManager,
nxstMessages,
nxllBDE,
nxllStreams, ncDebug, ncSalvaCredito, ncDebito,
ncLancExtra, ncMovEst, ncMsgCom, ncErros, ncServBD,
ncsCallbackEvents, ncVersionInfo, uLicEXECryptor, ncCert;
function BoolStr(B: Boolean): String;
begin
if B then
Result := 'True' else
Result := 'False';
end;
procedure Register;
begin
RegisterComponents('NexCafe',
[ TncnxServerPlugin,
TncnxCmdHandler ]);
end;
{ TncnxServerPlugin }
procedure TncnxServerPlugin.BroadcastKeepAlive;
var
I : Integer;
Dummy : Array[1..128] of Byte;
begin
Fillchar(Dummy, SizeOf(Dummy), $FF);
try
if not ServidorAtivo then Exit;
dmServidorBD.nxTCPIP.Broadcast(ncnmKeepAlive, 0, @Dummy, SizeOf(Dummy), 100);
// dmServidorBD.nxSMT.Broadcast(ncnmKeepAlive, 0, @Dummy, SizeOf(Dummy), 100);
except
end;
end;
constructor TncnxServerPlugin.Create(aOwner: TComponent);
begin
inherited;
FNexServ := nil;
end;
procedure TncnxServerPlugin.OnEnviaEvento(aMsg: Integer; aDados: Pointer);
var
SS : TArraySessionSocket;
begin
// DebugMsg('TncnxServerPlugin.OnEnviaEvento - 1');
if not ServidorAtivo then Exit;
// DebugMsg('TncnxServerPlugin.OnEnviaEvento - 2');
FNexServ.ObtemSessionSocketArray(SS);
try
// DebugMsg('TncnxServerPlugin.OnEnviaEvento - 3');
gCallbackMgr.AddEvent(TncCallbackEvent.CreateMsgCom(aMsg, aDados, SS));
// DebugMsg('TncnxServerPlugin.OnEnviaEvento - 4');
finally
FreeDados(aMsg, aDados);
end;
// DebugMsg('TncnxServerPlugin.OnEnviaEvento - 5');
end;
function TncnxServerPlugin.spRemoveSession(aSessionId: TnxSessionId): TnxResult;
var FCEList : TList;
begin
Result := DBIERR_NONE;
PostMessage(CliNotifyHandle, wm_removesession, aSessionID, 0);
gCallbackMgr.RemoveSession(aSessionID);
end;
class function TncnxServerPlugin.bpeIsRemote: Boolean;
begin
Result := False;
end;
function TncnxServerPlugin.scShowUpTime: Boolean;
begin
Result := True;
end;
procedure TncnxServerPlugin.SetNexServ(const Value: TncServidorBase);
begin
if FNexServ=Value then Exit;
if FNexServ<>nil then FNexServ.OnEnviaEvento := nil;
FNexServ := Value;
if FNexServ<>nil then FNexServ.OnEnviaEvento := OnEnviaEvento;
end;
{ TncnxCmdHandler }
function TncnxCmdHandler.GetPluginEngine: TncnxServerPlugin;
begin
Result := TncnxServerPlugin(bpchPluginEngine);
end;
procedure TncnxCmdHandler.SendReply(aEventos: TList; aMsgID: TnxMsgID;
aErrorCode: TnxResult; aReplyData: Pointer; aReplyDataLen: TnxWord32);
begin
TnxBaseTransport.Reply(aMsgID, aErrorCode, aReplyData, aReplyDataLen);
end;
function TncnxCmdHandler.Serv: TncServidorBase;
begin
Result := PluginEngine.NexServ;
end;
procedure TncnxCmdHandler.ServLock(aSessionID: TnxSessionID);
begin
// DebugMsg('TncnxCmdHandle.ServLock 1');
if not ServidorAtivo then begin
// DebugMsg('TncnxCmdHandle.ServLock 2');
Raise Exception.Create('Servidor Inativo');
end;
// DebugMsg('TncnxCmdHandle.ServLock 3');
Serv.Lock;
// DebugMsg('TncnxCmdHandle.ServLock 4');
if not ServidorAtivo then begin
// DebugMsg('TncnxCmdHandle.ServLock 5');
Serv.Unlock;
Raise Exception.Create('Servidor Inativo');
end;
try
// DebugMsg('TncnxCmdHandle.ServLock 6');
Serv.ObtemUsernameHandlePorSessionID(aSessionID, UsernameAtual, HandleCliAtual);
// DebugMsg('TncnxCmdHandle.ServLock 7');
if SameText(UsernameAtual, 'proxy') then
UsernameAtual := '';
except
UsernameAtual := '';
HandleCliAtual := -1;
end;
end;
function TncnxCmdHandler.ServUnlock: TList;
begin
try
Result := nil;
finally
PluginEngine.FNexServ.Unlock;
end;
end;
procedure TncnxCmdHandler.SetPluginEngine( aEngine: TncnxServerPlugin );
begin
bpchSetPluginEngine(aEngine);
end;
procedure TncnxCmdHandler.nmAbreCaixa(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
R : TnmAbreCaixaRpy;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmAbreCaixaReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmAbreCaixa - nmFunc: ' + nmFunc);
Erro := Serv.AbreCaixa(nmFunc, nmSaldo, R.nmID);
DebugMsg('TncnxCmdHandler.nmAbreCaixa - Res: ' + IntToStr(Erro) + ' - nmID: ' + IntToStr(R.nmID));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmAbreCaixa - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, @R, SizeOf(R));
end;
procedure TncnxCmdHandler.nmCancelaTran(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmCancelaTranReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmCancelaTran - nmTran: ' + IntToStr(nmTran) + ' - nmFunc: ' + nmFunc);
Erro := Serv.CancelaTran(nmTran, nmFunc);
DebugMsg('TncnxCmdHandler.nmCancelaTran - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmCancelaTran - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmConsultarSAT(var aMsg: TnxDataMessage);
var
S: TnxMemoryStream;
sl : TStrings;
erro : integer;
begin
S := nil;
try
sl := TStringList.Create;
try
erro := Serv.ConsultarSAT(sl);
if erro=0 then begin
S := TnxMemoryStream.Create;
sl.SaveToStream(S);
end;
S.Position := 0;
except
on E: Exception do begin
DebugMsgEsp('TncnxCmdHandler.nmConsultarSAT - Exception: '+E.Message, False, True);
erro := 2;
end;
end;
if Erro=0 then
SendReply(nil, ncnmConsultarSAT, 0, S.Memory, S.Size) else
SendReply(nil, ncnmConsultarSAT, Erro, nil, 0);
finally
if Assigned(S) then S.free;
end;
end;
procedure TncnxCmdHandler.nmCorrigeDataCaixa(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmCorrigeDataCaixaReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmCorrigeDataCaixa - nmFunc: ' + nmFunc +
' - nmCaixa: ' + IntToStr(nmCaixa) +
' - nmNovaAbertura: ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', nmNovaAbertura) +
' - nmNovoFechamento: ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', nmNovoFechamento));
Erro := Serv.CorrigeDataCaixa(nmFunc, nmCaixa, nmNovaAbertura, nmNovoFechamento);
DebugMsg('TncnxCmdHandler.nmCorrigeDataCaixa - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmCorrigeDataCaixa - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmDownloadArq(var aMsg: TnxDataMessage);
var
S: TnxMemoryStream;
Str: String;
Erro : TnxResult;
CEList : TList;
begin
S := TnxMemoryStream.Create;
try
ServLock(aMsg.dmSessionID);
try
with aMsg, TnmNomeArq(aMsg.dmData^) do
try
DebugMsg('TncnxCmdHandler.nmDownloadArq - NomeArq: ' + nmNomeArq);
Str := ExtractFilePath(ParamStr(0)) + nmNomeArq;
if FileExists(Str) then begin
Erro := 0;
S.LoadFromFile(Str);
end else
Erro := ncerrArqNaoEncontrado;
DebugMsg('TncnxCmdHandler.nmDownloadArq - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmDownloadArq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, S.Memory, S.Size);
finally
S.Free;
end;
end;
{
procedure TncnxCmdHandler.nmDownloadArqInterno(var aMsg: TnxDataMessage);
var
S: TnxMemoryStream;
Erro : TnxResult;
DM : TdmArqInt;
begin
S := TnxMemoryStream.Create;
try
with aMsg, TnmDownArqInt(aMsg.dmData^) do
try
DebugMsg('TncnxCmdHandler.nmDownloadArqInterno - nmArq: ' + nmArq + ' - nmVer: ' + IntToStr(nmVer));
DM := TdmArqInt.Create(nil);
try
Erro := DM.getArq(nmArq, nmVer, S)
finally
DM.Free;
end;
DebugMsg('TncnxCmdHandler.nmDownloadArqInterno - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmDownloadArqInterno - Exception: ' + E.Message);
end;
end;
if (Erro<10000) then
SendReply(nil, aMsg.dmMsg, Erro, nil, 0) else
SendReply(nil, aMsg.dmMsg, Erro, S.Memory, S.Size);
finally
S.Free;
end;
end;
}
procedure TncnxCmdHandler.nmFechaCaixa(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmFechaCaixaReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmFechaCaixa - nmFunc: ' + nmFunc +
' - nmID: ' + IntToStr(nmID));
Erro := Serv.FechaCaixa(nmFunc, nmSaldo, nmID);
DebugMsg('TncnxCmdHandler.nmFechaCaixa - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmFechaCaixa - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmGeraXMLProt(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmNFCeReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmGeraXMLProt - nmChave: ' + nmChave);
Erro := Serv.GeraXMLProt(nmChave);
DebugMsg('TncnxCmdHandler.nmGeraXMLProt - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmFechaCaixa - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmGetCertificados(var aMsg: TnxDataMessage);
var
S: TnxMemoryStream;
sl : TStrings;
erro : integer;
begin
S := nil;
try
sl := TStringList.Create;
try
sl.Text := ListaCertificados;
S := TnxMemoryStream.Create;
sl.SaveToStream(S);
S.Position := 0;
erro := 0;
except
on E: Exception do begin
DebugMsgEsp('TncnxCmdHandler.nmGetCertificados - Exception: '+E.Message, False, True);
erro := ncerrExcecaoNaoTratada_GetCertificados;
end;
end;
if Erro=0 then
SendReply(nil, ncnmObtemCertificados, 0, S.Memory, S.Size) else
SendReply(nil, ncnmObtemCertificados, Erro, nil, 0);
finally
if Assigned(S) then S.free;
end;
end;
procedure TncnxCmdHandler.nmGetLoginData(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
I : Integer;
U : TncListaUsuarios;
S : TnxMemoryStream;
SL : TStrings;
begin
S := TnxMemoryStream.Create;
try
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
Erro := 0;
DebugMsg('TncnxCmdHandler.nmGetLoginData');
SL := TStringList.Create;
try
sl.Add(Trim(prefixo_versao+Copy(SelfVersion, 7, 20)));
if gConfig.StatusConta in [scFree, scPremium, scPremiumVenc, scAnt] then
sl.Add(gConfig.Conta) else
sl.Add('');
U := TncListaUsuarios(Serv.ObtemLista(tcUsuario));
for I := 0 to U.Count - 1 do
if not U.Itens[I].Inativo then
SL.Add(U.Itens[I].Username+'='+U.Itens[I].Senha+#255+U.Itens[i].Email);
SL.SaveToStream(S);
finally
SL.Free;
end;
DebugMsg('TncnxCmdHandler.nmGetLoginData - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmGetLoginData - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, S.Memory, S.Size);
finally
S.Free;
end;
end;
procedure TncnxCmdHandler.nmInstalaNFCeDepend(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
DebugMsg('TncnxCmdHandler.nmInstalaNFCeDepend');
Erro := Serv.InstalaNFCeDepend;
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmInstalaNFCeDepend - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmInstalaNFeDepend(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
DebugMsg('TncnxCmdHandler.nmInstalaNFeDepend');
Erro := Serv.InstalaNFeDepend;
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmInstalaNFeDepend - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmInutilizarNFCE(var aMsg: TnxDataMessage);
var
S: TnxMemoryStream;
sl : TStrings;
erro : integer;
begin
S := nil;
sl := nil;
try
sl := TStringList.Create;
with aMsg, TnmInutilizarNFCE_Req(dmData^) do
try
erro := Serv.InutilizarNFCE(nmNFe, nmAno, nmInicio, nmFim, nmJust, sl);
if erro=0 then begin
S := TnxMemoryStream.Create;
sl.SaveToStream(S);
S.Position := 0;
end;
except
on E: Exception do begin
DebugMsgEsp('TncnxCmdHandler.nmInutilizarNFCE - Exception: '+E.Message, False, True);
erro := 2;
end;
end;
if Erro=0 then
SendReply(nil, ncnmInutilizarNFCE, 0, S.Memory, S.Size) else
SendReply(nil, ncnmInutilizarNFCE, Erro, nil, 0);
finally
if Assigned(S) then S.free;
if Assigned(sl) then sl.Free;
end;
end;
procedure TncnxCmdHandler.nmAjustaPontosFid(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmAjustaPontosFid(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmAjustaPontosFid - nmFunc: ' + nmFunc +
' - nmCliente: ' + IntToStr(nmCliente) +
' - nmFator: ' + IntToStr(nmFator) +
' - nmPontos: ' + FloatToStr(nmPontos) +
' - nmObs: ' + nmObs);
Erro := Serv.AjustaPontosFid(nmFunc, nmCliente, nmFator, nmPontos, nmObs);
DebugMsg('TncnxCmdHandler.nmAjustaPontosFid - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmAjustaPontosFid - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmAlteraObj(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
sCmd : String;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
if dmMsg=ncnmAlteraObj then
sCmd := 'TncnxCmdHandler.nmAlteraObj' else
sCmd := 'TncnxCmdHandler.nmNovoObj';
DebugMsg(sCmd);
Erro := Serv.SalvaStreamObj((dmMsg=ncnmNovoObj), TheStream);
DebugMsg(sCmd + ' - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg(sCmd + ' - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmApagaObj(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, PnmObj(dmData)^ do
try
try
DebugMsg('TncnxCmdHandler.nmApagaObj - nmCliente: ' + IntToStr(nmCliente) +
' - nmTipoClasse: ' + IntToStr(nmTipoClasse) +
' - nmChave: ' + nmChave);
Erro := Serv.ApagaObj(nmCliente, nmTipoClasse, nmChave);
DebugMsg('TncnxCmdHandler.nmApagaObj - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmApagaObj - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmReemitirNFCe(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
try
try
DebugMsg('TncnxCmdHandler.nmReemitirNFCe');
Erro := Serv.ReemitirNFCe(TGuid(aMsg.dmData^));
DebugMsg('TncnxCmdHandler.nmReemitirNFCe');
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmReemitirNFCe - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaApp(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
SL: TStrings;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
SL := TStringList.Create;
try
SL.LoadFromStream(TheStream);
DebugMsg('TncnxCmdHandler.nmSalvaApp - ' + sl.Text);
PostAppUpdate(sl);
Erro := 0;
DebugMsg('TncnxCmdHandler.nmSalvaApp - Res: ' + IntToStr(Erro));
finally
SL.Free;
end;
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaApp - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaCredito(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
C : TncSalvaCredito;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
DebugMsg('TncnxCmdHandler.nmSalvaCredito');
C := TncSalvaCredito.Create;
try
C.LeStream(TheStream);
Erro := Serv.SalvaCredito(C);
finally
C.Free;
end;
DebugMsg('TncnxCmdHandler.nmSalvaCredito - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaCredito - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaDebito(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
Deb : TncDebito;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
DebugMsg('TncnxCmdHandler.nmSalvaDebito');
Deb := TncDebito.Create;
try
Deb.LeStream(TheStream);
Erro := Serv.SalvaDebito(Deb);
finally
Deb.Free;
end;
DebugMsg('TncnxCmdHandler.nmSalvaDebito - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaDebito - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaLancExtra(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
Le : TncLancExtra;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
DebugMsg('TncnxCmdHandler.nmSalvaLancExtra');
LE := TncLancExtra.Create;
try
LE.LeStream(TheStream);
Erro := Serv.SalvaLancExtra(LE);
finally
LE.Free;
end;
DebugMsg('TncnxCmdHandler.nmSalvaLancExtra - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaLancExtra - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaLic(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
SL : TStrings;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
SL := TStringList.Create;
try
SL.LoadFromStream(TheStream);
DebugMsg('TncnxCmdHandler.nmSalvaLic - Lic: '+SL.Text);
Erro := Serv.SalvaLic(SL.Text);
finally
SL.Free;
end;
DebugMsg('TncnxCmdHandler.nmSalvaLic - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaLic - Exception: ' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmSalvaMovEst(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
ME : TncMovEst;
begin
ServLock(aMsg.dmSessionID);
try
with aMsg, TnxDataMessageStream.Create(aMsg) do try
try
DebugMsg('TncnxCmdHandler.nmSalvaMovEst - HandleCliAtual: '+IntToStr(HandleCliAtual));
ME := TncMovEst.Create;
try
ME.LeStream(TheStream);
Erro := Serv.SalvaMovEst(ME);
finally
ME.Free;
end;
DebugMsg('TncnxCmdHandler.nmSalvaMovEst - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmSalvaMovEst - Exception: ' + E.ClassName + '-' + E.Message);
end;
end;
finally
Free;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmTableUpdated(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmTableUpdated(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmTableUpdated - nmIDTab: ' + IntToStr(nmIDTab));
Erro := Serv.TableUpdated(nmIDTab);
DebugMsg('TncnxCmdHandler.nmTableUpdated - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmTableUpdated - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmUploadArq(var aMsg: TnxDataMessage);
var
S: TnxMemoryStream;
Str: String;
Erro : TnxResult;
CEList : TList;
begin
S := TnxMemoryStream.Create;
try
ServLock(aMsg.dmSessionID);
try
with aMsg, TnmUpload(aMsg.dmData^) do
try
DebugMsg('TncnxCmdHandler.nmUploadArq - NomeArq: ' + nmNomeArq +
' - Tamanho: ' + IntToStr(nmTamanho));
Str := ExtractFilePath(ParamStr(0)) + nmNomeArq;
if FileExists(Str) then
DeleteFile(Str);
S.SetSize(nmTamanho);
Move(nmArq, S.Memory^, nmTamanho);
S.SaveToFile(Str);
Erro := 0;
DebugMsg('TncnxCmdHandler.nmUploadArq - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmUploadArq - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
finally
S.Free;
end;
end;
procedure TncnxCmdHandler.nmZerarEstoque(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmZerarEstoqueReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmZerarEstoque - nmFunc: ' + nmFunc);
Erro := Serv.ZerarEstoque(nmFunc);
DebugMsg('TncnxCmdHandler.nmZerarEstoque - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmZerarEstoque - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmKeepAlive(var aMsg: TnxDataMessage);
var Erro : Integer;
begin
if {getPluginEngine.SessaoTerminou(aMsg.dmSessionID)} not gCallbackMgr.SessionExists(aMsg.dmSessionID) then
Erro := 1 else {qualquer resultado diferente de zero força a cliente a desconectar}
Erro := 0;
TnxBaseTransport.Reply(aMsg.dmMsg, Erro, nil, 0);
end;
type
THackTransp = Class (TnxBasePooledTransport )
function GetRemoteAddress(aSessionID: TnxSessionID): String;
End;
procedure TncnxCmdHandler.nmLogin(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
R : TnmLoginRpy;
I : Integer;
S : String;
begin
ServLock(aMsg.dmSessionID);
with aMsg, TnmLoginReq(dmData^) do
try
try
DebugMsg(
'TncnxCmdHandler.nmLogin - dmSessionID: ' + IntToStr(aMsg.dmSessionID) +
' - nmUsername: ' + nmUsername +
' - nmSenha: ' + nmSenha +
' - nmFuncAtual: ' + BoolStr(nmFuncAtual) +
' - nmProxyHandle: ' + IntToStr(nmProxyHandle));
S := '';
I := Integer(TnxBaseTransport.CurrentTransport);
try
S := dmServidorBD.GetSessionIP(aMsg.dmSessionID);
if Pos(':', S)>0 then Delete(S, Pos(':', S), 100);
except
S := '';
end;
try
gCallbackMgr.AddSession(TncSessionCallback.Create(aMsg.dmSessionID, TnxBaseTransport.CurrentTransport));
Erro := Serv.Login(nmUsername, nmSenha, nmFuncAtual, True, 0, nmProxyHandle,
I, aMsg.dmSessionID, S, R.nmHandle);
except
gCallbackMgr.RemoveSession(aMsg.dmSessionID);
raise;
end;
DebugMsg('TncnxCmdHandler.nmLogin - Handle Cliente: ' + IntToStr(R.nmHandle)+ ' - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmLogin - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, @R, SizeOf(R));
end;
procedure TncnxCmdHandler.nmLogout(var aMsg: TnxDataMessage);
var Erro : TnxResult; CEList : TList;
begin
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
DebugMsg('TncnxCmdHandler.nmLogout - nmCliente: ' + IntToStr(Integer(dmData^)));
Serv.Logout(Integer(dmData^));
Erro := 0;
DebugMsg('TncnxCmdHandler.nmLogout - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmLogout - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, nil, 0);
end;
procedure TncnxCmdHandler.nmNovoObj(var aMsg: TnxDataMessage);
begin
nmAlteraObj(aMsg);
end;
procedure TncnxCmdHandler.nmObtemLista(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
S : TnxMemoryStream;
begin
S := TnxMemoryStream.Create;
try
ServLock(aMsg.dmSessionID);
with aMsg, TnmObtemListaReq(dmData^) do
try
try
DebugMsg('TncnxCmdHandler.nmObtemLista - nmCliente: '+IntToStr(nmCliente) +
' - nmTipoClasse: ' + IntToStr(nmTipoClasse));
Erro := Serv.ObtemStreamListaObj(nmCliente, nmTipoClasse, S);
DebugMsg('TncnxCmdHandler.nmObtemLista - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmObtemLista - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, S.Memory, S.Size);
finally
S.Free;
end;
end;
procedure TncnxCmdHandler.nmObtemPastaServ(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
R : TnmNomeArq;
S : String;
begin
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
Erro := Serv.ObtemPastaServ(S);
R.nmNomeArq := S;
DebugMsg('TncnxCmdHandler.nmObtemPastaServ - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmObtemPastaServ - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, @R, SizeOf(R));
end;
procedure TncnxCmdHandler.nmObtemStreamConfig(var aMsg: TnxDataMessage);
var
Erro : TnxResult; CEList : TList;
S : TnxMemoryStream;
begin
S := TnxMemoryStream.Create;
try
ServLock(aMsg.dmSessionID);
with aMsg do
try
try
DebugMsg('TncnxCmdHandler.nmObtemStreamConfig');
Erro := Serv.ObtemStreamConfig(S);
DebugMsg('TncnxCmdHandler.nmObtemStreamConfig - Res: ' + IntToStr(Erro));
except
on E: Exception do begin
Erro := 2;
DebugMsg('TncnxCmdHandler.nmObtemStreamConfig - Exception: ' + E.Message);
end;
end;
finally
CEList := ServUnlock;
end;
SendReply(CEList, aMsg.dmMsg, Erro, S.Memory, S.Size);
finally
S.Free;
end;
end;
procedure TncnxCmdHandler.bpchProcess( aMsg: PnxDataMessage; var aHandled: Boolean );
begin
aHandled := False;
if (Serv=nil) or (not ServidorAtivo) then Exit;
IncPend;
try
try
if not ServidorAtivo then Exit;
_bpchProcess(aMsg, aHandled);
except
end;
finally
DecPend;
end;
end;
procedure TncnxCmdHandler._bpchProcess( aMsg: PnxDataMessage; var aHandled: Boolean );
begin
aHandled := True;
case aMsg^.dmMsg of
ncnmLogin : nmLogin(aMsg^);
ncnmLogout : nmLogout(aMsg^);
ncnmNovoObj : nmNovoObj(aMsg^);
ncnmAlteraObj : nmAlteraObj(aMsg^);
ncnmApagaObj : nmApagaObj(aMsg^);
ncnmObtemLista : nmObtemLista(aMsg^);
ncnmDownloadArq : nmDownloadArq(aMsg^);
// ncnmDownloadArqInterno : nmDownloadArqInterno(aMsg^);
ncnmUploadArq : nmUploadArq(aMsg^);
ncnmObtemStreamConfig : nmObtemStreamConfig(aMsg^);
ncnmObtemPastaServ : nmObtemPastaServ(aMsg^);
ncnmCancelaTran : nmCancelaTran(aMsg^);
ncnmSalvaMovEst : nmSalvaMovEst(aMsg^);
ncnmSalvaCredito : nmSalvaCredito(aMsg^);
ncnmSalvaDebito : nmSalvaDebito(aMsg^);
ncnmAbreCaixa : nmAbreCaixa(aMsg^);
ncnmFechaCaixa : nmFechaCaixa(aMsg^);
ncnmSalvaLancExtra : nmSalvaLancExtra(aMsg^);
ncnmCorrigeDataCaixa : nmCorrigeDataCaixa(aMsg^);
ncnmSalvaLic : nmSalvaLic(aMsg^);
ncnmAjustaPontosFid : nmAjustaPontosFid(aMsg^);
ncnmKeepAlive : nmKeepAlive(aMsg^);
ncnmGetLoginData : nmGetLoginData(aMsg^);
ncnmZerarEstoque : nmZerarEstoque(aMsg^);
ncnmSalvaApp : nmSalvaApp(aMsg^);
ncnmObtemCertificados : nmGetCertificados(aMsg^);
ncnmReemitirNFCe : nmReemitirNFCe(aMsg^);
ncnmInstalaNFCeDepend : nmInstalaNFCeDepend(aMsg^);
ncnmInstalaNFeDepend : nmInstalaNFeDepend(aMsg^);
ncnmTableUpdated : nmTableUpdated(aMsg^);
ncnmGeraXMLProt : nmGeraXMLProt(aMsg^);
ncnmInutilizarNFCE : nmInutilizarNFCE(aMsg^);
else
aHandled := False;
end;
end;
procedure TncnxCmdHandler.bpchRemoveSession(aTransport: TnxBaseTransport;
aSessionId: TnxSessionID);
begin
inherited;
if not ServidorAtivo then Exit;
PluginEngine.spRemoveSession( aSessionID );
end;
procedure TncnxCmdHandler.bpchSessionFailed(aTransport: TnxBaseTransport;
aSessionID: TnxSessionID);
begin
inherited;
if not ServidorAtivo then Exit;
PluginEngine.spRemoveSession( aSessionID );
end;
{ THackTransp }
type
THackSession = class ( TnxBaseRemoteSession );
THackRemTransp = class ( TnxBaseRemoteTransport )
function IsSessionID(aSessionID: TnxSessionID): Boolean;
end;
function THackTransp.GetRemoteAddress(aSessionID: TnxSessionID): String;
var
i: Integer;
begin
Result := '';
with btRemoteTransports, BeginRead do try
for I := 0 to Count - 1 do
with THackRemTransp(Items[i]) do
if IsSessionID(aSessionID) then begin
Result := RemoteAddress;
if Trim(Result)<>'' then
Exit;
end;
finally
EndRead;
end
end;
{ THackRemTransp }
function THackRemTransp.IsSessionID(aSessionID: TnxSessionID): Boolean;
var i: Integer;
begin
Result := False;
with brtSessions, BeginRead do
try
for i := 0 to Count - 1 do
if THackSession(Items[I]).brsSessionID=aSessionID then begin
Result := True;
Exit;
end;
finally
EndRead;
end
end;
{ TncEventoFalhou }
initialization
TncnxServerPlugin.rcRegister;
TncnxCmdHandler.rcRegister;
finalization
TncnxServerPlugin.rcUnregister;
TncnxCmdHandler.rcUnregister;
end.
|
unit uEmpresa;
interface
uses uCidade;
type
TEmpresa = class
private
codigo: Integer;
ativo: char;
razaoSocial: String;
fantasia: String;
endereco: String;
numero: String;
bairro: String;
complemento: String;
telefone: String;
cnpjcpf: String;
ierg: String;
email: String;
tipo: char;
cidade: TCidade;
public
// contrutor da classe
constructor TEmpresaCreate;
// destrutor da classe
destructor TEmpresaDestroy;
// metodo "procedimento" set do Objeto
procedure setCodigo(param: Integer);
procedure setAtivo(param: char);
procedure setRazaoSocial(param: String);
procedure setFantasia(param: String);
procedure setEndereco(param: String);
procedure setNumero(param: String);
procedure setBairro(param: String);
procedure setComplemento(param: String);
procedure setTelefone(param: String);
procedure setCnpjCpf(param: String);
procedure setIeRg(param: String);
procedure setEmail(param: String);
procedure setTipo(param: char);
procedure setCidade(param: TCidade);
// metodo "funcoes" get do Objeto
function getCodigo: Integer;
function getAtivo: char;
function getRazaoSocial: String;
function getFantasia: String;
function getEndereco: String;
function getNumero: String;
function getBairro: String;
function getComplemento: String;
function getTelefone: String;
function getCnpjCpf: String;
function getIeRg: String;
function getEmail: String;
function getTipo: char;
function getCidade: TCidade;
end;
var
empresa : TEmpresa;
implementation
{ TDistribuidor implemenetacao dos metodos Get e sey }
function TEmpresa.getAtivo: char;
begin
Result := ativo;
end;
function TEmpresa.getBairro: String;
begin
Result := bairro;
end;
function TEmpresa.getCidade: TCidade;
begin
Result := cidade;
end;
function TEmpresa.getCnpjCpf: String;
begin
Result := cnpjcpf;
end;
function TEmpresa.getCodigo: Integer;
begin
Result := codigo;
end;
function TEmpresa.getComplemento: String;
begin
Result := complemento;
end;
function TEmpresa.getEmail: String;
begin
Result := email;
end;
function TEmpresa.getEndereco: String;
begin
Result := endereco;
end;
function TEmpresa.getFantasia: String;
begin
Result := fantasia;
end;
function TEmpresa.getIeRg: String;
begin
Result := ierg;
end;
function TEmpresa.getNumero: String;
begin
Result := numero;
end;
function TEmpresa.getRazaoSocial: String;
begin
Result := razaoSocial;
end;
function TEmpresa.getTelefone: String;
begin
Result := telefone;
end;
function TEmpresa.getTipo: char;
begin
Result := tipo;
end;
procedure TEmpresa.setAtivo(param: char);
begin
ativo := param;
end;
procedure TEmpresa.setBairro(param: String);
begin
bairro := param;
end;
procedure TEmpresa.setCidade(param: TCidade);
begin
cidade := param;
end;
procedure TEmpresa.setCnpjCpf(param: String);
begin
cnpjcpf := param;
end;
procedure TEmpresa.setCodigo(param: Integer);
begin
codigo := param;
end;
procedure TEmpresa.setComplemento(param: String);
begin
complemento := param;
end;
procedure TEmpresa.setEmail(param: String);
begin
email := param;
end;
procedure TEmpresa.setEndereco(param: String);
begin
endereco := param;
end;
procedure TEmpresa.setFantasia(param: String);
begin
fantasia := param;
end;
procedure TEmpresa.setIeRg(param: String);
begin
ierg := param;
end;
procedure TEmpresa.setNumero(param: String);
begin
numero := param;
end;
procedure TEmpresa.setRazaoSocial(param: String);
begin
razaoSocial := param;
end;
procedure TEmpresa.setTelefone(param: String);
begin
telefone := param;
end;
procedure TEmpresa.setTipo(param: char);
begin
tipo := param;
end;
constructor TEmpresa.TEmpresaCreate;
begin
codigo := 0;
ativo := 'S';
razaoSocial := '';
fantasia := '';
endereco := '';
numero := '';
bairro := '';
complemento := '';
telefone := '';
cnpjcpf := '';
ierg := '';
email := '';
tipo := 'F';
cidade.TCidadeCreate;
end;
destructor TEmpresa.TEmpresaDestroy;
begin
cidade.TCidadeDestroy;
FreeInstance;
end;
end.
|
unit UFileUtilities;
interface
uses Classes, SysUtils, Forms, Dialogs, WinApi.Windows, VCLZip;
type
TFileUtilities = class
public
class function FindAllDirectory(InDirectory:String):TStringList;static;
class function FindAllFiles(InDirectory:String):TStringList;static;
class function Zip(ZipMode, PackSize:Integer; ZipFile, UnzipDir: String):Boolean; static;
class function ExtractLastDirectory(Dir:string):String;
class function IsSeparator(ch:char):boolean;static;
class function RemoveLastSeparator(Dir:string):string;
class function ReadToEnd(fileName:String):string;
class function AddSeparator(st:String):String;
class procedure WriteToFile(fileName, content:String);
class function CopyDir(sDirName, sToDirName:String):Boolean;
class procedure DeleteDir(sDirectory:String);
class function CurrentDir:String;
end;
implementation
class function TFileUtilities.CurrentDir:String;
begin
exit(ExtractFilePath(Application.ExeName));
end;
class function TFileUtilities.IsSeparator(ch: Char):Boolean;
begin
exit((ch = '/') or (ch = '\'));
end;
class function TFileUtilities.RemoveLastSeparator(Dir:string):string;
var ch:char;
begin
Dir := Trim(Dir);
ch := Dir[length(Dir)];
if IsSeparator(ch) then
delete(Dir, length(Dir), 1);
exit(Dir);
end;
class function TFileUtilities.FindAllDirectory(InDirectory:String):TStringList;
var
SR: TSearchRec;
begin
FindAllDirectory := TStringList.Create;
if InDirectory[Length(InDirectory)] <> '\' then
InDirectory := InDirectory + '\';
if FindFirst(InDirectory+'*.*', FADirectory, SR) = 0 then
repeat
if (SR.Attr and FADirectory) <> 0 then
if (SR.Name <> '.') and (SR.Name <> '..') then
begin
FindAllDirectory.Add(SR.Name);
end;
Application.ProcessMessages;
until FindNext(SR) <> 0;
SysUtils.FindClose(SR);
end;
class function TFileUtilities.FindAllFiles(InDirectory:String):TStringList;
var
SR: TSearchRec;
begin
FindAllFiles := TStringList.Create;
if InDirectory[Length(InDirectory)] <> '\' then
InDirectory := InDirectory + '\';
if FindFirst(InDirectory+'*.*', FaAnyFile, SR) = 0 then
repeat
if (SR.Attr and FADirectory) = 0 then
FindAllFiles.Add(sr.Name);
Application.ProcessMessages;
until FindNext(SR) <> 0;
SysUtils.FindClose(SR);
end;
class function TFileUtilities.Zip(ZipMode,PackSize:Integer;ZipFile,UnzipDir:String):Boolean; //压缩或解压缩文件
var ziper:TVCLZip;
begin
//函数用法:Zip(压缩模式,压缩包大小,压缩文件,解压目录)
//ZipMode为0:压缩;为1:解压缩 PackSize为0则不分包;否则为分包的大小
try
if copy(UnzipDir, length(UnzipDir), 1) = '\' then
UnzipDir := copy(UnzipDir, 1, length(UnzipDir) - 1); //去除目录后的“\”
ziper:=TVCLZip.Create(application); //创建zipper
ziper.DoAll:=true; //加此设置将对分包文件解压缩有效
//ziper.OverwriteMode:=TUZOverwriteMode.Always; //总是覆盖模式
if PackSize<>0 then begin //如果为0则压缩成一个文件,否则压成多文件
//ziper.MultiZipInfo.MultiMode:=TMultiMode.mmBlocks; //设置分包模式
ziper.MultiZipInfo.SaveZipInfoOnFirstDisk:=True; //打包信息保存在第一文件中
ziper.MultiZipInfo.FirstBlockSize:=PackSize; //分包首文件大小
ziper.MultiZipInfo.BlockSize:=PackSize; //其他分包文件大小
end;
ziper.FilesList.Clear;
ziper.ZipName := ZipFile; //获取压缩文件名
if ZipMode=0 then begin //压缩文件处理
ziper.FilesList.Add(UnzipDir+'\*.*'); //添加解压缩文件列表
Application.ProcessMessages; //响应WINDOWS事件
ziper.Zip; //压缩
end else begin
ziper.DestDir:= UnzipDir; //解压缩的目标目录
ziper.UnZip; //解压缩
end;
ziper.Free; //释放压缩工具资源
Result:=True; //执行成功
except
Result:=False;//执行失败
end;
end;
class function TFileUtilities.AddSeparator(st:string):string;
begin
st := Trim(st);
if st[length(st)] = '\' then
exit(st)
else
exit(st+'\');
end;
class function TFileUtilities.ExtractLastDirectory(Dir: string): string;
var i:integer;
begin
Dir := TFileUtilities.RemoveLastSeparator(Dir);
i := length(Dir);
while (i >= 1) and (Not IsSeparator(Dir[i])) do
begin
Dec(i);
end;
if i <= 0 then raise Exception.Create('Error Path');
exit(copy(Dir, i + 1, length(Dir) - i))
end;
function AnsiStringToWideString(const ansi: AnsiString): WideString;
var len:Integer;
begin
Result := '';
if ansi = '' then exit;
len := MultiByteToWideChar(936, MB_PRECOMPOSED, @ansi[1], -1, nil, 0);
SetLength(result, len - 1);
if Len > 1 then
MultiByteToWideChar(936, MB_PRECOMPOSED, @ansi[1], -1, PWideChar(@result[1]), len - 1);
end;
class function TFileUtilities.ReadToEnd(fileName: String): string;
var f: TextFile; j: String;
begin
if not fileexists(fileName) then
result := ''
else
begin
AssignFile(f, fileName);
ReSet(f);
while not eof(f) do
begin
readln(f, j); result := result + j;
end;
CloseFile(f);
end;
end;
class procedure TFileUtilities.WriteToFile(fileName, content: string);
var f: TextFile;
begin
ForceDirectories(ExtractFilePath(fileName));
AssignFile(f, fileName);
Rewrite(f);
Writeln(f,content);
CloseFile(f);
end;
class function TFileUtilities.CopyDir(sDirName:String;sToDirName:String):Boolean;
var
hFindFile:Cardinal;
t,tfile:String;
sCurDir:String[255];
FindFileData:WIN32_FIND_DATA;
begin
//记录当前目录
sCurDir:=GetCurrentDir;
ChDir(sDirName);
hFindFile:=FindFirstFile('*.*',FindFileData);
if hFindFile<>INVALID_HANDLE_VALUE then
begin
if not DirectoryExists(sToDirName) then
ForceDirectories(sToDirName);
repeat
tfile:=FindFileData.cFileName;
if (tfile='.') or (tfile='..') then
continue;
if FindFileData.dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY then
begin
t:=sToDirName+'\'+tfile;
if not DirectoryExists(t) then
ForceDirectories(t);
if sDirName[Length(sDirName)]<>'\' then
CopyDir(sDirName+'\'+tfile,t)
else
CopyDir(sDirName+tfile,sToDirName+tfile);
end
else
begin
t:=sToDirName+'\'+tFile;
CopyFile(PChar(tfile),PChar(t),True);
end;
until FindNextFile(hFindFile,FindFileData)=false;
/// FindClose(hFindFile);
end
else
begin
ChDir(sCurDir);
result:=false;
exit;
end;
//回到当前目录
ChDir(sCurDir);
result:=true;
end;
class procedure TFileUtilities.DeleteDir(sDirectory:String);
var
sr:TSearchRec;
sPath,sFile:String;
begin
//检查目录名后面是否有'\'
if Copy(sDirectory,Length(sDirectory),1)<>'\'then
sPath:=sDirectory+'\'
else
sPath:=sDirectory;
//------------------------------------------------------------------
if FindFirst(sPath+'*.*',faAnyFile,sr)=0 then
begin
repeat
sFile:=Trim(sr.Name);
if sFile='.' then Continue;
if sFile='..' then Continue;
sFile:=sPath+sr.Name;
if(sr.Attr and faDirectory)<>0 then
DeleteDir(sFile)
else if(sr.Attr and faAnyFile)=sr.Attr then
DeleteFile(PWideChar(WideString(sFile)));//删除文件
until FindNext(sr)<>0;
SysUtils.FindClose(sr);
end;
RemoveDir(sPath);
end;
end.
|
unit SJ_INTV;
{$ifdef VirtualPascal}
{$stdcall+}
{$else}
Error('Interface unit for VirtualPascal');
{$endif}
(*************************************************************************
DESCRIPTION : Interface unit for SJ_DLL
REQUIREMENTS : VirtualPascal
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 03.06.09 W.Ehrhardt Initial version a la XT_INTV
0.11 16.07.09 we SJ_DLL_Version returns PAnsiChar
0.12 06.08.10 we Longint ILen, SJ_CTR_Seek/64 via sj_seek.inc
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2009-2010 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
interface
const
SJ_Err_Invalid_Key_Size = -1; {Key size in bytes <> 10}
SJ_Err_Invalid_Length = -3; {No full block for cipher stealing}
SJ_Err_Data_After_Short_Block = -4; {Short block must be last}
SJ_Err_MultipleIncProcs = -5; {More than one IncProc Setting}
SJ_Err_NIL_Pointer = -6; {nil pointer to block with nonzero length}
SJ_Err_CTR_SeekOffset = -15; {Invalid offset in SJ_CTR_Seek}
SJ_Err_Invalid_16Bit_Length = -20; {Pointer + Offset > $FFFF for 16 bit code}
type
TSJBlock = packed array[0..7] of byte;
PSJBlock = ^TSJBlock;
TSJRKArray = packed array[0..9] of byte;
type
TSJIncProc = procedure(var CTR: TSJBlock); {user supplied IncCTR proc}
{$ifdef DLL} stdcall; {$endif}
type
TSJContext = packed record
CV : TSJRKArray; {key array, 'cryptovariable' in spec}
IV : TSJBlock; {IV or CTR }
buf : TSJBlock; {Work buffer }
bLen : word; {Bytes used in buf }
Flag : word; {Bit 1: Short block }
IncProc : TSJIncProc; {Increment proc CTR-Mode}
end;
const
SJBLKSIZE = sizeof(TSJBlock);
function SJ_DLL_Version: PAnsiChar;
{-Return DLL version as PAnsiChar}
function SJ_Init(const Key; KeyBytes: word; var ctx: TSJContext): integer;
{-SkipJack context initialization}
procedure SJ_Encrypt(var ctx: TSJContext; const BI: TSJBlock; var BO: TSJBlock);
{-encrypt one block}
procedure SJ_Decrypt(var ctx: TSJContext; const BI: TSJBlock; var BO: TSJBlock);
{-decrypt one block}
procedure SJ_XorBlock(const B1, B2: TSJBlock; var B3: TSJBlock);
{-xor two blocks, result in third}
procedure SJ_SetFastInit(value: boolean);
{-set FastInit variable}
function SJ_GetFastInit: boolean;
{-Returns FastInit variable}
function SJ_CBC_Init(const Key; KeyBytes: word; const IV: TSJBlock; var ctx: TSJContext): integer;
{-SkipJack key expansion, error if invalid key size, save IV}
procedure SJ_CBC_Reset(const IV: TSJBlock; var ctx: TSJContext);
{-Clears ctx fields bLen and Flag, save IV}
function SJ_CBC_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CBC mode}
function SJ_CBC_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CBC mode}
function SJ_CFB_Init(const Key; KeyBytes: word; const IV: TSJBlock; var ctx: TSJContext): integer;
{-SkipJack key expansion, error if invalid key size, encrypt IV}
procedure SJ_CFB_Reset(const IV: TSJBlock; var ctx: TSJContext);
{-Clears ctx fields bLen and Flag, encrypt IV}
function SJ_CFB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CFB mode}
function SJ_CFB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CFB mode}
function SJ_CTR_Init(const Key; KeyBytes: word; const CTR: TSJBlock; var ctx: TSJContext): integer;
{-SkipJack key expansion, error if inv. key size, encrypt CTR}
procedure SJ_CTR_Reset(const CTR: TSJBlock; var ctx: TSJContext);
{-Clears ctx fields bLen and Flag, encrypt CTR}
function SJ_CTR_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode}
function SJ_CTR_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CTR mode}
function SJ_CTR_Seek(const iCTR: TSJBlock; SOL, SOH: longint; var ctx: TSJContext): integer;
{-Setup ctx for random access crypto stream starting at 64 bit offset SOH*2^32+SOL,}
{ SOH >= 0. iCTR is the initial CTR for offset 0, i.e. the same as in SJ_CTR_Init.}
function SJ_SetIncProc(IncP: TSJIncProc; var ctx: TSJContext): integer;
{-Set user supplied IncCTR proc}
procedure SJ_IncMSBFull(var CTR: TSJBlock);
{-Increment CTR[7]..CTR[0]}
procedure SJ_IncLSBFull(var CTR: TSJBlock);
{-Increment CTR[0]..CTR[7]}
procedure SJ_IncMSBPart(var CTR: TSJBlock);
{-Increment CTR[7]..CTR[4]}
procedure SJ_IncLSBPart(var CTR: TSJBlock);
{-Increment CTR[0]..CTR[3]}
function SJ_ECB_Init(const Key; KeyBytes: word; var ctx: TSJContext): integer;
{-SkipJack key expansion, error if invalid key size}
procedure SJ_ECB_Reset(var ctx: TSJContext);
{-Clears ctx fields bLen and Flag}
function SJ_ECB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in ECB mode}
function SJ_ECB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in ECB mode}
function SJ_OFB_Init(const Key; KeyBits: word; const IV: TSJBlock; var ctx: TSJContext): integer;
{-SkipJack key expansion, error if invalid key size, encrypt IV}
procedure SJ_OFB_Reset(const IV: TSJBlock; var ctx: TSJContext);
{-Clears ctx fields bLen and Flag, encrypt IV}
function SJ_OFB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in OFB mode}
function SJ_OFB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSJContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in OFB mode}
implementation
function SJ_DLL_Version; external 'SJ_DLL' name 'SJ_DLL_Version';
function SJ_Init; external 'SJ_DLL' name 'SJ_Init';
procedure SJ_Encrypt; external 'SJ_DLL' name 'SJ_Encrypt';
procedure SJ_Decrypt; external 'SJ_DLL' name 'SJ_Decrypt';
procedure SJ_XorBlock; external 'SJ_DLL' name 'SJ_XorBlock';
procedure SJ_SetFastInit; external 'SJ_DLL' name 'SJ_SetFastInit';
function SJ_GetFastInit; external 'SJ_DLL' name 'SJ_GetFastInit';
function SJ_CBC_Init; external 'SJ_DLL' name 'SJ_CBC_Init';
procedure SJ_CBC_Reset; external 'SJ_DLL' name 'SJ_CBC_Reset';
function SJ_CBC_Encrypt; external 'SJ_DLL' name 'SJ_CBC_Encrypt';
function SJ_CBC_Decrypt; external 'SJ_DLL' name 'SJ_CBC_Decrypt';
function SJ_CFB_Init; external 'SJ_DLL' name 'SJ_CFB_Init';
procedure SJ_CFB_Reset; external 'SJ_DLL' name 'SJ_CFB_Reset';
function SJ_CFB_Encrypt; external 'SJ_DLL' name 'SJ_CFB_Encrypt';
function SJ_CFB_Decrypt; external 'SJ_DLL' name 'SJ_CFB_Decrypt';
function SJ_CTR_Init; external 'SJ_DLL' name 'SJ_CTR_Init';
procedure SJ_CTR_Reset; external 'SJ_DLL' name 'SJ_CTR_Reset';
function SJ_CTR_Encrypt; external 'SJ_DLL' name 'SJ_CTR_Encrypt';
function SJ_CTR_Decrypt; external 'SJ_DLL' name 'SJ_CTR_Decrypt';
function SJ_SetIncProc; external 'SJ_DLL' name 'SJ_SetIncProc';
procedure SJ_IncMSBFull; external 'SJ_DLL' name 'SJ_IncMSBFull';
procedure SJ_IncLSBFull; external 'SJ_DLL' name 'SJ_IncLSBFull';
procedure SJ_IncMSBPart; external 'SJ_DLL' name 'SJ_IncMSBPart';
procedure SJ_IncLSBPart; external 'SJ_DLL' name 'SJ_IncLSBPart';
function SJ_ECB_Init; external 'SJ_DLL' name 'SJ_ECB_Init';
procedure SJ_ECB_Reset; external 'SJ_DLL' name 'SJ_ECB_Reset';
function SJ_ECB_Encrypt; external 'SJ_DLL' name 'SJ_ECB_Encrypt';
function SJ_ECB_Decrypt; external 'SJ_DLL' name 'SJ_ECB_Decrypt';
function SJ_OFB_Init; external 'SJ_DLL' name 'SJ_OFB_Init';
procedure SJ_OFB_Reset; external 'SJ_DLL' name 'SJ_OFB_Reset';
function SJ_OFB_Encrypt; external 'SJ_DLL' name 'SJ_OFB_Encrypt';
function SJ_OFB_Decrypt; external 'SJ_DLL' name 'SJ_OFB_Decrypt';
{$define const}
{$i sj_seek.inc}
end.
|
{*********************************************}
{ TeeGrid Software Library }
{ TStringGrid emulation data class }
{ Copyright (c) 2016 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit Tee.Grid.Data.Strings;
{$I Tee.inc}
interface
{
"TStringGrid" emulator.
A virtual data class for custom "Column x Row" grid of Cells[col,row].
Usage:
var Data : TStringsData;
Data:= TStringsData.Create;
// Initial size
Data.Columns:= 5;
Data.Rows:= 4;
// Set data to grid
TeeGrid1.Data:= Data;
// Set header texts
Data.Headers[1]:='Company';
// Set cell values
Data[1,1]:= 'Steema';
// Optional events
Data.OnGetValue:=...
Data.OnSetValue:=...
}
uses
{System.}Classes,
Tee.Grid.Columns, Tee.Grid.Data, Tee.Painter;
type
TOnGetValue=procedure(Sender:TObject; const AColumn,ARow:Integer; var AValue:String) of object;
TOnSetValue=procedure(Sender:TObject; const AColumn,ARow:Integer; const AValue:String) of object;
{ TStringsData }
TStringsData=class(TVirtualData)
private
FColumns: Integer;
FRows: Integer;
IColumns : TColumns;
IHeaders : Array of String;
IData : Array of Array of String;
FOnSetValue: TOnSetValue;
FOnGetValue: TOnGetValue;
function GetCell(const Column,Row: Integer): String;
function GetHeader(const Column: Integer): String;
function IndexOf(const AColumn: TColumn):Integer; inline;
procedure SetCell(const Column,Row: Integer; const Value: String);
procedure SetColumns(const Value: Integer);
procedure SetHeader(const Column: Integer; const Value: String);
procedure SetRows(const Value: Integer);
public
procedure AddColumns(const AColumns:TColumns); override;
function AsString(const AColumn:TColumn; const ARow:Integer):String; override;
function AutoWidth(const APainter:TPainter; const AColumn:TColumn):Single; override;
function Count:Integer; override;
procedure Load; override;
procedure Resize(const AColumns,ARows:Integer);
procedure SetValue(const AColumn:TColumn; const ARow:Integer; const AText:String); override;
property Cells[const Column,Row:Integer]:String read GetCell write SetCell; default;
property ColumnList:TColumns read IColumns;
property Headers[const Column:Integer]:String read GetHeader write SetHeader;
//published
property Columns:Integer read FColumns write SetColumns default 0;
property Rows:Integer read FRows write SetRows default 0;
property OnGetValue:TOnGetValue read FOnGetValue write FOnGetValue;
property OnSetValue:TOnSetValue read FOnSetValue write FOnSetValue;
end;
implementation
|
program TabletopWeatherStation;
{$ifdef MSWINDOWS}{$apptype CONSOLE}{$endif}
{$ifdef FPC}{$mode OBJFPC}{$H+}{$endif}
uses
SysUtils, IPConnection, Device, BrickletLCD128x64, BrickletAirQuality;
const
HOST = 'localhost';
PORT = 4223;
type
TTabletopWeatherStation = class
private
ipcon: TIPConnection;
brickletLCD: TBrickletLCD128x64;
brickletAirQuality: TBrickletAirQuality;
public
constructor Create;
destructor Destroy; override;
procedure ConnectedCB(sender: TIPConnection; const connectedReason: byte);
procedure EnumerateCB(sender: TIPConnection; const uid: string;
const connectedUid: string; const position: char;
const hardwareVersion: TVersionNumber;
const firmwareVersion: TVersionNumber;
const deviceIdentifier: word; const enumerationType: byte);
procedure AllValuesCB(sender: TBrickletAirQuality; const iaqIndex: longint;
const iaqIndexAccuracy: byte; const temperature: longint;
const humidity: longint; const airPressure: longint);
procedure Execute;
end;
var
tws: TTabletopWeatherStation;
constructor TTabletopWeatherStation.Create;
begin
ipcon := nil;
brickletLCD := nil;
brickletAirQuality := nil;
end;
destructor TTabletopWeatherStation.Destroy;
begin
if (brickletLCD <> nil) then brickletLCD.Destroy;
if (brickletAirQuality <> nil) then brickletAirQuality.Destroy;
if (ipcon <> nil) then ipcon.Destroy;
inherited Destroy;
end;
procedure TTabletopWeatherStation.ConnectedCB(sender: TIPConnection; const connectedReason: byte);
begin
{ Eumerate again after auto-reconnect }
if (connectedReason = IPCON_CONNECT_REASON_AUTO_RECONNECT) then begin
WriteLn('Auto Reconnect');
while (true) do begin
try
ipcon.Enumerate;
break;
except
on e: Exception do begin
WriteLn('Enumeration Error: ' + e.Message);
Sleep(1000);
end;
end;
end;
end;
end;
procedure TTabletopWeatherStation.EnumerateCB(sender: TIPConnection; const uid: string;
const connectedUid: string; const position: char;
const hardwareVersion: TVersionNumber;
const firmwareVersion: TVersionNumber;
const deviceIdentifier: word; const enumerationType: byte);
begin
if ((enumerationType = IPCON_ENUMERATION_TYPE_CONNECTED) or
(enumerationType = IPCON_ENUMERATION_TYPE_AVAILABLE)) then begin
if (deviceIdentifier = BRICKLET_LCD_128X64_DEVICE_IDENTIFIER) then begin
try
{ Initialize newly enumerated LCD128x64 Bricklet }
brickletLCD := TBrickletLCD128x64.Create(UID, ipcon);
brickletLCD.ClearDisplay;
brickletLCD.WriteLine(0, 0, ' Weather Station');
WriteLn('LCD 128x64 initialized');
except
on e: Exception do begin
WriteLn('LCD 128x64 init failed: ' + e.Message);
brickletLCD := nil;
end;
end;
end
else if (deviceIdentifier = BRICKLET_AIR_QUALITY_DEVICE_IDENTIFIER) then begin
try
{ Initialize newly enumaratedy Air Quality Bricklet and configure callbacks }
brickletAirQuality := TBrickletAirQuality.Create(uid, ipcon);
brickletAirQuality.SetAllValuesCallbackConfiguration(1000, true);
brickletAirQuality.OnAllValues := {$ifdef FPC}@{$endif}AllValuesCB;
WriteLn('Air Quality initialized');
except
on e: Exception do begin
WriteLn('Air Quality init failed: ' + e.Message);
brickletAirQuality := nil;
end;
end;
end
end;
end;
procedure TTabletopWeatherStation.AllValuesCB(sender: TBrickletAirQuality; const iaqIndex: longint;
const iaqIndexAccuracy: byte; const temperature: longint;
const humidity: longint; const airPressure: longint);
var text: string;
begin
if (brickletLCD <> nil) then begin
text := Format('IAQ: %6d', [iaqIndex]);
brickletLCD.WriteLine(2, 0, text);
{ $F8 == ° on LCD 128x64 charset }
text := Format('Temp: %6.2f %sC', [temperature/100.0, '' + char($F8)]);
brickletLCD.WriteLine(3, 0, text);
text := Format('Humidity: %6.2f %%RH', [humidity/100.0]);
brickletLCD.WriteLine(4, 0, text);
text := Format('Air Pres: %6.2f hPa', [airPressure/100.0]);
brickletLCD.WriteLine(5, 0, text);
end;
end;
procedure TTabletopWeatherStation.Execute;
begin
ipcon := TIPConnection.Create; { Create IP connection }
{ Connect to brickd (retry if not possible) }
while (true) do begin
try
ipcon.Connect(HOST, PORT);
break;
except
on e: Exception do begin
WriteLn('Connection Error: ' + e.Message);
Sleep(1000);
end;
end;
end;
ipcon.OnEnumerate := {$ifdef FPC}@{$endif}EnumerateCB;
ipcon.OnConnected := {$ifdef FPC}@{$endif}ConnectedCB;
{ Enumerate Bricks and Bricklets (retry if not possible) }
while (true) do begin
try
ipcon.Enumerate;
break;
except
on e: Exception do begin
WriteLn('Enumeration Error: ' + e.Message);
Sleep(1000);
end;
end;
end;
WriteLn('Press key to exit');
ReadLn;
end;
begin
tws := TTabletopWeatherStation.Create;
tws.Execute;
tws.Destroy;
end.
|
unit Launch;
interface
uses
Windows, ShellAPI, Auth, Registry, Settings, ServersUtils;
type
TMinecraftData = record
Minepath: string;
Java: string;
Xms: string;
Xmx: string;
NativesPath: string;
CP: string;
LogonInfo: string;
end;
procedure PlayMinecraft(server: TServerData;auth: TAuthOutputData);
implementation
function GetJavaPath:string;
var
reg: TRegistry;
begin
reg := TRegistry.Create;
reg.RootKey := HKEY_LOCAL_MACHINE;
reg.OpenKeyReadOnly('SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\javaws.exe');
Result := reg.ReadString('Path');
reg.CloseKey;
reg.Free;
end;
function getCP(server:string):string;
begin
CheckFolder(settings.MinecraftDir+'libraries\', '*.jar');
CheckFolder(settings.MinecraftDir+'dists\' + server + '\', '*.jar');
result := settings.tCP;
end;
procedure PlayMinecraft(server: TServerData;auth: TAuthOutputData);
var
MinecraftData: TMinecraftData;
LibraryHandle: THandle;
ExecuteMinecraft: procedure(MinecraftData: TMinecraftData); stdcall;
begin
MinecraftData.Minepath := MinecraftDir;
MinecraftData.Java := getJavaPath;
MinecraftData.Xms := GameMemory;
MinecraftData.Xmx := GameMemory;
MinecraftData.NativesPath := MinecraftDir + 'dists\' + server.name + '\natives';
MinecraftData.CP := getCP(server.name);
MinecraftData.LogonInfo := '--username ' + auth.Login + ' ' +
'--session ' + auth.LaunchParams + ' ' +
'--version 1.6.4 ' +
'--gameDir ' + MinecraftDir + ' ' +
'--assetsDir ' + MinecraftDir + 'assets ';
@ExecuteMinecraft := nil;
LibraryHandle := LoadLibrary(PAnsiChar(AnsiString(MinecraftDir + 'dists\' + server.name + '\Launch.dll')));
if LibraryHandle <> 0 then
begin
@ExecuteMinecraft := GetProcAddress(LibraryHandle, 'ExecuteMinecraft');
if @ExecuteMinecraft <> nil then
begin
ExecuteMinecraft(MinecraftData);
end;
FreeLibrary(LibraryHandle);
end;
ExitProcess(0);
end;
end.
|
unit eSocial.Models.Entities.Responsavel;
interface
uses
System.SysUtils,
eSocial.Models.Entities.Interfaces;
type
TResponsavel<T> = class(TInterfacedObject, IResponsavel<T>)
private
FParent : T;
FNome ,
FCPF ,
FTelefone,
FCelular ,
FEmail : String;
public
constructor Create(aParent : T);
destructor Destroy; override;
class function New(aParent : T) : IResponsavel<T>;
function Nome(Value : String) : IResponsavel<T>; overload;
function Nome : String; overload;
function CPF(Value : String) : IResponsavel<T>; overload;
function CPF : String; overload;
function Telefone(Value : String) : IResponsavel<T>; overload;
function Telefone : String; overload;
function Celular(Value : String) : IResponsavel<T>; overload;
function Celular : String; overload;
function Email(Value : String) : IResponsavel<T>; overload;
function Email : String; overload;
function DadosCompletos : Boolean;
function &End : T;
end;
implementation
{ TResponsavel<T> }
constructor TResponsavel<T>.Create(aParent: T);
begin
FParent := aParent;
FNome := EmptyStr;
FCPF := EmptyStr;
FTelefone := EmptyStr;
FCelular := EmptyStr;
FEmail := EmptyStr;
end;
function TResponsavel<T>.DadosCompletos: Boolean;
begin
Result :=
(not FNome.IsEmpty)
and (not FCPF.IsEmpty)
and (not FCelular.IsEmpty)
and (not FEmail.IsEmpty);
end;
destructor TResponsavel<T>.Destroy;
begin
inherited;
end;
class function TResponsavel<T>.New(aParent: T): IResponsavel<T>;
begin
Result := Self.Create(aParent);
end;
function TResponsavel<T>.Celular(Value: String): IResponsavel<T>;
begin
Result := Self;
FCelular := Value.Trim;
end;
function TResponsavel<T>.Celular: String;
begin
Result := FCelular;
end;
function TResponsavel<T>.CPF(Value: String): IResponsavel<T>;
begin
Result := Self;
FCPF := Value.Trim;
end;
function TResponsavel<T>.CPF: String;
begin
Result := FCPF;
end;
function TResponsavel<T>.Email: String;
begin
Result := FEmail;
end;
function TResponsavel<T>.Email(Value: String): IResponsavel<T>;
begin
Result := Self;
FEmail := Value.Trim.ToLower;
end;
function TResponsavel<T>.Nome: String;
begin
Result := FNome;
end;
function TResponsavel<T>.Nome(Value: String): IResponsavel<T>;
begin
Result := Self;
FNome := Value.Trim;
end;
function TResponsavel<T>.Telefone(Value: String): IResponsavel<T>;
begin
Result := Self;
FTelefone := Value.Trim;
end;
function TResponsavel<T>.Telefone: String;
begin
Result := FTelefone;
end;
function TResponsavel<T>.&End: T;
begin
Result := FParent;
end;
end.
|
unit osParser;
interface
uses osLex, Classes, SysUtils, osParserErrorHand, System.Types;
type
// representa uma pilha generica
TStack = class (TList)
public
procedure push(const E: Pointer);
function pop: Pointer;
end;
// Representa um programa de expressoes a ser executado por uma maquina
TExprPrograma = class
FFonte: AnsiString;
FnLinhas: Integer;
private
function LeLinha(Index: Integer): String;
public
constructor Create;
procedure emit_Func(NomeFunc: String);
procedure emit_FuncArg(NumArgumentos: Integer);
procedure emit_ConstNum(Num: String);
procedure emit_ConstBool(Num: String);
procedure emit_ConstString(str: String);
procedure emit_RValor(NomeVariavel: String);
procedure emit_LValor(NomeVariavel: String);
procedure emit_Operador(Operador: String);
procedure emit_OperadorUnario(Operador: String);
procedure Clear;
property Fonte: AnsiString read FFonte;
property Linhas[Index: Integer]: String read LeLinha;
property nLinhas: Integer read FnLinhas;
end;
{ Classe que representa o Parser }
TosParser = class
FTokenAnterior: TToken;
FLookAhead: TToken;
FLex: TosLexico;
FPrograma: TExprPrograma; // Programa compilado pelo parser
FListaErros: TListErro; // Erros ocorridos durante a compilacao
FCompilado: Boolean; // Indica se a expressao ja foi compilada
FListaVariaveis: TStringList; // Lista de nomes de variaveis encontrados
FListaFuncoes: TStringList; // Lista de nomes de variaveis encontrados
private
procedure NovaExpressao(Expr: AnsiString);
function ObtemExpressao: AnsiString;
function RecuperaErro(Index: Integer): TNodoErro;
function RecuperaNumeroErros: Integer;
function LeNomeVariavel(Index: Integer): String;
function RecuperaNumeroVariaveis: Integer;
function Match(TokenID: Integer): Boolean;
// Gramatica; Forma: ExprN; N precedencia; N maior, prec. maior
procedure Expr; // relacionais
procedure Expr0; // aditivos, OR logico
procedure Expr1; // multiplicativos, AND logico
procedure Expr2; // unarios
procedure Fator; // variaveis e numeros
procedure ListaArg; // lista de argumentos passados para funcao
public
constructor Create;
function Compile: Boolean;
// Retorna true se o identificador e valido segundo os padroes do parser
function ValidaIdentificador(pIdent: String): Boolean;
property Expressao: AnsiString read ObtemExpressao write NovaExpressao;
property Programa: TExprPrograma read FPrograma;
property Compilado: Boolean read FCompilado;
property ListaVariaveis: TStringList read FListaVariaveis;
property ListaFuncoes: TStringList read FListaFuncoes;
property ListaErros: TListErro read FListaErros;
property Erros[Index: integer]: TNodoErro read RecuperaErro;
property nErros: Integer read RecuperaNumeroErros;
property Variavel[Index: Integer]: String read LeNomeVariavel;
property nVariaveis: Integer read RecuperaNumeroVariaveis;
end;
EParserError = class (Exception);
EPEUnrecoverable = class(EParserError);
EPEInternal = class(EParserError);
EPETokenInvalido = class(EParserError);
{ Tokens reconhecidos pelo parser }
TTokenID = (
tIdentificador = 1,
tOperadorUnario,
tOperadorMultiplicativo,
tOperadorAditivo,
tOperadorRelacional,
tOperadorLogicoConjuntivo,
tOperadorLogicoDisjuntivo,
tAbrePar,
tFechaPar,
tVirgula,
tConstNumero,
tConstBooleano,
tString); //adicionado tString MS0001
{ Erros detectaveis pelo parser }
TerrParser =
( epNone = 0,
epErrParsing, // erro generico
epErrParentesis, // falta parentesis
epErrTokenInvalido, // token desconhecido ou invalido
epErrTokenInesperado // encontrado um token qdo esperava-se outro
);
const
{ Textos dos erros }
CerrParserTexto: Array [0..Ord(High(TerrParser))] of String =
(('Nenhum erro de parsing'),
('Erro de parsing.'),
('Falta um '')'''),
('Token Invalido'),
('Esperava-se %s, mas encontrado %s')
);
{ Texto dos tokens }
CTokenTexto: Array [1..Ord(High(TTokenID))] of String =
(('identificador'),
('operador unário'),
('operador multiplicativo(div. ou mult.)'),
('operador aditivo(soma ou sub.)'),
('operador relacional(comparações)'),
('operador lógico conjuntivo'),
('operador lógico disjuntivo'),
('abre parêntesis'),
('fecha parêntesis'),
('vírgula'),
('constante numérica'),
('constante booleana'),
('constante string')); //MS0001
implementation
{ TosParser }
constructor TosParser.Create;
begin
FPrograma := TExprPrograma.Create;
FListaErros := TListErro.Create;
FListaVariaveis := TStringList.Create;
FListaFuncoes := TStringList.Create;
FTokenAnterior := TToken.Create;
FLookAhead := nil;
FListaVariaveis.Sorted := True;
FListaFuncoes.Sorted := True;
// indica que expressao atual (vazia) jah foi compilada
FCompilado := True;
// Criacao dos tokens
FLex := TosLexico.Create;
// Op. Logicos
FLex.AdicionaToken('"([^"]*)"', ord(tString));
FLex.AdicionaToken('NOT', ord(tOperadorUnario));
FLex.AdicionaToken('(OR|XOR)', ord(tOperadorLogicoDisjuntivo));
FLex.AdicionaToken('AND', ord(tOperadorLogicoConjuntivo));
// Op. Aritmeticos e relacionais
FLex.AdicionaToken('([*/]|MOD|DIV)', ord(tOperadorMultiplicativo));
FLex.AdicionaToken('[+-]', ord(tOperadorAditivo));
FLex.AdicionaToken('(>=|<=|<>|<|>|=)', ord(tOperadorRelacional));
// constantes
FLex.AdicionaToken('[0-9]+(\,[0-9]+)?', ord(tConstNumero));
FLex.AdicionaToken('(TRUE|FALSE)', ord(tConstBooleano));
// meta caracteres
FLex.AdicionaToken('\(', ord(tAbrePar));
FLex.AdicionaToken('\)', ord(tFechaPar));
FLex.AdicionaToken(',', ord(tVirgula));
// identificadores de variavel e funcao
FLex.AdicionaToken('[a-zA-Z_][a-zA-Z_0-9]*', ord(tIdentificador));
end;
{ Auxiliares }
procedure TosParser.NovaExpressao(Expr: AnsiString);
begin
FCompilado := False;
FLex.Expressao := AnsiUpperCase(String(Expr));
end;
function TosParser.ObtemExpressao: AnsiString;
begin
Result := AnsiString(FLex.Expressao);
end;
{ Confere token atual e le o proximo token }
function TosParser.Match(TokenID: Integer): Boolean;
begin
Result := True;
FTokenAnterior.ID := FLookAhead.ID;
FTokenAnterior.Value := FLookAhead.Value;
if TokenID <> FLookAhead.ID then
begin
// Tratamento de erros
case TokenID of
Ord(tFechaPar):
begin
// Erro de parentesis
FListaErros.Add(epError, Ord(epErrParentesis),
'Fórmula inválida: faltou fechar um parêntesis.', []);
end;
else
FListaErros.Add(epError, Ord(epErrTokenInesperado),
'Fórmula inválida: esperava-se "%s", mas "%s" encontrado.',
[ CTokenTexto[TokenID] , CTokenTexto[FLookAhead.ID] ]);
end;
Result := False;
end;
// remove o token anterior, se existir
if FLookAhead <> nil then
begin
FLookAhead.Free;
FLookAhead := nil;
end;
FLookAhead := FLex.ObtemToken;
if FLookAhead.ID = -1 then
begin
// Token desconhecido: erro irrecuperavel, levanta excessao
FListaErros.Add(epError, Ord(epErrTokenInvalido),
'Fórmula inválida: símbolo "%s" inválido.', [ FLex.Recupera ]);
if FLookAhead <> nil then
begin
FLookAhead.Free;
FLookAhead := nil;
end;
raise EPETokenInvalido.Create('Fórmula inválida: símbolo desconhecido.');
Result := False;
end;
end;
{ Chamada Principal }
function TosParser.Compile: Boolean;
begin
{ Se o parser jah compilou, sai fora }
if FCompilado then
begin
Result := FListaErros.Count = 0;
Exit;
end;
// Esvazia lista de variaveis, funcoes e erros e inicializa programa de saida
FListaVariaveis.Clear;
FListaFuncoes.Clear;
FListaErros.Clear;
FPrograma.Clear;
// obtem o primeiro token
FLex.Reinicializa;
FLookAhead := FLex.ObtemToken;
if FLookAhead.ID <> 0 then
begin
// Tenta fazer parsing da expressao
try
Expr;
except
on EPETokenInvalido do
begin
Result := False;
Exit;
end;
end;
if FLookAhead.ID <> 0 then
// Erro: nao terminou de processar string, erro de parsing
FListaErros.Add(epError, Ord(epErrParsing), 'Fórmula inválida: erro na expressão.', []);
end;
FCompilado := True; // expressao atual foi compilada, mesmo que tenha erros
Result := FListaErros.Count = 0;
end;
{ Gramatica }
// Operadores relacionais
procedure TosParser.Expr;
var
Operador: String;
begin
Expr0;
while (FLookAhead.ID = ord(tOperadorRelacional)) do
begin
Operador := FLookAhead.Value;
Match(ord(tOperadorRelacional));
Expr0;
// coloca o operador no programa
FPrograma.emit_Operador(Operador);
end;
end;
// Operadores aditivos e logicos disjuntivos
procedure TosParser.Expr0;
var
Operador: String;
begin
Expr1;
while (FLookAhead.ID = ord(tOperadorAditivo)) OR
(FLookAhead.ID = ord(tOperadorLogicoDisjuntivo)) do
begin
Operador := FLookAhead.Value;
if FLookAhead.ID = ord(tOperadorAditivo) then
Match(ord(tOperadorAditivo))
else
Match(ord(tOperadorLogicoDisjuntivo));
Expr1;
// coloca o operador no programa
FPrograma.emit_Operador(Operador);
end;
end;
// Operadores multiplicativos e logicos conjuntivos
procedure TosParser.Expr1;
var
Operador: String;
begin
Expr2;
while (FLookAhead.ID = ord(tOperadorMultiplicativo)) OR
(FLookAhead.ID = ord(tOperadorLogicoConjuntivo)) do
begin
Operador := FLookAhead.Value;
if FLookAhead.ID = ord(tOperadorMultiplicativo) then
Match(ord(tOperadorMultiplicativo))
else
Match(ord(tOperadorLogicoConjuntivo));
Expr2;
// coloca o operador no programa
FPrograma.emit_Operador(Operador);
end;
end;
// Operadores unarios
procedure TosParser.Expr2;
var
OperadorUn: String;
begin
if (FLookAhead.ID = ord(tOperadorAditivo)) or
(FLookAhead.ID = ord(tOperadorUnario)) then
begin
OperadorUn := FLookAhead.Value;
if (FLookAhead.ID = ord(tOperadorAditivo)) then
Match(ord(tOperadorAditivo))
else
Match(ord(tOperadorUnario));
Fator;
FPrograma.emit_OperadorUnario(OperadorUn);
end
else
Fator;
end;
// variaveis e constantes (numericas e booleanas)
procedure TosParser.Fator;
var
Rotulo: String;
begin
case FLookAhead.ID of
// expressao entre parentesis
ord(tAbrePar):
begin
Match(ord(tAbrePar));
Expr;
Match(ord(tFechaPar));
end;
// identificador (variavel ou funcao)
ord(tIdentificador):
begin
Rotulo := FLookAhead.Value;
Match(ord(tIdentificador));
if (FLookAhead.ID = Ord(tAbrePar)) then
begin
// funcao
Match(Ord(tAbrePar));
ListaArg;
Match(Ord(tFechaPar));
FPrograma.emit_Func(Rotulo);
// coloca funcao na lista, se nao existir
if FListaFuncoes.IndexOf(Rotulo) < 0 then
FListaFuncoes.Add(Rotulo);
end
else
begin
// variavel
FPrograma.emit_RValor(Rotulo);
// coloca variavel na lista, se nao existir
if FListaVariaveis.IndexOf(Rotulo) < 0 then
FListaVariaveis.Add(Rotulo);
end;
end;
// constante numerica
ord(tConstNumero):
begin
FPrograma.emit_ConstNum(FLookAhead.Value);
Match(ord(tConstNumero));
end;
// constante booleana
ord(tConstBooleano):
begin
FPrograma.emit_ConstBool(FLookAhead.Value);
Match(ord(tConstBooleano));
end;
//MS0001 aqui vai peghar a string mesmo
ord(tString):
begin
FPrograma.emit_ConstString(FLookAhead.Value);
Match(ord(tString));
end;
else
begin
FListaErros.Add(epError, Ord(epErrTokenInesperado),
'Fórmula inválida: esperava-se uma expressao depois de `%s´ ", mas `%s´ " encontrado',
[ FTokenAnterior.Value, FLookAhead.Value ]);
end;
end;
end;
procedure TosParser.ListaArg;
var
nParam: Integer;
begin
Expr;
nParam := 1;
while FLookAhead.ID = Ord(tVirgula) do
begin
Match(ord(tVirgula));
Expr;
Inc(nParam);
end;
FPrograma.emit_FuncArg(nParam);
end;
function TosParser.ValidaIdentificador(pIdent: String): Boolean;
var
tExpr: WideString;
begin
tExpr := FLex.Expressao;
FLex.Expressao := pIdent;
Result := (FLex.ObtemToken).ID = Ord(tIdentificador);
FLex.Expressao := tExpr;
end;
function TosParser.RecuperaErro(Index: Integer): TNodoErro;
begin
Result := FListaErros.Items[Index];
end;
function TosParser.RecuperaNumeroErros: Integer;
begin
Result := FListaErros.Count;
end;
function TosParser.LeNomeVariavel(Index: Integer): String;
begin
Result := FListaVariaveis[Index];
end;
function TosParser.RecuperaNumeroVariaveis: Integer;
begin
Result := FListaVariaveis.Count;
end;
{ TExprPrograma }
constructor TExprPrograma.Create;
begin
FFonte := '';
FnLinhas := 0;
end;
procedure TExprPrograma.Clear;
begin
FFonte := '';
FnLinhas := 0;
end;
procedure TExprPrograma.emit_ConstBool(Num: String);
begin
FFonte := FFonte + 'constbool:' + AnsiString(Num) + #13#10;
inc(FnLinhas);
end;
procedure TExprPrograma.emit_ConstNum(Num: String);
begin
FFonte := FFonte + 'constnum:' + AnsiString(Num) + #13#10;
inc(FnLinhas);
end;
procedure TExprPrograma.emit_Func(NomeFunc: String);
begin
FFonte := FFonte + 'func:' + AnsiString(Nomefunc) + #13#10;
inc(FnLinhas);
end;
procedure TExprPrograma.emit_FuncArg(NumArgumentos: Integer);
begin
FFonte := FFonte + 'arg:' + AnsiString(IntToStr(NumArgumentos)) + #13#10;
inc(FnLinhas);
end;
procedure TExprPrograma.emit_LValor(NomeVariavel: String);
begin
FFonte := FFonte + 'lvalue:' + AnsiString(NomeVariavel) + #13#10;
inc(FnLinhas);
end;
procedure TExprPrograma.emit_Operador(Operador: String);
begin
FFonte := FFonte + 'op:' + AnsiString(Operador) + #13#10;
inc(FnLinhas);
end;
procedure TExprPrograma.emit_OperadorUnario(Operador: String);
begin
FFonte := FFonte + 'opun:' + AnsiString(Operador) + #13#10;
inc(FnLinhas);
end;
procedure TExprPrograma.emit_RValor(NomeVariavel: String);
begin
FFonte := FFonte + 'rvalue:' + AnsiString(NomeVariavel) + #13#10;
inc(FnLinhas);
end;
function TExprPrograma.LeLinha(Index: Integer): String;
var
i: Integer;
PosI, PosF, Tamanho: Integer;
begin
i := 0;
PosI := 1;
PosF := AnsiPos(#13#10, String(FFonte));;
Tamanho := Length(FFonte);
while i < Index do
begin
PosI := PosF + 2;
PosF := PosI + AnsiPos(#13#10, Copy(String(FFonte), PosI, Tamanho - PosI + 1)) - 1;
inc(i);
end;
Result := Copy(String(FFonte), PosI, PosF-PosI);
end;
procedure TExprPrograma.emit_ConstString(str: String);
begin
FFonte := FFonte + 'conststring:' + AnsiString(str) + #13#10;
inc(FnLinhas);
end;
{ TStack }
function TStack.pop: Pointer;
begin
Result := Last;
Remove(Last);
end;
procedure TStack.push(const E: Pointer);
begin
Add(E);
end;
end.
|
unit FC.StockChart.GetTicksDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmDialogClose_B, StdCtrls, ExtendControls, ExtCtrls, Grids, DBGrids, MultiSelectDBGrid, ColumnSortDBGrid,
EditDBGrid, DB, FC.Dialogs.DockedDialogCloseAndAppWindow_B, ImgList, JvCaptionButton, JvComponentBase,
JvDockControlForm,StockChart.Definitions, FC.Definitions,FC.Singletons,DBUtils, ComCtrls, VclTee.TeEngine, VclTee.Series, VclTee.TeeProcs,
VclTee.Chart, JvExComCtrls, JvComCtrls,Contnrs, FC.StockChart.CustomDialog_B;
type
TfmGetTicksDialog = class(TfmStockChartCustomDialog_B)
dsData: TDataSource;
pcPages: TPageControl;
tsData: TTabSheet;
tsTicksInBar: TTabSheet;
Panel2: TPanel;
cbIntervals: TExtendComboBox;
Label5: TLabel;
tcTabs: TFlatTabControl;
pcAverageTickTabs: TJvPageControl;
tsAbsoluteValues: TTabSheet;
chTickInBarStatistics: TChart;
chTickInBarStatisticsValue: TBarSeries;
tsPercentage: TTabSheet;
chPercentage: TChart;
BarSeries1: TPieSeries;
Panel3: TPanel;
Label6: TLabel;
ckThu: TExtendCheckBox;
ckWed: TExtendCheckBox;
ckMon: TExtendCheckBox;
ckTue: TExtendCheckBox;
ckFri: TExtendCheckBox;
Label7: TLabel;
ckTime1: TExtendCheckBox;
ckTime2: TExtendCheckBox;
ckTime3: TExtendCheckBox;
ckTime4: TExtendCheckBox;
Bevel1: TBevel;
laTicksFound: TLabel;
chTickInBarStatisticsVolumes: TFastLineSeries;
chTicks: TChart;
chTicksEmulated: TFastLineSeries;
Splitter1: TSplitter;
Panel4: TPanel;
chTicksReal: TFastLineSeries;
paDataReal: TPanel;
grData: TEditDBGrid;
Label3: TLabel;
Panel6: TPanel;
EditDBGrid1: TEditDBGrid;
Label8: TLabel;
Panel1: TPanel;
Label1: TLabel;
laAverageTicksPerMinute: TLabel;
laTotalTicks: TLabel;
Label4: TLabel;
Label2: TLabel;
laTotalMinutes: TLabel;
Bevel2: TBevel;
ckTickDataShowMarks: TExtendCheckBox;
procedure ckTickDataShowMarksClick(Sender: TObject);
procedure tsDataResize(Sender: TObject);
procedure ckMonClick(Sender: TObject);
procedure tcTabsChange(Sender: TObject);
procedure cbIntervalsChange(Sender: TObject);
procedure pcPagesChange(Sender: TObject);
private
FDataSet: IDsPackage;
FAggregatedTicks : array [TStockTimeInterval] of TObjectList; //of TTickData
FStart,FEnd: TDateTime;
protected
procedure LoadData;
procedure LoadTicksInBarStatistics;
procedure LoadPercentageInBarStatistics;
public
class procedure Run(const aStockChart: IStockChart; const aStart,aEnd:TDateTime);
constructor Create(const aStockChart: IStockChart); override;
destructor Destroy; override;
end;
TTickData = class
public
DateTime: TDateTime;
CountInDateTime: integer;
constructor Create(const aDateTime: TDateTime; aCountInDateTime: integer);
end;
implementation
uses SystemService,Math,DateUtils, Collections.Map, Application.Definitions,
FC.DataUtils,FC.StockData.DataQueryToInputDataCollectionMediator,
FC.StockData.StockTickCollection,
ufmForm_B;
{$R *.dfm}
{ TfmDialogClose_B1 }
procedure TfmGetTicksDialog.cbIntervalsChange(Sender: TObject);
begin
inherited;
if pcPages.ActivePage=tsTicksInBar then
begin
tsTicksInBar.Tag:=0;
LoadTicksInBarStatistics;
end;
end;
procedure TfmGetTicksDialog.ckMonClick(Sender: TObject);
begin
if Visible then //Срабатывает при загрузке формы
LoadPercentageInBarStatistics;
end;
procedure TfmGetTicksDialog.ckTickDataShowMarksClick(Sender: TObject);
begin
inherited;
chTicksReal.Marks.Visible:=ckTickDataShowMarks.Checked;
chTicksEmulated.Marks.Visible:=ckTickDataShowMarks.Checked;
end;
constructor TfmGetTicksDialog.Create(const aStockChart: IStockChart);
var
aInt: TStockTimeInterval;
begin
inherited;
pcPages.ActivePageIndex:=0;
pcAverageTickTabs.ActivePageIndex:=0;
for aInt := low(TStockTimeInterval) to high(TStockTimeInterval) do
begin
cbIntervals.AddItem(StockTimeIntervalNames[aInt],TObject(aInt));
end;
ckMon.Caption:=WeekDaysLong[1];
ckTue.Caption:=WeekDaysLong[2];
ckWed.Caption:=WeekDaysLong[3];
ckThu.Caption:=WeekDaysLong[4];
ckFri.Caption:=WeekDaysLong[5];
RegisterPersistValue(ckMon,true);
RegisterPersistValue(ckTue,true);
RegisterPersistValue(ckWed,true);
RegisterPersistValue(ckThu,true);
RegisterPersistValue(ckFri,true);
RegisterPersistValue(ckTime1,true);
RegisterPersistValue(ckTime2,true);
RegisterPersistValue(ckTime3,true);
RegisterPersistValue(ckTime4,true);
end;
destructor TfmGetTicksDialog.Destroy;
var
i:TStockTimeInterval;
begin
for i := Low(TStockTimeInterval) to High(TStockTimeInterval) do
FreeAndNil(FAggregatedTicks[i]);
inherited;
end;
procedure TfmGetTicksDialog.LoadData;
var
aMinutes: integer;
aMinutesQuery: IStockDataQuery;
aMinBars: ISCInputDataCollection;
i: Integer;
aTicksInBar : IStockTickCollectionWriteable;
begin
if tsData.Tag=1 then
exit;
TWaitCursor.SetUntilIdle;
tsData.Tag:=1;
FDataSet:=StockDataStorage.QueryStockDataTicksAsDataSet(
StockChart.StockSymbol.Name,
StockDataStorage.CreateDataTickFilterAdapter.DateBetween(FStart,FEnd),
true);
FDataSet.Data.First;
chTicksReal.AutoRepaint:=false;
chTicksEmulated.AutoRepaint:=false;
try
//реальные
while not FDataSet.Data.EOF do
begin
chTicksReal.AddXY( FDataSet.Data.FieldByName('DATE_TICK').AsDateTime,FDataSet.Data.FieldByName('VALUE_TICK').AsFloat);
FDataSet.Data.Next;
end;
//эмуляция
aMinBars:=TStockDataQueryToInputDataCollectionMediator.Create(
StockDataStorage.QueryStockData(StockChart.StockSymbol.Name,sti1,
StockDataStorage.CreateDataFilterAdapter.DateBetween(FStart,FEnd)),nil);
aTicksInBar:=TStockTickCollection.Create;
for i := 0 to aMinBars.Count - 1 do
TStockDataUtils.GenerateTicksInBar(aMinBars,i,aTicksInBar);
for i := 0 to aTicksInBar.Count - 1 do
chTicksEmulated.AddXY(aTicksInBar.GetDateTime(i),aTicksInBar.GetValue(i));
finally
chTicksReal.AutoRepaint:=false;
chTicksReal.Repaint;
chTicksEmulated.AutoRepaint:=false;
chTicksEmulated.Repaint;
end;
FDataSet.Data.First;
aMinutesQuery:=StockDataStorage.QueryStockData(StockChart.StockSymbol.Name,sti1,
StockDataStorage.CreateDataFilterAdapter.DateBetween(FStart,FEnd));
aMinutes:=aMinutesQuery.RecordCount;
laTotalTicks.Caption:=IntToStr(FDataSet.Data.RecordCount);
laTotalMinutes.Caption:=IntToStr(aMinutes);
if (aMinutes=0) then
laAverageTicksPerMinute.Caption:='-'
else
laAverageTicksPerMinute.Caption:=FloatToStr(RoundTo(FDataSet.Data.RecordCount/aMinutes,-2));
dsData.DataSet:=FDataSet.Data;
end;
procedure TfmGetTicksDialog.LoadPercentageInBarStatistics;
var
it: TMapIterator<integer,integer>;
b: boolean;
aWeekdays: array [1..7] of boolean;
aHours: array [0..23] of boolean;
aCountRepetitions : TMap<integer,integer>;
aTickData : TTickData;
i: integer;
aInterval: TStockTimeInterval;
aCountFound: integer;
aTmp: integer;
begin
aWeekdays[1]:=ckMon.Checked;
aWeekdays[2]:=ckTue.Checked;
aWeekdays[3]:=ckWed.Checked;
aWeekdays[4]:=ckThu.Checked;
aWeekdays[5]:=ckFri.Checked;
aWeekdays[6]:=false;
aWeekdays[7]:=false;
for i := 2 to 7 do
aHours[i]:=ckTime1.Checked;
for i := 8 to 13 do
aHours[i]:=ckTime2.Checked;
for i := 14 to 19 do
aHours[i]:=ckTime3.Checked;
for i := 20 to 23 do
aHours[i]:=ckTime4.Checked;
aHours[0]:=ckTime4.Checked;
aHours[1]:=ckTime4.Checked;
aInterval:=TStockTimeInterval(cbIntervals.ItemIndex);
aCountRepetitions:=TMap<integer,integer>.Create();
aCountFound:=0;
try
BarSeries1.Clear;
for i := 0 to FAggregatedTicks[aInterval].Count - 1 do
begin
aTickData:=TTickData(FAggregatedTicks[aInterval][i]);
//Проверяем, чтобы удовлетворяло критериям выборки
if aWeekdays[DayOfTheWeek(aTickData.DateTime)] and aHours[HourOfTheDay(aTickData.DateTime)] then
begin
aTmp:=0;
aCountRepetitions.Lookup(aTickData.CountInDateTime,aTmp);
inc(aTmp);
aCountRepetitions.Add(aTickData.CountInDateTime,aTmp);
inc(aCountFound);
end;
end;
//считаем процент повторяемости баров
b:=aCountRepetitions.GetFirst(it);
while b do
begin
BarSeries1.Add(it.Value,'Bars with '+IntToStr(it.Key)+' ticks');
b:=aCountRepetitions.GetNext(it);
end;
laTicksFound.Caption:=Format('%d ticks found',[aCountFound]);
finally
aCountRepetitions.Free;
end;
end;
procedure TfmGetTicksDialog.LoadTicksInBarStatistics;
var
aTicks : IStockDataTickAggregatedQuery;
aBars : ISCInputDataCollection;
aInterval: TStockTimeInterval;
aDate,aDate2 : TDateTime;
aTickData : TTickData;
aMax: integer;
i: integer;
begin
if tsTicksInBar.Tag=1 then
exit;
aInterval:=TStockTimeInterval(cbIntervals.ItemIndex);
TWaitCursor.SetUntilIdle;
tsTicksInBar.Tag:=1;
//Загружаем собранные по count данные
if FAggregatedTicks[aInterval]=nil then
begin
aTicks:=StockDataStorage.QueryStockDataTicksAggregated(
StockChart.StockSymbol.Name,aInterval,
StockDataStorage.CreateDataTickFilterAdapter.DateBetween(FStart,FEnd));
FAggregatedTicks[aInterval]:=TObjectList.Create;
while not aTicks.EOF do
begin
FAggregatedTicks[aInterval].Add(TTickData.Create(aTicks.GetDateTime,aTicks.GetCountInDateTime));
aTicks.Next;
end;
end;
//загружаем бары, они нам будут нужны, чтобы показать дырки в истории
aBars:=TStockDataQueryToInputDataCollectionMediator.Create(
StockDataStorage.QueryStockData(StockChart.StockSymbol.Name,aInterval,
StockDataStorage.CreateDataFilterAdapter.DateBetween(FStart,FEnd)),
nil);
chTickInBarStatistics.BottomAxis.Increment:=StockTimeIntervalValues[aInterval]*MinuteAsDateTime;
chTickInBarStatistics.AutoRepaint:=false;
chTickInBarStatisticsVolumes.AutoRepaint:=false;
aMax:=0;
try
//Сначала заполняем тики
chTickInBarStatisticsValue.Clear;
chTickInBarStatisticsVolumes.Clear;
for i := 0 to FAggregatedTicks[aInterval].Count - 1 do
begin
aTickData:=TTickData(FAggregatedTicks[aInterval][i]);
chTickInBarStatisticsValue.AddXY(aTickData.DateTime,aTickData.CountInDateTime);
aMax:=max(aMax,aTickData.CountInDateTime);
end;
//Теперь поверх заполняем желтым цветом дырки в истории
TStockDataUtils.AlignTime(FStart,aInterval,aDate,aDate2);
while aDate<FEnd do
begin
if aBars.FindExactMatched(aDate)=-1 then
chTickInBarStatisticsValue.AddXY(aDate,aMax,'',clYellow);
aDate:=TStockDataUtils.AddMinutes(aDate,aInterval);
end;
for i := 0 to aBars.Count - 1 do
chTickInBarStatisticsVolumes.AddXY(aBars.DirectGetItem_DataDateTime(i),aBars.DirectGetItem_DataVolume(i))
finally
chTickInBarStatistics.AutoRepaint:=true;
chTickInBarStatisticsVolumes.AutoRepaint:=true;
chTickInBarStatistics.Repaint;
chTickInBarStatisticsVolumes.Repaint;
end;
LoadPercentageInBarStatistics;
end;
procedure TfmGetTicksDialog.pcPagesChange(Sender: TObject);
begin
inherited;
if ([csLoading, csReading, csDestroying] * ComponentState)=[] then
begin
if pcPages.ActivePage=tsData then
LoadData
else
LoadTicksInBarStatistics;
end;
end;
class procedure TfmGetTicksDialog.Run(const aStockChart: IStockChart; const aStart, aEnd: TDateTime);
begin
with TfmGetTicksDialog.Create(aStockChart) do
begin
TWaitCursor.SetUntilIdle;
Caption:='Ticks from '+DateTimeToStr(aStart)+' to '+DateTimeToStr(aEnd);
FStart:=aStart;
FEnd:=aEnd-1/SecsPerDay;
cbIntervals.ItemIndex:=integer(StockChart.StockSymbol.TimeInterval);
LoadData;
end;
end;
procedure TfmGetTicksDialog.tcTabsChange(Sender: TObject);
begin
pcAverageTickTabs.ActivePageIndex:=tcTabs.TabIndex;
end;
procedure TfmGetTicksDialog.tsDataResize(Sender: TObject);
begin
inherited;
paDataReal.Width:=paDataReal.Parent.Width div 2-10;
end;
{ TTickData }
constructor TTickData.Create(const aDateTime: TDateTime; aCountInDateTime: integer);
begin
DateTime:=aDateTime;
CountInDateTime:=aCountInDateTime;
end;
end.
|
unit Query;
interface
uses
{$IFDEF FPC}
LResources,
{$ENDIF}
{$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
DBCtrls, ExtCtrls, Db, Grids, DBGrids, StdCtrls, ToolWin, ComCtrls, Buttons,
{$IFNDEF FPC}
MemDS,
{$ELSE}
MemDataSet,
{$ENDIF}
DBAccess, Uni, UnidacVcl, DemoFrame, UniDacDemoForm;
type
TQueryFrame = class(TDemoFrame)
DataSource: TDataSource;
UniQuery: TUniQuery;
DBGrid: TDBGrid;
Panel9: TPanel;
btRefreshRecord: TSpeedButton;
DBNavigator: TDBNavigator;
Splitter1: TSplitter;
ToolBar: TPanel;
Panel1: TPanel;
btClose: TSpeedButton;
btOpen: TSpeedButton;
Panel2: TPanel;
cbRefreshBeforeEdit: TCheckBox;
cbRefreshAfterInsert: TCheckBox;
cbRefreshAfterUpdate: TCheckBox;
Panel5: TPanel;
StaticText1: TLabel;
edFetchRows: TEdit;
Panel6: TPanel;
Label5: TLabel;
edFilter: TEdit;
cbFiltered: TCheckBox;
Panel7: TPanel;
edUpdatingTable: TEdit;
Label2: TLabel;
Memo: TMemo;
btPrepare: TSpeedButton;
btUnPrepare: TSpeedButton;
btExecute: TSpeedButton;
btSaveToXML: TSpeedButton;
SaveDialog: TSaveDialog;
cbDMLRefresh: TCheckBox;
Panel3: TPanel;
Label1: TLabel;
cmbLockMode: TComboBox;
cbFetchAll: TCheckBox;
Panel4: TPanel;
btLockRecord: TSpeedButton;
btUnLock: TSpeedButton;
procedure btOpenClick(Sender: TObject);
procedure btCloseClick(Sender: TObject);
procedure btRefreshRecordClick(Sender: TObject);
procedure DataSourceDataChange(Sender: TObject; Field: TField);
procedure DataSourceStateChange(Sender: TObject);
procedure cbFilteredClick(Sender: TObject);
procedure cbRefreshOptionsClick(Sender: TObject);
procedure UniQueryAfterOpen(DataSet: TDataSet);
procedure edFetchRowsExit(Sender: TObject);
procedure btPrepareClick(Sender: TObject);
procedure btUnPrepareClick(Sender: TObject);
procedure btExecuteClick(Sender: TObject);
procedure btSaveToXMLClick(Sender: TObject);
procedure btLockRecordClick(Sender: TObject);
procedure cbDMLRefreshClick(Sender: TObject);
procedure btUnLockClick(Sender: TObject);
procedure cbFetchAllClick(Sender: TObject);
procedure edUpdatingTableExit(Sender: TObject);
procedure cmbLockModeChange(Sender: TObject);
procedure edFilterExit(Sender: TObject);
private
{ Private declarations }
procedure AssignProperties(PropertyNameToSet: string = ''); procedure ShowState;
public
// Demo management
procedure Initialize; override;
procedure SetDebug(Value: boolean); override;
end;
implementation
{$IFNDEF FPC}
{$IFDEF CLR}
{$R *.nfm}
{$ELSE}
{$R *.dfm}
{$ENDIF}
{$ENDIF}
procedure TQueryFrame.ShowState;
var
St: string;
procedure AddSt(S:string);
begin
if St <> '' then
St := St + ', ';
St := St + S;
end;
begin
St := '';
if UniQuery.Prepared then begin
AddSt('Prepared');
if UniQuery.IsQuery then
AddSt('IsQuery');
end;
if UniQuery.Active then
AddSt('Active')
else
AddSt('Inactive');
if UniQuery.Executing then
AddSt('Executing');
if UniQuery.Fetching then
AddSt('Fetching');
edUpdatingTable.Text := UniQuery.UpdatingTable;
UniDACForm.StatusBar.Panels[2].Text := St;
end;
procedure TQueryFrame.AssignProperties(PropertyNameToSet: string = ''); // empty string means all properties
begin
if CheckProperty('FetchRows', PropertyNameToSet) then
try
UniQuery.FetchRows := StrToInt(edFetchRows.Text);
except
edFetchRows.SetFocus;
raise;
end;
if CheckProperty('FetchAll', PropertyNameToSet) then
try
UniQuery.SpecificOptions.Values['FetchAll'] := BoolToStr(cbFetchAll.Checked, True);
except
cbFetchAll.Checked := StrToBool(UniQuery.SpecificOptions.Values['FetchAll']);
raise;
end;
if CheckProperty('UpdatingTable', PropertyNameToSet) then
try
UniQuery.UpdatingTable := edUpdatingTable.Text;
except
edUpdatingTable.SetFocus;
raise;
end;
if CheckProperty('Filter', PropertyNameToSet) then
UniQuery.Filter := edFilter.Text;
if CheckProperty('Filtered', PropertyNameToSet) then
try
UniQuery.Filtered := cbFiltered.Checked;
finally
cbFiltered.Checked := UniQuery.Filtered;
end;
if CheckProperty('SQL', PropertyNameToSet) then
if Trim(UniQuery.SQL.Text) <> Trim(Memo.Lines.Text) then
UniQuery.SQL.Assign(Memo.Lines);
if CheckProperty('RefreshOptions', PropertyNameToSet) then begin
if cbRefreshBeforeEdit.Checked then
UniQuery.RefreshOptions := UniQuery.RefreshOptions + [roBeforeEdit]
else
UniQuery.RefreshOptions := UniQuery.RefreshOptions - [roBeforeEdit];
if cbRefreshAfterInsert.Checked then
UniQuery.RefreshOptions := UniQuery.RefreshOptions + [roAfterInsert]
else
UniQuery.RefreshOptions := UniQuery.RefreshOptions - [roAfterInsert];
if cbRefreshAfterUpdate.Checked then
UniQuery.RefreshOptions := UniQuery.RefreshOptions + [roAfterUpdate]
else
UniQuery.RefreshOptions := UniQuery.RefreshOptions - [roAfterUpdate];
end;
if CheckProperty('DMLRefresh', PropertyNameToSet) then
UniQuery.DMLRefresh := cbDMLRefresh.Checked;
if CheckProperty('LockMode', PropertyNameToSet) then
case cmbLockMode.ItemIndex of
1:
UniQuery.LockMode := lmOptimistic;
2:
UniQuery.LockMode := lmPessimistic;
else
UniQuery.LockMode := lmNone;
end;
end;
procedure TQueryFrame.btOpenClick(Sender: TObject);
begin
try
AssignProperties;
UniQuery.Open;
finally
ShowState;
end;
end;
procedure TQueryFrame.btCloseClick(Sender: TObject);
begin
UniQuery.Close;
ShowState;
end;
procedure TQueryFrame.btRefreshRecordClick(Sender: TObject);
begin
UniQuery.RefreshRecord;
end;
procedure TQueryFrame.DataSourceStateChange(Sender: TObject);
begin
UniDACForm.StatusBar.Panels[1].Text := 'Record ' + IntToStr(UniQuery.RecNo) + ' of ' + IntToStr(UniQuery.RecordCount);
end;
procedure TQueryFrame.DataSourceDataChange(Sender: TObject; Field: TField);
begin
DataSourceStateChange(nil);
end;
procedure TQueryFrame.cbFilteredClick(Sender: TObject);
begin
AssignProperties('Filtered');
end;
procedure TQueryFrame.edFilterExit(Sender: TObject);
begin
AssignProperties('Filter');
end;
procedure TQueryFrame.cbRefreshOptionsClick(Sender: TObject);
begin
AssignProperties('RefreshOptions');
end;
procedure TQueryFrame.cbDMLRefreshClick(Sender: TObject);
begin
AssignProperties('DMLRefresh');
end;
procedure TQueryFrame.cbFetchAllClick(Sender: TObject);
begin
AssignProperties('FetchAll');
end;
procedure TQueryFrame.edFetchRowsExit(Sender: TObject);
begin
AssignProperties('FetchRows');
end;
procedure TQueryFrame.edUpdatingTableExit(Sender: TObject);
begin
AssignProperties('UpdatingTable');
end;
procedure TQueryFrame.cmbLockModeChange(Sender: TObject);
begin
AssignProperties('LockMode');
end;
procedure TQueryFrame.UniQueryAfterOpen(DataSet: TDataSet);
begin
ShowState;
end;
procedure TQueryFrame.btPrepareClick(Sender: TObject);
begin
try
AssignProperties;
UniQuery.Prepare;
finally
ShowState;
end;
end;
procedure TQueryFrame.btUnPrepareClick(Sender: TObject);
begin
UniQuery.UnPrepare;
ShowState;
end;
procedure TQueryFrame.btExecuteClick(Sender: TObject);
begin
try
AssignProperties;
UniQuery.Execute;
finally
ShowState;
end;
end;
procedure TQueryFrame.btSaveToXMLClick(Sender: TObject);
begin
if SaveDialog.Execute then
UniQuery.SaveToXML(SaveDialog.FileName);
end;
procedure TQueryFrame.btLockRecordClick(Sender: TObject);
begin
UniQuery.Lock;
end;
procedure TQueryFrame.btUnLockClick(Sender: TObject);
begin
UniQuery.UnLock;
end;
// Demo management
procedure TQueryFrame.Initialize;
begin
inherited;
UniQuery.Connection := Connection as TUniConnection;
edFetchRows.Text := IntToStr(UniQuery.FetchRows);
cbRefreshBeforeEdit.Checked := roBeforeEdit in UniQuery.RefreshOptions;
cbRefreshAfterInsert.Checked := roAfterInsert in UniQuery.RefreshOptions;
cbRefreshAfterUpdate.Checked := roAfterUpdate in UniQuery.RefreshOptions;
edFilter.Text := UniQuery.Filter;
cbFiltered.Checked := UniQuery.Filtered;
Memo.Lines.Text := UniQuery.SQL.Text;
end;
procedure TQueryFrame.SetDebug(Value: boolean);
begin
UniQuery.Debug := Value;
end;
{$IFDEF FPC}
initialization
{$i Query.lrs}
{$ENDIF}
end.
|
unit AMQP.Types;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{$INCLUDE config.inc}
interface
uses {$IFDEF FPC}SysUtils, Windows,{$Else} System.SysUtils, Winapi.Windows,{$ENDIF}
{$IFNDEF FPC}
{$IFDEF _WIN32}
Net.Winsock2
{$ELSE}
Net.SocketAPI
{$ENDIF}
{$ELSE}
winsock2
{$ENDIF};
const
UINT32_MAX = $ffffffff;
UINT8_MAX = $ff;
UINT64_MAX = $ffffffffffffffff;
UINT16_MAX = $ffff;
INT32_MAX = $7fffffff;
//EINTR = 3407;
EAGAIN = 3406;
type
uint16_t = uint16;
int16_t = Int16;
int8_t = Int8;
uint8_t = UInt8;
Puint8_t = ^uint8_t;
uint64_t = Uint64;
int64_t = Int64;
bool = Boolean ;
uint32_t = UInt32;
int32_t = int32;
int = Integer;
float = Single;
PAMQPChar = PByte;
AMQPChar = AnsiChar;
{$IFDEF OS64}
size_t = Uint64;
ssize_t = int64;
{$ELSE}
size_t = uint32;
Psize_t = ^size_t;
ssize_t = int32;
{$ENDIF}
(* 7 bytes up front, then payload, then 1 byte footer *)
const
HEADER_SIZE = 7;
FOOTER_SIZE = 1;
POOL_TABLE_SIZE = 16;
AMQP_PSEUDOFRAME_PROTOCOL_HEADER = 'A';
{$IFDEF OS64}
SIZE_MAX = $ffffffffffffffff;
{$ELSE}
SIZE_MAX = $ffffffff;
{$ENDIF}
type
PPTimeVal = ^PTimeVal;
Tamqp_time = record
time_point_ns: uint64_t;
class operator equal( l, r : Tamqp_time):Boolean;
class function infinite:Tamqp_time; static;
end;
Pamqp_time = ^Tamqp_time;
amqp_boolean_t = int;
amqp_method_number_t = uint32_t;
Pamqp_method_number_t = ^amqp_method_number_t;
amqp_flags_t = uint32_t ;
amqp_channel_t = uint16_t ;
Pamqp_flags_t = ^amqp_flags_t;
Tamqp_methods = array of amqp_method_number_t;
Tamqp_field_value_kind = (
AMQP_FIELD_KIND_BOOLEAN = Ord('t'), (**< boolean type. 0 = false, 1 = true @see amqp_boolean_t *)
AMQP_FIELD_KIND_I8 = Ord('b'), (**< 8-bit signed integer, datatype: int8_t *)
AMQP_FIELD_KIND_U8 = Ord('B'), (**< 8-bit unsigned integer, datatype: uint8_t *)
AMQP_FIELD_KIND_I16 = Ord('s'), (**< 16-bit signed integer, datatype: int16_t *)
AMQP_FIELD_KIND_U16 = Ord('u'), (**< 16-bit unsigned integer, datatype: uint16_t *)
AMQP_FIELD_KIND_I32 = Ord('I'), (**< 32-bit signed integer, datatype: int32_t *)
AMQP_FIELD_KIND_U32 = Ord('i'), (**< 32-bit unsigned integer, datatype: uint32_t *)
AMQP_FIELD_KIND_I64 = Ord('l'), (**< 64-bit signed integer, datatype: int64_t *)
AMQP_FIELD_KIND_U64 = Ord('L'), (**< 64-bit unsigned integer, datatype: uint64_t *)
AMQP_FIELD_KIND_F32 = Ord('f'), (**< single-precision floating point value, datatype: float *)
AMQP_FIELD_KIND_F64 = Ord('d'), (**< double-precision floating point value, datatype: double *)
AMQP_FIELD_KIND_DECIMAL = Ord('D'), (**< amqp-decimal value, datatype: amqp_decimal_t *)
AMQP_FIELD_KIND_UTF8 = Ord('S'), (**< UTF-8 null-terminated character string,
datatype: amqp_bytes_t *)
AMQP_FIELD_KIND_ARRAY = Ord('A'), (**< field array (repeated values of another
datatype. datatype: amqp_array_t *)
AMQP_FIELD_KIND_TIMESTAMP = Ord('T'), (**< 64-bit timestamp. datatype uint64_t *)
AMQP_FIELD_KIND_TABLE = Ord('F'), (**< field table. encapsulates a table inside a
table entry. datatype: amqp_table_t *)
AMQP_FIELD_KIND_VOID = Ord('V'), (**< empty entry *)
AMQP_FIELD_KIND_BYTES = Ord('x') (**< unformatted byte string, datatype: amqp_bytes_t *)
);
Tamqp_response_type_enum = (
AMQP_RESPONSE_NONE = 0, (**< the library got an EOF from the socket *)
AMQP_RESPONSE_NORMAL, (**< response normal, the RPC completed successfully *)
AMQP_RESPONSE_LIBRARY_EXCEPTION, (**< library error, an error occurred in the
library, examine the library_error *)
AMQP_RESPONSE_SERVER_EXCEPTION (**< server exception, the broker returned an
error, check replay *)
);
Pamqp_bytes = ^Tamqp_bytes;
Tamqp_bytes = record
len: size_t; (**< length of the buffer in bytes *)
bytes: PAMQPChar;//Pointer; (**< pointer to the beginning of the buffer *)
class operator Equal(r, l: Tamqp_bytes) : Boolean;
//{$if CompilerVersion >= 34}
//class operator Assign(var Dest: Tamqp_bytes; const [ref] Src: Tamqp_bytes);
class operator Implicit(src: Pamqp_bytes): Tamqp_bytes;
constructor Create(amount : size_t); overload;
constructor Create( Aname : PAnsiChar); overload;
procedure Destroy;
function malloc_dup_failed:integer;
end;
Tamqp_decimal_t_ = record
decimals: uint8_t; (**< the location of the decimal point *)
value: uint32_t; (**< the value before the decimal point is applied *)
end;
Tamqp_decimal = Tamqp_decimal_t_;
Tamqp_pool_blocklist = record
num_blocks: int ; (**< Number of blocks in the block list *)
blocklist: PPointer; (**< Array of memory blocks *)
end;
Pamqp_pool_blocklist = ^Tamqp_pool_blocklist;
(**
* A memory pool
*
* \since v0.1
*)
Tamqp_pool = record
pagesize: size_t ; (**< the size of the page in bytes. Allocations less than or
* equal to this size are allocated in the pages block list.
* Allocations greater than this are allocated in their own
* own block in the large_blocks block list *)
pages: Tamqp_pool_blocklist ; (**< blocks that are the size of pagesize *)
large_blocks: Tamqp_pool_blocklist ; (**< allocations larger than the pagesize
*)
next_page: int ; (**< an index to the next unused page block *)
alloc_block: PAMQPChar; (**< pointer to the current allocation block *)
alloc_used: size_t ; (**< number of bytes in the current allocation block that
has been used *)
constructor Create(pagesize : size_t);
function alloc(amount : size_t): Pointer;
procedure empty();
procedure recycle();
procedure alloc_bytes(amount : size_t;out output : Tamqp_bytes);
end;
Pamqp_pool = ^Tamqp_pool;
Pamqp_table_entry = ^Tamqp_table_entry;
Tamqp_table = record
num_entries: int ; (**< length of entries array *)
entries: Pamqp_table_entry; (**< an array of table entries *)
function clone(out Aclone : Tamqp_table; pool : Pamqp_pool):integer;
function get_entry_by_key(const key : Tamqp_bytes): Pamqp_table_entry;
end;
Pamqp_table = ^Tamqp_table;
Pamqp_field_value = ^Tamqp_field_value;
Tamqp_array = record
num_entries: int ; (**< Number of entries in the table *)
entries: Pamqp_field_value; (**< linked list of field values *)
end;
Pamqp_array = ^Tamqp_array;
Tamqp_field_value = record
kind: uint8_t; (**< the type of the entry /sa amqp_field_value_kind_t *)
value: record
&boolean: amqp_boolean_t; (**< boolean type *)
i8: int8_t ; (**< int8_t type *)
u8: uint8_t; (**< uint8_t *)
i16: int16_t; (**< int16_t type *)
u16:uint16_t; (**< uint16_t type *)
i32: int32_t; (**< int32_t type *)
u32: uint32_t; (**< uint32_t type *)
i64: int64_t; (**< int64_t type *)
u64: uint64_t; (**< uint64_t type ,
AMQP_FIELD_KIND_TIMESTAMP *)
f32: float; (**< float type *)
f64: double; (**< double type *)
decimal: Tamqp_decimal; (**< amqp_decimal_t *)
bytes: Tamqp_bytes; (**< amqp_bytes_t type AMQP_FIELD_KIND_UTF8,
AMQP_FIELD_KIND_BYTES *)
table: Tamqp_table; (**< amqp_table_t type *)
&array: Tamqp_array; (**< amqp_array_t type *)
end; (**< a union of the value *)
function clone(out Aclone : Tamqp_field_value; pool : Pamqp_pool):integer;
end;
Tamqp_method = record
id: amqp_method_number_t ; (**< the method id number *)
decoded: Pointer; (**< pointer to the decoded method,
* cast to the appropriate type to use *)
end;
Pamqp_method = ^Tamqp_method;
Tamqp_rpc_reply = record
reply_type: Tamqp_response_type_enum; (**< the reply type:
* - AMQP_RESPONSE_NORMAL - the RPC
* completed successfully
* - AMQP_RESPONSE_SERVER_EXCEPTION - the
* broker returned
* an exception, check the reply field
* - AMQP_RESPONSE_LIBRARY_EXCEPTION - the
* library
* encountered an error, check the
* library_error field
*)
reply: Tamqp_method ; (**< in case of AMQP_RESPONSE_SERVER_EXCEPTION this
* field will be set to the method returned from the
* broker *)
library_error: int ; (**< in case of AMQP_RESPONSE_LIBRARY_EXCEPTION this
* field will be set to an error code. An error
* string can be retrieved using amqp_error_string *)
end;
Pamqp_rpc_reply = ^Tamqp_rpc_reply;
Tamqp_connection_state_enum = (
CONNECTION_STATE_IDLE = 0,
CONNECTION_STATE_INITIAL,
CONNECTION_STATE_HEADER,
CONNECTION_STATE_BODY
);
Tamqp_status_private_enum = (
(* 0x00xx -> AMQP_STATUS_*)
(* 0x01xx -> AMQP_STATUS_TCP_* *)
(* 0x02xx -> AMQP_STATUS_SSL_* *)
AMQP_PRIVATE_STATUS_SOCKET_NEEDREAD = -$1301,
AMQP_PRIVATE_STATUS_SOCKET_NEEDWRITE = -$1302
);
Pamqp_link = ^Tamqp_link;
Tamqp_link = record
next: Pamqp_link ;
data: Pointer;
end;
Pamqp_pool_table_entry = ^Tamqp_pool_table_entry;
Tamqp_pool_table_entry = record
next: Pamqp_pool_table_entry;
pool: Tamqp_pool ;
channel: amqp_channel_t ;
end;
Tamqp_socket_flag_enum = (
AMQP_SF_NONE = 0,
AMQP_SF_MORE = 1,
AMQP_SF_POLLIN = 2,
AMQP_SF_POLLOUT = 4,
AMQP_SF_POLLERR = 8
) ;
Tamqp_socket_close_enum = ( AMQP_SC_NONE = 0, AMQP_SC_FORCE = 1 ) ;
(* Socket callbacks. *)
Tamqp_socket_send_fn = function(Aself: Pointer; const Abuf: Pointer; Alen : size_t; Aflags : integer): ssize_t;
Tamqp_socket_recv_fn = function(Aself: Pointer; Abuf: Pointer; Alen : size_t; Aflags : integer): ssize_t;
Tamqp_socket_open_fn = function(Aself: Pointer; const Ahost: PAnsiChar; Aport: int; const Atimeout: Ptimeval): int;
Tamqp_socket_close_fn = function(Aself: Pointer; Aforce: Tamqp_socket_close_enum): int;
Tamqp_socket_get_sockfd_fn = function(Aself: Pointer): int;
Tamqp_socket_delete_fn = procedure(Aself: Pointer);
(** V-table for Tamqp_socket *)
Tamqp_socket_class = record
send: Tamqp_socket_send_fn;
recv: Tamqp_socket_recv_fn;
open: Tamqp_socket_open_fn;
close: Tamqp_socket_close_fn;
get_sockfd: Tamqp_socket_get_sockfd_fn;
delete: Tamqp_socket_delete_fn;
end;
Pamqp_socket_class = ^Tamqp_socket_class;
(** Abstract base class for Tamqp_socket *)
Tamqp_socket = record
klass: Pamqp_socket_class;
function send(const Abuf: Pointer; Alen : size_t; Aflags : integer):ssize_t;
function recv(Abuf: Pointer; Alen : size_t; Aflags : integer):ssize_t;
function close(Aforce : Tamqp_socket_close_enum):integer;
function open( host : PAnsiChar; port : integer):integer;
function open_noblock(Ahost : PAnsiChar; Aport : integer;const Atimeout: Ptimeval):integer;
procedure delete;
end;
Pamqp_socket = ^Tamqp_socket;
Tamqp_tcp_socket = record
klass: Pamqp_socket_class;
sockfd,
internal_error,
state : int;
end;
Pamqp_tcp_socket = ^Tamqp_tcp_socket;
Tamqp_connection_state = record
pool_table: array[0..POOL_TABLE_SIZE -1] of Pamqp_pool_table_entry;
state: Tamqp_connection_state_enum;
channel_max: int ;
frame_max: int ;
(* Heartbeat interval in seconds. If this is <= 0, then heartbeats are not
* enabled, and next_recv_heartbeat and next_send_heartbeat are set to
* infinite *)
heart_beat: int ;
next_recv_heartbeat: Tamqp_time ;
next_send_heartbeat: Tamqp_time ;
(* buffer for holding frame headers. Allows us to delay allocating
* the raw frame buffer until the type, channel, and size are all known
*)
//char header_buffer[HEADER_SIZE + 1];
header_buffer: array[0..HEADER_SIZE] of Byte;
inbound_buffer: Tamqp_bytes ;
inbound_offset: size_t ;
target_size: size_t ;
outbound_buffer: Tamqp_bytes ;
Fsocket: Pamqp_socket ;
sock_inbound_buffer: Tamqp_bytes ;
sock_inbound_offset: size_t ;
sock_inbound_limit: size_t ;
first_queued_frame: Pamqp_link;
last_queued_frame: Pamqp_link;
most_recent_api_result: Tamqp_rpc_reply ;
server_properties: Tamqp_table ;
client_properties: Tamqp_table ;
properties_pool: Tamqp_pool ;
handshake_timeout: Ptimeval;
internal_handshake_timeout: TtimeVal;
rpc_timeout: Ptimeval;
internal_rpc_timeout: Ttimeval;
function get_sockfd:integer;
procedure set_socket(Asocket : Pamqp_socket);
function get_channel_pool(channel : amqp_channel_t):Pamqp_pool;
function get_or_create_channel_pool(channel : amqp_channel_t):Pamqp_pool;
property channelmax: Int read channel_max;
property framemax: Int read frame_max;
property heartbeat: Int read heart_beat;
property sockfd: Int read get_sockfd;
property socket: Pamqp_socket write set_socket;
property ServerProperties: Tamqp_table read server_properties;
property ClientProperties: Tamqp_table read client_properties;
end;
Pamqp_connection_state = ^Tamqp_connection_state;
Tamqp_status_enum = (
AMQP_STATUS_OK = $0, (**< Operation successful *)
AMQP_STATUS_NO_MEMORY = -$0001, (**< Memory allocation
failed *)
AMQP_STATUS_BAD_AMQP_DATA = -$0002, (**< Incorrect or corrupt
data was received from
the broker. This is a
protocol error. *)
AMQP_STATUS_UNKNOWN_CLASS = -$0003, (**< An unknown AMQP class
was received. This is
a protocol error. *)
AMQP_STATUS_UNKNOWN_METHOD = -$0004, (**< An unknown AMQP method
was received. This is
a protocol error. *)
AMQP_STATUS_HOSTNAME_RESOLUTION_FAILED = -$0005, (**< Unable to resolve the
* hostname *)
AMQP_STATUS_INCOMPATIBLE_AMQP_VERSION = -$0006, (**< The broker advertised
an incompaible AMQP
version *)
AMQP_STATUS_CONNECTION_CLOSED = -$0007, (**< The connection to the
broker has been closed
*)
AMQP_STATUS_BAD_URL = -$0008, (**< malformed AMQP URL *)
AMQP_STATUS_SOCKET_ERROR = -$0009, (**< A socket error
occurred *)
AMQP_STATUS_INVALID_PARAMETER = -$000A, (**< An invalid parameter
was passed into the
function *)
AMQP_STATUS_TABLE_TOO_BIG = -$000B, (**< The amqp_table_t object
cannot be serialized
because the output
buffer is too small *)
AMQP_STATUS_WRONG_METHOD = -$000C, (**< The wrong method was
received *)
AMQP_STATUS_TIMEOUT = -$000D, (**< Operation timed out *)
AMQP_STATUS_TIMER_FAILURE = -$000E, (**< The underlying system
timer facility failed *)
AMQP_STATUS_HEARTBEAT_TIMEOUT = -$000F, (**< Timed out waiting for
heartbeat *)
AMQP_STATUS_UNEXPECTED_STATE = -$0010, (**< Unexpected protocol
state *)
AMQP_STATUS_SOCKET_CLOSED = -$0011, (**< Underlying socket is
closed *)
AMQP_STATUS_SOCKET_INUSE = -$0012, (**< Underlying socket is
already open *)
AMQP_STATUS_BROKER_UNSUPPORTED_SASL_METHOD = -$0013, (**< Broker does not
support the requested
SASL mechanism *)
AMQP_STATUS_UNSUPPORTED = -$0014, (**< Parameter is unsupported
in this version *)
AMQP_STATUS_NEXT_VALUE = -$0015, (**< Internal value *)
AMQP_STATUS_TCP_ERROR = -$0100, (**< A generic TCP error
occurred *)
AMQP_STATUS_TCP_SOCKETLIB_INIT_ERROR = -$0101, (**< An error occurred trying
to initialize the
socket library*)
AMQP_STATUS_TCP_NEXT_VALUE = -$0102, (**< Internal value *)
AMQP_STATUS_SSL_ERROR = -$0200, (**< A generic SSL error
occurred. *)
AMQP_STATUS_SSL_HOSTNAME_VERIFY_FAILED = -$0201, (**< SSL validation of
hostname against
peer certificate
failed *)
AMQP_STATUS_SSL_PEER_VERIFY_FAILED = -$0202, (**< SSL validation of peer
certificate failed. *)
AMQP_STATUS_SSL_CONNECTION_FAILED = -$0203, (**< SSL handshake failed. *)
AMQP_STATUS_SSL_SET_ENGINE_FAILED = -$0204, (**< SSL setting engine failed *)
AMQP_STATUS_SSL_NEXT_VALUE = -$0205 (**< Internal value *)
);
Tamqp_sasl_method_enum = (
AMQP_SASL_METHOD_UNDEFINED = -1, (**< Invalid SASL method *)
AMQP_SASL_METHOD_PLAIN =
0, (**< the PLAIN SASL method for authentication to the broker *)
AMQP_SASL_METHOD_EXTERNAL =
1 (**< the EXTERNAL SASL method for authentication to the broker *)
);
Tva_list = record
username: PAnsiChar;
password: PAnsiChar;
identity: PAnsiChar;
end;
Tamqp_frame = record
frame_type: uint8_t ; (**< frame type. The types:
* - AMQP_FRAME_METHOD - use the method union member
* - AMQP_FRAME_HEADER - use the properties union member
* - AMQP_FRAME_BODY - use the body_fragment union member
*)
channel: amqp_channel_t ; (**< the channel the frame was received on *)
payload: record
method: Tamqp_method;
properties: record
class_id: uint16_t; (**< the class for the properties *)
body_size: uint64_t; (**< size of the body in bytes *)
decoded: Pointer; (**< the decoded properties *)
raw: Tamqp_bytes; (**< amqp-encoded properties structure *)
end ; (**< message header, a.k.a., properties,
use if frame_type == AMQP_FRAME_HEADER *)
body_fragment: Tamqp_bytes; (**< a body fragment, use if frame_type ==
AMQP_FRAME_BODY *)
protocol_header: record
transport_high: uint8_t ; (**< @internal first byte of handshake *)
transport_low: uint8_t ; (**< @internal second byte of handshake *)
protocol_version_major: uint8_t ; (**< @internal third byte of handshake *)
protocol_version_minor: uint8_t ; (**< @internal fourth byte of handshake *)
end ; (**< Used only when doing the initial handshake with the
broker, don't use otherwise *)
end; (**< the payload of the frame *)
end;
Pamqp_frame = ^Tamqp_frame;
(** connection.start method fields *)
Tamqp_connection_start = record
version_major: uint8_t; (**< version-major *)
version_minor: uint8_t; (**< version-minor *)
server_properties: Tamqp_table; (**< server-properties *)
mechanisms: Tamqp_bytes; (**< mechanisms *)
locales: Tamqp_bytes; (**< locales *)
end;
Pamqp_connection_start = ^Tamqp_connection_start;
(** connection.start-ok method fields *)
Tamqp_connection_start_ok = record
client_properties: Tamqp_table; (**< client-properties *)
mechanism: Tamqp_bytes; (**< mechanism *)
response: Tamqp_bytes; (**< response *)
locale: Tamqp_bytes; (**< locale *)
end;
Pamqp_connection_start_ok = ^Tamqp_connection_start_ok;
(** connection.secure method fields *)
Tamqp_connection_secure = record
challenge: Tamqp_bytes; (**< challenge *)
end;
Pamqp_connection_secure = ^Tamqp_connection_secure;
(** connection.secure-ok method fields *)
Tamqp_connection_secure_ok = record
response: Tamqp_bytes; (**< response *)
end;
Pamqp_connection_secure_ok = ^Tamqp_connection_secure_ok;
(** connection.blocked method fields *)
Tamqp_connection_blocked = record
reason: Tamqp_bytes ; (**< reason *)
end;
Pamqp_connection_blocked = ^Tamqp_connection_blocked;
(** connection.tune method fields *)
Tamqp_connection_tune = record
channel_max: uint16_t; (**< channel-max *)
frame_max: uint32_t; (**< frame-max *)
heartbeat: uint16_t; (**< heartbeat *)
end;
Pamqp_connection_tune = ^Tamqp_connection_tune;
(** connection.tune-ok method fields *)
Tamqp_connection_tune_ok = record
channel_max: uint16_t ; (**< channel-max *)
frame_max: uint32_t ; (**< frame-max *)
heartbeat: uint16_t ; (**< heartbeat *)
end;
Pamqp_connection_tune_ok = ^Tamqp_connection_tune_ok;
Tamqp_connection_open= record
virtual_host: Tamqp_bytes; (**< virtual-host *)
capabilities: Tamqp_bytes; (**< capabilities *)
insist: amqp_boolean_t; (**< insist *)
end;
Pamqp_connection_open = ^Tamqp_connection_open;
Tamqp_connection_open_ok = record
known_hosts: Tamqp_bytes; (**< known-hosts *)
end;
Pamqp_connection_open_ok = ^Tamqp_connection_open_ok;
Tamqp_connection_close = record
reply_code: uint16_t ; (**< reply-code *)
reply_text: Tamqp_bytes; (**< reply-text *)
class_id: uint16_t; (**< class-id *)
method_id: uint16_t; (**< method-id *)
end;
Pamqp_connection_close = ^Tamqp_connection_close;
Tamqp_connection_close_ok = record
dummy: AMQPchar ; (**< Dummy field to avoid empty struct *)
end;
Pamqp_connection_close_ok = ^Tamqp_connection_close_ok;
Tamqp_connection_unblocked = record
dummy: AMQPchar; (**< Dummy field to avoid empty struct *)
end;
Pamqp_connection_unblocked = ^Tamqp_connection_unblocked;
Tamqp_connection_update_secret = record
new_secret: Tamqp_bytes; (**< new-secret *)
reason: Tamqp_bytes; (**< reason *)
end;
Pamqp_connection_update_secret = ^Tamqp_connection_update_secret;
Tamqp_connection_update_secret_ok = record
dummy: AMQPchar; (**< Dummy field to avoid empty struct *)
end;
Pamqp_connection_update_secret_ok = ^Tamqp_connection_update_secret_ok;
Tamqp_channel_open = record
out_of_band: Tamqp_bytes; (**< out-of-band *)
end;
Pamqp_channel_open = ^Tamqp_channel_open;
Tamqp_channel_open_ok = record
channel_id: Tamqp_bytes; (**< channel-id *)
end;
Pamqp_channel_open_ok = ^Tamqp_channel_open_ok;
Tamqp_channel_flow = record
active: amqp_boolean_t; (**< active *)
end;
Pamqp_channel_flow = ^Tamqp_channel_flow;
Tamqp_channel_flow_ok = record
active: amqp_boolean_t; (**< active *)
end;
Pamqp_channel_flow_ok = ^Tamqp_channel_flow_ok;
Tamqp_channel_close = record
reply_code: uint16_t; (**< reply-code *)
reply_text: Tamqp_bytes; (**< reply-text *)
class_id: uint16_t; (**< class-id *)
method_id: uint16_t; (**< method-id *)
end;
Pamqp_channel_close = ^Tamqp_channel_close;
Tamqp_channel_close_ok = record
dummy: AMQPchar; (**< Dummy field to avoid empty struct *)
end;
Pamqp_channel_close_ok = ^Tamqp_channel_close_ok;
Tamqp_access_request = record
realm : Tamqp_bytes;
exclusive,
passive,
active,
write,
read : amqp_boolean_t;
end;
Pamqp_access_request = ^Tamqp_access_request;
Tamqp_access_request_ok = record
ticket: uint16_t; (**< ticket *)
end;
Pamqp_access_request_ok = ^Tamqp_access_request_ok;
Tamqp_exchange_declare = record
ticket : uint16;
exchange,
&type : Tamqp_bytes;
passive,
durable,
auto_delete,
internal,
nowait : amqp_boolean_t;
arguments : Tamqp_table;
end;
Pamqp_exchange_declare = ^Tamqp_exchange_declare;
Tamqp_exchange_declare_ok = record
dummy: AMQPchar; (**< Dummy field to avoid empty struct *)
end;
Pamqp_exchange_declare_ok = ^Tamqp_exchange_declare_ok;
Tamqp_exchange_delete = record
ticket : uint16;
exchange : Tamqp_bytes;
if_unused,
nowait : amqp_boolean_t;
end;
Pamqp_exchange_delete = ^Tamqp_exchange_delete;
Tamqp_exchange_delete_ok = record
dummy: AMQPchar; (**< Dummy field to avoid empty struct *)
end;
Pamqp_exchange_delete_ok = ^Tamqp_exchange_delete_ok;
Tamqp_exchange_bind = record
ticket : uint16;
destination,
source,
routing_key : Tamqp_bytes;
nowait : amqp_boolean_t;
arguments : Tamqp_table;
end;
Pamqp_exchange_bind = ^Tamqp_exchange_bind;
Tamqp_exchange_bind_ok = record
dummy: AMQPchar; (**< Dummy field to avoid empty struct *)
end;
Pamqp_exchange_bind_ok = ^Tamqp_exchange_bind_ok;
Tamqp_exchange_unbind = record
ticket : uint16;
destination,
source,
routing_key : Tamqp_bytes;
nowait : amqp_boolean_t;
arguments : Tamqp_table;
end;
Pamqp_exchange_unbind = ^Tamqp_exchange_unbind;
Tamqp_exchange_unbind_ok = record
dummy: AMQPchar ;
end;
Pamqp_exchange_unbind_ok = ^Tamqp_exchange_unbind_ok;
Tamqp_queue_declare = record
ticket : uint16;
queue : Tamqp_bytes;
passive,
durable,
exclusive,
auto_delete,
nowait : amqp_boolean_t;
arguments : Tamqp_table;
end;
Pamqp_queue_declare = ^Tamqp_queue_declare;
Tamqp_queue_declare_ok = record
queue : Tamqp_bytes;
message_count,
consumer_count : uint32;
end;
Pamqp_queue_declare_ok = ^Tamqp_queue_declare_ok;
Tamqp_queue_bind = record
ticket : uint16;
queue,
exchange,
routing_key : Tamqp_bytes;
nowait : amqp_boolean_t;
arguments : Tamqp_table;
end;
Pamqp_queue_bind = ^Tamqp_queue_bind;
Tamqp_queue_bind_ok = record
dummy: AMQPchar ; (**< Dummy field to avoid empty struct *)
end;
Pamqp_queue_bind_ok = ^Tamqp_queue_bind_ok;
Tamqp_queue_purge = record
ticket : uint16;
queue : Tamqp_bytes;
nowait : amqp_boolean_t;
end;
Pamqp_queue_purge = ^Tamqp_queue_purge;
Tamqp_queue_purge_ok = record
message_count: uint32_t;
end;
Pamqp_queue_purge_ok = ^Tamqp_queue_purge_ok;
Tamqp_queue_delete = record
ticket : uint16;
queue : Tamqp_bytes;
if_unused,
if_empty,
nowait : amqp_boolean_t;
end;
Pamqp_queue_delete = ^Tamqp_queue_delete;
Tamqp_queue_delete_ok = record
message_count: uint32_t;
end;
Pamqp_queue_delete_ok = ^Tamqp_queue_delete_ok;
Tamqp_queue_unbind = record
ticket : uint16;
queue,
exchange,
routing_key : Tamqp_bytes;
arguments : Tamqp_table;
end;
Pamqp_queue_unbind = ^Tamqp_queue_unbind;
Tamqp_queue_unbind_ok = record
dummy: AMQPchar ; (**< Dummy field to avoid empty struct *)
end;
Pamqp_queue_unbind_ok = ^Tamqp_queue_unbind;
Tamqp_basic_qos = record
prefetch_size : uint32;
prefetch_count : uint16;
global : amqp_boolean_t;
end;
Pamqp_basic_qos = ^Tamqp_basic_qos;
Tamqp_basic_qos_ok = record
dummy: AMQPchar; (**< Dummy field to avoid empty struct *)
end;
Pamqp_basic_qos_ok = ^Tamqp_basic_qos_ok;
Tamqp_basic_consume = record
ticket : uint16;
queue,
consumer_tag : Tamqp_bytes;
no_local,
no_ack,
exclusive,
nowait : amqp_boolean_t;
arguments : Tamqp_table;
end;
Pamqp_basic_consume = ^Tamqp_basic_consume;
Tamqp_basic_consume_ok = record
consumer_tag: Tamqp_bytes; (**< consumer-tag *)
end;
Pamqp_basic_consume_ok = ^Tamqp_basic_consume_ok;
Tamqp_basic_cancel = record
consumer_tag : Tamqp_bytes;
nowait : amqp_boolean_t;
end;
Pamqp_basic_cancel = ^Tamqp_basic_cancel;
Tamqp_basic_cancel_ok = record
consumer_tag: Tamqp_bytes; (**< consumer-tag *)
end;
Pamqp_basic_cancel_ok = ^Tamqp_basic_cancel_ok;
Tamqp_basic_publish = record
ticket : uint16;
exchange,
routing_key : Tamqp_bytes;
mandatory,
immediate : amqp_boolean_t;
end;
Pamqp_basic_publish = ^Tamqp_basic_publish;
Tamqp_basic_return = record
reply_code : uint16;
reply_text,
exchange,
routing_key : Tamqp_bytes;
end;
Pamqp_basic_return = ^Tamqp_basic_return;
Tamqp_basic_deliver = record
consumer_tag : Tamqp_bytes;
delivery_tag : uint64;
redelivered : amqp_boolean_t;
exchange,
routing_key : Tamqp_bytes;
end;
Pamqp_basic_deliver = ^Tamqp_basic_deliver;
Tamqp_basic_get = record
ticket : uint16;
queue : Tamqp_bytes;
no_ack : amqp_boolean_t;
end;
Pamqp_basic_get = ^Tamqp_basic_get;
Tamqp_basic_get_ok = record
delivery_tag : uint64;
redelivered : amqp_boolean_t;
exchange,
routing_key : Tamqp_bytes;
message_count : uint32;
end;
Pamqp_basic_get_ok = ^Tamqp_basic_get_ok;
Tamqp_basic_get_empty = record
cluster_id: Tamqp_bytes; (**< cluster-id *)
end;
Pamqp_basic_get_empty = ^Tamqp_basic_get_empty;
Tamqp_basic_ack = record
delivery_tag : uint64;
multiple : amqp_boolean_t;
end;
Pamqp_basic_ack = ^Tamqp_basic_ack;
Tamqp_basic_reject = record
delivery_tag : uint64;
requeue : amqp_boolean_t;
end;
Pamqp_basic_reject = ^Tamqp_basic_reject;
Tamqp_basic_recover_async = record
requeue: amqp_boolean_t;
end;
Pamqp_basic_recover_async = ^Tamqp_basic_recover_async;
Tamqp_basic_recover = record
requeue: amqp_boolean_t;
end;
Pamqp_basic_recover = ^Tamqp_basic_recover;
Tamqp_basic_recover_ok = record
dummy: AMQPchar;
end;
Pamqp_basic_recover_ok = ^Tamqp_basic_recover_ok;
Tamqp_basic_nack = record
delivery_tag : uint64;
multiple,
requeue : amqp_boolean_t;
end;
Pamqp_basic_nack = ^Tamqp_basic_nack;
Tamqp_tx_select = record
dummy: AMQPchar;
end;
Pamqp_tx_select = ^Tamqp_tx_select;
Tamqp_tx_select_ok = record
dummy: AMQPchar;
end;
Pamqp_tx_select_ok = ^Tamqp_tx_select_ok;
Tamqp_tx_commit= record
dummy: AMQPchar;
end;
Pamqp_tx_commit = ^Tamqp_tx_commit;
Tamqp_tx_commit_ok = record
dummy: AMQPchar;
end;
Pamqp_tx_commit_ok = ^Tamqp_tx_commit_ok;
Tamqp_tx_rollback = record
dummy: AMQPchar;
end;
Pamqp_tx_rollback = ^Tamqp_tx_rollback;
Tamqp_tx_rollback_ok= record
dummy: AMQPchar;
end;
Pamqp_tx_rollback_ok = ^Tamqp_tx_rollback_ok;
Tamqp_confirm_select = record
nowait: amqp_boolean_t;
end;
Pamqp_confirm_select = ^Tamqp_confirm_select;
Tamqp_confirm_select_ok= record
dummy: AMQPchar;
end;
Pamqp_confirm_select_ok = ^Tamqp_confirm_select_ok;
Tamqp_basic_properties = record
_flags : amqp_flags_t;
content_type,
content_encoding : Tamqp_bytes;
headers : Tamqp_table;
delivery_mode,
priority : byte;
correlation_id,
reply_to,
expiration,
message_id : Tamqp_bytes;
timestamp : uint64;
&type,
user_id,
app_id,
cluster_id : Tamqp_bytes;
function Clone(out AClone : Tamqp_basic_properties;
pool : Pamqp_pool):integer;
end;
Pamqp_basic_properties = ^Tamqp_basic_properties;
Tamqp_connection_properties = record
_flags: amqp_flags_t;
dummy: AMQPchar ;
end;
Pamqp_connection_properties = ^Tamqp_connection_properties;
Tamqp_channel_properties = record
_flags: amqp_flags_t;
dummy: AMQPchar ;
end;
Pamqp_channel_properties = ^Tamqp_channel_properties;
Tamqp_access_properties= record
_flags: amqp_flags_t;
dummy: AMQPchar ;
end;
Pamqp_access_properties = ^Tamqp_access_properties;
Tamqp_exchange_properties= record
_flags: amqp_flags_t;
dummy: AMQPchar ;
end;
Pamqp_exchange_properties = ^Tamqp_exchange_properties;
Tamqp_queue_properties= record
_flags: amqp_flags_t;
dummy: AMQPchar ;
end;
Pamqp_queue_properties = ^Tamqp_queue_properties;
Tamqp_tx_properties= record
_flags: amqp_flags_t;
dummy: AMQPchar ;
end;
Pamqp_tx_properties = ^Tamqp_tx_properties;
Tamqp_confirm_properties= record
_flags: amqp_flags_t;
dummy: AMQPchar ;
end;
Pamqp_confirm_properties = ^Tamqp_confirm_properties;
Tamqp_message = record
properties: Tamqp_basic_properties; (**< message properties *)
body: Tamqp_bytes; (**< message body *)
pool: Tamqp_pool; (**< pool used to allocate properties *)
procedure Destroy;
end;
Pamqp_message = ^Tamqp_message;
Tamqp_envelope = record
channel : amqp_channel_t;
consumer_tag : Tamqp_bytes;
delivery_tag : uint64;
redelivered : amqp_boolean_t;
exchange,
routing_key : Tamqp_bytes;
&message : Tamqp_message;
procedure destroy;
end;
Pamqp_envelope = ^Tamqp_envelope;
Terror_category_enum = ( EC_base = 0, EC_tcp = 1, EC_ssl = 2 );
Tamqp_table_entry = record
key: Tamqp_bytes; (**< the table entry key. Its a null-terminated UTF-8
* string, with a maximum size of 128 bytes *)
value: Tamqp_field_value; (**< the table entry values *)
constructor Create(const Akey : PAnsiChar; const Avalue : integer); overload;
constructor Create(const Akey : PAnsiChar; const Avalue : PAnsiChar); overload;
constructor Create(const Akey : PAnsiChar; const Avalue : Tamqp_table); overload;
function clone(out Aclone : Tamqp_table_entry; pool : Pamqp_pool):integer;
end;
var
amqp_empty_bytes: Tamqp_bytes;
amqp_empty_array: Tamqp_array;
amqp_empty_table: Tamqp_table;
gLevel: Integer;
const
AMQP_VERSION_STRING = '0.9.1';
AMQ_PLATFORM = 'win32/64';
AMQ_COPYRIGHT = 'softwind';
AMQP_PROTOCOL_VERSION_MAJOR = 0; (**< AMQP protocol version major *)
AMQP_PROTOCOL_VERSION_MINOR = 9; (**< AMQP protocol version minor *)
AMQP_PROTOCOL_VERSION_REVISION = 1; (**< AMQP protocol version revision \
*)
AMQP_PROTOCOL_PORT =5672; (**< Default AMQP Port *)
AMQP_FRAME_METHOD =1; (**< Constant: FRAME-METHOD *)
AMQP_FRAME_HEADER =2; (**< Constant: FRAME-HEADER *)
AMQP_FRAME_BODY =3; (**< Constant: FRAME-BODY *)
AMQP_FRAME_HEARTBEAT =8; (**< Constant: FRAME-HEARTBEAT *)
AMQP_FRAME_MIN_SIZE =4096; (**< Constant: FRAME-MIN-SIZE *)
AMQP_FRAME_END =206; (**< Constant: FRAME-END *)
AMQP_REPLY_SUCCESS =200; (**< Constant: REPLY-SUCCESS *)
AMQP_CONTENT_TOO_LARGE =311; (**< Constant: CONTENT-TOO-LARGE *)
AMQP_NO_ROUTE =312; (**< Constant: NO-ROUTE *)
AMQP_NO_CONSUMERS =313; (**< Constant: NO-CONSUMERS *)
AMQP_ACCESS_REFUSED =403; (**< Constant: ACCESS-REFUSED *)
AMQP_NOT_FOUND =404; (**< Constant: NOT-FOUND *)
AMQP_RESOURCE_LOCKED =405; (**< Constant: RESOURCE-LOCKED *)
AMQP_PRECONDITION_FAILED =406; (**< Constant: PRECONDITION-FAILED *)
AMQP_CONNECTION_FORCED =320; (**< Constant: CONNECTION-FORCED *)
AMQP_INVALID_PATH =402; (**< Constant: INVALID-PATH *)
AMQP_FRAME_ERROR =501; (**< Constant: FRAME-ERROR *)
AMQP_SYNTAX_ERROR =502; (**< Constant: SYNTAX-ERROR *)
AMQP_COMMAND_INVALID =503; (**< Constant: COMMAND-INVALID *)
AMQP_CHANNEL_ERROR =504; (**< Constant: CHANNEL-ERROR *)
AMQP_UNEXPECTED_FRAME =505; (**< Constant: UNEXPECTED-FRAME *)
AMQP_RESOURCE_ERROR =506; (**< Constant: RESOURCE-ERROR *)
AMQP_NOT_ALLOWED =530; (**< Constant: NOT-ALLOWED *)
AMQP_NOT_IMPLEMENTED =540; (**< Constant: NOT-IMPLEMENTED *)
AMQP_INTERNAL_ERROR =541; (**< Constant: INTERNAL-ERROR *)
AMQP_CONNECTION_START_METHOD = amqp_method_number_t($000A000A); (**< connection.start method id @internal \
10, 10; 655370 *)
AMQP_CONNECTION_START_OK_METHOD = amqp_method_number_t($000A000B); (**< connection.start-ok method id \
@internal 10, 11; 655371 *)
AMQP_CONNECTION_SECURE_METHOD = amqp_method_number_t($000A0014); (**< connection.secure method id \
@internal 10, 20; 655380 *)
AMQP_CONNECTION_SECURE_OK_METHOD = amqp_method_number_t($000A0015); (**< connection.secure-ok method id \
@internal 10, 21; 655381 *)
AMQP_CONNECTION_BLOCKED_METHOD = amqp_method_number_t($000A003C); (**< connection.blocked method id \
@internal 10, 60; 655420 *)
AMQP_CONNECTION_TUNE_METHOD = amqp_method_number_t($000A001E); (**< connection.tune method id @internal \
10, 30; 655390 *)
AMQP_CONNECTION_TUNE_OK_METHOD = amqp_method_number_t($000A001F); (**< connection.tune-ok method id \
@internal 10, 31; 655391 *)
AMQP_CONNECTION_OPEN_METHOD = amqp_method_number_t($000A0028); (**< connection.open method id @internal \
10, 40; 655400 *)
AMQP_CONNECTION_OPEN_OK_METHOD = amqp_method_number_t($000A0029); (**< connection.open-ok method id \
@internal 10, 41; 655401 *)
AMQP_CONNECTION_CLOSE_METHOD = amqp_method_number_t($000A0032); (**< connection.close method id @internal \
10, 50; 655410 *)
AMQP_CONNECTION_CLOSE_OK_METHOD = amqp_method_number_t($000A0033); (**< connection.close-ok method id \
@internal 10, 51; 655411 *)
AMQP_CONNECTION_UNBLOCKED_METHOD = amqp_method_number_t($000A003D); (**< connection.unblocked method id \
@internal 10, 61; 655421 *)
AMQP_CONNECTION_UPDATE_SECRET_METHOD = amqp_method_number_t($000A0046); (**< connection.update-secret method id \
@internal 10, 70; 655430 *)
AMQP_CONNECTION_UPDATE_SECRET_OK_METHOD = amqp_method_number_t($000A0047); (**< connection.update-secret-ok method \
id @internal 10, 71; 655431 *)
AMQP_CHANNEL_OPEN_METHOD = amqp_method_number_t($0014000A); (**< channel.open method id @internal 20, \
10; 1310730 *)
AMQP_CHANNEL_OPEN_OK_METHOD = amqp_method_number_t($0014000B); (**< channel.open-ok method id @internal \
20, 11; 1310731 *)
AMQP_CHANNEL_FLOW_METHOD = amqp_method_number_t($00140014); (**< channel.flow method id @internal 20, \
20; 1310740 *)
AMQP_CHANNEL_FLOW_OK_METHOD = amqp_method_number_t($00140015); (**< channel.flow-ok method id @internal \
20, 21; 1310741 *)
AMQP_CHANNEL_CLOSE_METHOD = amqp_method_number_t($00140028); (**< channel.close method id @internal \
20, 40; 1310760 *)
AMQP_CHANNEL_CLOSE_OK_METHOD = amqp_method_number_t($00140029); (**< channel.close-ok method id @internal \
20, 41; 1310761 *)
AMQP_ACCESS_REQUEST_METHOD = amqp_method_number_t($001E000A); (**< access.request method id @internal \
30, 10; 1966090 *)
AMQP_ACCESS_REQUEST_OK_METHOD = amqp_method_number_t($001E000B); (**< access.request-ok method id \
@internal 30, 11; 1966091 *)
AMQP_EXCHANGE_DECLARE_METHOD = amqp_method_number_t($0028000A); (**< exchange.declare method id @internal \
40, 10; 2621450 *)
AMQP_EXCHANGE_DECLARE_OK_METHOD = amqp_method_number_t($0028000B); (**< exchange.declare-ok method id \
@internal 40, 11; 2621451 *)
AMQP_EXCHANGE_DELETE_METHOD = amqp_method_number_t($00280014); (**< exchange.delete method id @internal \
40, 20; 2621460 *)
AMQP_EXCHANGE_DELETE_OK_METHOD = amqp_method_number_t($00280015); (**< exchange.delete-ok method id \
@internal 40, 21; 2621461 *)
AMQP_EXCHANGE_BIND_METHOD = amqp_method_number_t($0028001E); (**< exchange.bind method id @internal \
40, 30; 2621470 *)
AMQP_EXCHANGE_BIND_OK_METHOD = amqp_method_number_t($0028001F); (**< exchange.bind-ok method id @internal \
40, 31; 2621471 *)
AMQP_EXCHANGE_UNBIND_METHOD = amqp_method_number_t($00280028); (**< exchange.unbind method id @internal \
40, 40; 2621480 *)
AMQP_EXCHANGE_UNBIND_OK_METHOD = amqp_method_number_t($00280033); (**< exchange.unbind-ok method id \
@internal 40, 51; 2621491 *)
AMQP_QUEUE_DECLARE_METHOD = amqp_method_number_t($0032000A); (**< queue.declare method id @internal \
50, 10; 3276810 *)
AMQP_QUEUE_DECLARE_OK_METHOD = amqp_method_number_t($0032000B); (**< queue.declare-ok method id @internal \
50, 11; 3276811 *)
AMQP_QUEUE_BIND_METHOD = amqp_method_number_t($00320014); (**< queue.bind method id @internal 50, \
20; 3276820 *)
AMQP_QUEUE_BIND_OK_METHOD = amqp_method_number_t($00320015); (**< queue.bind-ok method id @internal \
50, 21; 3276821 *)
AMQP_QUEUE_PURGE_METHOD = amqp_method_number_t($0032001E); (**< queue.purge method id @internal 50, \
30; 3276830 *)
AMQP_QUEUE_PURGE_OK_METHOD = amqp_method_number_t($0032001F); (**< queue.purge-ok method id @internal \
50, 31; 3276831 *)
AMQP_QUEUE_DELETE_METHOD = amqp_method_number_t($00320028); (**< queue.delete method id @internal 50, \
40; 3276840 *)
AMQP_QUEUE_DELETE_OK_METHOD = amqp_method_number_t($00320029); (**< queue.delete-ok method id @internal \
50, 41; 3276841 *)
AMQP_QUEUE_UNBIND_METHOD = amqp_method_number_t($00320032); (**< queue.unbind method id @internal 50, \
50; 3276850 *)
AMQP_QUEUE_UNBIND_OK_METHOD = amqp_method_number_t($00320033); (**< queue.unbind-ok method id @internal \
50, 51; 3276851 *)
AMQP_BASIC_QOS_METHOD = amqp_method_number_t($003C000A); (**< basic.qos method id @internal 60, \
10; 3932170 *)
AMQP_BASIC_QOS_OK_METHOD = amqp_method_number_t($003C000B); (**< basic.qos-ok method id @internal 60, \
11; 3932171 *)
AMQP_BASIC_CONSUME_METHOD = amqp_method_number_t($003C0014); (**< basic.consume method id @internal \
60, 20; 3932180 *)
AMQP_BASIC_CONSUME_OK_METHOD = amqp_method_number_t($003C0015); (**< basic.consume-ok method id @internal \
60, 21; 3932181 *)
AMQP_BASIC_CANCEL_METHOD = amqp_method_number_t($003C001E); (**< basic.cancel method id @internal 60, \
30; 3932190 *)
AMQP_BASIC_CANCEL_OK_METHOD = amqp_method_number_t($003C001F); (**< basic.cancel-ok method id @internal \
60, 31; 3932191 *)
AMQP_BASIC_PUBLISH_METHOD = amqp_method_number_t($003C0028); (**< basic.publish method id @internal \
60, 40; 3932200 *)
AMQP_BASIC_RETURN_METHOD = amqp_method_number_t($003C0032); (**< basic.return method id @internal 60, \
50; 3932210 *)
AMQP_BASIC_DELIVER_METHOD = amqp_method_number_t($003C003C); (**< basic.deliver method id @internal \
60, 60; 3932220 *)
AMQP_BASIC_GET_METHOD = amqp_method_number_t($003C0046); (**< basic.get method id @internal 60, \
70; 3932230 *)
AMQP_BASIC_GET_OK_METHOD = amqp_method_number_t($003C0047); (**< basic.get-ok method id @internal 60, \
71; 3932231 *)
AMQP_BASIC_GET_EMPTY_METHOD = amqp_method_number_t($003C0048); (**< basic.get-empty method id @internal \
60, 72; 3932232 *)
AMQP_BASIC_ACK_METHOD = amqp_method_number_t($003C0050); (**< basic.ack method id @internal 60, \
80; 3932240 *)
AMQP_BASIC_REJECT_METHOD = amqp_method_number_t($003C005A); (**< basic.reject method id @internal 60, \
90; 3932250 *)
AMQP_BASIC_RECOVER_ASYNC_METHOD = amqp_method_number_t($003C0064); (**< basic.recover-async method id \
@internal 60, 100; 3932260 *)
AMQP_BASIC_RECOVER_METHOD = amqp_method_number_t($003C006E); (**< basic.recover method id @internal \
60, 110; 3932270 *)
AMQP_BASIC_RECOVER_OK_METHOD = amqp_method_number_t($003C006F); (**< basic.recover-ok method id @internal \
60, 111; 3932271 *)
AMQP_BASIC_NACK_METHOD = amqp_method_number_t($003C0078); (**< basic.nack method id @internal 60, \
120; 3932280 *)
AMQP_TX_SELECT_METHOD = amqp_method_number_t($005A000A); (**< tx.select method id @internal 90, \
10; 5898250 *)
AMQP_TX_SELECT_OK_METHOD = amqp_method_number_t($005A000B); (**< tx.select-ok method id @internal 90, \
11; 5898251 *)
AMQP_TX_COMMIT_METHOD = amqp_method_number_t($005A0014); (**< tx.commit method id @internal 90, \
20; 5898260 *)
AMQP_TX_COMMIT_OK_METHOD = amqp_method_number_t($005A0015); (**< tx.commit-ok method id @internal 90, \
21; 5898261 *)
AMQP_TX_ROLLBACK_METHOD = amqp_method_number_t($005A001E); (**< tx.rollback method id @internal 90, \
30; 5898270 *)
AMQP_TX_ROLLBACK_OK_METHOD = amqp_method_number_t($005A001F); (**< tx.rollback-ok method id @internal \
90, 31; 5898271 *)
AMQP_CONFIRM_SELECT_METHOD = amqp_method_number_t($0055000A); (**< confirm.select method id @internal \
85, 10; 5570570 *)
AMQP_CONFIRM_SELECT_OK_METHOD = amqp_method_number_t($0055000B); (**< confirm.select-ok method id \
@internal 85, 11; 5570571 *)
AMQP_BASIC_CLASS = ($003C) ;(**< basic class id @internal 60 *)
AMQP_BASIC_CONTENT_TYPE_FLAG = (1 shl 15) ;(**< basic.content-type property flag *)
AMQP_BASIC_CONTENT_ENCODING_FLAG = (1 shl 14) ;(**< basic.content-encoding property flag *)
AMQP_BASIC_HEADERS_FLAG = (1 shl 13) ;(**< basic.headers property flag *)
AMQP_BASIC_DELIVERY_MODE_FLAG = (1 shl 12) ;(**< basic.delivery-mode property flag *)
AMQP_BASIC_PRIORITY_FLAG = (1 shl 11) ;(**< basic.priority property flag =
*)
AMQP_BASIC_CORRELATION_ID_FLAG = (1 shl 10) ;(**< basic.correlation-id property flag *)
AMQP_BASIC_REPLY_TO_FLAG = (1 shl 9) ;(**< basic.reply-to property flag *)
AMQP_BASIC_EXPIRATION_FLAG = (1 shl 8) ;(**< basic.expiration property flag *)
AMQP_BASIC_MESSAGE_ID_FLAG = (1 shl 7) ;(**< basic.message-id property flag *)
AMQP_BASIC_TIMESTAMP_FLAG = (1 shl 6) ;(**< basic.timestamp property flag =
*)
AMQP_BASIC_TYPE_FLAG = (1 shl 5) ;(**< basic.type property flag *)
AMQP_BASIC_USER_ID_FLAG = (1 shl 4) ;(**< basic.user-id property flag *)
AMQP_BASIC_APP_ID_FLAG = (1 shl 3) ;(**< basic.app-id property flag *)
AMQP_BASIC_CLUSTER_ID_FLAG = (1 shl 2) ;(**< basic.cluster-id property flag *)
ERROR_CATEGORY_MASK = ($FF00);
ERROR_MASK = $00FF;
unknown_error_string: PAnsiChar = '(unknown error)';
{$IFNDEF FPC}
{$if CompilerVersion <= 23}
base_error_strings: array[0..20] of PAnsiChar = (
{$else}
base_error_strings: array of PAnsiChar = [
{$ifend}
{$ELSE}
base_error_strings: array[0..20] of PAnsiChar = (
{$ENDIF}
(* AMQP_STATUS_OK 0x0 *)
'operation completed successfully',
(* AMQP_STATUS_NO_MEMORY -0x0001 *)
'could not allocate memory',
(* AMQP_STATUS_BAD_AQMP_DATA -0x0002 *)
'invalid AMQP data',
(* AMQP_STATUS_UNKNOWN_CLASS -0x0003 *)
'unknown AMQP class id',
(* AMQP_STATUS_UNKNOWN_METHOD -0x0004 *)
'unknown AMQP method id',
(* AMQP_STATUS_HOSTNAME_RESOLUTION_FAILED -0x0005 *)
'hostname lookup failed',
(* AMQP_STATUS_INCOMPATIBLE_AMQP_VERSION -0x0006 *)
'incompatible AMQP version',
(* AMQP_STATUS_CONNECTION_CLOSED -0x0007 *)
'connection closed unexpectedly',
(* AMQP_STATUS_BAD_AMQP_URL -0x0008 *)
'could not parse AMQP URL',
(* AMQP_STATUS_SOCKET_ERROR -0x0009 *)
'a socket error occurred',
(* AMQP_STATUS_INVALID_PARAMETER -0x000A *)
'invalid parameter',
(* AMQP_STATUS_TABLE_TOO_BIG -0x000B *)
'table too large for buffer',
(* AMQP_STATUS_WRONG_METHOD -0x000C *)
'unexpected method received',
(* AMQP_STATUS_TIMEOUT -0x000D *)
'request timed out',
(* AMQP_STATUS_TIMER_FAILED -0x000E *)
'system timer has failed',
(* AMQP_STATUS_HEARTBEAT_TIMEOUT -0x000F *)
'heartbeat timeout, connection closed',
(* AMQP_STATUS_UNEXPECTED STATE -0x0010 *)
'unexpected protocol state',
(* AMQP_STATUS_SOCKET_CLOSED -0x0011 *)
'socket is closed',
(* AMQP_STATUS_SOCKET_INUSE -0x0012 *)
'socket already open',
(* AMQP_STATUS_BROKER_UNSUPPORTED_SASL_METHOD -0x00013 *)
'unsupported sasl method requested',
(* AMQP_STATUS_UNSUPPORTED -0x0014 *)
'parameter value is unsupported'
{$IFNDEF FPC}
{$if CompilerVersion <= 23} );{$else} ]; {$ifend}
{$ELSE} ); {$ENDIF}
{$IFNDEF FPC}
{$if CompilerVersion <= 23}
tcp_error_strings: array[0..1] of PAnsiChar = (
{$else}
tcp_error_strings: array of PAnsiChar = [
{$ifend}
{$ELSE}
tcp_error_strings: array[0..1] of PAnsiChar = (
{$ENDIF}
(* AMQP_STATUS_TCP_ERROR -0x0100 *)
'a socket error occurred',
(* AMQP_STATUS_TCP_SOCKETLIB_INIT_ERROR -0x0101 *)
'socket library initialization failed'
{$IFNDEF FPC}
{$if CompilerVersion <= 23} );{$else} ]; {$ifend}
{$ELSE} ); {$ENDIF}
{$IFNDEF FPC}
{$if CompilerVersion <= 23}
ssl_error_strings: array[0..4] of PAnsiChar =(
{$else}
ssl_error_strings: array of PAnsiChar =[
{$ifend}
{$ELSE}
ssl_error_strings: array[0..4] of PAnsiChar =(
{$ENDIF}
(* AMQP_STATUS_SSL_ERROR -0x0200 *)
'a SSL error occurred',
(* AMQP_STATUS_SSL_HOSTNAME_VERIFY_FAILED -0x0201 *)
'SSL hostname verification failed',
(* AMQP_STATUS_SSL_PEER_VERIFY_FAILED -0x0202 *)
'SSL peer cert verification failed',
(* AMQP_STATUS_SSL_CONNECTION_FAILED -0x0203 *)
'SSL handshake failed',
(* AMQP_STATUS_SSL_SET_ENGINE_FAILED -0x0204 *)
'SSL setting engine failed'
{$IFNDEF FPC}
{$if CompilerVersion <= 23} );{$else} ]; {$ifend}
{$ELSE} ); {$ENDIF}
function htobe16(x: Word): uint16;
function htobe32(x: Cardinal): Uint32;
function htobe64(x: Uint64): Uint64;
function calloc(Anum, ASize: Integer): Pointer;
function malloc(Size: NativeInt): Pointer;
procedure Free(P: Pointer);
procedure memset(var X; Value: Integer; Count: NativeInt );
procedure DebugOut(const ALevel: Integer; const AOutStr: String);
procedure memcpy(dest: Pointer; const source: Pointer; count: Integer);
procedure die_on_amqp_error( x : Tamqp_rpc_reply; const context: PAnsiChar);
function amqp_error_string2( code : integer):PAnsiChar;
procedure die_on_error( x : integer; const context: PAnsiChar);
function now_microseconds:uint64;
implementation
function Tamqp_connection_state.get_or_create_channel_pool(channel : amqp_channel_t):Pamqp_pool;
var
Lentry : Pamqp_pool_table_entry;
Lindex : size_t;
Level: int;
begin
Inc(gLevel);
Level := gLevel;
Lindex := channel mod POOL_TABLE_SIZE;
Lentry := Self.pool_table[Lindex];
while nil <> Lentry do
begin
if channel = Lentry.channel then
Exit(@Lentry.pool);
Lentry := Lentry.next;
end;
Lentry := malloc(sizeof(Tamqp_pool_table_entry));
if nil = Lentry then
Exit(nil);
Lentry.channel := channel;
Lentry.next := Self.pool_table[Lindex];
Self.pool_table[Lindex] := Lentry;
{$IFDEF _DEBUG_}
DebugOut(Level, 'step into amqp.mem::init_amqp_pool==>');
{$ENDIF}
//init_amqp_pool(@Lentry.pool, Self.frame_max);
Lentry.pool.Create(Self.frame_max);
{$IFDEF _DEBUG_}
DebugOut(Level, 'step over amqp.mem::init_amqp_pool.');
{$ENDIF}
Result := @Lentry.pool;
end;
function Tamqp_connection_state.get_channel_pool(channel : amqp_channel_t):Pamqp_pool;
var
entry : Pamqp_pool_table_entry;
index : size_t;
begin
index := channel mod POOL_TABLE_SIZE;
entry := Self.pool_table[index];
while nil <> entry do
begin
if channel = entry.channel then
Exit(@entry.pool);
entry := entry.next
end;
Result := nil;
end;
function Tamqp_socket.open( host : PAnsiChar; port : integer):integer;
begin
assert(@self<>nil);
assert(Assigned(self.klass.open));
Result := self.klass.open(@self, host, port, nil);
end;
function Tamqp_socket.open_noblock(Ahost : PAnsiChar;
Aport : integer;const Atimeout: Ptimeval):integer;
begin
assert(@self <> nil);
assert(Assigned(self.klass.open));
Result := self.klass.open(@self, Ahost, Aport, Atimeout);
end;
function now_microseconds:uint64;
var
ft : TFILETIME;
begin
GetSystemTimeAsFileTime(ft);
Result := ( (uint64_t(ft.dwHighDateTime) shl 32) or uint64_t(ft.dwLowDateTime)) div
10;
end;
function Tamqp_basic_properties.Clone(out AClone : Tamqp_basic_properties;
pool : Pamqp_pool):integer;
var
res : integer;
function Clone_BYTES_POOL(const ASelf: Tamqp_bytes; out AClone: Tamqp_bytes; pool: Pamqp_pool): int;
begin
if 0 = ASelf.len then
AClone := amqp_empty_bytes
else
begin
pool.alloc_bytes( ASelf.len, AClone);
if nil = AClone.bytes then
Exit(Int(AMQP_STATUS_NO_MEMORY));
memcpy(AClone.bytes, ASelf.bytes, AClone.len);
end;
end;
begin
memset(AClone, 0, sizeof(AClone));
AClone._flags := Self._flags;
if (AClone._flags and AMQP_BASIC_CONTENT_TYPE_FLAG)>0 then begin
Clone_BYTES_POOL(Self.content_type, AClone.content_type, pool)
end;
if (AClone._flags and AMQP_BASIC_CONTENT_ENCODING_FLAG)>0 then
Clone_BYTES_POOL(Self.content_encoding, AClone.content_encoding, pool);
if (AClone._flags and AMQP_BASIC_HEADERS_FLAG)>0 then
begin
res := Self.headers.Clone( AClone.headers, pool);
if Int(AMQP_STATUS_OK) <> res then
Exit(res);
end;
if (AClone._flags and AMQP_BASIC_DELIVERY_MODE_FLAG)>0 then
AClone.delivery_mode := Self.delivery_mode;
if (AClone._flags and AMQP_BASIC_PRIORITY_FLAG)>0 then
AClone.priority := Self.priority;
if (AClone._flags and AMQP_BASIC_CORRELATION_ID_FLAG)>0 then
Clone_BYTES_POOL(Self.correlation_id, AClone.correlation_id, pool);
if (AClone._flags and AMQP_BASIC_REPLY_TO_FLAG)>0 then
Clone_BYTES_POOL(Self.reply_to, AClone.reply_to, pool);
if (AClone._flags and AMQP_BASIC_EXPIRATION_FLAG)>0 then
Clone_BYTES_POOL(Self.expiration, AClone.expiration, pool);
if (AClone._flags and AMQP_BASIC_MESSAGE_ID_FLAG)>0 then
Clone_BYTES_POOL(Self.message_id, AClone.message_id, pool);
if (AClone._flags and AMQP_BASIC_TIMESTAMP_FLAG)>0 then
AClone.timestamp := Self.timestamp;
if (AClone._flags and AMQP_BASIC_TYPE_FLAG)>0 then ;
Clone_BYTES_POOL(Self.&type, AClone.&type, pool);
if (AClone._flags and AMQP_BASIC_USER_ID_FLAG)>0 then
Clone_BYTES_POOL(Self.user_id, AClone.user_id, pool);
if (AClone._flags and AMQP_BASIC_APP_ID_FLAG)>0 then
Clone_BYTES_POOL(Self.app_id, AClone.app_id, pool) ;
if (AClone._flags and AMQP_BASIC_CLUSTER_ID_FLAG)>0 then
Clone_BYTES_POOL(Self.cluster_id, AClone.cluster_id, pool);
Exit(Int(AMQP_STATUS_OK));
end;
function amqp_cstring_bytes( const cstr: PAnsiChar):Tamqp_bytes;
begin
result.len := Length(cstr);
result.bytes := PAMQPChar(cstr);
end;
function Tamqp_table.get_entry_by_key(const key : Tamqp_bytes): Pamqp_table_entry;
var
i : integer;
begin
{$POINTERMATH ON}
for i := 0 to num_entries-1 do
begin
if entries[i].key = key then
begin
Exit(@entries[i]);
end;
end;
Result := nil;
{$POINTERMATH OFF}
end;
function Tamqp_field_value.clone(out Aclone : Tamqp_field_value; pool : Pamqp_pool):integer;
var
i, res : integer;
begin
{$POINTERMATH ON}
Aclone.kind := Self.kind;
case Aclone.kind of
Byte(AMQP_FIELD_KIND_BOOLEAN):
Aclone.value.boolean := Self.value.boolean;
Byte(AMQP_FIELD_KIND_I8):
Aclone.value.i8 := Self.value.i8;
Byte(AMQP_FIELD_KIND_U8):
Aclone.value.u8 := Self.value.u8;
Byte(AMQP_FIELD_KIND_I16):
Aclone.value.i16 := Self.value.i16;
Byte(AMQP_FIELD_KIND_U16):
Aclone.value.u16 := Self.value.u16;
Byte(AMQP_FIELD_KIND_I32):
Aclone.value.i32 := Self.value.i32;
Byte(AMQP_FIELD_KIND_U32):
Aclone.value.u32 := Self.value.u32;
Byte(AMQP_FIELD_KIND_I64):
Aclone.value.i64 := Self.value.i64;
Byte(AMQP_FIELD_KIND_U64),
Byte(AMQP_FIELD_KIND_TIMESTAMP):
Aclone.value.u64 := Self.value.u64;
Byte(AMQP_FIELD_KIND_F32):
Aclone.value.f32 := Self.value.f32;
Byte(AMQP_FIELD_KIND_F64):
Aclone.value.f64 := Self.value.f64;
Byte(AMQP_FIELD_KIND_DECIMAL):
Aclone.value.decimal := Self.value.decimal;
Byte(AMQP_FIELD_KIND_UTF8),
Byte(AMQP_FIELD_KIND_BYTES):
begin
if 0 = Self.value.bytes.len then
Aclone.value.bytes := amqp_empty_bytes
else
begin
pool.alloc_bytes(Self.value.bytes.len,
Aclone.value.bytes);
if nil = Aclone.value.bytes.bytes then
Exit(Int(AMQP_STATUS_NO_MEMORY));
memcpy(Aclone.value.bytes.bytes, Self.value.bytes.bytes,
Aclone.value.bytes.len);
end;
end;
Byte(AMQP_FIELD_KIND_ARRAY):
begin
if nil = Self.value.&array.entries then
Aclone.value.&array := amqp_empty_array
else
begin
Aclone.value.&array.num_entries := Self.value.&array.num_entries;
Aclone.value.&array.entries := pool.alloc( Aclone.value.&array.num_entries * sizeof(Tamqp_field_value));
if nil = Aclone.value.&array.entries then
Exit(Int(AMQP_STATUS_NO_MEMORY));
for i := 0 to Aclone.value.&array.num_entries-1 do
begin
res := Self.value.&array.entries[i].clone(Aclone.value.&array.entries[i], pool);
if Int(AMQP_STATUS_OK) <> res then
Exit(res);
end;
end;
end;
Byte(AMQP_FIELD_KIND_TABLE):
Exit(Self.value.table.clone(Aclone.value.table, pool));
Byte(AMQP_FIELD_KIND_VOID):
begin
//
end;
else
Exit(Int(AMQP_STATUS_INVALID_PARAMETER));
end;
Result := Int(AMQP_STATUS_OK);
{$POINTERMATH OFF}
end;
(*********************************Tamqp_table_entry****************************)
//construct_utf8_entry
constructor Tamqp_table_entry.Create(const Akey , Avalue : PAnsiChar);
begin
key := amqp_cstring_bytes(Akey);
value.kind := Int(AMQP_FIELD_KIND_UTF8);
value.value.bytes := amqp_cstring_bytes(Avalue);
end;
//construct_bool_entry
constructor Tamqp_table_entry.Create(const Akey : PAnsiChar; const Avalue : integer);
begin
key := amqp_cstring_bytes(Akey);
value.kind := Int(AMQP_FIELD_KIND_BOOLEAN);
value.value.boolean := Avalue;
end;
//construct_table_entry
constructor Tamqp_table_entry.Create(const Akey : PAnsiChar; const Avalue : Tamqp_table);
begin
key := amqp_cstring_bytes(Akey);
value.kind := Int(AMQP_FIELD_KIND_TABLE);
value.value.table := Avalue;
end;
function Tamqp_table_entry.clone(out Aclone : Tamqp_table_entry; pool : Pamqp_pool):integer;
begin
if 0 = Self.key.len then
Exit(Int(AMQP_STATUS_INVALID_PARAMETER));
pool.alloc_bytes(Self.key.len, Aclone.key);
if nil = Aclone.key.bytes then
Exit(Int(AMQP_STATUS_NO_MEMORY));
memcpy(Aclone.key.bytes, Self.key.bytes, Aclone.key.len);
Result := Self.value.clone(Aclone.value, pool);
end;
function Tamqp_table.clone(out Aclone : Tamqp_table; pool : Pamqp_pool):integer;
var
i,
res : integer;
label error_out1 ;
begin
{$POINTERMATH ON}
Aclone.num_entries := Self.num_entries;
if 0 = Aclone.num_entries then
begin
Aclone := amqp_empty_table;
Exit(Int(AMQP_STATUS_OK));
end;
Aclone.entries := pool.alloc( Aclone.num_entries * sizeof(Tamqp_table_entry));
if nil = Aclone.entries then
Exit(Int(AMQP_STATUS_NO_MEMORY));
for i := 0 to Aclone.num_entries-1 do
begin
res := Self.entries[i].clone(Aclone.entries[i], pool);
if Int(AMQP_STATUS_OK) <> res then
goto error_out1;
end;
Exit(Int(AMQP_STATUS_OK));
error_out1:
Result := res;
{$POINTERMATH ON}
end;
(**********************************Tamqp_socket********************************)
procedure Tamqp_socket.delete;
begin
assert(Assigned(self.klass.delete));
self.klass.delete(@self);
end;
function Tamqp_socket.close(Aforce : Tamqp_socket_close_enum):integer;
begin
assert(@self <> nil);
assert(assigned(self.klass.close));
Result := self.klass.close(@self, Aforce);
end;
function Tamqp_socket.recv(Abuf: Pointer; Alen : size_t; Aflags : integer):ssize_t;
var Level: int;
begin
Inc(gLevel);
Level := gLevel;
assert(@self <> nil);
assert(Assigned(self.klass.recv));
{$IFDEF _DEBUG_}
DebugOut(Level, 'step into amqp.socket:: Aself.klass.recv==>');
{$ENDIF}
result := self.klass.recv(@self, Abuf, Alen, Aflags);
{$IFDEF _DEBUG_}
DebugOut(Level, 'step over amqp.socket::Aself.klass.recv, res=' + IntToStr(Result));
{$ENDIF}
end;
function Tamqp_socket.send(const Abuf: Pointer; Alen : size_t; Aflags : integer):ssize_t;
begin
assert(@self <> nil);
assert(Assigned(self.klass.send));
Result := self.klass.send(@self, Abuf, Alen, Aflags);
end;
class function Tamqp_time.infinite:Tamqp_time;
begin
Result.time_point_ns := UINT64_MAX;
end;
class operator Tamqp_time.equal( l, r : Tamqp_time):Boolean;
begin
if l.time_point_ns = r.time_point_ns then
Result := TRUE
else
Result := FALSE;
end;
procedure Tamqp_envelope.destroy;
begin
&message.Destroy;
routing_key.Destroy;
exchange.Destroy;
consumer_tag.Destroy;
end;
procedure Tamqp_message.destroy;
begin
pool.empty;
body.Destroy;
end;
procedure empty_blocklist(x : Pamqp_pool_blocklist);
var
i : integer;
begin
{$POINTERMATH ON}
if x.blocklist <> nil then
begin
for i := 0 to x.num_blocks-1 do
free(x.blocklist[i]);
Dispose(x.blocklist);
end;
x.num_blocks := 0;
x.blocklist := nil;
{$POINTERMATH OFF}
end;
procedure Tamqp_pool.recycle();
begin
empty_blocklist(@large_blocks);
next_page := 0;
alloc_block := nil;
alloc_used := 0;
end;
procedure Tamqp_pool.empty();
begin
recycle();
empty_blocklist(@pages);
end;
function record_pool_block(x : Pamqp_pool_blocklist; block: Pointer):integer;
var
blocklistlength : size_t;
newbl: Pointer;
begin
{$POINTERMATH ON}
blocklistlength := sizeof(Pointer) * (x.num_blocks + 1);
if x.blocklist = nil then
begin
x.blocklist := allocMem(blocklistlength);
if x.blocklist = nil then
Exit(0);
end
else
begin
//newbl := realloc(x.blocklist, blocklistlength);
reallocMem(x.blocklist, blocklistlength);
newbl := x.blocklist;
if newbl = nil then
Exit(0);
//x.blocklist := newbl;
end;
x.blocklist[x.num_blocks] := block;
Inc(x.num_blocks);
Result := 1;
{$POINTERMATH OFF}
end;
procedure Tamqp_pool.alloc_bytes(amount : size_t;out output : Tamqp_bytes);
begin
output.len := amount;
output.bytes := alloc(amount);
end;
function Tamqp_pool.alloc(amount : size_t): Pointer;
var
temp: size_t;
begin
{$POINTERMATH ON}
if amount = 0 then
Exit(nil);
amount := (amount + 7) and (not 7); { round up to nearest 8-byte boundary }
if amount > pagesize then
begin
//result1 := calloc(1, amount);
result := allocmem(1*amount);
if result = nil then
Exit(nil);
if 0= record_pool_block(@large_blocks, result )then
begin
freeMemory(result);
Exit(nil);
end;
Exit(result);
end;
if alloc_block <> nil then
begin
assert(alloc_used <= pagesize);
if alloc_used + amount <= pagesize then
begin
inc(alloc_block , alloc_used);
result := alloc_block;
alloc_used := alloc_used + amount;
Exit(result);
end;
end;
if next_page >= pages.num_blocks then
begin
alloc_block := AllocMem(1*pagesize);
if alloc_block = nil then
Exit(nil);
if 0= record_pool_block(@pages, alloc_block) then
Exit(nil);
next_page := pages.num_blocks;
end
else
begin
alloc_block := pages.blocklist[next_page];
Inc(next_page);
end;
alloc_used := amount;
Result := alloc_block;
{$POINTERMATH OFF}
end;
constructor Tamqp_pool.Create(pagesize : size_t);
begin
if pagesize > 0 then
self.pagesize := pagesize
else
self.pagesize := 4096;
self.pages.num_blocks := 0;
self.pages.blocklist := nil;
self.large_blocks.num_blocks := 0;
self.large_blocks.blocklist := nil;
self.next_page := 0;
self.alloc_block := nil;
self.alloc_used := 0;
end;
(*
//Delphi 10.4 Sydney 34 VER340
{$if CompilerVersion >= 34}
class operator Tamqp_bytes.Assign(var Dest: Tamqp_bytes; const [ref] Src: Tamqp_bytes);
begin
Dest.len := src.len;
Dest.bytes := malloc(src.len);
if Dest.bytes <> nil then
memcpy(Dest.bytes, src.bytes, src.len);
end;
{$ELSE} *)
class operator Tamqp_bytes.Implicit(src: Pamqp_bytes): Tamqp_bytes;
begin
Result.len := src.len;
Result.bytes := malloc(src.len);
if Result.bytes <> nil then
memcpy(Result.bytes, src.bytes, src.len);
end;
function Tamqp_bytes.malloc_dup_failed:integer;
begin
if (len <> 0) and (bytes = nil) then begin
Exit(1);
end;
Result := 0;
end;
procedure Tamqp_bytes.Destroy;
begin
free(bytes);
end;
constructor Tamqp_bytes.Create( Aname : PAnsiChar);
var
len: Integer;
begin
len := Length(Aname);
Self.len := len;
//Each byte in the allocated buffer is set to zero
bytes := AllocMem(len);
memcpy(bytes, Aname, len);
end;
constructor Tamqp_bytes.Create( amount : size_t);
begin
len := amount;
bytes := AllocMem(amount); { will return nil if it fails }
end;
class operator Tamqp_bytes.Equal(r, l: Tamqp_bytes) : Boolean;
begin
if l.len = r.len then
begin
if (l.bytes<>nil) and (r.bytes<>nil) then
begin
if CompareMem(l.bytes, r.bytes, l.len) then
Exit(true);
end;
end;
Result := False;
end;
procedure die_on_error( x : integer; const context: PAnsiChar);
begin
if x < 0 then begin
WriteLn(Format('%s: %s',[context, amqp_error_string2(x)]));
Halt(1);
end;
end;
function amqp_error_string2( code : integer):PAnsiChar;
var
category,
error : size_t;
error_string: PAnsiChar;
begin
category := (((-code) and ERROR_CATEGORY_MASK) shr 8);
error := (-code) and ERROR_MASK;
case category of
0://EC_base:
begin
if error < (sizeof(base_error_strings) div sizeof(PAMQPChar)) then
error_string := base_error_strings[error]
else
error_string := unknown_error_string;
end;
1://EC_tcp:
begin
if error < (sizeof(tcp_error_strings) div sizeof(PAMQPChar)) then
error_string := tcp_error_strings[error]
else
error_string := unknown_error_string;
end;
2://EC_ssl:
begin
if error < (sizeof(ssl_error_strings) div sizeof(PAMQPChar)) then
error_string := ssl_error_strings[error]
else
error_string := unknown_error_string;
end;
else
error_string := unknown_error_string;
end;
Result := error_string;
end;
procedure die_on_amqp_error( x : Tamqp_rpc_reply; const context: PAnsiChar);
var
stderr: string;
CONNECTION_CLOSE: Pamqp_connection_close;
CHANNEL_CLOSE: Pamqp_channel_close;
begin
case x.reply_type of
AMQP_RESPONSE_NORMAL:
exit;
AMQP_RESPONSE_NONE:
WriteLn(Format('%s: missing RPC reply type!',[context]));
AMQP_RESPONSE_LIBRARY_EXCEPTION:
WriteLn(Format('%s: %s',[context, amqp_error_string2(x.library_error)]));
AMQP_RESPONSE_SERVER_EXCEPTION:
case x.reply.id of
AMQP_CONNECTION_CLOSE_METHOD:
begin
CONNECTION_CLOSE := Pamqp_connection_close(x.reply.decoded);
stderr := Format( '%s: server connection error %uh, message: %.*s\n',
[context, CONNECTION_CLOSE.reply_code, CONNECTION_CLOSE.reply_text.len,
PAMQPChar(CONNECTION_CLOSE.reply_text.bytes)]);
WriteLn(stderr);
end;
AMQP_CHANNEL_CLOSE_METHOD:
begin
CHANNEL_CLOSE := Pamqp_channel_close(x.reply.decoded);
stderr := Format( '%s: server channel error %uh, message: %.*s\n',
[context, CHANNEL_CLOSE.reply_code, CHANNEL_CLOSE.reply_text.len,
PAMQPChar(CHANNEL_CLOSE.reply_text.bytes)]);
WriteLn(stderr);
end;
else
WriteLn(Format('%s: unknown server error, method id 0x%08X',[context, x.reply.id]));
end;
end;
Halt(1);
end;
function Tamqp_connection_state.get_sockfd:integer;
begin
if Assigned(Fsocket) and Assigned(Fsocket.klass.get_sockfd) then
Result := Fsocket.klass.get_sockfd(Fsocket)
else
Result := -1;
end;
procedure Tamqp_connection_state.set_socket(Asocket : Pamqp_socket);
begin
if Assigned(Fsocket) then
begin
assert(Assigned(Fsocket.klass.delete));
Fsocket.klass.delete(Fsocket);
end;
Fsocket := Asocket;
end;
function BinToString(const s: RawByteString): String;
begin
assert(length(s) mod SizeOf(result[1])=0);
setlength(result, length(s) div SizeOf(result[1]));
move(s[1], result[1], length(result)*SizeOf(result[1]));
end;
function StringToBin(const s: String): RawByteString;
begin
setlength(result, length(s)*SizeOf(s[1]));
move(s[1], result[1], length(result));
end;
procedure memcpy(Dest: Pointer; const source: Pointer; count: Integer);
begin
move(Source^,Dest^, Count);
end;
procedure DebugOut(const ALevel: Integer; const AOutStr: String);
var
I: int;
s1, s2, res: string;
begin
for I:= 1 to ALevel do
begin
s1 := s1 + ' ';
s2 := s2 + '#';
end;
Res := s2 + s1;
Writeln(res + AOutStr);
end;
procedure memset(var X; Value: Integer; Count: NativeInt );
begin
FillChar(X, Count, VALUE);
end;
procedure Free(P: Pointer);
begin
FreeMemory(P);
end;
function malloc(Size: NativeInt): Pointer;
begin
Result := AllocMem(Size);
end;
function calloc(Anum, ASize: Integer): Pointer;
begin
Result := AllocMem(Anum*ASize);
end;
function htobe16(x: Word): uint16;
begin
Result := htons(x);
end;
function htobe32(x: Cardinal): Uint32;
begin
Result := htonl(x);
end;
function htobe64(x: Uint64): Uint64;
begin
if 1=htonl(1) then
Result := (x)
else
Result := uint64_t(htonl(x and $FFFFFFFF) shl 32) or htonl(x shr 32);
end;
{var
intim,intim2:PInteger;
x:Integer;
begin
x := 0;
intim := AllocMem(SizeOf(Integer)*imsize);
intim2 := intim;
// dereference pointer intim2, store something, then increment pointer
intim2^ := x;
Inc(intim2);
FreeMem(intim);}
initialization
amqp_empty_bytes.len:=0; amqp_empty_bytes.bytes:= nil;
amqp_empty_array.num_entries:= 0; amqp_empty_array.entries:= nil;
amqp_empty_table.num_entries:= 0; amqp_empty_table.entries:= nil;
end.
|
unit dynarray_of_string_2;
interface
implementation
type
TItem = record
Key: string;
Value: Int32;
end;
var
FList: array of TItem;
procedure Add(const Str: string);
var
Len: Int32;
begin
Len := Length(FList);
SetLength(FList, Len + 1);
FList[Len].Key := Str;
FList[Len].Value := Len;
end;
procedure Test;
begin
Add('aaa');
Add('bbb');
Add('ccc');
end;
initialization
Test();
finalization
Assert(Length(FList) = 3);
Assert(FList[0].Key = 'aaa');
Assert(FList[1].Key = 'bbb');
Assert(FList[2].Key = 'ccc');
Assert(FList[0].Value = 0);
Assert(FList[1].Value = 1);
Assert(FList[2].Value = 2);
end. |
unit AdoxDumper;
(*
Dedicated to dumping ADOX structures.
Unlike DAO, ADOX does not store all individual fields in Properties.
We need to output both Properties and those individual fields which are not covered.
*)
interface
uses SysUtils, ComObj, ADOX_TLB, JetCommon;
procedure PrintAdoxSchema(adox: Catalog);
function AdoxDataTypeToStr(const t: DataTypeEnum): string;
function AdoxKeyTypeToStr(const t: KeyTypeEnum): string;
function AdoxRuleTypeToStr(const t: RuleEnum): string;
implementation
function AdoxDataTypeToStr(const t: DataTypeEnum): string;
begin
case t of
adEmpty: Result := 'Empty';
adTinyInt: Result := 'TinyInt';
adSmallInt: Result := 'SmallInt';
adInteger: Result := 'Integer';
adBigInt: Result := 'BigInt';
adUnsignedTinyInt: Result := 'UnsignedTinyInt';
adUnsignedSmallInt: Result := 'UnsignedSmallInt';
adUnsignedInt: Result := 'UnsignedInt';
adUnsignedBigInt: Result := 'UnsignedBigInt';
adSingle: Result := 'Single';
adDouble: Result := 'Double';
adCurrency: Result := 'Currency';
adDecimal: Result := 'Decimal';
adNumeric: Result := 'Numeric';
adBoolean: Result := 'Boolean';
adError: Result := 'Error';
adUserDefined: Result := 'UserDefined';
adVariant: Result := 'Variant';
adIDispatch: Result := 'IDispatch';
adIUnknown: Result := 'IUnknown';
adGUID: Result := 'GUID';
adDate: Result := 'Date';
adDBDate: Result := 'DBDate';
adDBTime: Result := 'DBTime';
adDBTimeStamp: Result := 'DBTimeStamp';
adBSTR: Result := 'BSTR';
adChar: Result := 'Char';
adVarChar: Result := 'VarChar';
adLongVarChar: Result := 'LongVarChar';
adWChar: Result := 'WChar';
adVarWChar: Result := 'VarWChar';
adLongVarWChar: Result := 'LongVarWChar';
adBinary: Result := 'Binary';
adVarBinary: Result := 'VarBinary';
adLongVarBinary: Result := 'LongVarBinary';
adChapter: Result := 'Chapter';
adFileTime: Result := 'FileTime';
adPropVariant: Result := 'PropVariant';
adVarNumeric: Result := 'VarNumeric';
else Result := '';
end;
if Result <> '' then
Result := Result + ' (' + IntToStr(t) + ')'
else
Result := IntToStr(t);
end;
type
TPropertyNames = array of WideString;
//Handy function for inplace array initialization
function PropNames(Names: array of WideString): TPropertyNames;
var i: integer;
begin
SetLength(Result, Length(Names));
for i := 0 to Length(Names) - 1 do
Result[i] := Names[i];
end;
function IsBanned(Banned: TPropertyNames; PropName: WideString): boolean;
var i: integer;
begin
Result := false;
for i := 0 to Length(Banned) - 1 do
if WideSameText(Banned[i], PropName) then begin
Result := true;
exit;
end;
end;
//Many ADOX objects have Properties
// Prop1=Value1
// Prop2=Value2 (inherited)
procedure DumpAdoxProperties(Props: Properties; Banned: TPropertyNames);
var i: integer;
prop: Property_;
proptype: integer;
propname: WideString;
propval: WideString;
propflags: WideString;
procedure AddPropFlag(flag: WideString);
begin
if propflags='' then
propflags := flag
else
propflags := ', ' + flag;
end;
begin
for i := 0 to Props.Count-1 do begin
prop := Props[i];
propname := prop.Name;
proptype := prop.type_;
//Some properties are unsupported in some objects, or take too long to query
if IsBanned(Banned, PropName) then begin
// writeln(PropName+'=[skipping]');
continue;
end;
propflags := '';
// AddPropFlag('type='+IntToStr(proptype)); //we mostly don't care about types
// AddPropFlag('attr='+IntToStr(prop.Attributes));
if propflags <> '' then
propflags := ' (' + propflags + ')';
try
if proptype=0 then
propval := 'Unsupported type'
else
propval := str(prop.Value);
except
on E: EOleException do begin
propval := E.Classname + ': ' + E.Message;
end;
end;
writeln(
propname + '=',
propval,
propflags
);
end;
end;
{
Not all Column object properties are available in all contexts.
Index and Key columns only support:
- Name
- SortOrder (if Index)
- RelatedColumn (if Key)
Table columns do not support:
- SortOrder
- RelatedColumn
Tested in Jet 4.0 and ACE12 from Office 2010.
}
type
TColumnMode = (cmTable, cmIndex, cmKey);
procedure PrintAdoxColumn(f: Column; mode: TColumnMode);
begin
writeln('Name: ', f.Name);
if not (mode in [cmIndex, cmKey]) then begin
writeln('Type: ', AdoxDataTypeToStr(f.type_));
writeln('Attributes: ', f.Attributes);
writeln('DefinedSize: ', f.DefinedSize);
writeln('NumericScale: ', f.NumericScale);
writeln('Precision: ', f.Precision);
end;
if not (mode in [cmTable, cmKey]) then
writeln('SortOrder: ', f.SortOrder);
if not (mode in [cmTable, cmIndex]) then
writeln('RelatedColumn: ', f.RelatedColumn);
if not (mode in [cmIndex, cmKey]) then
DumpAdoxProperties(f.Properties, PropNames([]));
end;
procedure PrintAdoxIndex(f: Index);
var i: integer;
begin
writeln('Name: ', f.Name);
writeln('IndexNulls: ', f.IndexNulls);
DumpAdoxProperties(f.Properties, PropNames([]));
writeln('');
for i := 0 to f.Columns.Count - 1 do try
writeln('Index column ['+IntToStr(i)+']:');
PrintAdoxColumn(f.Columns[i], cmIndex);
writeln('');
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message);
end;
end;
function AdoxKeyTypeToStr(const t: KeyTypeEnum): string;
begin
case t of
adKeyPrimary: Result := 'Primary key';
adKeyForeign: Result := 'Foreign key';
adKeyUnique: Result := 'Unique key';
else Result := 'Unknown ('+IntToStr(t)+')';
end;
end;
function AdoxRuleTypeToStr(const t: RuleEnum): string;
begin
case t of
adRINone: Result := 'Do nothing';
adRICascade: Result := 'Cascade';
adRISetNull: Result := 'Set Null';
adRISetDefault: Result := 'Set Default';
else Result := 'Unknown action ('+IntToStr(t)+')';
end;
end;
procedure PrintAdoxKey(f: Key);
var i: integer;
begin
(* [no Properties] *)
writeln('Name: ', f.Name);
writeln('Type: ', AdoxKeyTypeToStr(f.Type_));
writeln('UpdateRule: ', AdoxRuleTypeToStr(f.UpdateRule));
writeln('DeleteRule: ', AdoxRuleTypeToStr(f.DeleteRule));
writeln('RelatedTable: ', f.RelatedTable);
writeln('');
for i := 0 to f.Columns.Count - 1 do try
writeln('Key column ['+IntToStr(i)+']:');
PrintAdoxColumn(f.Columns[i], cmKey);
writeln('');
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message+''#13#10);
end;
end;
procedure PrintAdoxTable(f: Table);
var i: integer;
begin
writeln('Name: ', f.Name);
writeln('Type: ', f.type_);
DumpAdoxProperties(f.Properties, PropNames([]));
writeln('');
for i := 0 to f.Columns.Count - 1 do try
Subsection('Column['+IntToStr(i)+']');
PrintAdoxColumn(f.Columns[i], cmTable);
writeln('');
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message+''#13#10);
end;
for i := 0 to f.Indexes.Count - 1 do try
Subsection('Index['+IntToStr(i)+']');
PrintAdoxIndex(f.Indexes[i]);
writeln('');
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message+''#13#10);
end;
for i := 0 to f.Keys.Count - 1 do try
Subsection('Key['+IntToStr(i)+']');
PrintAdoxKey(f.Keys[i]);
writeln('');
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message+''#13#10);
end;
end;
procedure PrintAdoxProcedure(f: Procedure_);
begin
(* [no Properties] *)
writeln('Name: ', f.Name);
writeln('DateCreated: ', str(f.DateCreated));
writeln('DateModified: ', str(f.DateModified));
end;
procedure PrintAdoxView(f: View);
begin
(* [no Properties] *)
writeln('Name: ', f.Name);
writeln('DateCreated: ', str(f.DateCreated));
writeln('DateModified: ', str(f.DateModified));
end;
procedure PrintAdoxSchema(adox: Catalog);
var i: integer;
begin
for i := 0 to adox.Tables.Count-1 do try
Section('Table: '+adox.Tables[i].Name);
PrintAdoxTable(adox.Tables[i]);
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message+''#13#10);
end;
for i := 0 to adox.Procedures.Count-1 do try
Section('Procedure: '+adox.Procedures[i].Name);
PrintAdoxProcedure(adox.Procedures[i]);
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message+''#13#10);
end;
for i := 0 to adox.Views.Count-1 do try
Section('View: '+adox.Views[i].Name);
PrintAdoxView(adox.Views[i]);
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message+''#13#10);
end;
(*
Not dumping:
Groups
Users
*)
end;
end.
|
(*!------------------------------------------------------------
* Fano CLI Application (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano-cli
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano-cli/blob/master/LICENSE (MIT)
*------------------------------------------------------------- *)
unit CreateFcgidAppBootstrapTaskImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
TaskOptionsIntf,
TaskIntf,
CreateAppBootstrapTaskImpl;
type
(*!--------------------------------------
* Task that create FastCGI web application project
* with Apache web server and mod_fcgid module
* application bootstrapper using Fano Framework
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
*---------------------------------------*)
TCreateFcgidAppBootstrapTask = class(TCreateAppBootstrapTask)
protected
procedure createApp(
const opt : ITaskOptions;
const longOpt : shortstring;
const dir : string
); override;
procedure createBootstrap(
const opt : ITaskOptions;
const longOpt : shortstring;
const dir : string
); override;
end;
implementation
uses
sysutils;
procedure TCreateFcgidAppBootstrapTask.createApp(
const opt : ITaskOptions;
const longOpt : shortstring;
const dir : string
);
var
{$INCLUDE src/Tasks/Implementations/ProjectFcgid/Includes/app.pas.inc}
begin
createTextFile(dir + '/app.pas', strAppPas);
end;
procedure TCreateFcgidAppBootstrapTask.createBootstrap(
const opt : ITaskOptions;
const longOpt : shortstring;
const dir : string
);
var
{$INCLUDE src/Tasks/Implementations/ProjectFcgid/Includes/bootstrap.pas.inc}
begin
createTextFile(dir + '/bootstrap.pas', strBootstrapPas);
end;
end.
|
Program HashChaining;
CONST
MAX = 100;
TYPE
NodePtr = ^Node;
Node = record
val: string;
next: NodePtr;
end;
ListPtr = NodePtr;
HashTable = array [0..MAX - 1] OF ListPtr;
FUNCTION NewNode(val: string; next: NodePtr): NodePtr;
var n: NodePtr;
BEGIN
New(n);
n^.val := val;
n^.next := next;
NewNode := n;
END;
PROCEDURE InitHashTable(var table: HashTable);
var i: integer;
BEGIN
for i := Low(table) to High(table) do begin
table[i] := NIL;
end;
END;
FUNCTION GetHashCode(val: string): integer;
BEGIN
If (Length(val) = 0) then begin
GetHashCode := 0;
end else if Length(val) = 0 then begin
GetHashCode := (Ord(val[1]) * 7 + 1) * 17;
end else begin
GetHashCode := (Ord(val[1]) * 7 + Ord(val[2]) + Length(val)) * 17;
end;
END;
PROCEDURE Insert(var table: HashTable; val: string);
var hashcode: integer;
BEGIN
hashcode := GetHashCode(val);
hashcode := hashcode MOD MAX;
table[hashcode] := NewNode(val, table[hashcode]);
END;
FUNCTION Contains(table: HashTable; val: string): boolean;
var hashcode: integer;
n: NodePtr;
BEGIN
hashcode := GetHashCode(val);
hashcode := hashcode MOD MAX;
n := table[hashcode];
while (n <> NIL) AND (n^.val <> val) do begin
n := n^.next;
end;
Contains := (n <> NIL);
END;
PROCEDURE WriteHashTable(table: HashTable);
var i: integer;
n: NodePtr;
BEGIN
for i := 0 to MAX - 1 do begin
if(table[i] <> NIL) then begin
Write(i, ': ');
n := table[i];
while n <> NIL do begin
Write(n^.val, ' -> ');
n := n^.next;
end;
WriteLn('|');
end;
end;
END;
var table: HashTable;
s: string;
BEGIN
InitHashTable(table);
Insert(table, 'Stefan');
Insert(table, 'Sabine');
Insert(table, 'Albert');
Insert(table, 'Alina');
Insert(table, 'Gisella');
Insert(table, 'Gisbert');
WriteLn('Contains(Sabine)? = ', Contains(table, 'Sabine'));
WriteLn('Contains(Alina)? = ', Contains(table, 'Alina'));
WriteLn('Contains(Fridolin)? = ', Contains(table, 'Fridolin'));
WriteLn('Contains(Sebastian)? = ', Contains(table, 'Sebastian'));
WriteHashTable(table);
END. |
unit SMCnst;
interface
{Japanese strings}
const
strMessage = '印刷...';
strSaveChanges = '変更を保存しますか?';
strErrSaveChanges = 'データを保存できません! サーバへの接続を確認してください。';
strDeleteWarning = 'テーブルを削除します。よろしいですか? %s?';
strEmptyWarning = 'Do you really want to empty a table %s?';
const
PopUpCaption: array [0..22] of string[33] =
('レコードの追加',
'Insert record',
'レコードの編集',
'レコードの削除',
'-',
'印刷 ...',
'エクスポート ...',
'-',
'変更の保存',
'変更の破棄',
'表示の更新',
'-',
'レコード選択/選択の解除',
'レコードの選択',
'すべてのレコードの選択',
'-',
'レコード選択の解除',
'すべてのレコード選択の解除',
'-',
'レイアウトの保存',
'レイアウト保存の呼び出し',
'-',
'セットアップ...');
const //for TSMSetDBGridDialog
SgbTitle = ' Title ';
SgbData = ' Data ';
STitleCaption = 'Caption:';
STitleAlignment = 'Alignment:';
STitleColor = 'Color:';
STitleFont = 'Font:';
SWidth = 'Width:';
SWidthFix = 'characters';
SAlignLeft = 'left';
SAlignRight = 'right';
SAlignCenter = 'center';
const //for SMDBNavigator
SFirstRecord = '先頭';
SPriorRecord = '前へ';
SNextRecord = '次へ';
SLastRecord = '最終';
SInsertRecord = '挿入';
SCopyRecord = 'コピー';
SDeleteRecord = '削除';
SEditRecord = '編集';
SFilterRecord = 'フィルタ';
SFindRecord = '検索';
SPrintRecord = '印刷';
SExportRecord = 'エクスポート';
SPostEdit = '保存';
SCancelEdit = 'キャンセル';
SRefreshRecord = '更新';
SChoice = '選択';
SClear = '選択破棄';
SDeleteRecordQuestion = 'レコードを削除しますか?';
SDeleteMultipleRecordsQuestion = '選択されたレコードを削除しますか?';
SRecordNotFound = 'レコードが見つかりません';
SFirstName = '先頭';
SPriorName = '前へ';
SNextName = '次へ';
SLastName = '最終';
SInsertName = '挿入';
SCopyName = 'コピー';
SDeleteName = '削除';
SEditName = '編集';
SFilterName = 'フィルタ';
SFindName = '検索';
SPrintName = '印刷';
SExportName = 'エクスポート';
SPostName = '保存';
SCancelName = 'キャンセル';
SRefreshName = '更新';
SChoiceName = '選択';
SClearName = 'クリア';
SRecNo = '#';
SRecOf = ' of ';
const //for EditTyped
etValidNumber = '数値';
etValidInteger = '整数値';
etValidDateTime = '日付/時刻';
etValidDate = '日付';
etValidTime = '時刻';
etValid = '有効';
etIsNot = 'is not a';
etOutOfRange = '値 %s 範囲を超えています %s..%s';
implementation
end.
|
unit DrawGrid;
interface
uses Windows, Controls, Forms, SysUtils, Graphics, CLasses, ScaleData,
Global;
procedure GridControl(ColorBack: COLORREF);
procedure RulerVertical(X, Y: Integer);
procedure RulerHorizontal(X, Y: Integer);
implementation
uses CADFunction;
procedure RulerHorizontal(X, Y: Integer);
var
OldPen, HP: HPEN;
OldBkMode: Integer;
begin
OldBkMode:= SetBkMode(mDC, TRANSPARENT);
HP:= CreatePen(PS_DOT, 1, clBlue);
OldPen:= SelectObject(mDC, HP);
try
Line(mDC, SIZE_RULER, Y - GRID_Y, GRID_HEIGHT, Y - GRID_Y);
finally
SelectObject(mDC, OldPen);
DeleteObject(HP);
SetBkMode(mDC, OldBkMode);
end;
end;
procedure RulerVertical(X, Y: Integer);
var
OldPen, HP: HPEN;
OldBkMode: Integer;
begin
OldBkMode:= SetBkMode(mDC, TRANSPARENT);
HP:= CreatePen(PS_DOT, 1, clBlue);
OldPen:= SelectObject(mDC, HP);
try
Line(mDC, X - GRID_X, SIZE_RULER, X - GRID_X, GRID_HEIGHT);
finally
SelectObject(mDC, OldPen);
DeleteObject(HP);
SetBkMode(mDC, OldBkMode);
end;
end;
procedure GridControl(ColorBack: COLORREF);
var
OldBrush,HB : HBRUSH;
lgBrush: LOGBRUSH;
OldPen, HP: HPEN;
OldFont, HF: HFONT;
i, OldBkMode: Integer;
recFont: LOGFONT;
s: String;
begin
// Создать кисть для заливки
lgBrush.lbStyle:= BS_SOLID;
lgBrush.lbColor:= ColorBack;
lgBrush.lbHatch:= HS_CROSS;
HB:= CreateBrushIndirect(lgBrush);
OldBrush:= SelectObject(mDC, HB);
// Копируем кисть в контекст
PatBlt(mDC, 0, 0, GRID_WIDTH, GRID_HEIGHT, PATCOPY);
SelectObject(mDC, OldBrush);
DeleteObject(HB);
HP:= CreatePen(PS_SOLID, 1, clLtGray);
OldPen:= SelectObject(mDC, HP);
try
// Сетка
for i:= 1 to MX do
Line(mDC, i * STEP_GRID + SIZE_RULER, SIZE_RULER,
i * STEP_GRID + SIZE_RULER, GRID_HEIGHT);
for i:= 1 to MY do
Line(mDC, SIZE_RULER, i * STEP_GRID + SIZE_RULER,
GRID_WIDTH, i * STEP_GRID + SIZE_RULER);
// Рамка сетки
SelectObject(mDC, GetStockObject(NULL_BRUSH));
SelectObject(mDC, GetStockObject(BLACK_PEN));
Rectangle(mDC, 0, 0, GRID_WIDTH, GRID_HEIGHT );
// Ограничивающие линии линеек
Line(mDC, SIZE_RULER, SIZE_RULER, GRID_WIDTH - 1, SIZE_RULER);
Line(mDC, SIZE_RULER, SIZE_RULER, SIZE_RULER, GRID_HEIGHT - 1);
// Подготовка шрифта
with recFont do
begin
lfHeight:= 8;
lfWidth:= 0;
lfEscapement:= 0;
lfOrientation:= 0;
lfWeight:= FW_NORMAL;
lfItalic:= 0;
lfUnderline:= 0;
lfStrikeOut:= 0;
lfCharSet:= DEFAULT_CHARSET;
lfOutPrecision:= OUT_DEFAULT_PRECIS;
lfClipPrecision:= CLIP_DEFAULT_PRECIS;
lfQuality:= DEFAULT_QUALITY;
lfPitchAndFamily:= FF_ROMAN;
StrCopy(lfFaceName, 'MS Serif');
end;
HF:= CreateFontIndirect(recFont);
OldFont:= SelectObject(mDC, HF);
SetTextAlign(mDC, TA_CENTER);
OldBkMode:= SetBkMode(mDC, TRANSPARENT);
// Вывести обозначения на линейках
for i:= 0 to MX - 1 do
if (i mod STEP_RULER) = 0 then
begin
s:= IntToStr(i);
TextOut(mDC, i * PT_FYS + SIZE_RULER, 2, PChar(s), Length(s));
Line(mDC, i * PT_FYS + SIZE_RULER, 15, i * PT_FYS + SIZE_RULER, SIZE_RULER)
end;
SetTextAlign(mDC, TA_LEFT);
for i:= 0 to MY - 1 do
if (i mod STEP_RULER) = 0 then
begin
s:= IntToStr(i);
TextOut(mDC, 2, i * PT_FYS + SIZE_RULER - 6, PChar(s), Length(s));
Line(mDC, 15, i * PT_FYS + SIZE_RULER, SIZE_RULER, i * PT_FYS + SIZE_RULER)
end;
SelectObject(mDC, OldFont);
DeleteObject(HF);
SetBkMode(mDC, OldBkMode);
// Нарисовать штрихи
for i:= 1 to MX do
begin
Line(mDC, i * STEP_GRID + SIZE_RULER, SIZE_RULER - PT_FYS div 2,
i * STEP_GRID + SIZE_RULER, SIZE_RULER);
Line(mDC, SIZE_RULER - PT_FYS div 2, i * STEP_GRID + SIZE_RULER,
SIZE_RULER, i * STEP_GRID + SIZE_RULER);
end;
finally
SelectObject(mDC, OldPen);
DeleteObject(HP);
end;
end;
end.
|
unit Common.DatabaseUtils;
interface
uses
Aurelius.Criteria.Base,
Aurelius.Drivers.Interfaces,
Aurelius.Engine.DatabaseManager,
Aurelius.Engine.ObjectManager,
Aurelius.Criteria.Linq,
Model.Entities, System.Classes;
type
TCreateMode = (cmCreate, cmReplicate);
procedure UpdateDatabaseShema(Conn: IDBConnection);
procedure FillData(Conn: IDBConnection);
implementation
uses
System.IniFiles,
System.SysUtils,
Vcl.FileCtrl,
Common.Utils,
WaitForm;
var
AutoReplicate: Boolean;
procedure AddRecordsToDatabase(FR: TFileRecordList; AManager: TObjectManager;
AMode: TCreateMode);
var
Category: TCategory;
Book: TBook;
I: Integer;
begin
if (AMode = cmCreate) then begin
Category := AManager.Find<TCategory>(1);
if (Category = nil) and (AMode = cmCreate) then begin
Category := TCategory.Create;
try
Category.ID := 1;
Category.CategoryName := 'Все книги';
AManager.Replicate<TCategory>(Category);
finally
Category.Free;
end;
for I := 0 to FR.Count - 1 do begin
TWaiting.Status(Format('Добавление записи: %s', [ FR[ I ].FileName ]));
Book := TBook.Create;
try
Book.ID := I + 1;
Book.BookName := FR[ I ].FileName;
Book.BookLink := FR[ I ].FilePath;
Category := AManager.Find<TCategory>(1);
Category.Books.Add(AManager.Replicate<TBook>(Book));
finally
Book.Free;
end;
end;
AManager.Flush;
end;
end else if (AMode = cmReplicate) then begin
Category := AManager.Find<TCategory>(1000);
if (Category = nil) then begin
Category := TCategory.Create;
try
Category.ID := 1000;
Category.CategoryName := 'Новые книги';
AManager.Replicate<TCategory>(Category);
finally
Category.Free;
end;
end;
for I := 0 to FR.Count - 1 do begin
TWaiting.Status(Format('Обработка записи: %s', [ FR[ I ].FileName ]));
Book := AManager.Find<TBook>
.Where(
Linq['BookLink'].Like(FR[ I ].FilePath)
)
.UniqueResult;
if (Book = nil) then begin
Book := TBook.Create;
try
Book.BookName := FR[ I ].FileName;
Book.BookLink := FR[ I ].FilePath;
Category := AManager.Find<TCategory>(1000);
Category.Books.Add(AManager.Replicate<TBook>(Book));
finally
Book.Free;
end;
end;
end;
AManager.Flush;
end;
end;
procedure CreateDataFromFiles(AManager: TObjectManager; AMode: TCreateMode);
var
FilesList: TFileRecordList;
StartDir: string;
begin
// Синхронизация библиотеки
with TMemIniFile.Create(IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'conn.ini') do begin
StartDir := ReadString('Path', 'SearchPath', 'D:\Книги');
end;
if (StartDir = '') or (not DirectoryExists(StartDir)) then begin
// вызов диалога для выбора каталога
if not SelectDirectory('Выберите каталог', 'C:\', StartDir) then Exit;
end;
FilesList := TFileRecordList.Create;
try
FindAllFiles(FilesList, StartDir, ['pdf', 'djvu', 'fb2', 'chw']);
AddRecordsToDatabase(FilesList, AManager, AMode);
finally
FilesList.Free;
end;
end;
procedure UpdateDatabaseShema(Conn: IDBConnection);
var
DB: TDatabaseManager;
begin
DB := TDatabaseManager.Create(Conn);
try
DB.UpdateDatabase;
finally
DB.Free;
end;
end;
procedure FillData(Conn: IDBConnection);
var
Manager: TObjectManager;
Trans: IDBTransaction;
UpdateMode: TCreateMode;
begin
Manager := TObjectManager.Create(Conn);
with TMemIniFile.Create(IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'conn.ini') do begin
AutoReplicate := ReadBool('Config', 'AutoReplicate', False);
end;
try
Trans := conn.BeginTransaction;
try
if Manager.Find<TBook>.List.Count = 0 then
UpdateMode := cmCreate
else
UpdateMode := cmReplicate;
if (UpdateMode = cmReplicate) and not AutoReplicate then Exit;
TWaiting.Start('Обновление библиотеки',
procedure
begin
CreateDataFromFiles(Manager, UpdateMode);
end);
Trans.Commit;
except
Trans.Rollback;
raise;
end;
finally
Manager.Free;
end;
end;
end.
|
unit PEDIDO;
interface
uses
Classes,
DB,
SysUtils,
Generics.Collections,
ormbr.mapping.attributes,
ormbr.types.mapping,
ormbr.types.lazy,
ormbr.types.nullable,
ormbr.mapping.register, PRODUTO;
type
//[Entity]
//[Table('PEDIDO','')]
//[PrimaryKey('ID', AutoInc, NoSort, True, 'Chave primária')]
TPEDIDO = class
private
FID: Integer;
fProdutos: TObjectList<TPRODUTO>;
fOBS: String;
fCodUsr: Integer;
fTotal: Double;
fMesa: Integer;
fReImprimir: String;
fOBS_MESA: String;
ftermicod: Integer;
{ Private declarations }
public
constructor create;
destructor destroy; override;
{ Public declarations }
//[Dictionary('GRUPICOD','Mensagem de validação','','','',taCenter)]
property id: Integer read FID write FID;
property CodUsr: Integer read fCodUsr write fCodUsr;
property Total: Double read fTotal write fTotal;
property Mesa: Integer read fMesa write fMesa;
property OBS:String read fOBS write fOBS;
property ReImprimir:String read fReImprimir write fReImprimir;
property OBS_MESA:String read fOBS_MESA write fOBS_MESA;
property termicod: Integer read ftermicod write ftermicod;
//[Restrictions([NoValidate])]
property Produtos: TObjectList<TPRODUTO> read fProdutos write fProdutos;
end;
implementation
constructor TPEDIDO.create;
begin
fProdutos := TObjectList<TPRODUTO>.Create;
end;
destructor TPEDIDO.destroy;
begin
fProdutos.Free;
inherited;
end;
initialization
TRegisterClass.RegisterEntity(TPEDIDO);
end.
|
unit GrafLib0;
(* ---------------------------------------------------------------------
Source : HIGH RESOLUTION GRAPHICS IN PASCAL by Angell & Griffith
Listing(s): 1.1, 1.3
Purpose: Graphics primitives adopted for Turbo Pascal
Adapted by: Art Steinmetz
----------------------------------------------------------------------- *)
interface
uses GRAPH;
CONST
(* Pixel Oriented *)
SizeOfPixelArray = 32;
(* Cooridate Oriented *)
VectorArraySize = 32;
epsilon = 0.0000001;
{ pi = 3.1415926535 already defined in Turbo}
TYPE
(* Pixel Oriented *)
PixelVector = RECORD x,y : INTEGER END;
PixelArray = ARRAY[1..SizeOfPixelArray] OF PixelVector;
(* Cooridate Oriented *)
Vector2 = RECORD x,y : REAL END;
Vector2Array = ARRAY[1..VectorArraySize] OF Vector2;
RealArray = ARRAY[1..VectorArraySize] OF REAL;
IntegerArray = ARRAY[1..VectorArraySize] OF Integer;
VAR
(* Pixel Oriented *)
CurrCol : INTEGER;
nxpix, nypix : INTEGER;
InData, OutData : { File of } TEXT;
(* Cooridate Oriented *)
horiz, vert, XYScale : REAL;
(* Pixel Oriented Procedures *)
PROCEDURE Finish;
{CleanUp}
PROCEDURE SetCol(Col : INTEGER);
{ set color in lookup table }
PROCEDURE Erase;
{ Clear the view port }
PROCEDURE SetPix(pixel : PixelVector);
{ change the pixel to the current color }
PROCEDURE MovePix(pixel : PixelVector);
{change the current position pointer}
PROCEDURE LinePix(pixel : PixelVector);
{draw a line for the current point to pixel. Update the current pointer }
PROCEDURE PolyPix(n : INTEGER; poly : PixelArray);
{fill a polygon defined by poly having n vertices }
PROCEDURE RGBLog(i : INTEGER; Red, Green, Blue :REAL);
{change the colors in the lookup table. }
{Use fractional values between 0 and 1.0 }
PROCEDURE PrepIt;
{ Set up the graphics display }
(* Coordinate Oriented Procedures *)
FUNCTION fx(x : REAL) : INTEGER;
{ scale units to pixels }
FUNCTION fy(y : REAL) : INTEGER;
{ scale units to pixels }
PROCEDURE MoveTo(pt : Vector2);
{change the current position pointer}
PROCEDURE LineTo(pt : Vector2);
{draw a line for the current point to pixel. Update the current pointer }
PROCEDURE PolyFill(n : INTEGER; polygon : Vector2Array);
{fill a polygon defined by poly having n vertices }
PROCEDURE Start(horiz : REAL);
{ Set up the graphics display }
(* =========================================================== *)
implementation
CONST
MaxColorLevel = 63 {with VGA};
VAR
MaxCol : INTEGER;
PROCEDURE Finish;
{CleanUp}
BEGIN
{ PAUSE } Readln;
CloseGraph;
END {Finish};
(* Pixel Oriented Procedures *)
(*----------------------------------------------------------- *)
PROCEDURE SetCol(Col : INTEGER);
{ set color in lookup table }
BEGIN
SetColor(Col);
SetFillStyle(SolidFill,Col);
CurrCol := Col;
END;
(*----------------------------------------------------------- *)
PROCEDURE Erase;
{ Clear the view port }
BEGIN
ClearViewPort;
END {Erase};
(*----------------------------------------------------------- *)
PROCEDURE SetPix(pixel : PixelVector);
{ change the pixel to the current color }
BEGIN
PutPixel(pixel.X,nypix-1-pixel.Y,CurrCol);
END {SetPix};
(*----------------------------------------------------------- *)
PROCEDURE MovePix(pixel : PixelVector);
{change the current position pointer}
BEGIN
Graph.MoveTo(pixel.X,nypix-1-pixel.Y);
END {MovePix};
(*----------------------------------------------------------- *)
PROCEDURE LinePix(pixel : PixelVector);
{draw a line for the current point to pixel. Update the current pointer }
BEGIN
Graph.LineTo(pixel.X,nypix-1-pixel.Y);
END {LinePix};
(*----------------------------------------------------------- *)
PROCEDURE PolyPix(n : INTEGER; poly : PixelArray);
{fill a polygon defined by poly having n vertices }
VAR
i : INTEGER;
BEGIN
{ tranlate coordinate scheme }
FOR i := 1 TO n DO
poly[i].Y := nypix - 1 - poly[i].Y;
FillPoly(n,poly);
END;
(*----------------------------------------------------------- *)
PROCEDURE RGBLog(i : INTEGER; Red, Green, Blue :REAL);
{change the colors in the lookup table. }
{Use fractional values between 0 and 1.0 }
BEGIN
SetRGBPalette(i, TRUNC(Red * MaxColorLevel),
TRUNC(Green * MaxColorLevel),
TRUNC(Blue * MaxColorLevel));
END {RGBLog};
(*----------------------------------------------------------- *)
PROCEDURE PrepIt;
{ Set up the graphics display }
VAR
i,
GraphDriver, GraphMode : INTEGER;
BEGIN
GraphDriver := Detect;
InitGraph(GraphDriver, GraphMode,'');
IF (GraphResult <> grOK) OR (GraphDriver <> VGA) THEN HALT(1);
FOR i := 0 TO GetMaxColor DO {use the lowest colors in palette register}
SetPalette(i,i);
{ initial colors }
RGBLog(0, 0.0, 0.0, 0.0) {Black};
RGBLog(1, 1.0, 0.0, 0.0) {Red};
RGBLog(2, 0.0, 1.0, 0.0) {Green};
RGBLog(3, 1.0, 1.0, 0.0) {Yellow};
RGBLog(4, 0.0, 0.0, 1.0) {Blue};
RGBLog(5, 1.0, 0.0, 1.0) {Magenta};
RGBLog(6, 0.0, 1.0, 1.0) {Cyan};
RGBLog(7, 1.0, 1.0, 1.0) {White};
nxpix := GetMaxX+1;
nypix := GetMaxY+1;
END {PrepIt};
(* Coordinate Oriented Procedures *)
(*----------------------------------------------------------- *)
FUNCTION fx(x : REAL) : INTEGER;
{ scale units to pixels }
BEGIN
fx := TRUNC(x*XYScale+nxpix*0.5-0.5);
END {fx};
(*----------------------------------------------------------- *)
FUNCTION fy(y : REAL) : INTEGER;
{ scale units to pixels }
BEGIN
fy := TRUNC(y*XYScale+nypix*0.5-0.5);
END {fy};
(*----------------------------------------------------------- *)
PROCEDURE MoveTo(pt : Vector2);
{change the current position pointer}
BEGIN
Graph.MoveTo(fx(pt.x),nypix-1-fy(pt.y));
END {MoveTo};
(*----------------------------------------------------------- *)
PROCEDURE LineTo(pt : Vector2);
{draw a line for the current point to pixel. Update the current pointer }
VAR
pixel : pixelvector;
BEGIN
Graph.LineTo(fx(pt.x),nypix-1-fy(pt.y));
END {LineTo};
(*----------------------------------------------------------- *)
PROCEDURE PolyFill(n : INTEGER; polygon : Vector2Array);
{fill a polygon defined by poly having n vertices }
VAR
i : INTEGER;
pixelpolygon : pixelarray;
BEGIN
{ tranlate coordinate scheme }
FOR i := 1 TO n DO
BEGIN
pixelpolygon[i].x := fx(polygon[i].x);
pixelpolygon[i].y := nypix-1-fy(polygon[i].y);
END;
FillPoly(n,pixelpolygon);
END {PolyFill};
(*----------------------------------------------------------- *)
FUNCTION Angle(x,y : REAL) :REAL;
{ listing 3.3 }
{ return angle in radians vs. X axis of line from origin to point (x, y) }
BEGIN
IF ABS(x) < epsilon { close enough to zero ?}
THEN IF abs(y) < epsilon
THEN Angle := 0.0
ELSE IF y > 0.0
THEN Angle := pi * 0.5
ELSE Angle := pi * 1.5
ELSE IF x < 0.0
THEN Angle := arctan(y/x) + pi;
ELSE Angle := arctan(y/x);
END {Angle};
(*----------------------------------------------------------- *)
PROCEDURE Start;
{ Set up the graphics display }
VAR
i,
GraphDriver, GraphMode : INTEGER;
BEGIN
PrepIt;
IF horiz < 1 THEN horiz := nxpix; {default}
vert := horiz*nypix/nxpix;
XYScale := (nxpix-1)/horiz;
END {Start};
(*----------------------------------------------------------- *)
BEGIN
horiz := 0;
END {GraphLib0}. |
unit uTranslateVclVDBConsts;
interface
uses
Windows,
Vcl.VDBConsts,
uTranslate;
Type
TTranslateVclVDBConsts = Class(TTranslate)
private
public
class procedure ChangeValues; override;
End;
Implementation
class procedure TTranslateVclVDBConsts.ChangeValues;
begin
{ DBCtrls }
SetResourceString(@SFirstRecord, 'Primeiro Registro');
SetResourceString(@SPriorRecord, 'Registro Anterior');
SetResourceString(@SNextRecord, 'Próximo Registro');
SetResourceString(@SLastRecord, 'Último Registro');
SetResourceString(@SInsertRecord, 'Inserir registro');
SetResourceString(@SDeleteRecord, 'Apagar registro');
SetResourceString(@SEditRecord, 'Editar registro');
SetResourceString(@SPostEdit, 'Gravar edição');
SetResourceString(@SCancelEdit, 'Cancelar edição');
SetResourceString(@SConfirmCaption, 'Confirmar');
SetResourceString(@SRefreshRecord, 'Atualizar dados');
SetResourceString(@SApplyUpdates, 'Aplicar alterações');
SetResourceString(@SCancelUpdates, 'Cancelar alterações');
SetResourceString(@SDeleteRecordQuestion, 'Apaga registro?');
SetResourceString(@SDeleteMultipleRecordsQuestion, 'Apagar todos os registros selecioandos?');
SetResourceString(@SDataSourceFixed, 'Operação não permitida em um DBCtrlGrid');
SetResourceString(@SNotReplicatable, 'Controle não pode ser usado em um DBCtrlGrid');
SetResourceString(@SPropDefByLookup, 'Propriedade já definida pelo campo lookup');
SetResourceString(@STooManyColumns, 'Grid requisitada possui mais de 256 colunas');
{ DBLogDlg }
SetResourceString(@SRemoteLogin, 'Login Remoto');
{ DBOleEdt }
SetResourceString(@SDataBindings, 'Data Bindings...');
end;
End. |
unit Unit1;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
IdBaseComponent,
IdComponent,
IdCustomTCPServer,
IdCustomHTTPServer,
IdHTTPServer,
IdContext;
type
TForm1 = class(TForm)
server: TIdHTTPServer;
procedure serverCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.serverCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo);
var
data:TStringStream;
begin
if (ARequestInfo.Command = 'GET') and Assigned(ARequestInfo.PostStream) then
begin
data:=TStringStream.Create;
try
try
data.LoadFromStream(ARequestInfo.PostStream);
ShowMessage(data.DataString);
except
on E:Exception do
begin
AResponseInfo.ResponseNo:=501;
AResponseInfo.ResponseText:='You gay';
AResponseInfo.ContentText:=E.Message;
end;
end;
finally
data.Free;
end;
end;
ShowMessage(ARequestInfo.Document);
end;
end.
|
unit uInterfaceManager;
/// реализует объект, управляющий интерфейсом игры.
/// - имеет массив привязок ко всем значимым элементам интерфейса для полного контроля над ним
/// - получает данные от менеджера игры и отображает их в интерфейсе / изменяет состояние интерфейса
/// - получает события от интерфейса и передает менеджеру игры
interface
uses
FMX.Objects, FMX.StdCtrls, FMX.types, UITypes, Classes, FMX.Layouts,
uConstants, uGameManager, uAtlas, uTypes;
type
TInterfaceManager = class
private
pMain: TMainComponents;
pWalk: TPanelWalk;
pPers: TPanelPers;
pAbility : TPanelAbility;
pState : TPanelState;
pInfo : TPanelInfo;
pLootPanel : TLootPanel;
procedure ResetMainComponents;
procedure ResetWalkPanel;
procedure ResetPersPanel;
procedure ResetAbilityPanel;
procedure ResetStatePanel;
procedure ResetInfoPanel;
procedure ResetTopPanel;
procedure CreateInnerProgressbar( component: TComponent; var objBG, objFG: TObject );
procedure SetPanelFS( obj: TObject; fill, stroke: integer );
procedure SetProgress( objBG, objFG: TObject; BG, FG: integer);
public
////////////////////////////////////////////////////////////////////////////////
/// методы привязки к компонентам различных блоков интерфейса
////////////////////////////////////////////////////////////////////////////////
procedure GetMainComponents( topPanel, landscape, bottomPanel, lootPanel, travelBG, travelFG: TObject);
/// ключевые блоки экрана, содержащие в себе прочие подразделы
procedure GetWalkComponents( panel, stepPanel1, stepImg1, stepPanel2,
stepImg2, stepPanel3, stepImg3, jumpPanel, jumpImg, jumpBG, jumpProgress: TObject );
/// панель скорости ходьбы
procedure GetPersComponents( panel, pers1, pers2, pers3 : TObject );
/// панель персонажей
procedure GetAbilityComponents( panel, abilityButton, abilityCaption,
itemButton, itemCaption, slot1, slot2, slot3, slot4, slot5, slot6 : TObject );
/// панель способностей/предметов
procedure GetStatComponents(
panel, HPpanel, HPLabel, HPCount, HPCountBG, HPCountFG,
MPPanel, MPLabel, MPCount, MPCountBG, MPCountFG,
DEFPanel, DEFLabel, DEFCount, ATKPanel, ATKLabel, ATKCount,
GLDPanel, GLDLabel, GLDCount, EXPPanel, EXPLabel, EXPCount,
buttonBG, buttonLabel : TObject );
/// панель характеристик игрока
procedure GetDescriptComponents( panel, layout: TObject );
/// информационная панель
procedure GetTopPanelComponents(
resourcePanel, buttonSettings : TObject);
/// основные компоенеты-контейнеры экрана путешествия
////////////////////////////////////////////////////////////////////////////////
/// сервисные методы
////////////////////////////////////////////////////////////////////////////////
procedure Init;
/// сброс интерфейса в базовое состояние (установка стилей, положения, видимости и т.п.)
procedure OnCooldown( ticks: integer = 1 );
// procedure ToCooldown( length: real; BG, FG: TObject );
/// запустить отработку кулдауна для указанного прогрессбара
////////////////////////////////////////////////////////////////////////////////
/// блок обработчиков событий интерфейса (активация элементов игроком)
/// вызывают методы-обработчики mngGameManager для определения им необходимой реакции
////////////////////////////////////////////////////////////////////////////////
procedure OnJumpClick(source: TObject);
// клик по кнопке прыжка
////////////////////////////////////////////////////////////////////////////////
/// блок действий с интерфейсом
/// методы вызываются mngGameManager для изменения состояния интерфейса игры
////////////////////////////////////////////////////////////////////////////////
procedure ActivateJump( JumpLength: integer; progressValue, CooldownLength: real );
/// отработать запуск режима прыжка:
/// - разово прокрутить экран приключения на JumpLength пикселей
/// - установить позицию прогресса приключения на progressValue процентов
/// - запустить кулдаун способности длительностью CooldownLength секунд
procedure SetKindProgress( kind: integer; percent: real; isFinished: boolean );
end;
var
mngInterface : TInterfaceManager;
implementation
{ TInterfaceManager }
procedure TInterfaceManager.ActivateJump(JumpLength: integer; progressValue,
CooldownLength: real);
begin
// (pWalk.jumpProgress as TRectangle).Width := 0;
// fCooldown.AddCooldown( CooldownLength * 1000, pWalk.jumpBG, pWalk.jumpProgress );
end;
procedure TInterfaceManager.CreateInnerProgressbar( component: TComponent; var objBG, objFG: TObject );
/// метод создает для указанного компонента вложенный прогрессбар выровненный понизу
/// component - владелец будущего прогрессбара
/// objBG - поле в хранилище, в которое положить ссылку на фоновый компонент прогрессбара
/// objFG - поле в хранилище, в которое положить ссылку на активный компонент прогрессбара
var
rect, rect2: TRectangle;
begin
// бекграунд прогрессбара
rect := TRectangle.Create(component);
rect.Parent := (component as TFmxObject);
rect.Align := TAlignLayout.Bottom;
rect.Height := 4;
rect.Fill.color := COLOR_COMMON_PROGRESS_BG;
rect.Stroke.color := COLOR_COMMON_PROGRESS_BG;
// активная полоска
rect2 := TRectangle.Create(rect);
rect2.Parent := rect;
rect2.Align := TAlignLayout.Left;
rect2.Height := 4;
rect2.Width := rect.Width - 10;
rect2.Fill.color := COLOR_COMMON_PROGRESS_FG;
rect2.Stroke.color := COLOR_COMMON_PROGRESS_FG;
// кладем созданные объекты в хранилище
objBG := rect;
objFG := rect2;
end;
procedure TInterfaceManager.GetAbilityComponents(panel, abilityButton,
abilityCaption, itemButton, itemCaption, slot1, slot2, slot3, slot4, slot5,
slot6: TObject);
begin
pAbility.panel := panel;
pAbility.abilityButton := abilityButton;
pAbility.abilityCaption := abilityCaption;
pAbility.itemButton := itemButton;
pAbility.itemCaption := itemCaption;
pAbility.slot1 := slot1;
pAbility.slot2 := slot2;
pAbility.slot3 := slot3;
pAbility.slot4 := slot4;
pAbility.slot5 := slot5;
pAbility.slot6 := slot6;
end;
procedure TInterfaceManager.GetDescriptComponents(panel, layout: TObject);
begin
pInfo.panel := panel;
pInfo.layout := layout;
end;
procedure TInterfaceManager.GetMainComponents(topPanel, landscape,
bottomPanel, lootPanel, travelBG, travelFG: TObject);
begin
pMain.topPanel := topPanel;
pMain.landscape := landscape;
pMain.bottomPanel := bottomPanel;
pMain.lootPanel := lootPanel;
pMain.travelBG := travelBG;
pMain.travelFG := travelFG;
end;
procedure TInterfaceManager.GetPersComponents(panel, pers1, pers2,
pers3: TObject);
/// привязка к панели иконок персонажей
begin
pPers.panel := panel;
pPers.pers1 := pers1;
pPers.pers2 := pers2;
pPers.pers3 := pers3;
end;
procedure TInterfaceManager.GetStatComponents(panel, HPpanel, HPLabel, HPCount,
HPCountBG, HPCountFG, MPPanel, MPLabel, MPCount, MPCountBG, MPCountFG,
DEFPanel, DEFLabel, DEFCount, ATKPanel, ATKLabel, ATKCount, GLDPanel,
GLDLabel, GLDCount, EXPPanel, EXPLabel, EXPCount, buttonBG, buttonLabel: TObject);
begin
pState.panel := panel;
pState.HPpanel := HPpanel;
pState.HPLabel := HPLabel;
pState.HPCount := HPCount;
pState.HPCountBG := HPCountBG;
pState.HPCountFG := HPCountFG;
pState.MPPanel := MPPanel;
pState.MPLabel := MPLabel;
pState.MPCount := MPCount;
pState.MPCountBG := MPCountBG;
pState.MPCountFG := MPCountFG;
pState.DEFPanel := DEFPanel;
pState.DEFLabel := DEFLabel;
pState.DEFCount := DEFCount;
pState.ATKPanel := ATKPanel;
pState.ATKLabel := ATKLabel;
pState.ATKCount := ATKCount;
pState.GLDPanel := GLDPanel;
pState.GLDLabel := GLDLabel;
pState.GLDCount := GLDCount;
pState.EXPPanel := EXPPanel;
pState.EXPLabel := EXPLabel;
pState.EXPCount := EXPCount;
pState.buttonBG := buttonBG;
pState.buttonLabel := buttonLabel;
end;
procedure TInterfaceManager.GetTopPanelComponents(resourcePanel, buttonSettings: TObject);
begin
pLootPanel.resourcePanel := resourcePanel;
pLootPanel.buttonSettings := buttonSettings;
end;
procedure TInterfaceManager.GetWalkComponents(panel, stepPanel1, stepImg1,
stepPanel2, stepImg2, stepPanel3, stepImg3, jumpPanel, jumpImg, jumpBG,
jumpProgress: TObject);
/// привязка к компонентам панели скорости путешествия
begin
pWalk.panel := panel;
pWalk.stepPanel1 := stepPanel1;
pWalk.stepImg1 := stepImg1;
pWalk.stepPanel2 := stepPanel2;
pWalk.stepImg2 := stepImg2;
pWalk.stepPanel3 := stepPanel3;
pWalk.stepImg3 := stepImg3;
pWalk.jumpPanel := jumpPanel;
pWalk.jumpImg := jumpImg;
pWalk.jumpBG := jumpBG;
pWalk.jumpProgress := jumpProgress;
end;
procedure TInterfaceManager.Init;
begin
ResetWalkPanel;
ResetPersPanel;
ResetAbilityPanel;
ResetStatePanel;
ResetInfoPanel;
ResetTopPanel;
end;
procedure TInterfaceManager.OnCooldown(ticks: integer);
begin
mngGame.OnCooldownTick;
end;
procedure TInterfaceManager.OnJumpClick(source: TObject);
// игрок кликнул по кнопке активации прыжка
begin
mngGame.DoJump;
end;
procedure TInterfaceManager.ResetAbilityPanel;
/// задаем раскраску и картинки панели способностей/предметов
begin
SetPanelFS( pAbility.panel, COLOR_PANEL_FILL_NORMAL, COLOR_PANEL_STROKE_LIGHT);
SetPanelFS( pAbility.abilityButton, COLOR_PANEL_FILL_DARK, COLOR_PANEL_STROKE_NORMAL);
(pAbility.abilityCaption as TLabel).TextSettings.FontColor := COLOR_PANEL_FILL_LIGHT;
(pAbility.abilityCaption as TLabel).Cursor := crHandPoint;
SetPanelFS( pAbility.itemButton, COLOR_PANEL_FILL_DARK, COLOR_PANEL_STROKE_NORMAL);
(pAbility.itemCaption as TLabel).TextSettings.FontColor := COLOR_PANEL_FILL_LIGHT;
(pAbility.itemCaption as TLabel).Cursor := crHandPoint;
fAtlas.EmptyBitmap( pAbility.slot1 );
fAtlas.EmptyBitmap( pAbility.slot2 );
fAtlas.EmptyBitmap( pAbility.slot3 );
fAtlas.EmptyBitmap( pAbility.slot4 );
fAtlas.EmptyBitmap( pAbility.slot5 );
fAtlas.EmptyBitmap( pAbility.slot6 );
(pAbility.slot1 as TImage).Cursor := crHandPoint;
(pAbility.slot2 as TImage).Cursor := crHandPoint;
(pAbility.slot3 as TImage).Cursor := crHandPoint;
(pAbility.slot4 as TImage).Cursor := crHandPoint;
(pAbility.slot5 as TImage).Cursor := crHandPoint;
(pAbility.slot6 as TImage).Cursor := crHandPoint;
end;
procedure TInterfaceManager.ResetInfoPanel;
begin
pInfo.layout.free;
pInfo.layout := TLayout.Create( (pInfo.panel as TComponent) );
(pInfo.layout as TLayout).Parent := (pInfo.panel as TRectangle);
end;
procedure TInterfaceManager.ResetMainComponents;
begin
(pMain.topPanel as TRectangle).Height := TOP_PANEL_HEIGHT;
(pMain.bottomPanel as TRectangle).Height := BOTTOM_PANEL_HEIGHT;
end;
procedure TInterfaceManager.ResetPersPanel;
/// задаем раскраску и картинки панели персонажей
begin
SetPanelFS( pPers.panel, COLOR_PANEL_FILL_DARK, COLOR_PANEL_STROKE_DARK);
fAtlas.EmptyBitmap( pPers.pers1 );
fAtlas.EmptyBitmap( pPers.pers2 );
fAtlas.EmptyBitmap( pPers.pers3 );
end;
procedure TInterfaceManager.ResetStatePanel;
/// задаем стартовые параметры панели статуса
begin
SetPanelFS( pState.panel, COLOR_PANEL_FILL_NORMAL, COLOR_PANEL_STROKE_LIGHT);
SetPanelFS( pState.HPpanel, COLOR_PANEL_FILL_NORMAL, COLOR_PANEL_STROKE_LIGHT);
SetProgress( pState.HPCountBG, pState.HPCountFG, COLOR_COMMON_PROGRESS_BG, COLOR_HP );
SetPanelFS( pState.MPpanel, COLOR_PANEL_FILL_NORMAL, COLOR_PANEL_STROKE_LIGHT);
SetProgress( pState.MPCountBG, pState.MPCountFG, COLOR_COMMON_PROGRESS_BG, COLOR_MP );
SetPanelFS( pState.DEFPanel, COLOR_PANEL_FILL_NORMAL, COLOR_PANEL_STROKE_LIGHT);
SetPanelFS( pState.ATKPanel, COLOR_PANEL_FILL_NORMAL, COLOR_PANEL_STROKE_LIGHT);
SetPanelFS( pState.GLDPanel, COLOR_PANEL_FILL_NORMAL, COLOR_PANEL_STROKE_LIGHT);
SetPanelFS( pState.EXPPanel, COLOR_PANEL_FILL_NORMAL, COLOR_PANEL_STROKE_LIGHT);
SetPanelFS( pState.buttonBG, COLOR_PANEL_FILL_DARK, COLOR_PANEL_STROKE_NORMAL);
(pState.buttonLabel as TLabel).Cursor := crHandPoint;
{
fAtlas.EmptyBitmap( pState.bonus1 );
fAtlas.EmptyBitmap( pState.bonus2 );
fAtlas.EmptyBitmap( pState.bonus3 );
fAtlas.EmptyBitmap( pState.bonus4 );
fAtlas.EmptyBitmap( pState.bonus5 );
fAtlas.EmptyBitmap( pState.bonus6 );
fAtlas.EmptyBitmap( pState.bonus7 );
fAtlas.EmptyBitmap( pState.bonus8 );
}
end;
procedure TInterfaceManager.ResetTopPanel;
/// сброс настроек элементов верхней панели
begin
// SetProgress( pTopPanel.progressBG, pTopPanel.progressFG, COLOR_COMMON_PROGRESS_BG, COLOR_COMMON_PROGRESS_FG );
(pLootPanel.buttonSettings as TImage).Cursor := crHandPoint;
end;
procedure TInterfaceManager.ResetWalkPanel;
/// задаем раскраску и картинки панели скорости перемещений
begin
SetPanelFS( pWalk.panel, COLOR_PANEL_FILL_NORMAL, COLOR_PANEL_STROKE_LIGHT);
SetPanelFS( pWalk.stepPanel1, COLOR_PANEL_FILL_NORMAL, COLOR_PANEL_STROKE_LIGHT);
SetPanelFS( pWalk.stepPanel2, COLOR_PANEL_FILL_NORMAL, COLOR_PANEL_STROKE_LIGHT);
SetPanelFS( pWalk.stepPanel3, COLOR_PANEL_FILL_NORMAL, COLOR_PANEL_STROKE_LIGHT);
fAtlas.AssignBitmap( (pWalk.stepImg1 as TImage), INT_WALK_1 );
(pWalk.stepImg1 as TImage).Cursor := crHandPoint;
fAtlas.AssignBitmap( (pWalk.stepImg2 as TImage), INT_WALK_2 );
(pWalk.stepImg2 as TImage).Cursor := crHandPoint;
fAtlas.AssignBitmap( (pWalk.stepImg3 as TImage), INT_WALK_3 );
(pWalk.stepImg3 as TImage).Cursor := crHandPoint;
fAtlas.AssignBitmap( (pWalk.jumpImg as TImage), INT_WALK_JUMP );
(pWalk.jumpImg as TImage).Cursor := crHandPoint;
SetProgress( pWalk.jumpBG, pWalk.jumpProgress, COLOR_COMMON_PROGRESS_BG, COLOR_COMMON_PROGRESS_FG );
end;
procedure TInterfaceManager.SetProgress(objBG, objFG: TObject; BG, FG: integer);
begin
// проверяем текущую цветность, чтобы запускать переотрисовку только при изменении
if (objBG as TRectangle).Fill.Color <> BG
then (objBG as TRectangle).Fill.Color := BG;
if (objBG as TRectangle).Stroke.Color <> BG
then (objBG as TRectangle).Stroke.Color := BG;
if (objFG as TRectangle).Fill.Color <> FG
then (objFG as TRectangle).Fill.Color := FG;
if (objFG as TRectangle).Stroke.Color <> FG
then (objFG as TRectangle).Stroke.Color := FG;
end;
procedure TInterfaceManager.SetKindProgress( kind: integer; percent: real; isFinished: boolean);
/// установка позиции прогресса отката
/// kind - константа указывающая на то, прогресс какого элемента требуется обновить
/// проверяется по константам KIND_PROGRESS_XXX
var
BG, FG: TObject;
begin
case kind of
KIND_PROGRESS_JUMP: begin BG := pWalk.jumpBG; FG := pWalk.jumpProgress; end;
// KIND_PROGRESS_LEVEL: begin BG := pTopPanel.progressBG; FG := pTopPanel.progressFG; end;
// KIND_PROGRESS_WEIGHT: begin BG := pTopPanel.weightBG; FG := pTopPanel.weightFG; end;
end;
if Assigned(BG) and Assigned(FG) then
begin
(FG as TRectangle).Width := (BG as TRectangle).Width * percent;
if isFinished
then SetProgress( BG, FG, COLOR_COMMON_PROGRESS_BG, COLOR_COMMON_PROGRESS_FG )
else SetProgress( BG, FG, COLOR_COMMON_PROGRESS_BG, COLOR_COMMON_PROGRESS_FULL_FG )
end;
end;
procedure TInterfaceManager.SetPanelFS(obj: TObject; fill, stroke: integer);
begin
(obj as TRectangle).Fill.Color := fill;
(obj as TRectangle).Stroke.Color := stroke;
end;
initialization
mngInterface := TInterfaceManager.Create;
finalization
mngInterface.Free;
end.
|
unit Controller.Register.Base;
interface
uses
Model.Register.Base, View.List.Base, View.Register.Base,
Controller.Singleton.Base, System.Classes;
type
TRegister<T: class; AModel: TdtmdlRegister; AViewList: TfrmList;
AViewRegister: TfrmRegister> = class(TSingleton<T>)
private
FModel: AModel;
FRegiste: AViewRegister;
FList: AViewList;
procedure SetList(const Value: AViewList);
procedure SetModel(const Value: AModel);
procedure SetRegiste(const Value: AViewRegister);
protected
procedure NewRegister; virtual;
procedure EditRegister; virtual;
procedure AssignPointer; virtual;
public
property Model: AModel read FModel write SetModel;
property List: AViewList read FList write SetList;
property Registe: AViewRegister read FRegiste write SetRegiste;
procedure ShowList; virtual;
constructor Create(AOwner: TComponent); override;
end;
implementation
uses
Vcl.Controls;
{ TRegister<T, AModel, AViewList, AViewRegister> }
procedure TRegister<T, AModel, AViewList, AViewRegister>.AssignPointer;
begin
FList.OnNewRegister := Self.NewRegister;
FList.OnEditRegister := Self.EditRegister;
FList.OnFilterList := FModel.FilterList;
FList.OnIndexFilter := FModel.IndexFilter;
FList.OnFillInField := FModel.FillInField;
FRegiste.OnSaveRegister := Model.SaveRegister;
FRegiste.OnCancelRegister := Model.CancelRegister;
end;
constructor TRegister<T, AModel, AViewList, AViewRegister>.Create
(AOwner: TComponent);
begin
inherited;
FModel := TComponentClass(AModel).Create(Self) as AModel;
FList := TComponentClass(AViewList).Create(Self) as AViewList;
FRegiste := TComponentClass(AViewRegister).Create(Self) as AViewRegister;
AssignPointer;
end;
procedure TRegister<T, AModel, AViewList, AViewRegister>.EditRegister;
begin
try
if not Model.IsListActive then
Exit;
Model.EditRegister;
Registe.ShowModal;
except
raise;
end;
end;
procedure TRegister<T, AModel, AViewList, AViewRegister>.NewRegister;
begin
try
Model.NewRegister;
Registe.ShowModal;
except
raise;
end;
end;
procedure TRegister<T, AModel, AViewList, AViewRegister>.SetList
(const Value: AViewList);
begin
FList := Value;
end;
procedure TRegister<T, AModel, AViewList, AViewRegister>.SetModel
(const Value: AModel);
begin
FModel := Value;
end;
procedure TRegister<T, AModel, AViewList, AViewRegister>.SetRegiste
(const Value: AViewRegister);
begin
FRegiste := Value;
end;
procedure TRegister<T, AModel, AViewList, AViewRegister>.ShowList;
begin
List.ShowModal();
end;
end.
|
unit TreeEditor;
//{$MODE Delphi}
interface
uses
{SysUtils, Windows,} Messages, {Classes,} Graphics, Controls,
Nodes;
type
TTreeEditor =
class(TObject)
protected
FTree : TNode;
FFocus : TNode;
FModified: Boolean;
procedure SetTree(ATree: TNode); virtual;
procedure SetFocus(AFocus: TNode); virtual;
public
property Tree : TNode read FTree write SetTree;
property Focus: TNode read FFocus write SetFocus;
property Modified: Boolean read FModified;
constructor Create;
destructor Destroy; override;
end;
implementation //================================================
{ TTreeEditor }
constructor TTreeEditor.Create;
begin
inherited Create;
FTree := nil;
FFocus := nil;
FModified := false;
end;
destructor TTreeEditor.Destroy;
begin
FTree.Free;
inherited Destroy;
end;
procedure TTreeEditor.SetFocus(AFocus: TNode);
begin
// should check whether AFocus occurs in FTree;
FFocus := AFocus;
end;
procedure TTreeEditor.SetTree(ATree: TNode);
begin
if FTree <> nil
then FTree.Free;
FTree := ATree;
end;
initialization
end.
|
unit Catalogs;
interface
uses
Windows, SysUtils, Classes, Controls, Forms, StdCtrls, ForestTypes,
ComCtrls, Grids, Dialogs;
type
TfrmCatalogs = class(TForm)
lblCatalog: TLabel;
lblValues: TLabel;
cmbCatalogs: TComboBox;
btnOk: TButton;
btnApply: TButton;
btnCancel: TButton;
lvValues: TListView;
btnClear: TButton;
btnEdit: TButton;
btnAdd: TButton;
btnDelete: TButton;
StatusBar1: TStatusBar;
procedure Apply;
procedure btnApplyClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure cmbCatalogsSelect(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
procedure lvValuesDblClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure lvValuesClick(Sender: TObject);
procedure lvValuesColumnClick(Sender: TObject; Column: TListColumn);
procedure lvValuesCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
private
{ Private declarations }
FWordsArr: TCatalogArr;
FCheckedCount: Integer;
FSortedColumn: Integer;
FDescending: Boolean;
procedure EditItem(ItemIndex: Integer; MultiValue: Boolean = False);
procedure ResetControls;
function GetClickedItemIndex: Integer;
public
{ Public declarations }
end;
var
frmCatalogs: TfrmCatalogs;
implementation
uses
Data, ForestConsts, Edit;
{$R *.dfm}
//---------------------------------------------------------------------------
{ TfrmCatalogs }
procedure TfrmCatalogs.Apply;
var
I, NewLength: Integer;
begin
SetLength(FWordsArr, 0);
for I := 0 to lvValues.Items.Count - 1 do
begin
NewLength := Length(FWordsArr);
SetLength(FWordsArr, NewLength + 1);
FWordsArr[I].OldWord := lvValues.Items.Item[I].Caption;
FWordsArr[I].NewWord := lvValues.Items.Item[I].SubItems[0];
FWordsArr[I].NewIndex := StrToInt(lvValues.Items.Item[I].SubItems[1]);
end;
dmData.Validator.GetDictionary(cmbCatalogs.Text).CatalogArr := FWordsArr;
cmbCatalogsSelect(Application);
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.btnAddClick(Sender: TObject);
var
Item: TListItem;
begin
Item := lvValues.Items.Add;
Item.Caption := '';
Item.SubItems.Add('');
Item.SubItems.Add('');
EditItem(lvValues.Items.IndexOf(Item));
ResetControls();
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.btnApplyClick(Sender: TObject);
begin
Apply();
ResetControls();
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.btnClearClick(Sender: TObject);
begin
lvValues.Clear();
ResetControls();
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.btnDeleteClick(Sender: TObject);
var
I: Integer;
begin
for I := lvValues.Items.Count - 1 downto 0 do
if lvValues.Items.Item[I].Checked then
lvValues.Items.Delete(I);
ResetControls();
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.btnEditClick(Sender: TObject);
var
I, EditedID: Integer;
begin
EditedID := -1;
for I := 0 to lvValues.Items.Count - 1 do
if lvValues.Items.Item[I].Checked then
begin
EditedID := I;
EditItem(EditedID, True);
Break;
end;
if EditedID = -1 then
Exit;
for I := 0 to lvValues.Items.Count - 1 do
begin
if I = EditedID then // dot't touch edited item
Continue;
if lvValues.Items.Item[I].Checked then
begin
lvValues.Items.Item[I].SubItems[0] := lvValues.Items.Item[EditedID].SubItems[0];
lvValues.Items.Item[I].SubItems[1] := lvValues.Items.Item[EditedID].SubItems[1];
end;
end;
ResetControls();
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.btnOkClick(Sender: TObject);
begin
Apply();
ResetControls();
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.cmbCatalogsSelect(Sender: TObject);
var
I: Integer;
Item: TListItem;
begin
lvValues.Clear();
FWordsArr := dmData.Validator.GetDictionary(cmbCatalogs.Text).CatalogArr;
for I := 0 to Length(FWordsArr) - 1 do
begin
Item := lvValues.Items.Add;
Item.Caption := FWordsArr[I].OldWord;
Item.SubItems.Add(FWordsArr[I].NewWord);
Item.SubItems.Add(IntToStr(FWordsArr[I].NewIndex));
end;
ResetControls();
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.EditItem(ItemIndex: Integer; MultiValue: Boolean = False);
var
Prompt: AnsiString;
begin
if MultiValue then
Prompt := 'Несколько значений'
else
Prompt := lvValues.Items.Item[ItemIndex].Caption;
ShowEditEx(Prompt, 'Выберите новое значение', dmData.Validator.GetDictionary(cmbCatalogs.Text), True);
lvValues.Items.Item[ItemIndex].Caption := frmEdit.edtWord.Text;
lvValues.Items.Item[ItemIndex].SubItems[0] := frmEdit.CurrentText;
lvValues.Items.Item[ItemIndex].SubItems[1] := IntToStr(frmEdit.CurrentIndex);
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.FormCreate(Sender: TObject);
begin
cmbCatalogs.Clear();
// Yes, this! Because i can modify caption later
cmbCatalogs.Items.Add(dmData.Validator.GetDictionary(S_DICT_FORESTRIES_NAME).Caption);
cmbCatalogs.Items.Add(dmData.Validator.GetDictionary(S_DICT_LOCAL_FORESTRIES_NAME).Caption);
cmbCatalogs.Items.Add(dmData.Validator.GetDictionary(S_DICT_LANDUSE_NAME).Caption);
cmbCatalogs.Items.Add(dmData.Validator.GetDictionary(S_DICT_PROTECT_CATEGORY_NAME).Caption);
cmbCatalogs.Items.Add(dmData.Validator.GetDictionary(S_DICT_SPECIES_NAME).Caption);
cmbCatalogs.Items.Add(dmData.Validator.GetDictionary(S_DICT_DAMAGE_NAME).Caption);
cmbCatalogs.Items.Add(dmData.Validator.GetDictionary(S_DICT_PEST_NAME).Caption);
cmbCatalogs.ItemIndex := 0;
cmbCatalogsSelect(Sender);
ResetControls();
end;
//---------------------------------------------------------------------------
function TfrmCatalogs.GetClickedItemIndex: Integer;
var
CursorPos: TPoint;
Item: TListItem;
begin
GetCursorPos(CursorPos);
CursorPos := ScreenToClient(CursorPos);
CursorPos.X := CursorPos.X - lvValues.Left - 2;
CursorPos.Y := CursorPos.Y - lvValues.Top;
try
Item := lvValues.GetItemAt(CursorPos.X, CursorPos.Y);
Result := lvValues.Items.IndexOf(Item);
except
Result := -1;
end;
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.lvValuesClick(Sender: TObject);
begin
ResetControls();
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.lvValuesColumnClick(Sender: TObject;
Column: TListColumn);
begin
TListView(Sender).SortType := stNone;
if Column.Index <> FSortedColumn then
begin
FSortedColumn := Column.Index;
FDescending := False;
end
else
FDescending := not FDescending;
TListView(Sender).SortType := stText;
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.lvValuesCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
begin
if FSortedColumn = 0 then
Compare := CompareText(Item1.Caption, Item2.Caption)
else
if FSortedColumn <> 0 then
Compare := CompareText(Item1.SubItems[FSortedColumn - 1], Item2.SubItems[FSortedColumn - 1]);
if FDescending then Compare := -Compare;
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.lvValuesDblClick(Sender: TObject);
var
ItemIndex: Integer;
begin
ItemIndex := GetClickedItemIndex();
if ItemIndex = -1 then
Exit;
EditItem(ItemIndex);
ResetControls();
end;
//---------------------------------------------------------------------------
procedure TfrmCatalogs.ResetControls;
var
I: Integer;
begin
FCheckedCount := 0;
for I := 0 to lvValues.Items.Count - 1 do
if lvValues.Items.Item[I].Checked then
Inc(FCheckedCount);
btnDelete.Enabled := FCheckedCount > 0;
btnEdit.Enabled := FCheckedCount > 0;
end;
end.
|
unit uzEstruturaTabs;
//************************************************
//* Source created with NexusDb Source Maker *
//* Version 1.1.4 *
//* *
//* by Roberto Nicchi *
//* M a s t e r Informatica *
//* Italy *
//* software@masterinformatica.net *
//* *
//* Source creation date: 10/3/2008 *
//* *
//************************************************
Interface
Uses classes, nxdb, nxsdDataDictionary, nxsdTypes, nxlltypes, nxllutils, nxsqlProxies, nxsdserverengine;
type
TsmDictFn=function(tablename:string):TnxDataDictionary;
TnsmCreateDatabaseCb=procedure(table:string;tableindex:integer);
TnsmRestructureDatabaseCb=procedure(table:string;tableindex:integer;op:smallint);
TnsmRestructureTableCb=procedure(table:string;perc:integer);
TnsmVerifyDatabaseCb=procedure(table:string;tableindex:integer);
TnsmVerifyDatabaseErrorCb=procedure(table:string);
TnsmRenamedFieldCb=procedure(table,field:string;var newfield:string);
// Database methods
procedure CreateZorroDatabase(db:TnxDatabase;overwrite:boolean=false;creating:TnsmCreateDatabaseCb=nil);
procedure RestructureZorroDatabase(db:TnxDatabase;MatchFieldsBy:smallint=0;RestructuringDatabase:TnsmRestructureDatabaseCb=nil;RestructuringTable:TnsmRestructureTableCb=nil;VerifyRenamedField:TnsmRenamedFieldCb=nil);
function VerifyZorroDatabase(db:TnxDatabase;Verifying:TnsmVerifyDatabaseCb=nil;verifyerror:TnsmVerifyDatabaseErrorCb=nil):boolean;
function ZorroDbVersion:string;
function ZorroTablesCount:integer;
procedure ZorroGetTableNames(tables:Tstrings);
// Tables methods
function TableDataDictionary(tablename:string):TnxDataDictionary;
procedure CreateTableByDict(db:TnxDatabase;tablename:string;dict:TnxDataDictionary;overwrite:boolean=false);
procedure CreateTable(db:TnxDatabase;tablename:string;overwrite:boolean=false);
function VerifyTableStructureByDict(db:TnxDatabase;tablename:string;dict:TnxDataDictionary):integer;
function VerifyTableStructure(db:TnxDatabase;tablename:string):integer;
procedure RestructureTableByDict(db:TnxDatabase;tablename:string;newdict:TnxDataDictionary;MatchFieldsBy:smallint=0;Restructuring:TnsmRestructureTableCb=nil;VerifyRenamedField:TnsmRenamedFieldCb=nil);
procedure RestructureTable(db:TnxDatabase;tablename:string;MatchFieldsBy:smallint=0;Restructuring:TnsmRestructureTableCb=nil;VerifyRenamedField:TnsmRenamedFieldCb=nil);
function bancoTableDataDictionary:TnxDataDictionary;
function boletoTableDataDictionary:TnxDataDictionary;
Implementation
var
Ftables:Tstringlist;
procedure SetExtTextKeyFieldDescriptorOptions(kfd:TnxKeyFieldDescriptor;ignorecase,ignorekanatype,ignorenonspace,ignoresymbols,ignorewidth,usestringsort:boolean;locale:integer);
begin
(kfd as TnxExtTextKeyFieldDescriptor).ignorecase:=ignorecase;
(kfd as TnxExtTextKeyFieldDescriptor).ignoreKanatype:=ignoreKanatype;
(kfd as TnxExtTextKeyFieldDescriptor).ignorenonspace:=ignorenonspace;
(kfd as TnxExtTextKeyFieldDescriptor).ignoresymbols:=ignoresymbols;
(kfd as TnxExtTextKeyFieldDescriptor).ignorewidth:=ignorewidth;
(kfd as TnxExtTextKeyFieldDescriptor).usestringsort:=usestringsort;
(kfd as TnxExtTextKeyFieldDescriptor).locale:=locale;
end;
function bancoTableDataDictionary:TnxDataDictionary;
var
dict:TnxDataDictionary;
indexdescriptor:TnxIndexDescriptor;
kfd:TnxKeyFieldDescriptor;
fd:TnxFieldDescriptor;
filedescriptorindex:integer;
begin
dict:=TnxDataDictionary.create;
filedescriptorindex:=0;
dict.filedescriptor[filedescriptorindex].blocksize:=nxbs4k;
dict.filedescriptor[filedescriptorindex].desc:='';
dict.filedescriptor[filedescriptorindex].initialsize:=4;
dict.filedescriptor[filedescriptorindex].growsize:=1;
dict.encryptionengine:='';
// Fields
dict.addfield('Num','',nxtNullString,3,0,False);
dict.addfield('Nome','',nxtNullString,60,0,False);
dict.addfield('Abrev','',nxtNullString,20,0,False);
// Indexes
FileDescriptorIndex:=0;
indexdescriptor:=dict.AddIndex('INum',filedescriptorindex,True,'',TnxCompKeyDescriptor);
indexdescriptor.desc:='';
indexdescriptor.indexfile.blocksize:=nxbs4k;
kfd:=TnxCompKeyDescriptor(indexdescriptor.keydescriptor).Add(dict.GetFieldFromName('Num'),TnxExtTextKeyFieldDescriptor);
SetExtTextKeyFieldDescriptorOptions(kfd,True,True,True,False,True,False,1046);
FileDescriptorIndex:=0;
indexdescriptor:=dict.AddIndex('INome',filedescriptorindex,True,'',TnxCompKeyDescriptor);
indexdescriptor.desc:='';
indexdescriptor.indexfile.blocksize:=nxbs4k;
kfd:=TnxCompKeyDescriptor(indexdescriptor.keydescriptor).Add(dict.GetFieldFromName('Nome'),TnxExtTextKeyFieldDescriptor);
SetExtTextKeyFieldDescriptorOptions(kfd,True,True,True,False,True,False,1046);
FileDescriptorIndex:=0;
indexdescriptor:=dict.AddIndex('IAbrev',filedescriptorindex,True,'',TnxCompKeyDescriptor);
indexdescriptor.desc:='';
indexdescriptor.indexfile.blocksize:=nxbs4k;
kfd:=TnxCompKeyDescriptor(indexdescriptor.keydescriptor).Add(dict.GetFieldFromName('Abrev'),TnxExtTextKeyFieldDescriptor);
SetExtTextKeyFieldDescriptorOptions(kfd,True,True,True,False,True,False,1046);
result:=dict;
end;
function boletoTableDataDictionary:TnxDataDictionary;
var
dict:TnxDataDictionary;
indexdescriptor:TnxIndexDescriptor;
kfd:TnxKeyFieldDescriptor;
fd:TnxFieldDescriptor;
filedescriptorindex:integer;
begin
dict:=TnxDataDictionary.create;
filedescriptorindex:=0;
dict.filedescriptor[filedescriptorindex].blocksize:=nxbs4k;
dict.filedescriptor[filedescriptorindex].desc:='';
dict.filedescriptor[filedescriptorindex].initialsize:=4;
dict.filedescriptor[filedescriptorindex].growsize:=1;
dict.encryptionengine:='';
// Fields
dict.addfield('ID','',nxtAutoinc,10,0,False);
fd:=dict.addfield('Tipo','',nxtByte,3,0,False);
with TnxConstDefaultValueDescriptor(fd.AddDefaultValue(TnxConstDefaultValueDescriptor)) do VariantToNative(fd.fdType, '0', cdvDefaultValue, fd.fdLength);
dict.addfield('Fornecedor','',nxtInt32,10,0,False);
dict.addfield('CodigoBarras','',nxtNullString,44,0,False);
dict.addfield('LinhaDig','',nxtNullString,47,0,False);
dict.addfield('Scan','',nxtDateTime,0,0,False);
dict.addfield('Vencimento','',nxtDate,0,0,False);
dict.addfield('Pagamento','',nxtDateTime,0,0,False);
dict.addfield('Valor','',nxtCurrency,0,0,False);
dict.addfield('Banco','',nxtNullString,3,0,False);
dict.addfield('ImBoleto','',nxtBlobGraphic,0,0,False);
dict.addfield('ImPagto','',nxtBlobGraphic,0,0,False);
dict.addfield('ServPub','',nxtBoolean,0,0,False);
dict.addfield('Descr','',nxtNullString,50,0,False);
dict.addfield('Obs','',nxtBlobMemo,0,0,False);
// Indexes
FileDescriptorIndex:=0;
indexdescriptor:=dict.AddIndex('IID',filedescriptorindex,True,'',TnxCompKeyDescriptor);
indexdescriptor.desc:='';
indexdescriptor.indexfile.blocksize:=nxbs4k;
kfd:=TnxCompKeyDescriptor(indexdescriptor.keydescriptor).Add(dict.GetFieldFromName('ID'));
FileDescriptorIndex:=0;
indexdescriptor:=dict.AddIndex('ICodBar',filedescriptorindex,True,'',TnxCompKeyDescriptor);
indexdescriptor.desc:='';
indexdescriptor.indexfile.blocksize:=nxbs4k;
kfd:=TnxCompKeyDescriptor(indexdescriptor.keydescriptor).Add(dict.GetFieldFromName('CodigoBarras'),TnxExtTextKeyFieldDescriptor);
SetExtTextKeyFieldDescriptorOptions(kfd,True,True,True,False,True,False,1046);
FileDescriptorIndex:=0;
indexdescriptor:=dict.AddIndex('IVencimento',filedescriptorindex,True,'',TnxCompKeyDescriptor);
indexdescriptor.desc:='';
indexdescriptor.indexfile.blocksize:=nxbs4k;
kfd:=TnxCompKeyDescriptor(indexdescriptor.keydescriptor).Add(dict.GetFieldFromName('Vencimento'));
FileDescriptorIndex:=0;
indexdescriptor:=dict.AddIndex('IPagto',filedescriptorindex,True,'',TnxCompKeyDescriptor);
indexdescriptor.desc:='';
indexdescriptor.indexfile.blocksize:=nxbs4k;
kfd:=TnxCompKeyDescriptor(indexdescriptor.keydescriptor).Add(dict.GetFieldFromName('Pagamento'));
result:=dict;
end;
procedure inittableslist;
begin
if assigned(Ftables) then exit;
Ftables:=Tstringlist.create;
Ftables.addobject('banco',@bancoTableDataDictionary);
Ftables.addobject('boleto',@boletoTableDataDictionary);
end;
procedure cleanuptableslist;
begin
if assigned(Ftables) then
begin
Ftables.free;
Ftables:=nil;
end
end;
function TableDataDictionary(tablename:string):TnxDataDictionary;
var
dictfn:TsmDictFn;
idx:integer;
begin
idx:=Ftables.indexof(tablename);
dictfn:=TsmDictFn(Ftables.Objects[idx]);
result:=dictfn(tablename);
end;
procedure CreateTableByDict(db:TnxDatabase;tablename:string;dict:TnxDataDictionary;overwrite:boolean=false);
begin
db.createtable(overwrite,tablename,dict);
end;
procedure CreateTable(db:TnxDatabase;tablename:string;overwrite:boolean=false);
var
dict:TnxDataDictionary;
begin
dict:=tabledatadictionary(tablename);
try
CreateTableByDict(db,tablename,dict,overwrite);
finally
dict.free;
end;
end;
function VerifyTableStructureByDict(db:TnxDatabase;tablename:string;dict:TnxDataDictionary):integer;
var
tmptable:TnxTable;
begin
result:=0;
if not(db.tableexists(tablename)) then
begin
result:=1;
exit;
end;
tmptable:=TnxTable.create(nil);
try
tmptable.database:=db;
tmptable.tablename:=tablename;
tmptable.open;
if not(tmptable.dictionary.isequal(dict)) then
result:=2;
finally
tmptable.free;
end;
end;
function VerifyTableStructure(db:TnxDatabase;tablename:string):integer;
var
dict:TnxDataDictionary;
begin
dict:=tabledatadictionary(tablename);
try
result:=VerifyTableStructureByDict(db,tablename,dict);
finally
dict.free;
end;
end;
procedure RestructureTableByDict(db:TnxDatabase;tablename:string;newdict:TnxDataDictionary;MatchFieldsBy:smallint=0;Restructuring:TnsmRestructureTableCb=nil;VerifyRenamedField:TnsmRenamedFieldCb=nil);
var
tmptable:TnxTable;
idx:integer;
dict:TnxDataDictionary;
fieldmap:Tstringlist;
done:boolean;
TaskStatus : TnxTaskStatus;
TaskInfo : TnxAbstractTaskInfo;
res:Tnxresult;
fieldname:string;
newfield:string;
begin
tmptable:=TnxTable.create(nil);
try
tmptable.database:=db;
tmptable.tablename:=tablename;
tmptable.open;
dict:=TnxDataDictionary.create;
try
dict.assign(tmptable.dictionary);
tmptable.close;
tmptable.dictionary.assign(newdict);
fieldmap:=Tstringlist.create;
try
for idx:=0 to dict.fieldcount-1 do
begin
if MatchFieldsBy=0 then
begin
if not(tmptable.Dictionary.GetFieldFromName(dict.fielddescriptor[idx].name)=-1) then
fieldmap.add(dict.fielddescriptor[idx].name+'='+dict.fielddescriptor[idx].name)
else begin
if assigned(VerifyRenamedField) then
begin
newfield:='';
VerifyRenamedField(tablename,dict.fielddescriptor[idx].name,newfield);
if not(newfield='') then
fieldmap.add(newfield+'='+dict.fielddescriptor[idx].name);
end;
end;
end;
if MatchFieldsBy=1 then
begin
if (idx < newdict.FieldCount) then
begin
fieldname:=newdict.fielddescriptor[idx].name;
fieldmap.add(fieldname+'='+dict.fielddescriptor[idx].name);
end;
end;
end;
res:=tmptable.restructuretable(newdict,fieldmap,taskinfo);
finally
fieldmap.free;
end;
finally
dict.free;
end;
taskinfo.GetStatus(Done,TaskStatus);
while not Done do
begin
if assigned(Restructuring) then Restructuring(tablename,TaskStatus.tsPercentDone);
taskinfo.GetStatus(Done,TaskStatus);
end;
finally
if assigned(taskinfo) then taskinfo.free;
tmptable.free;
end;
end;
procedure RestructureTable(db:TnxDatabase;tablename:string;MatchFieldsBy:smallint=0;Restructuring:TnsmRestructureTableCb=nil;VerifyRenamedField:TnsmRenamedFieldCb=nil);
var
dict:TnxDataDictionary;
begin
dict:=TableDataDictionary(tablename);
try
RestructureTableByDict(db,tablename,dict,MatchFieldsBy,Restructuring,VerifyRenamedField);
finally
dict.free;
end;
end;
procedure CreateZorroDatabase(db:TnxDatabase;overwrite:boolean=false;Creating:TnsmCreateDatabaseCb=nil);
var
idx:integer;
tablename:string;
begin
for idx:=0 to Ftables.count-1 do
begin
tablename:=Ftables[idx];
if assigned(Creating) then Creating(tablename,1);
createtable(db,tablename,overwrite);
end;
end;
procedure RestructureZorroDatabase(db:TnxDatabase;MatchFieldsBy:smallint=0;RestructuringDatabase:TnsmRestructureDatabaseCb=nil;RestructuringTable:TnsmRestructureTableCb=nil;VerifyRenamedField:TnsmRenamedFieldCb=nil);
var
idx:integer;
tablename:string;
res:smallint;
begin
for idx:=0 to Ftables.count-1 do
begin
tablename:=Ftables[idx];
res:=verifytablestructure(db,tablename);
if assigned(RestructuringDatabase) then RestructuringDatabase(tablename,idx+1,res);
if res=1 then createtable(db,tablename)
else if res=2 then restructuretable(db,tablename,matchfieldsby,RestructuringTable,VerifyRenamedField);
end;
end;
function VerifyZorroDatabase(db:TnxDatabase;Verifying:TnsmVerifyDatabaseCb=nil;verifyerror:TnsmVerifyDatabaseErrorCb=nil):boolean;
var
idx:integer;
tablename:string;
res:smallint;
begin
result:=true;
for idx:=0 to Ftables.count-1 do
begin
tablename:=Ftables[idx];
if assigned(Verifying) then Verifying(tablename,idx+1);
res:=verifytablestructure(db,tablename);
if not(res=0) then
begin
result:=false;
if assigned(verifyerror) then verifyerror(tablename);
end;
end;
end;
function ZorroDbVersion:string;
begin
result:='';
end;
function ZorroTablesCount:integer;
begin
result:=2;
end;
procedure ZorroGetTableNames(tables:Tstrings);
begin
tables.assign(Ftables);
end;
initialization
inittableslist;
finalization
cleanuptableslist;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSAzureTable;
interface
uses AzureUI, System.Classes, Vcl.ComCtrls, Vcl.Controls, Vcl.ImgList, Vcl.Menus;
type
///<summary> The possible types of Azure table nodes.
///</summary>
TNodeType = (aztUnknown, aztTables, aztTable, aztLoading, aztTruncated);
///<summary>
/// Data to store with a node which holds its value, and type.
///</summary>
TNodeData = class
protected
FValue: String;
FNodeType: TNodeType;
public
constructor Create(NodeType: TNodeType = aztUnknown); Virtual;
///<summary> The value associated with the node. </summary>
///<remarks> May be the same as the Node's text, although this value will never be truncated. </remarks>
property Value: String read FValue write FValue;
///<summary> The node's type. </summary>
property NodeType: TNodeType read FNodeType write FNodeType;
end;
///<summary>
/// Component for managing Azure Tables on Windows Azure.
///</summary>
///<remarks>
/// A tree component for viewing all of the tables stored for the given Windows Azure connection.
/// Each table has entities (rows) which are visible in a dialog accessable from each table node.
///</remarks>
TAzureTableManagement = class(TAzureManagement)
protected
FActive: Boolean;
FCustomImages: TCustomImageList;
FMenuNode: TTreeNode;
FAdvancedFilterPrefix: String;
FForceCollapse: Boolean;
procedure SetCustomImages(Value: TCustomImageList);
procedure ForceCollapse(Node: TTreeNode; FullCollapse: Boolean = True);
procedure InitializeTree;
procedure HandleNodeExpanded(Sender: TObject; Node: TTreeNode);
procedure HandleCreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass);
procedure HandleNodeCollapsing(Sender: TObject; Node: TTreeNode; var AllowCollapse: Boolean);
function Activate: Boolean;
procedure SetActive(Active: Boolean);
//Checks given node and recursivly searches all child nodes
//to see if any node is expanded and has a loading node as its child.
function HasLoadingNode(Node: TTreeNode): Boolean;
function isNodeLoading(Node: TTreeNode): Boolean;
function CreatePopupMenu: TPopupMenu;
procedure UpdatePopupMenu(Sender: TObject);
function CreateImageList: TCustomImageList;
procedure OnImageIndex(Sender: TObject; Node: TTreeNode);
procedure HandleDoubleClick(Sender: TObject);
procedure HandleKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
//Context Menu actions
procedure ActivateAction(Sender: TObject);
procedure AddTableAction(Sender: TObject);
procedure RemoveTableAction(Sender: TObject);
procedure ViewTableAction(Sender: TObject);
procedure RefreshTablesAction(Sender: TObject);
procedure OpenViewTableDialog(TableNode: TTreeNode);
//Callbacks for action threads (refresh/add/remove)
procedure PopulateTables(Node: TTreeNode; TableNames: TStringList; StartingTable: String;
NextTableName: String; ForceExpand: Boolean; ErrorMessage: String);
procedure TableCreated(TableName: String; Success: Boolean; ForceExpand: Boolean);
procedure TableDeleted(TableName: String; Success: Boolean; ForceExpand: Boolean);
//Helper functions for managing nodes
function CreateLoadingNode(ParentNode: TTreeNode): TTreeNode;
function CreateLoadMoreNode(ParentNode: TTreeNode): TTreeNode;
procedure PopulateForNode(Node: TTreeNode; ForceExpand: Boolean = True);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Align;
property Anchors;
property AutoExpand;
property BevelEdges;
property BevelInner;
property BevelOuter;
property BevelKind default bkNone;
property BevelWidth;
property BiDiMode;
property BorderStyle;
property BorderWidth;
property ChangeDelay;
property Color;
property Ctl3D;
property Constraints;
property DoubleBuffered;
property DragKind;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property RowSelect;
property Touch;
property Visible;
property ConnectionInfo;
/// <summary>
/// Character(s) to type first into the filter field of the table dialog for advanced filtering
/// </summary>
/// <remarks> To have the rest of the filter treated as an expression instead of a RowKey or PartitionKey </remarks>
property AdvancedFilterPrefix: String read FAdvancedFilterPrefix write FAdvancedFilterPrefix;
/// <summary> Images to use instead of the default tree node images </summary>
/// <remarks> In the (index) order of: Tables, Table, Load More Tables </remarks>
property CustomImages: TCustomImageList read FCustomImages write SetCustomImages;
/// <summary> Set to True to be able to connect to azure and populate the tree. </summary>
property Active: Boolean read FActive write SetActive;
end;
const
ADD_TABLE = 'AddTable';
REMOVE_TABLE = 'RemoveTable';
VIEW_TABLE_DATA = 'ViewData';
REFRESH_SEL = 'Refresh';
ACTIVATE_ITEM = 'Activate';
NODE_TABLE = 'entry';
NODE_TABLE_CONTENT = 'content';
NODE_PROPERTIES = 'm:properties';
NODE_TABLE_NAME = 'd:TableName';
implementation
uses
Winapi.ActiveX, Data.DBXClientResStrs, Vcl.Dialogs, DSAzure, DSAzureTableDialog, Vcl.ExtCtrls,
Vcl.Graphics, System.SysUtils, Winapi.Windows, Xml.XMLDoc, Xml.XMLIntf;
type
TTablesPopulatedCallback = procedure(Node: TTreeNode; TableNames: TStringList; StartingTable: String;
NextTableName: String; ForceExpand: Boolean; ErrorMessage: String) of object;
TTableCreatedCallback = procedure(TableName: String; Success: Boolean; ForceExpand: Boolean) of object;
TTableDeletedCallback = procedure(TableName: String; Success: Boolean; ForceExpand: Boolean) of object;
TTablesPopulator = class(TThread)
protected
FNode: TTreeNode;
FConnectionInfo: TAzureConnectionString;
FCallback: TTablesPopulatedCallback;
FTableService: TAzureTableService;
FForceExpand: Boolean;
FStartingTable: String;
public
constructor Create(Node: TTreeNode; ConnectionInfo: TAzureConnectionString;
Callback: TTablesPopulatedCallback; StartingTable: String;
ForceExpand: Boolean); Virtual;
destructor Destroy; override;
procedure Execute; override;
end;
TTableCreator = class(TThread)
protected
FTableName: String;
FConnectionInfo: TAzureConnectionString;
FCallback: TTableCreatedCallback;
FTableService: TAzureTableService;
FForceExpand: Boolean;
public
constructor Create(TableName: String; ConnectionInfo: TAzureConnectionString;
Callback: TTableCreatedCallback; ForceExpand: Boolean); Virtual;
destructor Destroy; override;
procedure Execute; override;
end;
TTableDeletor = class(TThread)
protected
FTableName: String;
FConnectionInfo: TAzureConnectionString;
FCallback: TTableDeletedCallback;
FTableService: TAzureTableService;
FForceExpand: Boolean;
public
constructor Create(TableName: String; ConnectionInfo: TAzureConnectionString;
Callback: TTableDeletedCallback; ForceExpand: Boolean); Virtual;
destructor Destroy; override;
procedure Execute; override;
end;
function GetNodeData(Node: TTreeNode; NodeType: TNodeType = aztUnknown): TNodeData;
begin
//NodeType should only be unknown if the data is already assigned and not being created here
Assert((NodeType <> aztUnknown) or Assigned(Node.Data));
if not Assigned(Node.Data) then
begin
Node.Data := Pointer(TNodeData.Create);
TNodeData(Node.Data).NodeType := NodeType;
end;
Result := TNodeData(Node.Data);
end;
{ TNodeData }
constructor TNodeData.Create(NodeType: TNodeType);
begin
FNodeType := NodeType;
end;
{ TAzureTableManagement }
function TAzureTableManagement.Activate: Boolean;
begin
Result := False;
if FConnectionInfo <> nil then
begin
InitializeTree;
Result := True;
end;
end;
procedure TAzureTableManagement.ActivateAction(Sender: TObject);
begin
SetActive(True);
end;
procedure TAzureTableManagement.AddTableAction(Sender: TObject);
var
TableName: String;
begin
if not IsNodeLoading(GetNodeAt(0, 0)) then
begin
TableName := InputBox(SAddTable, SAddTableMessage, EmptyStr);
if TableName <> EmptyStr then
begin
TableName := AnsiLowerCase(TableName);
TTableCreator.Create(TableName, FConnectionInfo, TableCreated, True);
end;
end;
end;
constructor TAzureTableManagement.Create(AOwner: TComponent);
begin
inherited;
FActive := False;
ReadOnly := True;
OnExpanded := HandleNodeExpanded;
OnCollapsing := HandleNodeCollapsing;
OnGetImageIndex := OnImageIndex;
OnCreateNodeClass := HandleCreateNodeClass;
OnDblClick := HandleDoubleClick;
OnKeyUp := HandleKeyUp;
PopupMenu := CreatePopupMenu;
Images := CreateImageList;
RightClickSelect := True;
FMenuNode := nil;
FAdvancedFilterPrefix := '~';
TAzureService.SetUp;
end;
function TAzureTableManagement.CreateImageList: TCustomImageList;
var
Images: TCustomImageList;
BMP: Vcl.Graphics.TBitmap;
begin
Images := TCustomImageList.Create(Self);
BMP := GetAzureImage('IMG_AZURETABLES');
Images.Add(BMP, nil);
BMP.Free;
BMP := GetAzureImage('IMG_AZURETABLE');
Images.Add(BMP, nil);
BMP.Free;
BMP := GetAzureImage('IMG_AZUREMORETABLES');
Images.Add(BMP, nil);
BMP.Free;
Result := Images;
end;
function TAzureTableManagement.CreateLoadingNode(ParentNode: TTreeNode): TTreeNode;
var
Node: TTreeNode;
Nodedata: TNodeData;
begin
Node := Items.AddChild(ParentNode, SNodeLoading);
NodeData := GetNodeData(Node, aztLoading);
NodeData.Value := Node.Text;
Result := Node;
end;
function TAzureTableManagement.CreateLoadMoreNode(ParentNode: TTreeNode): TTreeNode;
var
Node: TTreeNode;
Nodedata: TNodeData;
begin
Node := Items.AddChild(ParentNode, SMoreTables);
NodeData := GetNodeData(Node, aztTruncated);
NodeData.Value := Node.Text;
CreateLoadingNode(Node);
Result := Node;
end;
function TAzureTableManagement.CreatePopupMenu: TPopupMenu;
var
Menu: TPopupMenu;
Item: TMenuItem;
begin
Menu := TPopupMenu.Create(Self);
Menu.OnPopup := UpdatePopupMenu;
Item := Menu.CreateMenuItem;
Item.Name := ACTIVATE_ITEM;
Item.Caption := SActivate;
Item.OnClick := ActivateAction;
Menu.Items.Add(Item);
Item := Menu.CreateMenuItem;
Item.Name := ADD_TABLE;
Item.Caption := SAddTable;
Item.OnClick := AddTableAction;
Menu.Items.Add(Item);
Item := Menu.CreateMenuItem;
Item.Name := REMOVE_TABLE;
Item.Caption := SRemoveTable;
Item.OnClick := RemoveTableAction;
Menu.Items.Add(Item);
Item := Menu.CreateMenuItem;
Item.Name := VIEW_TABLE_DATA;
Item.Caption := SViewTableData;
Item.OnClick := ViewTableAction;
Menu.Items.Add(Item);
Item := Menu.CreateMenuItem;
Item.Name := 'N1';
Item.Caption := cLineCaption;
Menu.Items.Add(Item);
Item := Menu.CreateMenuItem;
Item.Name := REFRESH_SEL;
Item.Caption := SRefresh;
Item.OnClick := RefreshTablesAction;
Menu.Items.Add(Item);
Result := Menu;
end;
destructor TAzureTableManagement.Destroy;
begin
if not Assigned(CustomImages) and Assigned(Images) then
begin
Images.Clear;
Images.Free;
Images := nil;
end;
inherited;
end;
procedure TAzureTableManagement.ForceCollapse(Node: TTreeNode; FullCollapse: Boolean);
begin
FForceCollapse := True;
try
if Node = nil then
Node := Items.GetFirstNode;
if Node <> nil then
Node.Collapse(FullCollapse);
finally
FForceCollapse := False;
end;
end;
procedure TAzureTableManagement.HandleCreateNodeClass(Sender: TCustomTreeView; var NodeClass: TTreeNodeClass);
begin
NodeClass := TAzureTreeNode;
end;
procedure TAzureTableManagement.HandleDoubleClick(Sender: TObject);
begin
OpenViewTableDialog(Selected);
end;
procedure TAzureTableManagement.HandleKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
var
Data: TNodeData;
begin
if Selected = nil then
Exit;
Data := Selected.Data;
if (Data.NodeType = aztTables) and (Key = VK_F5) then
RefreshTablesAction(Sender)
else if Data.NodeType = aztTable then
begin
if (Key = VK_DELETE) then
begin
FMenuNode := Selected;
RemoveTableAction(Sender);
end
else if (Key = VK_RETURN) then
begin
while ssShift in Shift do
begin
OpenViewTableDialog(Selected);
Break;
end;
end;
end;
end;
procedure TAzureTableManagement.HandleNodeCollapsing(Sender: TObject; Node: TTreeNode; var AllowCollapse: Boolean);
begin
AllowCollapse := FForceCollapse or not isNodeLoading(Node);
end;
procedure TAzureTableManagement.HandleNodeExpanded(Sender: TObject; Node: TTreeNode);
var
NodeData: TNodeData;
LoadingNode: TTreeNode;
begin
if isNodeLoading(Node) then
begin
LoadingNode := Node.getFirstChild;
NodeData := GetNodeData(LoadingNode);
Assert(NodeData.NodeType = aztLoading);
PopulateForNode(Node);
end;
end;
function TAzureTableManagement.HasLoadingNode(Node: TTreeNode): Boolean;
var
ChildNode: TTreeNode;
begin
if Node = nil then
Exit(False);
Result := False;
if Node.Expanded and isNodeLoading(Node) then
Exit(True);
if Node.HasChildren then
begin
ChildNode := Node.getFirstChild;
while ChildNode <> nil do
begin
if HasLoadingNode(ChildNode) then
Exit(True);
ChildNode := ChildNode.getNextSibling;
end;
end;
end;
procedure TAzureTableManagement.UpdatePopupMenu(Sender: TObject);
var
Data: TNodeData;
MenuItem: TMenuItem;
begin
FMenuNode := Selected;
Data := nil;
if FMenuNode <> nil then
Data := FMenuNode.Data;
for MenuItem in PopupMenu.Items do
begin
if not FActive then
MenuItem.Visible := MenuItem.Name = ACTIVATE_ITEM
else if (MenuItem.Name = REMOVE_TABLE) or (MenuItem.Name = VIEW_TABLE_DATA) then
MenuItem.Visible := (Data <> nil) and (Data.NodeType = aztTable)
else
MenuItem.Visible := MenuItem.Name <> ACTIVATE_ITEM;
end;
end;
procedure TAzureTableManagement.ViewTableAction(Sender: TObject);
begin
OpenViewTableDialog(FMenuNode);
end;
procedure TAzureTableManagement.InitializeTree;
var
Node: TTreeNode;
NodeData: TNodeData;
begin
Items.Clear;
Node := Items.AddChild(nil, SNodeAzureTableRoot);
NodeData := GetNodeData(Node, aztTables);
NodeData.Value := Node.Text;
CreateLoadingNode(Node);
end;
function TAzureTableManagement.isNodeLoading(Node: TTreeNode): Boolean;
var
LoadingNode: TTreeNode;
begin
Result := False;
//is only loading if the loading node is exposed
if (Node <> nil) and (Node.Count = 1) and Node.Expanded then
begin
LoadingNode := Node.getFirstChild;
Result := (GetNodeData(LoadingNode).NodeType = aztLoading);
end;
end;
procedure TAzureTableManagement.OnImageIndex(Sender: TObject; Node: TTreeNode);
var
Data: TNodeData;
Indx: Integer;
begin
Data := GetNodeData(Node);
case Data.NodeType of
aztTables: Indx := 0;
aztTable: Indx := 1;
aztTruncated: Indx := 2;
else
Indx := -1;
end;
Node.ImageIndex := Indx;
Node.SelectedIndex := Indx;
end;
procedure TAzureTableManagement.OpenViewTableDialog(TableNode: TTreeNode);
var
Data: TNodeData;
Dialog: TTAzureTableDialog;
begin
if (TableNode <> nil) then
begin
Data := TableNode.Data;
if Data.NodeType = aztTable then
begin
Dialog := nil;
try
Dialog := TTAzureTableDialog.Create(Self, FConnectionInfo);
Dialog.AdvancedFilterPrefix := FAdvancedFilterPrefix;
Dialog.SetTable(TableNode.Text);
Dialog.ShowModal;
finally
Dialog.Free;
end;
end;
end;
end;
procedure TAzureTableManagement.PopulateForNode(Node: TTreeNode; ForceExpand: Boolean);
var
NodeData: TNodeData;
begin
NodeData := GetNodeData(Node);
if (NodeData.NodeType = aztTables) then
TTablesPopulator.Create(Node, FConnectionInfo, PopulateTables, EmptyStr, ForceExpand)
else if (NodeData.NodeType = aztTruncated) and (NodeData.Value <> EmptyStr) then
TTablesPopulator.Create(Node.Parent, FConnectionInfo, PopulateTables, NodeData.Value, ForceExpand);
end;
procedure TAzureTableManagement.PopulateTables(Node: TTreeNode; TableNames: TStringList; StartingTable: String;
NextTableName: String; ForceExpand: Boolean; ErrorMessage: String);
var
TableName: String;
TableNode: TTreeNode;
TableNodeData: TNodeData;
begin
if not FActive then
begin
ForceCollapse(nil);
Exit;
end;
if (ErrorMessage <> EmptyStr) then
begin
MessageDlg(ErrorMessage, mtError, [mbOK], 0);
ForceCollapse(nil);
Exit;
end;
if (TableNames = nil) then
begin
if (StartingTable <> EmptyStr) and Node.HasChildren then
Node.GetLastChild.Collapse(False)
else
Node.Collapse(False);
Exit;
end;
Items.BeginUpdate;
try
//If the tables being passed in at the first tables, clear all old tables,
//otherwise clear only the fake ('load more') node.
if StartingTable = EmptyStr then
Node.DeleteChildren
else if Node.HasChildren then
begin
TableNodeData := Node.GetLastChild.Data;
//should always be true
if TableNodeData.NodeType = aztTruncated then
Node.GetLastChild.Delete;
end;
for TableName in TableNames do
begin
TableNode := Items.AddChild(Node, TableName);
TableNodeData := GetNodeData(TableNode, aztTable);
TableNodeData.Value := TableNode.Text;
end;
//If there are more tables to load, add the 'load more' node
if NextTableName <> EmptyStr then
begin
TableNode := CreateLoadMoreNode(Node);
TableNodeData := TableNode.Data;
TableNodeData.Value := NextTableName;
end;
finally
if ForceExpand and not Node.Expanded then
Node.Expand(False);
Items.EndUpdate;
FreeAndNil(TableNames);
end;
end;
procedure TAzureTableManagement.RefreshTablesAction(Sender: TObject);
var
RootNode: TTreeNode;
begin
RootNode := GetNodeAt(0, 0);
if not HasLoadingNode(RootNode) then
begin
//add a loading node when refreshing tables
Items.BeginUpdate;
RootNode.DeleteChildren;
CreateLoadingNode(RootNode);
RootNode.Expand(False);
Items.EndUpdate;
PopulateForNode(RootNode, True);
end;
end;
procedure TAzureTableManagement.RemoveTableAction(Sender: TObject);
var
Data: TNodeData;
begin
if (FMenuNode <> nil) and not IsNodeLoading(FMenuNode) then
begin
if ConfirmDeleteItem then
begin
Data := FMenuNode.Data;
Assert(Data.NodeType = aztTable);
TTableDeletor.Create(FMenuNode.Text, FConnectionInfo, TableDeleted, True);
end;
end;
end;
procedure TAzureTableManagement.SetActive(Active: Boolean);
begin
if (FActive <> Active) then
begin
if not Active then
begin
FActive := False;
Items.Clear;
end
else
FActive := Activate;
end;
end;
procedure TAzureTableManagement.SetCustomImages(Value: TCustomImageList);
begin
if Value <> nil then
begin
//If the current Images are ones made internally, not set through CustomImages property, Free them
if FCustomImages <> Images then
begin
Images.Free;
end;
Images := Value;
end
else
Images := CreateImageList;
FCustomImages := Value;
end;
procedure TAzureTableManagement.TableCreated(TableName: String; Success, ForceExpand: Boolean);
begin
if not FActive then
Exit;
if Success then
PopulateForNode(GetNodeAt(0, 0), ForceExpand)
else
MessageDlg(Format(SAddTableError, [TableName]), mtError, [mbOK], 0);
end;
procedure TAzureTableManagement.TableDeleted(TableName: String; Success, ForceExpand: Boolean);
begin
if not FActive then
Exit;
if Success then
PopulateForNode(GetNodeAt(0, 0), ForceExpand)
else
MessageDlg(Format(SDeleteTableError, [TableName]), mtError, [mbOK], 0);
end;
{ TTablesPopulator }
constructor TTablesPopulator.Create(Node: TTreeNode; ConnectionInfo: TAzureConnectionString;
Callback: TTablesPopulatedCallback; StartingTable: String;
ForceExpand: Boolean);
begin
inherited Create;
Assert(Node <> nil);
Assert(ConnectionInfo <> nil);
FNode := Node;
FConnectionInfo := ConnectionInfo;
FCallback := Callback;
FForceExpand := ForceExpand;
FStartingTable := StartingTable;
end;
destructor TTablesPopulator.Destroy;
begin
FreeAndNil(FTableService);
inherited;
end;
procedure TTablesPopulator.Execute;
var
xml: String;
xmlDoc: IXMLDocument;
TableNames: TStringList;
TableNode: IXMLNode;
ContentNode: IXMLNode;
PropertiesNode: IXMLNode;
TableNameNode: IXMLNode;
NextTableName: String;
ErrorMessage: String;
begin
inherited;
FreeOnTerminate := True;
CoInitialize(nil);
TableNames := nil;
xmlDoc := nil;
NextTableName := EmptyStr;
ErrorMessage := EmptyStr;
try
try
FTableService := TAzureTableService.Create(FConnectionInfo);
xml := FTableService.QueryTables(FStartingTable);
xmlDoc := TXMLDocument.Create(nil);
xmlDoc.LoadFromXML(xml);
//continuation token support, for the case when more tables exist than were returned
NextTableName := FTableService.ResponseHeader['x-ms-continuation-NextTableName'];
TableNames := TStringList.Create;
TableNode := xmlDoc.DocumentElement.ChildNodes.FindNode(NODE_TABLE);
while (TableNode <> nil) and (TableNode.HasChildNodes) do
begin
if (TableNode.NodeName = NODE_TABLE) then
begin
ContentNode := TableNode.ChildNodes.FindNode(NODE_TABLE_CONTENT);
if (ContentNode <> nil) and (ContentNode.HasChildNodes) then
begin
PropertiesNode := GetFirstMatchingChildNode(ContentNode, NODE_PROPERTIES);
if (PropertiesNode <> nil) and (PropertiesNode.HasChildNodes) then
begin
TableNameNode := GetFirstMatchingChildNode(PropertiesNode, NODE_TABLE_NAME);
TableNames.Add(TableNameNode.Text);
end;
end;
end;
TableNode := TableNode.NextSibling;
end;
except
on E : Exception do
begin
FreeAndNil(TableNames);
if (FTableService <> nil) and (FTableService.ResponseText <> EmptyStr) then
ErrorMessage := SErrorGeneric + FTableService.ResponseText
else
ErrorMessage := E.Message;
end;
end;
finally
CoUnInitialize();
TThread.Synchronize(nil, procedure begin FCallback(FNode, TableNames, FStartingTable,
NextTableName, FForceExpand, ErrorMessage); end);
end;
end;
{ TTableCreator }
constructor TTableCreator.Create(TableName: String; ConnectionInfo: TAzureConnectionString;
Callback: TTableCreatedCallback; ForceExpand: Boolean);
begin
inherited Create;
Assert(ConnectionInfo <> nil);
FTableName := TableName;
FConnectionInfo := ConnectionInfo;
FCallback := Callback;
FForceExpand := ForceExpand;
end;
destructor TTableCreator.Destroy;
begin
FreeAndNil(FTableService);
inherited;
end;
procedure TTableCreator.Execute;
var
Success: Boolean;
begin
inherited;
FreeOnTerminate := True;
try
try
FTableService := TAzureTableService.Create(FConnectionInfo);
Success := FTableService.CreateTable(FTableName);
except
Success := False;
end;
finally
TThread.Synchronize(nil, procedure begin FCallback(FTableName, Success, FForceExpand); end);
end;
end;
{ TTableDeletor }
constructor TTableDeletor.Create(TableName: String; ConnectionInfo: TAzureConnectionString;
Callback: TTableDeletedCallback; ForceExpand: Boolean);
begin
inherited Create;
Assert(ConnectionInfo <> nil);
FTableName := TableName;
FConnectionInfo := ConnectionInfo;
FCallback := Callback;
FForceExpand := ForceExpand;
end;
destructor TTableDeletor.Destroy;
begin
FreeAndNil(FTableService);
inherited;
end;
procedure TTableDeletor.Execute;
var
Success: Boolean;
begin
inherited;
FreeOnTerminate := True;
try
try
FTableService := TAzureTableService.Create(FConnectionInfo);
Success := FTableService.DeleteTable(FTableName);
except
Success := False;
end;
finally
TThread.Synchronize(nil, procedure begin FCallback(FTableName, Success, FForceExpand); end);
end;
end;
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Реализация брокера, работящего с TestServer См проект
"X:\Trade\Forecaster\Stock Server"
History:
-----------------------------------------------------------------------------}
unit FC.Trade.Brokers.TestServer.Broker;
{$I Compiler.inc}
interface
uses Classes, BaseUtils, SysUtils,
FC.Definitions,StockChart.Definitions,
FC.Trade.Brokers.BrokerBase,
FC.Trade.Brokers.TestServer.Order,
StockServer_TLB;
type
TStockBroker = class (TStockBrokerBase,IStockBroker,IStockBrokerTestServerSupport)
private
FBrokerNative: IStockServerBroker;
FOrders : TList;
procedure AddOrder(aOrder: TStockOrder);
procedure DeleteOrder(index: integer);
procedure ClearOrders;
function GetOrder(index:integer): TStockOrder;
//Доступ к COM-объекту сервера
function GetNative: IStockServerBroker;
public
//IStockObjct
function GetHashCode: integer;
//from IStockBroker
function GetDeposit: TStockRealNumber;
function GetCurrentPrice(aKind: TStockBrokerPriceKind): TStockRealNumber;
function GetCurrentTime: TDateTime;
function GetMargin: integer;
//Получение информации о параметрах торговли
function GetMarketInfo:TStockMarketInfo;
//Создать пустой ордер
function CreateOrder(aTrader: IStockTrader): IStockOrder;
//Дать все ордера у брокера (закрытые, открытые...)
function GetAllOrders: IStockOrderCollection;
//Дать все текущие открытые у брокера ордера
function GetOpenedOrders: IStockOrderCollection;
//Дать все отложенные ордера (стоповые и лимитные)
function GetPendingOrders: IStockOrderCollection;
//end of IStockBroker
procedure NewData(const aSymbol: string; aInterval: TStockTimeInterval; const aData: ISCInputData);
procedure OnCloseOrder(aOrder: IStockOrder);
procedure OnOpenOrder(aOrder: IStockOrder);
function GetOrderFromComOrder(const aOrder:IStockServerOrder): IStockOrder;
constructor Create(const aBrokerNative: IStockServerBroker);
destructor Destroy; override;
end;
implementation
uses Math,FC.DataUtils,FC.Trade.OrderCollection;
{ TStockBroker }
constructor TStockBroker.Create(const aBrokerNative: IStockServerBroker);
begin
inherited Create;
FOrders:=TList.Create;
FBrokerNative:=aBrokerNative;
end;
destructor TStockBroker.Destroy;
begin
inherited;
ClearOrders;
FreeAndNil(FOrders);
FBrokerNative:=nil;
end;
function TStockBroker.GetHashCode: integer;
begin
result:=integer(self);
end;
function TStockBroker.GetCurrentPrice(aKind: TStockBrokerPriceKind): TStockRealNumber;
begin
if aKind=bpkBid then
result:=GetNative.GetCurrentBidPrice
else
result:=GetNative.GetCurrentAskPrice;
Assert(result>0);
end;
procedure TStockBroker.OnCloseOrder(aOrder: IStockOrder);
begin
RaiseOnCloseOrderEvent(aOrder);
end;
procedure TStockBroker.OnOpenOrder(aOrder: IStockOrder);
begin
RaiseOnOpenOrderEvent(aOrder);
end;
function TStockBroker.CreateOrder(aTrader: IStockTrader): IStockOrder;
var
aOrder: TStockOrder;
begin
aOrder:=TStockOrder.Create(self,aTrader);
AddOrder(aOrder);
result:=aOrder;
end;
function TStockBroker.GetOpenedOrders: IStockOrderCollection;
var
aCollection: TStockOrderCollection;
i: integer;
begin
aCollection:=TStockOrderCollection.Create();
for i := 0 to FOrders.Count - 1 do
if GetOrder(i).GetState=osOpened then
aCollection.Add(GetOrder(i));
result:=aCollection;
end;
function TStockBroker.GetPendingOrders: IStockOrderCollection;
var
aCollection: TStockOrderCollection;
i: integer;
begin
aCollection:=TStockOrderCollection.Create();
for i := 0 to FOrders.Count - 1 do
if (GetOrder(i).GetState=osPending) then
aCollection.Add(GetOrder(i));
result:=aCollection;
end;
function TStockBroker.GetNative: IStockServerBroker;
begin
if FBrokerNative=nil then
raise EAssertionFailed.Create('There is no active server');
result:=FBrokerNative;
end;
procedure TStockBroker.NewData(const aSymbol: string; aInterval: TStockTimeInterval; const aData: ISCInputData);
begin
RaiseOnNewDataEvent(aSymbol,aInterval,aData);
end;
function TStockBroker.GetAllOrders: IStockOrderCollection;
var
aCollection: TStockOrderCollection;
i: integer;
begin
aCollection:=TStockOrderCollection.Create();
for i := 0 to FOrders.Count - 1 do
aCollection.Add(GetOrder(i));
result:=aCollection;
end;
function TStockBroker.GetCurrentTime: TDateTime;
begin
result:=GetNative.GetCurrentTime;
end;
function TStockBroker.GetDeposit: TStockRealNumber;
begin
result:=GetNative.GetDeposit;
end;
function TStockBroker.GetMargin: integer;
begin
result:=Round(GetNative.GetMargin);
end;
function TStockBroker.GetMarketInfo: TStockMarketInfo;
begin
FillChar(result,sizeof(result),0);
result.Spread:=3; //TODO
result.StopLevel:=3; //TODO
end;
procedure TStockBroker.AddOrder(aOrder: TStockOrder);
begin
IInterface(aOrder)._AddRef;
FOrders.Add(aOrder);
end;
procedure TStockBroker.DeleteOrder(index: integer);
begin
TStockOrder(FOrders[index]).Dispose;
IInterface(TStockOrder(FOrders[index]))._Release;
FOrders.Delete(index);
end;
procedure TStockBroker.ClearOrders;
begin
while FOrders.Count>0 do
DeleteOrder(0);
end;
function TStockBroker.GetOrder(index: integer): TStockOrder;
begin
result:=FOrders[index];
end;
function TStockBroker.GetOrderFromComOrder(const aOrder: IStockServerOrder): IStockOrder;
var
i: integer;
begin
for I :=FOrders.Count - 1 downto 0 do
begin
if GetOrder(i).Native=aOrder then
begin
result:=GetOrder(i);
exit;
end;
end;
raise EAlgoError.Create;
end;
end.
|
unit FC.StockChart.UnitTask.BBExpert.NavigatorDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmDialogClose_B, StdCtrls, CheckLst, ComCtrls, ExtCtrls, ExtendControls,
StockChart.Definitions.Units,
FC.Definitions;
type
TfmNavigator = class(TfmDialogClose_B)
Panel2: TPanel;
Panel1: TPanel;
pbProgress: TProgressBar;
buSearchNext: TButton;
buReset: TButton;
buPrev: TButton;
lbAttributes: TCheckListBox;
Label1: TLabel;
laFound: TLabel;
procedure buPrevClick(Sender: TObject);
procedure buSearchNextClick(Sender: TObject);
procedure buResetClick(Sender: TObject);
procedure buOKClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FStockChart: IStockChart;
FExpert: ISCExpertBB;
FIndex: integer;
function IsRequiredAttribute(aAttribute: TExpertBBGuessAttribute): boolean;
public
constructor Create(const aExpert: ISCExpertBB; const aStockChart: IStockChart); reintroduce;
class procedure Run(const aExpert: ISCExpertBB; const aStockChart: IStockChart);
end;
implementation
uses ufmDialog_B,Application.Definitions;
{$R *.dfm}
{ TfmNavigator }
procedure TfmNavigator.buOKClick(Sender: TObject);
begin
inherited;
Close;
end;
procedure TfmNavigator.buPrevClick(Sender: TObject);
begin
laFound.Caption:='';
if FIndex>FStockChart.GetInputData.Count then
FIndex:=FStockChart.GetInputData.Count;
while true do
begin
Dec(FIndex);
if FIndex<0 then
break;
if IsRequiredAttribute(FExpert.GetGuessAttribute(FIndex)) then
begin
FStockChart.LocateTo(FStockChart.GetInputData.DirectGetItem_DataDateTime(FIndex),lmCenter);
FStockChart.Hilight(FStockChart.GetInputData.DirectGetItem_DataDateTime(FIndex),
FStockChart.GetInputData.DirectGetItem_DataDateTime(FIndex)+1/MinsPerDay);
break;
end;
end;
end;
procedure TfmNavigator.buResetClick(Sender: TObject);
begin
inherited;
FIndex:=-1;
end;
procedure TfmNavigator.buSearchNextClick(Sender: TObject);
begin
laFound.Caption:='';
if FIndex<-1 then
FIndex:=-1;
while true do
begin
Inc(FIndex);
if FIndex>=FStockChart.GetInputData.Count then
break;
if IsRequiredAttribute(FExpert.GetGuessAttribute(FIndex)) then
begin
FStockChart.LocateTo(FStockChart.GetInputData.DirectGetItem_DataDateTime(FIndex),lmCenter);
FStockChart.Hilight(FStockChart.GetInputData.DirectGetItem_DataDateTime(FIndex),
FStockChart.GetInputData.DirectGetItem_DataDateTime(FIndex)+1/MinsPerDay);
break;
end;
end;
end;
constructor TfmNavigator.Create(const aExpert: ISCExpertBB; const aStockChart: IStockChart);
var
i:TExpertBBGuessAttribute;
b:boolean;
begin
inherited Create(nil);
FStockChart:=aStockChart;
FExpert:=aExpert;
Caption:=aExpert.GetName+' Navigator';
for i := low(TExpertBBGuessAttribute) to High(TExpertBBGuessAttribute) do
begin
lbAttributes.AddItem(ExpertBBGuessAttributeNames[i],TObject(i));
b:=i<>ebbNone;
lbAttributes.Checked[lbAttributes.Count-1]:=Workspace.Storage(self).ReadBoolean(lbAttributes,ExpertBBGuessAttributeNames[i],b);
end;
buResetClick(nil);
end;
procedure TfmNavigator.FormClose(Sender: TObject; var Action: TCloseAction);
var
i:TExpertBBGuessAttribute;
begin
inherited;
for i := low(TExpertBBGuessAttribute) to High(TExpertBBGuessAttribute) do
Workspace.Storage(self).WriteBoolean(lbAttributes,ExpertBBGuessAttributeNames[i],lbAttributes.Checked[integer(i)]);
Action:=caFree;
end;
function TfmNavigator.IsRequiredAttribute(aAttribute: TExpertBBGuessAttribute): boolean;
begin
result:=lbAttributes.Checked[integer(aAttribute)];
if result then
laFound.Caption:=lbAttributes.Items[integer(aAttribute)];
end;
class procedure TfmNavigator.Run(const aExpert: ISCExpertBB; const aStockChart: IStockChart);
begin
with TfmNavigator.Create(aExpert,aStockChart) do
Show;
end;
end.
|
PROGRAM Shuffle;
const n = 10;
type ListNodePtr = ^ListNode;
ListNode = record
val: integer;
next: ListNodePtr;
end;
List = ListNodePtr;
PROCEDURE InitList(var l: List);
BEGIN
l := NIL;
END;
FUNCTION NewNode(x: integer): ListNodePtr;
var node: ListNodePtr;
BEGIN
New(node);
node^.val := x;
node^.next := NIL;
NewNode := node;
END;
PROCEDURE WriteList(l: List);
BEGIN
while l <> nil do begin
Write('->');
Write(l^.val);
l := l^.next;
end; (* WHILE *)
WriteLn('-|')
END; (* WRITELIST *)
PROCEDURE Prepend(var l: List; n: ListNodePtr);
BEGIN
n^.next := l;
l := n;
END;
PROCEDURE Append(var l: List; n: ListNodePtr);
var cur: ListNodePtr;
BEGIN
if l = nil then
Prepend(l, n)
else begin
cur := l;
while cur^.next <> NIL do
cur := cur^.next;
cur^.next := n;
end; (* WHILE *)
END; (* APPEND *)
FUNCTION CopyNode(n: ListNodePtr): ListNodePtr;
var node: ListNodePtr;
BEGIN
node := NewNode(n^.val);
node^.next := NIL;
CopyNode := node;
END;
PROCEDURE ShuffleList(var l: List);
var l1, l2: List;
cur: ListNodePtr;
i: integer;
BEGIN
i := 1;
InitList(l1);
InitList(l2);
cur := l;
l1 := cur;
while (i < (n/2)) AND (cur^.next <> NIL) do begin
cur := cur^.next;
Inc(i);
end; (* WHILE *)
l2 := cur^.next;
cur^.next := NIL;
l := NIL;
for i := 1 to n do begin
if i = 1 then begin
l := l2;
cur := l;
l2 := l2^.next;
end else if i mod 2 = 0 then begin
cur^.next := l1;
cur := l1;
l1 := l1^.next;
end else if i mod 2 <> 0 then begin
cur^.next := l2;
cur := l2;
if l2^.next <> NIL then
l2 := l2^.next;
end; (* IF *)
end; (* FOR *)
END; (* SHUFFLELIST *)
var i: integer;
l: List;
BEGIN
InitList(l);
FOR i := 1 to n do begin
Append(l, NewNode(Random(20)));
end; (* FOR *)
WriteList(l);
ShuffleList(l);
WriteList(l);
ShuffleList(l);
WriteList(l);
END. |
program _demo;
Array[0]
var
X : TReal1DArray;
Y : TReal1DArray;
N : AlglibInteger;
I : AlglibInteger;
Info : AlglibInteger;
S : Spline1DInterpolant;
T : Double;
Rep : Spline1DFitReport;
begin
//
// Fitting by unconstrained natural cubic spline
//
Write(Format('FITTING BY UNCONSTRAINED NATURAL CUBIC SPLINE'#13#10''#13#10'',[]));
Write(Format('F(x)=sin(x) function being fitted'#13#10'',[]));
Write(Format('[0, pi] interval'#13#10'',[]));
Write(Format('M=4 number of basis functions to use'#13#10'',[]));
Write(Format('N=100 number of points to fit'#13#10'',[]));
//
// Create and fit
//
N := 100;
SetLength(X, N);
SetLength(Y, N);
I:=0;
while I<=N-1 do
begin
X[I] := Pi*I/(N-1);
Y[I] := Sin(X[I]);
Inc(I);
end;
Spline1DFitCubic(X, Y, N, 4, Info, S, Rep);
//
// Output results
//
if Info>0 then
begin
Write(Format(''#13#10'OK, we have finished'#13#10''#13#10'',[]));
Write(Format(' x F(x) S(x) Error'#13#10'',[]));
T := 0;
while AP_FP_Less(T,0.999999*Pi) do
begin
Write(Format('%6.3f %6.3f %6.3f %6.3f'#13#10'',[
T,
Sin(T),
Spline1DCalc(S, T),
AbsReal(Spline1DCalc(S, T)-Sin(T))]));
T := Min(Pi, T+0.25);
end;
Write(Format('%6.3f %6.3f %6.3f %6.3f'#13#10''#13#10'',[
T,
Sin(T),
Spline1DCalc(S, T),
AbsReal(Spline1DCalc(S, T)-Sin(T))]));
Write(Format('rms error is %6.3f'#13#10'',[
Rep.RMSError]));
Write(Format('max error is %6.3f'#13#10'',[
Rep.MaxError]));
end
else
begin
Write(Format(''#13#10'Something wrong, Info=%0d',[
Info]));
end;
end. |
unit kehilangan_handler;
interface
uses
tipe_data;
{ KONSTANTA }
const
nmax = 1000; // Asumsi bahwa size terbesar dari database adalah 1000
{ DEKLARASI TIPE }
type
kehilangan = record
Username, ID_Buku, Tanggal_Laporan: string;
end;
tabel_kehilangan = record
t: array [0..nmax] of kehilangan;
sz: integer; // effective size
end;
{ DEKLARASI FUNGSI DAN PROSEDUR }
function tambah(s: arr_str): tabel_kehilangan;
procedure output(data_tempkehilangan: tabel_kehilangan);
function konversi_csv(data_tempkehilangan: tabel_kehilangan): arr_str;
{ IMPLEMENTASI FUNGSI DAN PROSEDUR }
implementation
function tambah(s: arr_str): tabel_kehilangan;
{ DESKRIPSI : Memasukkan data dari array of string kedalam tabel_kehilangan }
{ PARAMETER : array of string }
{ RETURN : data kehilangan }
var
col, row: integer; // col = data ke-N, row = baris ke-N dari file csv
temp: string; // string temporer, berfungsi
c: char;
data_tempkehilangan : tabel_kehilangan;
begin
data_tempkehilangan.sz := 0;
for row:=0 to s.sz-1 do
begin
col := 0;
temp := '';
for c in s.st[row] do
begin
if(c=',') then
begin
// 0 based indexing
case col of
0: data_tempkehilangan.t[data_tempkehilangan.sz].Username := temp;
1: data_tempkehilangan.t[data_tempkehilangan.sz].ID_Buku := temp;
end;
col := col+1;
temp := '';
end else temp := temp+c;
end;
data_tempkehilangan.t[data_tempkehilangan.sz].Tanggal_Laporan := temp;
data_tempkehilangan.sz := data_tempkehilangan.sz+1;
end;
tambah := data_tempkehilangan;
end;
function konversi_csv(data_tempkehilangan: tabel_kehilangan): arr_str;
{ DESKRIPSI : Fungsi untuk mengubah data kehilangan menjadi array of string }
{ PARAMETER : data kehilangan }
{ RETURN : array of string }
{ KAMUS LOKAL }
var
i : integer;
ret : arr_str;
begin
ret.sz := data_tempkehilangan.sz;
for i:=0 to data_tempkehilangan.sz do
begin
ret.st[i] := data_tempkehilangan.t[i].Username + ',' +
data_tempkehilangan.t[i].ID_Buku + ',' +
data_tempkehilangan.t[i].Tanggal_Laporan;
end;
konversi_csv := ret;
end;
procedure output(data_tempkehilangan: tabel_kehilangan);
{ DESKRIPSI : Prosedur sederhana yang digunakan pada proses pembuatan program untuk debugging, prosedur ini mencetak data ke layar }
{ PARAMETER : Data yang akan dicetak }
{ KAMUS LOKAL }
var
i: integer;
{ ALGORITMA }
begin
for i:=0 to data_tempkehilangan.sz-1 do
begin
writeln(data_tempkehilangan.t[i].Username, ' | ', data_tempkehilangan.t[i].ID_Buku, ' | ', data_tempkehilangan.t[i].Tanggal_Laporan);
end;
end;
end.
|
unit UBaseShape;
{$mode objfpc}{$H+}
interface
uses
Classes, Graphics, UViewPort, UGeometry, math, LCLIntf, LCLType, sysutils;
type
{ TShape }
TPenWidth = type Integer;
TPenColor = type TColor;
TLeft = type Double;
TRight = type Double;
TTop = type Double;
TBottom = type Double;
TShape = class abstract(TPersistent)
protected
FPoints: TFloatPoints;
FRect: TFloatRect;
FPenColor: TPenColor;
FPenWidth: TPenWidth;
FPenStyle: TPenStyle;
FSelected: Boolean;
FPrevSelected: Boolean;
function GetPoints: TStrings;
function GetRect: TFloatRect; virtual;
procedure SetLeft(d: TLeft);
procedure SetPoints(AValue: TStrings); virtual;
procedure SetRight(d: TRight);
procedure SetTop(d: TTop);
procedure SetBottom(d: TBottom);
procedure UpdateRect;
public
constructor Create; virtual;
procedure SetPoint(APoint: TPoint); virtual;
procedure Draw(ACanvas: TCanvas); virtual;
procedure DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double); virtual;
procedure MovePoint(APoint: TPoint);
procedure DrawSelection(ACanvas: TCanvas);
function PointInShape(APoint: TPoint): Boolean; virtual; abstract;
function RectInShape(ARect: TRect): Boolean; virtual; abstract;
procedure Shift(AShift: TPoint);
function PointInEditPoint(APoint: TPoint): Integer;
procedure MoveEditPoint(AShift: TPoint; AIndex: Integer); virtual;
property Rect: TFloatRect read GetRect;
property TrueRect: TFloatRect read FRect;
property IsSelected: Boolean read FSelected write FSelected;
property PrevSelected: Boolean read FPrevSelected write FPrevSelected;
published
property PenColor: TPenColor read FPenColor write FPenColor;
property PenWidth: TPenWidth read FPenWidth write FPenWidth;
property PenStyle: TPenStyle read FPenStyle write FPenStyle;
property AlignLeft: TLeft write SetLeft;
property AlignRight: TRight write SetRight;
property AlignTop: TTop write SetTop;
property AlignBottom: TBottom write SetBottom;
property Points: TStrings read GetPoints write SetPoints;
end;
TShapes = array of TShape;
implementation
{ TShape }
function TShape.GetRect: TFloatRect;
var
p1, p2, dp: TPoint;
r: TRect;
begin
dp := Point(
Round(PenWidth * VP.Scale / 2 + 5 * VP.Scale),
Round(PenWidth * VP.Scale / 2 + 5 * VP.Scale));
r := VP.WorldToScreen(FRect);
p1 := r.TopLeft - dp;
p2 := r.BottomRight + dp;
Result := VP.ScreenToWorld(UGeometry.Rect(p1, p2));
end;
function TShape.GetPoints: TStrings;
var i: Integer;
begin
Result := TStringList.Create;
for i := 0 to High(FPoints) do
begin
Result.Add(FloatToStr(FPoints[i].X));
Result.Add(FloatToStr(FPoints[i].Y));
end;
end;
procedure TShape.SetLeft(d: TLeft);
var
i: Integer;
dx: Double;
begin
dx := d - FRect.Left;
for i := 0 to High(FPoints) do
FPoints[i] += FloatPoint(dx, 0);
FRect.Left += dx;
FRect.Right += dx;
end;
procedure TShape.SetPoints(AValue: TStrings);
var i: Integer;
begin
if AValue.Count mod 2 = 1 then
raise Exception.Create('File is damaged');
SetLength(FPoints, AValue.Count div 2);
for i := 0 to AValue.Count div 2 - 1 do
begin
FPoints[i].X := StrToFloat(AValue[2 * i]);
FPoints[i].Y := StrToFloat(AValue[2 * i + 1]);
end;
UpdateRect;
end;
procedure TShape.SetRight(d: TRight);
var
i: Integer;
dx: Double;
begin
dx := d - FRect.Right;
for i := 0 to High(FPoints) do
FPoints[i] += FloatPoint(dx, 0);
FRect.Left += dx;
FRect.Right += dx;
end;
procedure TShape.SetTop(d: TTop);
var
i: Integer;
dy: Double;
begin
dy := d - FRect.Top;
for i := 0 to High(FPoints) do
FPoints[i] += FloatPoint(0, dy);
FRect.Top += dy;
FRect.Bottom += dy;
end;
procedure TShape.SetBottom(d: TBottom);
var
i: Integer;
dy: Double;
begin
dy := d - FRect.Bottom;
for i := 0 to High(FPoints) do
FPoints[i] += FloatPoint(0, dy);
FRect.Top += dy;
FRect.Bottom += dy;
end;
procedure TShape.UpdateRect;
var i: Integer;
begin
FRect := FloatRect(FPoints[0], FPoints[0]);
for i := 1 to High(FPoints) do
begin
FRect.Left := Min(FRect.Left, FPoints[i].X);
FRect.Right := Max(FRect.Right, FPoints[i].X);
FRect.Top := Min(FRect.Top, FPoints[i].Y);
FRect.Bottom := Max(FRect.Bottom, FPoints[i].Y);
end;
end;
constructor TShape.Create;
begin
FPenWidth := 1;
FPenColor := clBlack;
FPenStyle := psSolid;
FSelected := False;
FPrevSelected := False;
end;
procedure TShape.SetPoint(APoint: TPoint);
begin
SetLength(FPoints, 1);
FPoints[0] := VP.ScreenToWorld(APoint);
FRect := FloatRect(FPoints[0], FPoints[0]);
end;
procedure TShape.Draw(ACanvas: TCanvas);
begin
ACanvas.Pen.Width := round(FPenWidth * VP.Scale);
ACanvas.Pen.Color := FPenColor;
ACanvas.Pen.Style := FPenStyle;
end;
procedure TShape.DrawExport(ACanvas: TCanvas; TopLeft: TPoint; Scale: Double);
begin
ACanvas.Pen.Width := round(FPenWidth * Scale);
ACanvas.Pen.Color := FPenColor;
ACanvas.Pen.Style := FPenStyle;
end;
procedure TShape.MovePoint(APoint: TPoint);
begin
if Length(FPoints) = 1 then
begin
SetLength(FPoints, 2);
end;
FPoints[High(FPoints)] := VP.ScreenToWorld(APoint);
UpdateRect;
end;
procedure TShape.DrawSelection(ACanvas: TCanvas);
var
i: Integer;
p: TPoint;
begin
ACanvas.Pen.Width := 1;
ACanvas.Pen.Color := clBlack;
ACanvas.Pen.Style := psDash;
ACanvas.Brush.Style := bsClear;
ACanvas.Rectangle(VP.WorldToScreen(Rect));
ACanvas.Pen.Style := psSolid;
ACanvas.Brush.Style := bsSolid;
ACanvas.Brush.Color := clWhite;
for i := 0 to High(FPoints) do
begin
p := VP.WorldToScreen(FPoints[i]);
ACanvas.EllipseC(p.X, p.Y, 5, 5);
end;
end;
procedure TShape.Shift(AShift: TPoint);
var i: Integer;
begin
for i := 0 to High(FPoints) do
FPoints[i] += FloatPoint(AShift) / VP.Scale;
FRect.Left += AShift.X / VP.Scale;
FRect.Right += AShift.X / VP.Scale;
FRect.Top += AShift.Y / VP.Scale;
FRect.Bottom += AShift.Y / VP.Scale;
end;
function TShape.PointInEditPoint(APoint: TPoint): Integer;
var
r: HRGN;
i: Integer;
p: TPoint;
b: Boolean;
begin
Result := -1;
for i := High(FPoints) downto 0 do
begin
p := VP.WorldToScreen(FPoints[i]);
r := CreateEllipticRgn(p.X - 5, p.Y - 5, p.X + 5, p.Y + 5);
b := PtInRegion(r, APoint.X, APoint.Y);
DeleteObject(r);
if b then
begin
Result := i;
Exit;
end;
end;
end;
procedure TShape.MoveEditPoint(AShift: TPoint; AIndex: Integer);
begin
FPoints[AIndex] += FloatPoint(AShift) / VP.Scale;
UpdateRect;
end;
end.
|
unit ServerMethodsUnit;
interface
uses System.SysUtils, System.Classes, System.Json,
Datasnap.DSServer, Datasnap.DSAuth, DataSnap.DSProviderDataModuleAdapter,
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.IB, FireDAC.Phys.IBDef, FireDAC.Stan.Param,
FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.FMXUI.Wait,
FireDAC.Phys.IBBase, FireDAC.Comp.UI, Datasnap.Provider, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TServerMethods = class(TDSServerModule)
FDConnection: TFDConnection;
BookLogQuery: TFDQuery;
DSPBooklog: TDataSetProvider;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDPhysIBDriverLink1: TFDPhysIBDriverLink;
private
{ Private declarations }
public
{ Public declarations }
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
end;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
uses System.StrUtils;
function TServerMethods.EchoString(Value: string): string;
begin
Result := Value;
end;
function TServerMethods.ReverseString(Value: string): string;
begin
Result := System.StrUtils.ReverseString(Value);
end;
end.
|
unit DBUtil;
interface
uses
AppData, IFinanceGlobal, SysUtils, Vcl.ExtCtrls, DB;
type
TSequenceObject = (soEntity,soGroup,soEmployer,soBankBranch,soDesignation,
soLoanClass,soLoan,soCompetitor,soPurpose, soLoanType,
soAcctType,soLoanCancelReason,soLoanRejectReason,
soPayment,soLedger,soInterest,soLoanCloseReason,
soAccountClass,soLineItem,soExpense,soSubsidiary,
soRebate,soVoucher);
procedure RefreshDataSet(const key: integer; const keyField: string; DataSet: TDataSet); overload;
procedure RefreshDataSet(const key, keyField: string; DataSet: TDataSet); overload;
procedure SetCreatedFields(dataSet: TDataSet);
procedure ExecuteSQL(const sql: string; const inCoreDB: boolean = false);
procedure ExecuteSP(const sp: string);
procedure FixSequence;
procedure UpdateLoanDeficit(const ADate: TDateTime);
function GetEntityId: string;
function GetGroupId: string;
function GetEmployerId: string;
function GetBankBranchId: string;
function GetDesignationId: integer;
function GetLoanClassId: integer;
function GetLoanId: string;
function GetCompetitorId: string;
function GetPurposeId: integer;
function GetLoanTypeId: integer;
function GetAccountTypeId: integer;
function GetLoanCancellationReasonId: integer;
function GetLoanRejectionReasonId: integer;
function GetPaymentId: string;
function GetGenericId: string;
function GetLedgerId: string;
function GetInterestId: string;
function GetLoanClosureReasonId: integer;
function GetAccountClassId: integer;
function GetAccountGroupId: integer;
function GetExpenseId: string;
function GetSubsidiaryId: string;
function GetRebateId: string;
function GetVoucherId: string;
implementation
procedure RefreshDataSet(const key: integer; const keyField: string; DataSet: TDataSet);
begin
with DataSet do
begin
DisableControls;
Close;
Open;
Locate(keyField,key,[]);
EnableControls;
end;
end;
procedure RefreshDataSet(const key, keyField: string; DataSet: TDataSet);
begin
with DataSet do
begin
DisableControls;
Close;
Open;
Locate(keyField,key,[]);
EnableControls;
end;
end;
procedure SetCreatedFields(dataSet: TDataSet);
begin
dataSet.FieldByName('created_date').AsDateTime := Now;
dataSet.FieldByName('created_by').AsString := ifn.User.UserId;
end;
procedure ExecuteSQL(const sql: string; const inCoreDB: boolean = false);
begin
if inCoreDB then with dmApplication.acCore do Execute(sql)
else with dmApplication.acMain do Execute(sql);
end;
procedure ExecuteSP(const sp: string);
begin
with dmApplication.acMain do Execute('EXEC ' + sp);
end;
procedure FixSequence;
begin
ExecuteSP('dbo.sp_dev_fix_sequence');
end;
procedure UpdateLoanDeficit(const ADate: TDateTime);
begin
ExecuteSP('dbo.sp_ln_update_deficits ' + QuotedStr(FormatDateTime('yyyy-mm-dd',ADate)));
end;
function GetSequenceID(const seqObj: TSequenceObject): integer;
var
parm: string;
begin
case seqObj of
soEntity: parm := 'ENT';
soGroup: parm := 'GRP';
soEmployer: parm := 'EML';
soBankBranch: parm := 'BNK';
soDesignation: parm := 'DSG';
soLoanClass: parm := 'LNC';
soLoan: parm := 'LON';
soCompetitor: parm := 'CMP';
soPurpose: parm := 'PRP';
soLoanType: parm := 'LNT';
soAcctType: parm := 'ACT';
soPayment: parm := 'PAY';
soLedger: parm := 'LDG';
soInterest: parm := 'ITS';
soLoanCancelReason: parm := 'LCR';
soLoanRejectReason: parm := 'LRR';
soLoanCloseReason: parm := 'LSR';
soAccountClass: parm := 'ACC';
soLineItem: parm := 'LIN';
soExpense: parm := 'EXP';
soSubsidiary: parm := 'SBY';
soRebate: parm := 'RBT';
soVoucher: parm := 'VCH';
else parm := '';
end;
with dmApplication.spGenId do
try
Parameters.ParamByName('@seq_object').Value := parm;
Open;
Result := FieldByName('last_id').AsInteger;
finally
Close;
end;
end;
function GetEntityId: string;
begin
Result := ifn.LocationPrefix + '-' + IntToStr(GetSequenceID(soEntity));
end;
function GetGroupId: string;
begin
Result := ifn.LocationPrefix + '-' + IntToStr(GetSequenceID(soGroup));
end;
function GetEmployerId: string;
begin
Result := ifn.LocationPrefix + '-' + IntToStr(GetSequenceID(soEmployer));
end;
function GetBankBranchId: string;
begin
Result := ifn.LocationPrefix + '-' + IntToStr(GetSequenceID(soBankBranch));
end;
function GetDesignationId: integer;
begin
Result := GetSequenceID(soDesignation);
end;
function GetLoanClassId: integer;
begin
Result := GetSequenceId(soLoanClass);
end;
function GetLoanId: string;
begin
Result := ifn.LocationPrefix + '-' + IntToStr(GetSequenceID(soLoan));
end;
function GetCompetitorId: string;
begin
Result := ifn.LocationPrefix + '-' + IntToStr(GetSequenceID(soCompetitor));
end;
function GetPurposeId: integer;
begin
Result := GetSequenceID(soPurpose);
end;
function GetLoanTypeId: integer;
begin
Result := GetSequenceID(soLoanType);
end;
function GetAccountTypeId: integer;
begin
Result := GetSequenceID(soAcctType);
end;
function GetLoanCancellationReasonId: integer;
begin
Result := GetSequenceID(soLoanCancelReason);
end;
function GetLoanRejectionReasonId: integer;
begin
Result := GetSequenceID(soLoanRejectReason);
end;
function GetPaymentId: string;
begin
Result := ifn.LocationPrefix + '-' + IntToStr(GetSequenceID(soPayment));
end;
function GetGenericId: string;
begin
Result := FormatDateTime('mmddyyyyhhmmsszzz',Now);
end;
function GetLedgerId: string;
begin
Result := ifn.LocationPrefix + '-' + IntToStr(GetSequenceID(soLedger));
end;
function GetInterestId: string;
begin
Result := ifn.LocationPrefix + '-' + IntToStr(GetSequenceID(soInterest));
end;
function GetLoanClosureReasonId: integer;
begin
Result := GetSequenceID(soLoanCloseReason);
end;
function GetAccountClassId: integer;
begin
Result := GetSequenceID(soAccountClass);
end;
function GetAccountGroupId: integer;
begin
Result := GetSequenceID(soLineItem);
end;
function GetExpenseId: string;
begin
Result := ifn.LocationPrefix + '-' + IntToStr(GetSequenceID(soExpense));
end;
function GetSubsidiaryId: string;
begin
Result := IntToStr(GetSequenceID(soSubsidiary));
end;
function GetRebateId: string;
begin
Result := ifn.LocationPrefix + '-' + IntToStr(GetSequenceID(soRebate));
end;
function GetVoucherId: string;
begin
Result := ifn.LocationPrefix + '-' + IntToStr(GetSequenceID(soVoucher));
end;
end.
|
{***************************************************************
*
* Project : MailDemo
* Unit Name: MsgEditor
* Purpose : Sub form
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:28:29
* Author : Hadi Hari <hadi@pbe.com>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit MsgEditor;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QComCtrls, QExtCtrls,
QGrids, QButtons, QMenus, QImgList,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls, ExtCtrls, Grids,
Buttons, Menus, ImgList,
{$ENDIF}
windows, messages, SysUtils, Classes, IdBaseComponent, IdMessage, IdComponent,
IdTCPConnection, IdTCPClient, IdMessageClient, IdSMTP;
type
TfrmMessageEditor = class(TForm)
bbtnAdvanced: TBitBtn;
bbtnCancel: TBitBtn;
bbtnOk: TBitBtn;
btnAttachment: TBitBtn;
btnText: TBitBtn;
cboPriority: TComboBox;
chkReturnReciept: TCheckBox;
Edit1: TEdit;
edtBCC: TEdit;
edtCC: TEdit;
edtSubject: TEdit;
edtTo: TEdit;
grpAttachment: TGroupBox;
IdMsgSend: TIdMessage;
lblBCC: TLabel;
lblCC: TLabel;
lblPriority: TLabel;
lblSubject: TLabel;
lblTo: TLabel;
lvFiles: TListView;
Memo1: TMemo;
pnlBottom: TPanel;
pnlButtons: TPanel;
pnlMainDetails: TPanel;
pnlSmallButtons: TPanel;
pnlTop: TPanel;
pnlTopLeft: TPanel;
StatusBar1: TStatusBar;
SMTP: TIdSMTP;
OpenDialog1: TOpenDialog;
procedure bbtnAdvancedClick(Sender: TObject);
procedure bbtnOkClick(Sender: TObject);
procedure btnAttachmentClick(Sender: TObject);
procedure btnTextClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure ResetAttachmentListView;
public
{ Public declarations }
end;
var
frmMessageEditor: TfrmMessageEditor;
{TODO: Handle message body which is typed in the RichEdit}
implementation
uses msgEdtAdv, main;
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
procedure TfrmMessageEditor.bbtnOkClick(Sender: TObject);
begin
with IdMsgSend do
begin
Body.Assign(Memo1.Lines);
From.Text := UserEmail;
Recipients.EMailAddresses := edtTo.Text; { To: header }
Subject := edtSubject.Text; { Subject: header }
Priority := TIdMessagePriority(cboPriority.ItemIndex); { Message Priority }
CCList.EMailAddresses := edtCC.Text; {CC}
BccList.EMailAddresses := edtBCC.Text; {BBC}
if chkReturnReciept.Checked then
begin {We set the recipient to the From E-Mail address }
ReceiptRecipient.Text := From.Text;
end
else
begin {indicate that there is no receipt recipiant}
ReceiptRecipient.Text := '';
end;
end;
{authentication settings}
case SmtpAuthType of
0: SMTP.AuthenticationType := atNone;
1: SMTP.AuthenticationType := atLogin; {Simple Login}
end;
SMTP.UserID := SmtpServerUser;
SMTP.Password := SmtpServerPassword;
{General setup}
SMTP.Host := SmtpServerName;
SMTP.Port := SmtpServerPort;
{now we send the message}
SMTP.Connect;
try
SMTP.Send(IdMsgSend);
finally
SMTP.Disconnect;
end;
end;
procedure TfrmMessageEditor.bbtnAdvancedClick(Sender: TObject);
begin
with TfrmAdvancedOptions.Create(Application) do
try
edtSender.Text := IdMsgSend.Sender.Text;
mmoExtraHeaders.Lines := IdMsgSend.ExtraHeaders;
if ShowModal = mrOk then
begin
{Sender header}
IdMsgSend.Sender.Text := edtSender.Text;
{Extra header}
IdMsgSend.ExtraHeaders.Assign(mmoExtraHeaders.Lines);
end;
finally
Free;
end;
end;
procedure TfrmMessageEditor.FormCreate(Sender: TObject);
begin
cboPriority.ItemIndex := Ord(IdMsgSend.Priority);
end;
procedure TfrmMessageEditor.btnAttachmentClick(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
TIdAttachment.Create(IdMsgSend.MessageParts, OpenDialog1.FileName);
ResetAttachmentListView;
end;
end;
procedure TfrmMessageEditor.ResetAttachmentListView;
var
li: TListItem;
idx: Integer;
begin
lvFiles.Items.Clear;
for idx := 0 to Pred(IdMsgSend.MessageParts.Count) do
begin
li := lvFiles.Items.Add;
if IdMsgSend.MessageParts.Items[idx] is TIdAttachment then
begin
li.ImageIndex := 0;
li.Caption := TIdAttachment(IdMsgSend.MessageParts.Items[idx]).Filename;
li.SubItems.Add(TIdAttachment(IdMsgSend.MessageParts.Items[idx]).ContentType);
end
else
begin
li.ImageIndex := 1;
li.Caption := IdMsgSend.MessageParts.Items[idx].ContentType;
end;
end;
end;
procedure TfrmMessageEditor.btnTextClick(Sender: TObject);
begin
if Length(Edit1.Text) = 0 then
begin
MessageDlg('Indicate ContentType first', mtError, [mbOk], 0);
end
else
begin
with TIdText.Create(IdMsgSend.MessageParts, Memo1.Lines) do
begin
ContentType := Edit1.Text;
end;
Memo1.Clear;
ResetAttachmentListView;
end;
end;
end.
|
// ====================================================================
// Unit uDSProcessMgmt.pas
//
// This unit contains the most importants funcions and procedures for
// reading the memory information.
//
// Esta "unit" contém as funções e procedures mais importantes para a
// leitura de informação em memória.
//
//
// All the memory addresses and pointers, and offsets was get by using
// the Cheat Engine scanner, and tables from the people in the forum.
//
// Todos os endereços de memória, ponteiros e offsets foram obtidos
// pelo scanner do Cheat Engine, e de tabelas de terceiros em foruns.
// ====================================================================
unit uDSProcessMgmt;
interface
uses
Windows, SysUtils, uWarrior, uDefaultPlayer, uBluePhantom,
uWhitePhantom, uRedPhantom;
// This procedure get the stamina and HP just in progress
// Esta procedure obtém a stamina e HP durante o progresso do jogo
procedure UpdateStaminaHPStatus(var AWarrior: TWarrior);
// This procedure checks the status of the player, such as Soul Level, Vitality, etc
// Esta procedure checa o status do jogador, como por exemplo: Soul Level, Vitality, etc
procedure UpdateStatus(var AWarrior: TWarrior);
// This function just increase the Stamina value when using some special ring (ex.: FaP ring)
// Esta função apenas aumenta a Stamina no caso do jogador estar usando um anel especial (ex.: FaP ring)
function IncreaseStaminaWithRingBonus(const ARing1, ARing2, ActualStamina: Cardinal): Cardinal;
// This function just increase the HP value when using some special ring (ex.: FaP ring)
// Esta função apenas aumenta o HP no caso do jogador estar usando um anel especial (ex.: FaP ring)
function IncreaseHPWithRingAndMaskBonus(const ARing1, ARing2, AMask, ActualHP: Cardinal): Cardinal;
// This function obtains the max value of the main player's Stamina
// Esta função obtém o valor máximo da Stamina do jogador principal
function GetDefaultPlayerMaxStamina(const AWarrior: TWarrior): Cardinal;
// This function obtains the max value of the Red Phantom's Stamina
// Esta função obtém o valor máximo da Stamina do Red Phantom
function GetRedPhantomMaxStamina(const AWarrior: TWarrior): Cardinal;
// This function obtains the max value of the Blue Phantom's Stamina
// Esta função obtém o valor máximo da Stamina do Blue Phantom
function GetBluePhantomMaxStamina(const AWarrior: TWarrior): Cardinal;
// This function obtains the max value of the White Phantom's Stamina
// Esta função obtém o valor máximo da Stamina do White Phantom
function GetWhitePhantomMaxStamina(const AWarrior: TWarrior): Cardinal;
// This function obtains the max value of the main player's HP
// Esta função obtém o valor máximo dao HP do jogador principal
function GetDefaultPlayerMaxHP(const AWarrior: TWarrior): Cardinal;
// This function obtains the max value of the Red Phantom's HP
// Esta função obtém o valor máximo dao HP do Red Phantom
function GetRedPhantomMaxHP(const AWarrior: TWarrior): Cardinal;
// This function obtains the max value of the Blue Phantom's HP
// Esta função obtém o valor máximo dao HP do Blue Phantom
function GetBluePhantomMaxHP(const AWarrior: TWarrior): Cardinal;
// This function obtains the max value of the White Phantom's HP
// Esta função obtém o valor máximo dao HP do White Phantom
function GetWhitePhantomMaxHP(const AWarrior: TWarrior): Cardinal;
implementation
uses
uDSProcessMgmtUtils, uDSProcessMgmtNameUtils, uDSProcessMgmtWCUtils;
// Function for reading the value of some Pointer address in memory
// Função para ler o valor de algum endereço de ponteiro na memória
function GetPointerValue(const APointer: Cardinal; AOffSets: array of Cardinal): Cardinal;
var
wHandle: hwnd;
hProcess: integer;
pId: integer;
Value: Cardinal;
Read: NativeUInt;
i: Integer;
begin
Result := 0;
if not IsDarkSoulsRunning then
Exit;
wHandle := FindWindow(nil,'DARK SOULS');
GetWindowThreadProcessId(wHandle,@pId);
if wHandle <> 0 then
begin
hProcess := OpenProcess(PROCESS_ALL_ACCESS,False,pId);
ReadProcessMemory(hProcess, Ptr(APointer), Addr(Value), 4, Read);
for i := Low(AOffSets) to High(AOffSets) do
begin
ReadProcessMemory(hProcess, Ptr(Value + AOffSets[i]), Addr(Value), 4, Read);
end;
Result := Value;
end;
end;
// This function get the name of the player
// Esta função obtém o nome do jogador
function GetWarriorName(AWarrior: TWarrior): String;
begin
if AWarrior.ClassType = TDefaultPlayer then
Result := GetDefaultPlayerName
else
if AWarrior.ClassType = TRedPhantom then
Result := GetRedPhantomName
else
if AWarrior.ClassType = TBluePhantom then
Result := GetBluePhantomName
else
Result := GetWhitePhantomName;
end;
// This function get the class of the player
// Esta função obtém a classe do jogador
function GetWarriorClass(AWarrior: TWarrior): TWarriorClass;
begin
if AWarrior.ClassType = TDefaultPlayer then
Result := GetDefaultPlayerWarriorClass
else
if AWarrior.ClassType = TRedPhantom then
Result := GetRedPhantomWarriorClass //TODO: Need implementation / Precisa de implementação
else
if AWarrior.ClassType = TBluePhantom then
Result := GetBluePhantomWarriorClass //TODO: Need implementation / Precisa de implementação
else
Result := GetWhitePhantomWarriorClass; //TODO: Need implementation / Precisa de implementação
end;
function IncreaseStaminaWithRingBonus(const ARing1, ARing2, ActualStamina: Cardinal): Cardinal;
begin
Result := ActualStamina;
if (ARing1 = 143) or (ARing2 = 143) then
Result := Round(ActualStamina * 1.2);
end;
function GetDefaultPlayerMaxStamina(const AWarrior: TWarrior): Cardinal;
var
MaxStamina, Ring1, Ring2: Cardinal;
begin
MaxStamina := GetPointerValue(AWarrior.FPointer, AWarrior.FMaxStaminaOffsets);
Result := MaxStamina;
Ring1 := GetPointerValue(AWarrior.FPointer, [$8, $280]);
Ring2 := GetPointerValue(AWarrior.FPointer, [$8, $284]);
Result := IncreaseStaminaWithRingBonus(Ring1, Ring2, Result);
end;
function GetRedPhantomMaxStamina(const AWarrior: TWarrior): Cardinal;
begin
Result := AWarrior.ActualStamina;
end;
function GetBluePhantomMaxStamina(const AWarrior: TWarrior): Cardinal;
begin
Result := AWarrior.ActualStamina;
end;
function GetWhitePhantomMaxStamina(const AWarrior: TWarrior): Cardinal;
begin
Result := AWarrior.ActualStamina;
end;
function CalculateMaxStamina(AWarrior: TWarrior): Cardinal;
begin
if AWarrior.ClassType = TDefaultPlayer then
Result := GetDefaultPlayerMaxStamina(AWarrior)
else
if AWarrior.ClassType = TRedPhantom then
Result := GetRedPhantomMaxStamina(AWarrior)
else
if AWarrior.ClassType = TBluePhantom then
Result := GetBluePhantomMaxStamina(AWarrior)
else
Result := GetWhitePhantomMaxStamina(AWarrior);
end;
// Ring and Mask Bonus
// Bonus de anel e máscara
function IncreaseHPWithRingAndMaskBonus(const ARing1, ARing2, AMask, ActualHP: Cardinal): Cardinal;
var
V1, V2, V3: cardinal;
begin
V1 := 0; V2 := 0; V3 := 0;
Result := ActualHP;
if (ARing1 = 143) or (ARing2 = 143) then
begin
V1 := Round(ActualHP * 0.2);
if (ARing1 = 111) or (ARing2 = 111) then
begin
V2 := Round((ActualHP + V1) * 0.05);
if (AMask = 600000) then
V3 := (Round(V2 * 0.1) - 1);
end
else
if (AMask = 600000) then
V3 := (Round((ActualHP + V1) * 0.1) - 1);
end;
if (V1 <> 0) and (V2 <> 0) and (V3 <> 0) then
begin
Result := Result + V1 + V2 + V3;
Exit;
end;
if (ARing1 = 111) or (ARing2 = 111) then
begin
V2 := Round(ActualHP * 0.05);
if (AMask = 600000) then
V3 := V2 + (Round((ActualHP + V2) * 0.1) - 1);
end;
if (V2 <> 0) and (V3 <> 0) then
begin
Result := Result + V1 + V2 + V3;
Exit;
end;
if (V2 = 0) and (V1 = 0) then
if (AMask = 600000) then
V3 := Round(ActualHP * 0.1) - 1;
if (V1 + V2 + V3) = 0 then Exit;
Result := Result + V1 + V2 + V3;
end;
function GetDefaultPlayerMaxHP(const AWarrior: TWarrior): Cardinal;
var
HPt: Cardinal;
Ring1, Ring2: Cardinal;
Head: Cardinal;
begin
HPt := GetPointerValue(AWarrior.FPointer, AWarrior.FMaxHPOffSets);
Result := Hpt;
Ring1 := GetPointerValue(AWarrior.FPointer, [$8, $280]);
Ring2 := GetPointerValue(AWarrior.FPointer, [$8, $284]);
Head := GetPointerValue(AWarrior.FPointer, [$8, $26c]);
Result := IncreaseHPWithRingAndMaskBonus(Ring1, Ring2, Head, Result);
end;
function GetRedPhantomMaxHP(const AWarrior: TWarrior): Cardinal;
var
HPt: Cardinal;
begin
HPt := GetPointerValue(AWarrior.FPointer, AWarrior.FMaxHPOffSets);
Result := HPt;
end;
function GetBluePhantomMaxHP(const AWarrior: TWarrior): Cardinal;
var
HPt: Cardinal;
begin
HPt := GetPointerValue(AWarrior.FPointer, AWarrior.FMaxHPOffSets);
Result := HPt;
end;
function GetWhitePhantomMaxHP(const AWarrior: TWarrior): Cardinal;
var
HPt: Cardinal;
begin
HPt := GetPointerValue(AWarrior.FPointer, AWarrior.FMaxHPOffSets);
Result := HPt;
end;
function CalculateMaxHP(AWarrior: TWarrior): Cardinal;
begin
if AWarrior.ClassType = TDefaultPlayer then
Result := GetDefaultPlayerMaxHP(AWarrior)
else
if AWarrior.ClassType = TRedPhantom then
Result := GetRedPhantomMaxHP(AWarrior)
else
if AWarrior.ClassType = TBluePhantom then
Result := GetBluePhantomMaxHP(AWarrior)
else
Result := GetWhitePhantomMaxHP(AWarrior)
end;
procedure UpdateStaminaHPStatus(var AWarrior: TWarrior);
begin
AWarrior.ActualStamina := GetPointerValue(AWarrior.FInfoPointer, AWarrior.FActualStaminaOffsets);
AWarrior.HP := GetPointerValue(AWarrior.FInfoPointer, AWarrior.FActualHPOffsets);
end;
procedure UpdateStatus(var AWarrior: TWarrior);
begin
AWarrior.Level := GetPointerValue(AWarrior.FPointer, AWarrior.FLevelOffsets);
AWarrior.Vitality := GetPointerValue(AWarrior.FPointer, AWarrior.FVitalityOffsets);
AWarrior.Attunement := GetPointerValue(AWarrior.FPointer, AWarrior.FAttunementOffsets);
AWarrior.Endurance := GetPointerValue(AWarrior.FPointer, AWarrior.FEnduranceOffsets);
AWarrior.Strength := GetPointerValue(AWarrior.FPointer, AWarrior.FStrengthOffsets);
AWarrior.Dexterity := GetPointerValue(AWarrior.FPointer, AWarrior.FDexterityOffsets);
AWarrior.Resistance := GetPointerValue(AWarrior.FPointer, AWarrior.FResistanceOffsets);
AWarrior.Intelligence := GetPointerValue(AWarrior.FPointer, AWarrior.FIntelligenceOffsets);
AWarrior.Faith := GetPointerValue(AWarrior.FPointer, AWarrior.FFaithOffsets);
AWarrior.WarriorClass := GetWarriorClass(AWarrior);
AWarrior.MaxStamina := CalculateMaxStamina(AWarrior);
AWarrior.MaxHP := CalculateMaxHP(AWarrior);
AWarrior.Name := GetWarriorName(AWarrior);
end;
end.
|
{***************************************************************************}
{ }
{ This file is part of the Gofy "Arkham Horror: The Board Game" migration }
{ and implementation. }
{ }
{ Licensed under GPL License, Version 3.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You should have received a copy of the GNU General Public License }
{ along with Gofy "Arkham Horror: The Board Game" migration Source Code. }
{ If not, see }
{ }
{ <http://www.gnu.org/licenses/> }
{ }
{ Gofy "Arkham Horror: The Board Game" migration Source Code is free }
{ software: you can redistribute it and/or modify it under the terms }
{ of the GNU General Public License as published by the }
{ Free Software Foundation, either version 3 of the License, or }
{ (at your option) any later version. }
{ }
{ Gofy "Arkham Horror: The Board Game" migration Source Code is }
{ distributed in the hope that it will be useful, }
{ but WITHOUT ANY WARRANTY; without even the implied warranty of }
{ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the }
{ GNU General Public License for more details. }
{ }
{ The Original Code is Street.pas. }
{ }
{ Contains logic for handling monster, gates, clues appearing and }
{ interaction. }
{ }
{ Unit owner: Ronar }
{ Last modified: March 7, 2021 }
{ }
{***************************************************************************}
unit uStreet;
interface
uses Winapi.Windows, Graphics, uCommon, uLocationCardDeck, uCardXML, SysUtils, Dialogs, Controls, uMonster;
type
TLocation = record
lok_id: integer; // id of location (2100, 2200, 2300, etc..)
lok_name: string;
clues: integer; // Улики на локации
gate: TGate; // Врата открытые на локации
HasGate: Boolean;
lok_monsters: array [1..MONSTER_MAX_ON_LOK] of TMonster;
lok_mon_count: integer;
end;
TStreet = class(TObject)
private
fId: integer; // id of streets (1000, 2000, 3000, etc..)
fLok: array [1..3] of TLocation;
fDeck: TLocationCardsDeck;
fAdjacent: array [1..6] of integer; // Прилегающие локации
fMonsters: array [1..MONSTER_MAX_ON_LOK] of TMonster; // Mobs in the streets :)
fStreetMonsterCount: integer;
function GetDeck: TLocationCardsDeck;
function GetLok(i: integer): TLocation;
function GetMonster(i: integer): TMonster;
procedure SetMonster(i: integer; mob: TMonster);
public
constructor Create(street_id: integer);
property StreetId: integer read fId write fId;
property Deck: TLocationCardsDeck read GetDeck;
property Lok[i: integer]: TLocation read GetLok;
property Monsters[i: integer]: TMonster read GetMonster write SetMonster;
property st_mob_count: Integer read fStreetMonsterCount write fStreetMonsterCount;
function GetLokByID(id: integer): TLocation;
procedure Encounter(lok_id: integer; crd_num: integer);
function AddMonster(to_lok: integer; mob: TMonster): Boolean;
function AddClue(lok_id: integer; n: integer): Boolean;
function SpawnGate(lok_id: integer; gate: TGate): Boolean;
procedure RemoveClue(lok_id: integer; n: integer);
procedure TakeAwayMonster(from_lok: integer; mob: TMonster);
procedure CloseGate(lok_id: integer);
procedure MoveMonsters;
end;
function GetLokIDByName(lok_name: string): integer; // Получение ID локации по названию
function GetStreetIDByName(street_name: string): integer;
//function GetStreetIndxByLokID(id: integer): integer; // Searches the array for location that matches the id param
function GetStreetNameByID(id: integer): string;
function GetLokNameByID(id: integer): string;
// function ProcessCondition(cond: integer; prm: integer; n: Integer; suxxess: integer): boolean;
// function ProcessMultiCondition(cond: integer; prm: integer; n: Integer; suxxess: integer): integer;
// procedure ProcessAction(action: integer; action_value: integer; suxxess: string = '0');
procedure ProcessNode(Node : PLLData; add_data: integer = 0);
implementation
uses uTradeForm, uMainForm, uEncounterInquiryForm, uDrop, uLocationSelectorForm, uCardForm, Classes;
constructor TStreet.Create(street_id: integer);
var
n: integer;
begin
//for i := 1 to NUMBER_OF_STREETS do
begin
fId := street_id;
for n := 1 to 3 do
begin
fLok[n].lok_id := fId + 100 * n;
fLok[n].clues := 0;
fLok[n].gate.other_world := 0;
fLok[n].gate.modif := 0;
fLok[n].gate.dimension := 0;
fLok[n].HasGate := false;
fLok[n].lok_monsters[1] := nil;
fLok[n].lok_monsters[2] := nil;
fLok[n].lok_monsters[3] := nil;
fLok[n].lok_monsters[4] := nil;
fLok[n].lok_monsters[5] := nil;
fLok[n].lok_mon_count := 0;
end;
fDeck := TLocationCardsDeck.Create;
fStreetMonsterCount := 0;
end;
end;
function TStreet.GetDeck: TLocationCardsDeck;
begin
result := fDeck;
end;
function TStreet.GetLok(i: integer): TLocation;
begin
Result := fLok[i];
end;
function TStreet.GetMonster(i: integer): TMonster;
begin
Result := fMonsters[i];
end;
procedure TStreet.SetMonster(i: integer; mob: TMonster);
begin
Monsters[i] := mob;
end;
function TStreet.GetLokByID(id: integer): TLocation;
var
i: integer;
ln: integer;
begin
//ln := GetStreetIndxByLokID( ton(id) * 1000 );
result := fLok[hon(id)];
end;
// Проверка выполнилось ли условие на карте
function ProcessCondition(cond: integer; prm: integer; n: Integer; suxxess: integer): boolean;
var
skill_test: integer;
begin
ProcessCondition := False;
case cond of
1: begin // Если True
ProcessCondition := True;
end;
2: begin // Проверка скила
MainForm.lstLog.Items.Add('Проверяется навык ' + aStats[prm] + '(=' + IntToStr(gCurrentPlayer.Stats[prm]) + ' -' + IntToStr(n) + ')..');
skill_test := gCurrentPlayer.RollADice(gCurrentPlayer.Stats[prm] + n, 1); // Choise - номер скилла
{ TODO -oRonar : Choise is in dependence with structure of construction
of program. In another words if indices have been changed, program
will be broken }
MainForm.lstLog.Items.Add('Проверка навыка ' + aStats[prm] + ' выпало: ' + IntToStr(skill_test) + ' успех(ов)');
if (skill_test >= suxxess) then
ProcessCondition := True
else
begin
ProcessCondition := False;
end;
end;
3: begin // Проверка наличия
MainForm.lstLog.Items.Add('Проверка наличия чего-либо у игрока');
if gCurrentPlayer.CheckAvailability(prm, N) then //
ProcessCondition := True
else
begin
ProcessCondition := False;
MainForm.lstLog.Items.Add('Не хватат!');
end;
end; // case 3
4: begin // Проверка наличия карты в колоде
case (prm div 1000) of // Extract 1st digit
1: begin // Common item
if Common_Items_Deck.CheckAvailability(prm) then // Временно карты простых вещей
ProcessCondition := True
else
ProcessCondition := False;
end;
end;
//ProcessCondition := True;
MainForm.lstLog.Items.Add('Проверка наличия карты в колоде');
end; // case 4
5: begin // Отдать что-либо
if MessageDlg('Отдать ' + things[prm] + IntToStr(N) + '?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
ProcessCondition := True
else
ProcessCondition := False;
end; // case 5
{7: begin // Spec. card
if MessageDlg('Confirm?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
frmMain.lstLog.Items.Add('Проверяется навык ' + IntToStr(Choise - 1) + '(=' + IntToStr(gCurrentPlayer.Stats[Choise - 1]) + ')..');
skill_test := gPlayer.RollADice(gCurrentPlayer.Stats[Choise - 1] - N); // Choise - номер скилла
frmMain.lstLog.Items.Add('Проверка навыка ' + IntToStr(Choise - 1) + ' выпало: ' + IntToStr(skill_test) + ' успех(ов');
if (skill_test >= min) then
ProcessCondition := True
else
ProcessCondition := False;
end;
end;}
end;
UpdStatus;
end;
function ProcessMultiCondition(cond: integer; prm: integer; n: Integer; suxxess: integer): integer;
var
skill_test: integer;
begin
ProcessMultiCondition := 0;
// Проверка скила
MainForm.lstLog.Items.Add('Проверяется навык ' + aStats[prm] + '(=' + IntToStr(gCurrentPlayer.Stats[prm]) + ' -' + IntToStr(n) + ')..');
skill_test := gCurrentPlayer.RollADice(gCurrentPlayer.Stats[prm] + n, 1); // prm - order num of skill (1 - speed, ...)
MainForm.lstLog.Items.Add('Проверка навыка ' + aStats[prm] + ' выпало: ' + IntToStr(skill_test) + ' успеъ(ов)');
ProcessMultiCondition := skill_test;
end;
function Choise2(act1: string; act2: string): integer;
begin
EncounterInquiryForm.Choise2(act1, act2);
EncounterInquiryForm.ShowModal;
if EncounterInquiryForm.RadioButton1.Checked then
Choise2 := 1
else
if EncounterInquiryForm.RadioButton2.Checked then
Choise2 := 2;
end;
function Choise3(act1: string; act2: string; act3: string): integer;
begin
EncounterInquiryForm.Choise3(act1, act2, act3);
EncounterInquiryForm.ShowModal;
if EncounterInquiryForm.RadioButton1.Checked then
Choise3 := 1
else
if EncounterInquiryForm.RadioButton2.Checked then
Choise3 := 2
else
Choise3 := 3;
end;
function Choise4(act1: string; act2: string; act3: string; act4: string): integer;
begin
EncounterInquiryForm.Choise4(act1, act2, act3, act4);
EncounterInquiryForm.ShowModal;
if EncounterInquiryForm.RadioButton1.Checked then
Choise4 := 1
else
if EncounterInquiryForm.RadioButton2.Checked then
Choise4 := 2
else
if EncounterInquiryForm.RadioButton3.Checked then
Choise4 := 3
else
Choise4 := 4;
end;
// Выполнение действия согласно карте
procedure ProcessAction(action: integer; action_value: integer; suxxess: string = '0');
var
i: integer;
drawn_monster: TMonster;
begin
case action of
1: begin
if action_value = 88 then
begin
Randomize;
action_value := random(6)+1;
end;
if action_value = 882 then
begin
Randomize;
action_value := random(6)+1 + random(6)+1;
end;
gPlayer.Money := gPlayer.Money + action_value;
MainForm.lstLog.Items.Add('Игрок получил деньги: ' + IntToStr(action_value) + '.');
end;
2: begin
if action_value = 88 then
begin
Randomize;
action_value := random(6)+1;
end;
if action_value = 882 then
begin
Randomize;
action_value := random(6)+1 + random(6)+1;
end;
if action_value > 99 then
begin
gPlayer.Money := 0;
MainForm.lstLog.Items.Add('Игрок потерял все деньги.');
end
else
begin
gPlayer.Money := gPlayer.Money - action_value;
MainForm.lstLog.Items.Add('Игрок потерял деньги: ' + IntToStr(action_value) + '.');
end;
end;
3: begin // Take stamina
if action_value = 88 then
begin
Randomize;
action_value := random(6)+1;
end;
if action_value = 882 then
begin
Randomize;
action_value := random(6)+1 + random(6)+1;
end;
gPlayer.Stamina := gPlayer.Stamina + action_value;
MainForm.lstLog.Items.Add('Игрок получил тело: ' + IntToStr(action_value) + '.');
end;
4: begin // Take sanity
if action_value = 88 then
begin
Randomize;
action_value := random(6)+1;
end;
if action_value = 882 then
begin
Randomize;
action_value := random(6)+1 + random(6)+1;
end;
gPlayer.Stamina := gPlayer.Sanity + action_value;
MainForm.lstLog.Items.Add('Игрок получил разум: ' + IntToStr(action_value) + '.');
end;
5: begin // Lose stamina
if action_value = 88 then
begin
Randomize;
action_value := random(6)+1;
end;
if action_value = 882 then
begin
Randomize;
action_value := random(6)+1 + random(6)+1;
end;
gCurrentPlayer.Stamina := gCurrentPlayer.Stamina - action_value;
MainForm.lstLog.Items.Add('Игрок потерял тело: ' + IntToStr(action_value) + '.');
end; // case 5
6: begin // Lose sanity
if action_value = 88 then
begin
Randomize;
action_value := random(6)+1;
end;
if action_value = 882 then
begin
Randomize;
action_value := random(6)+1 + random(6)+1;
end;
gCurrentPlayer.Sanity := gCurrentPlayer.Sanity - action_value;
MainForm.lstLog.Items.Add('Игрок потерял разум: ' + IntToStr(action_value) + '.');
end; // case 6
7: begin // Take clues
if action_value = 88 then
begin
Randomize;
action_value := random(6)+1;
end;
if action_value = 882 then
begin
Randomize;
action_value := random(6)+1 + random(6)+1;
end;
gCurrentPlayer.Clues := gCurrentPlayer.Clues + action_value;
MainForm.lstLog.Items.Add('Игрок получил улику(и): ' + IntToStr(action_value) + '.');
end; // case 7
8: begin // Lose clues
gCurrentPlayer.Clues := gCurrentPlayer.Clues - action_value;
MainForm.lstLog.Items.Add('Игрок потерял улику(и): ' + IntToStr(action_value) + '.');
end; // case 8
9: begin // Draw common item
if action_value > 1000 then // id of card is defined
gCurrentPlayer.AddItem(Common_Items_Deck, action_value)
else
begin
for i := 1 to action_value do
gCurrentPlayer.AddItem(Common_Items_Deck, Common_Items_Deck.DrawCard);
end;
MainForm.lstLog.Items.Add('Игрок вытянул карту простого предмета: ' + IntToStr(action_value));
end; // case 9
10: begin // Draw unique item
if action_value > 1000 then // id of card is defined
gCurrentPlayer.AddItem(Common_Items_Deck, action_value)
else
begin
for i := 1 to action_value do // Draw 'action_value' number of cards
//gCurrentPlayer.AddItem(Unique_Items_Deck.DrawCard);
gCurrentPlayer.AddItem(Common_Items_Deck, Common_Items_Deck.DrawCard);
end;
MainForm.lstLog.Items.Add('Игрок вытянул карту уникального предмета.');
end; // case 10
11: begin // Draw spell
//gCurrentPlayer.AddItem(Spells_Deck.DrawCard);
MainForm.lstLog.Items.Add('Игрок вытянул карту закла.');
end; // case 11
12: begin // Draw skill
//gCurrentPlayer.AddItem(Spells_Deck.DrawCard);
MainForm.lstLog.Items.Add('Игрок берет карту навыка.');
end; // case 12
13: begin // Draw ally card
//gCurrentPlayer.AddItem(Spells_Deck.DrawCard);
for i := 1 to ALLIES_MAX do
if StrToInt(Allies[i, 1]) = action_value then
MainForm.lstLog.Items.Add('Игрок вытянул карту союзника: ' + Allies[i, 2] + '.');
end; // case 13
15: begin // Drop item of player's choise
PrepareCardsToDrop(gCurrentPlayer, action_value);
DropForm.ShowModal;
//gCurrentPlayer.AddItem(Spells_Deck.DrawCard);
MainForm.lstLog.Items.Add('Игрок потерял предмет (на выбор).');
end; // case 15
16: begin // Drop weapon of player's choise or amt.
//gCurrentPlayer.AddItem(Spells_Deck.DrawCard);
MainForm.lstLog.Items.Add('Игрок потерял оружие ' + IntToStr(action_value));
end; // case 16
18: begin // Drop spell
//gCurrentPlayer.AddItem(Spells_Deck.DrawCard);
MainForm.lstLog.Items.Add('Игрок потерял закл.');
end; // case 18
19: begin // Drop skill
//gCurrentPlayer.AddItem(Spells_Deck.DrawCard);
MainForm.lstLog.Items.Add('Игрок потерял навык.');
end; // case 19
20: begin // Move to street
//gCurrentPlayer.Blessed := True;
MainForm.lstLog.Items.Add('Игрок вышел на улицу (overlapping).');
end; // case 20
22: begin //
end; // case 22
25: begin // Busted
//gCurrentPlayer.MoveToLocation(3200);
gCurrentPlayer.Location := 3200;
MainForm.lstLog.Items.Add('Игрок арестован.');
end; // case 25
{ 21: begin // Draw another card for encounter
MainForm.lstLog.Items.Add('Игрок тянет другую карту контакта для локации');
end; // case 25
} 26: begin // Draw common items, buy for 1 above of it's price, any or all
MainForm.lstLog.Items.Add('Encounter');
end; // case 26
30: begin // Move to lok/street (ID or 0 - to street, -1 - to any lok/street)
if action_value = 0 then
begin
gCurrentPlayer.Location := ton(gCurrentPlayer.Location) * 1000;
MainForm.lstLog.Items.Add('Игрок вышел на улицу');
end
else
if action_value = -1 then
begin
LocationSelectorForm.ShowModal;
gCurrentPlayer.Location := StrToInt(LocationSelectorForm.edtLocationId.text);
MainForm.lstLog.Items.Add('Игрок перешел на локацию: ' + GetLokNameByID(StrToInt(LocationSelectorForm.edtLocationId.text)));
end
else
begin
gCurrentPlayer.Location := action_value;
MainForm.lstLog.Items.Add('Игрок перешел на локацию: ' + GetLokNameByID(action_value));
end;
//gCurrentPlayer.Location := ton(gCurrentPlayer.Location) * 1000;
end; // case 30
32: begin // Encounter
//TODO: top card in deck, not 7
MainForm.lstLog.Items.Add('Игрок вступает в контакт');
//Encounter(gCurrentPlayer, Arkham_Streets[ton(gCurrentPlayer.Location)].deck.cards[7, hon(gCurrentPlayer.Location)]);
end; // case 32
33: begin // Blessed
gCurrentPlayer.Blessed := True;
MainForm.lstLog.Items.Add('Игрок благословен.');
end; // case 33
34: begin //
end; // case 34
35: begin // Sucked into gate
//gCurrentPlayer.Location := ton(gCurrentPlayer.Location) * 1000;
MainForm.lstLog.Items.Add('Игрока затянуло во врата.');
end; // case 35
36: begin // Monster apeeared
//gCurrentPlayer.Location := ton(gCurrentPlayer.Location) * 1000;
drawn_monster := DrawMonsterCard(Monsters);
Arkham_Streets[ton(gCurrentPlayer.Location)].AddMonster(gCurrentPlayer.Location, drawn_monster);
MainForm.lstLog.Items.Add('Появился монстр: ' + IntToStr(drawn_monster.id));
end; // case 36
37: begin // Gate appeared
Arkham_Streets[ton(gCurrentPlayer.Location)].SpawnGate(gCurrentPlayer.Location, gates[random(8)+1]);
//gCurrentPlayer.Location := ton(gCurrentPlayer.Location) * 1000;
MainForm.lstLog.Items.Add('Появились врата.');
end; // case 37
38: begin // Pass turn
//gCurrentPlayer.Location := ton(gCurrentPlayer.Location) * 1000;
MainForm.lstLog.Items.Add('Игрок пропускает ход.');
gCurrentPlayer.Moves := 0;
end; // case 38
39: begin // Lost in time and space
//gCurrentPlayer.Location := ton(gCurrentPlayer.Location) * 1000;
MainForm.lstLog.Items.Add('Игрок потерян во времени и пространстве.');
end; // case 39
{ 41: begin // Check skill
MainForm.lstLog.Items.Add('Прове яется навык ' + IntToStr(Choise - 1) + '(=' + IntToStr(gCurrentPlayer.Stats[Choise - 1]) + ' -' + IntToStr(N) + ')..');
skill_test := gCurrentPlayer.RollADice(gCurrentPlayer.Stats[Choise - 1] - N); // Choise - номер скилла
MainForm.lstLog.Items.Add('Проверка навыка ' + IntToStr(Choise - 1) + ' выпало: ' + IntToStr(skill_test) + ' успех(ов)');
if (skill_test >= min) then
Take_Action();
else
begin
Take_Action();
end;
end; }// case 41
40: // Игрок тянет 1 простую вещь бесплатно из n
begin
Trade(TR_TAKE_ITEMS, CT_COMMON_ITEM, action_value);
MainForm.lstLog.Items.Add('Игрок тянет 1 простую вещь бесплатно из ' + IntToStr(action_value));
end; // case 42
42: // Игрок тянет 1 заклинание бесплатно из n
begin
MainForm.lstLog.Items.Add('Игрок тянет 1 заклинание бесплатно из ' + IntToStr(action_value));
end; // case 42
43: begin
MainForm.lstLog.Items.Add('Игрок берет верхню карту из любой колоды локаций. Она достанется тому сыщику, который первый получит контакт в той локации :)');
end; // case 43
51: // Take common weapon
begin
MainForm.lstLog.Items.Add('Игрок берет простое оружие бесплатно: ' + IntToStr(action_value));
end; // case 51
53: // Take common tome
begin
MainForm.lstLog.Items.Add('Игрок берет первую попавшеюся просту книгу: ' + IntToStr(action_value));
end; // case 51
55: // Sell an item for 2x price
begin
card_to_load := CT_COMMON_ITEM;
CardForm.ShowModal;
MainForm.lstLog.Items.Add('Игрок может продать любую вещь в 2 раза дороже: ' + IntToStr(action_value));
end; // case 51
66: begin // Cursed
gCurrentPlayer.Cursed := True;
MainForm.lstLog.Items.Add('Игрок проклят.');
end; // case 66
28: // Move to location, enc
if action_value = 0 then
begin
LocationSelectorForm.ShowModal;
end
else
MainForm.lstLog.Items.Add('Ничего не произошло.'); //gPlayer.Location := StrToInt(IntToStr(Round(action_value / 3 + 0.4)) + IntToStr(action_value - (Round(action_value / 3 + 0.4) - 1) * 3));
end; // case
UpdStatus;
end; // ProcessAction
procedure ProcessNode(Node : PLLData; add_data: integer = 0);
var
s: string;
output_data: TStringList;
b: boolean;
i, j: integer;
st, rolls, pl_choise: Integer; // skill_test
tmp_str: string;
procedure SplitData(delimiter: Char; str: string; var output_data: TStringList);
var
tmp: StrDataArray;
begin
output_data.Clear;
output_data.QuoteChar := '''';
output_data.Delimiter := delimiter;
output_data.DelimitedText := str;
end;
begin
output_data := TStringList.Create;
splitdata('|', Node.data, output_data);
if output_data[1] = '0' then // Action
begin
MainForm.lstLog.Items.Add('Ничего не произошло.');
end;
if output_data[1] = '3' then // Условие
begin
b := ProcessCondition(StrToInt(output_data[2]), StrToInt(output_data[3]), StrToInt(output_data[4]), StrToInt(output_data[5]));
if b then
begin
//ProcessNode(Node.mnChild[0].mnChild[0]);
for i := 0 to Node.mnChild[0].mnChildCount-1 do
begin
ProcessNode(Node.mnChild[0].mnChild[i]);
end;
end
else
begin
//ProcessNode(Node.mnChild[1].mnChild[0]);
for i := 0 to Node.mnChild[1].mnChildCount-1 do
begin
ProcessNode(Node.mnChild[1].mnChild[i]);
end;
end;
//ProcessAction(StrToInt(output_data[1]), StrToInt(output_data[2]));
end;
if output_data[1] = '4' then // Action
begin
if output_data[3] = '77' then // Instead of certain amt, we use result of roll
ProcessAction(StrToInt(output_data[2]), add_data)
else
ProcessAction(StrToInt(output_data[2]), StrToInt(output_data[3]));
end;
if output_data[1] = '2' then // OR
begin
if output_data[2] = '2' then
pl_choise := Choise2(output_data[3], output_data[4])
else
if output_data[2] = '3' then
pl_choise := Choise3(output_data[3], output_data[4], output_data[5])
else
if output_data[2] = '4' then
pl_choise := Choise4(output_data[3], output_data[4], output_data[5], output_data[6]);
if pl_choise = 1 then
begin
for i := 0 to Node.mnChild[0].mnChildCount-1 do
ProcessNode(Node.mnChild[0].mnChild[i]);
end
else
if pl_choise = 2 then
begin
for i := 0 to Node.mnChild[1].mnChildCount-1 do
ProcessNode(Node.mnChild[1].mnChild[i]);
end
else
if pl_choise = 3 then
begin
for i := 0 to Node.mnChild[2].mnChildCount-1 do
ProcessNode(Node.mnChild[2].mnChild[i]);
end
else
if pl_choise = 4 then
for i := 0 to Node.mnChild[3].mnChildCount-1 do
ProcessNode(Node.mnChild[3].mnChild[i]);
end;
if output_data[1] = '5' then // condition with various num of suxxess
begin
if output_data[2] = '1' then // just roll a dice
begin
randomize;
rolls := 0;
for i := 1 to StrToInt(output_data[4]) do // How many rolls
rolls := rolls + random(6) + 1;
for i := 0 to StrToInt(output_data[5])-1 do
begin
tmp_str := node.mnChild[i].data;
if (tmp_str = 'one-three')and(rolls > 0)and(rolls <= 3) then
for j := 0 to node.mnChild[i].mnChildCount-1 do
ProcessNode(node.mnChild[i].mnChild[j], rolls);
if (tmp_str = 'three-six')and(rolls > 3)and(rolls <= 6) then
for j := 0 to node.mnChild[i].mnChildCount-1 do
ProcessNode(node.mnChild[i].mnChild[j], rolls);
end;
exit;
end;
st := ProcessMultiCondition(StrToInt(output_data[2]), StrToInt(output_data[3]), StrToInt(output_data[4]), StrToInt(output_data[5]));
for i := 0 to StrToInt(output_data[5])-1 do
begin
//tmp_str := TStringList.Create;
tmp_str := Node.mnChild[i].data;
if st = 0 then
begin
if pos('zero', tmp_str) <> 0 then
for j := 0 to Node.mnChild[i].mnChildCount-1 do
ProcessNode(Node.mnChild[i].mnChild[j]);
end;
{else
if (tmp_str = 'zero-one') then
for j := 0 to Node.mnChild[i].mnChildCount-1 do
ProcessNode(Node.mnChild[i].mnChild[j]);
}
if st = 1 then
begin
if pos('one', tmp_str) <> 0 then
for j := 0 to Node.mnChild[i].mnChildCount-1 do
ProcessNode(Node.mnChild[i].mnChild[j]);
end;{
else
if (tmp_str = 'zero-one')and(st = 1) then
for j := 0 to Node.mnChild[i].mnChildCount-1 do
ProcessNode(Node.mnChild[i].mnChild[j]);
}
if st = 2 then
begin
if pos('two', tmp_str) <> 0 then
for j := 0 to Node.mnChild[i].mnChildCount-1 do
ProcessNode(Node.mnChild[i].mnChild[j]);
end;{
else
if (tmp_str = 'twoplus')and(st >= 2) then
for j := 0 to Node.mnChild[i].mnChildCount-1 do
ProcessNode(Node.mnChild[i].mnChild[j]);
}
if (st = 3) then
begin
if pos('twoplus', tmp_str) <> 0 then
for j := 0 to Node.mnChild[i].mnChildCount-1 do
ProcessNode(Node.mnChild[i].mnChild[j])
else
if pos('three', tmp_str) <> 0 then
for j := 0 to Node.mnChild[i].mnChildCount-1 do
ProcessNode(Node.mnChild[i].mnChild[j]);
end;
if (st > 3) then
begin
if pos('twoplus', tmp_str) <> 0 then
for j := 0 to Node.mnChild[i].mnChildCount-1 do
ProcessNode(Node.mnChild[i].mnChild[j])
else
if pos('threeplus', tmp_str) <> 0 then
for j := 0 to Node.mnChild[i].mnChildCount-1 do
ProcessNode(Node.mnChild[i].mnChild[j]);
end;
{else
if (tmp_str = 'threeplus')and(st >= 3) then
for j := 0 to Node.mnChild[i].mnChildCount-1 do
ProcessNode(Node.mnChild[i].mnChild[j]);
}
end;
end;
//ProcessAction(StrToInt(output_data[1]), StrToInt(output_data[2]));
output_data.Free;
end; (*ProcessNode*)
procedure TStreet.Encounter(lok_id: integer; crd_num: integer);
var
lok: TLocation;
drawn_items: array [1..3] of integer;
card: TLocationCard;
i: integer;
c_node: PLLData;
crd_name: string;
PrevStretchBltMode : Integer;
bmp: TBitmap;
begin
//if lok_id mod 1000 = 0 then exit; // No encounters on streets
lok := fLok[hon(lok_id)];
if lok.HasGate then
begin
if MessageDlg('Закрыть врата ведущие в иной мир?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
if gCurrentPlayer.CloseGate then
MainForm.lstLog.Items.Add('Игрок подзакрыл врата!')
else
MainForm.lstLog.Items.Add('Игрок не смог подзакрыть врата!')
end;
Exit;
end;
case lok_id of
4200: begin
if MessageDlg('Trade?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
Trade(TR_BUY_NOM_PRICE, CT_COMMON_ITEM, 3);
Exit;
end
// Получили данные карты
end;
end;
// TODO: таблицу с картами | N | ID_Card |, чтобы находить карты для условия
// и добавлять новые
card := fDeck.cards[crd_num, hon(lok_id)];
if card.crd_head <> nil then
begin
crd_name := path_to_exe + 'CardsData\Locations\' + aNeighborhoodsNames[ton(card.id), 2] + '\' + IntToStr((ton(card.ID) * 1000) + StrToInt(IntToStr(card.ID)[4])) + '.jpg';
MainForm.imgEncounter.AutoSize := True;
MainForm.imgEncounter.Picture.LoadFromFile(crd_name);
// bmp := MainForm.imgEncounter.Picture.Bitmap;
bmp := TBitmap.Create;
//
try
with bmp do begin
// bmp.Assign(MainForm.imgEncounter.Bitmap);
Width := MainForm.imgEncounter.Width;
Height := MainForm.imgEncounter.Height;
Canvas.Draw(0, 0, MainForm.imgEncounter.Picture.Graphic);
MainForm.imgEncounter.Picture := nil;
// Transparent := True;
// TransParentColor := bmp.canvas.pixels[50,50];
// MainForm.Canvas.Draw(0, 0, bmp);
MainForm.imgEncounter.AutoSize := False;
MainForm.imgEncounter.Width := 273;
MainForm.imgEncounter.Height := 428;
// TransparentMode := tmAuto;
// MainForm.Canvas.StretchDraw(rect(0, 0, 500, 500), MainForm.imgEncounter.Picture.Graphic);
PrevStretchBltMode := SetStretchBltMode(bmp.Canvas.Handle, STRETCH_HALFTONE);// устанавливаем режим сглаживания
StretchBlt(MainForm.imgEncounter.Canvas.Handle, 0, 0, 273, 428, bmp.Canvas.handle,
0, 0, bmp.Width, bmp.Height, SRCCOPY);
SetStretchBltMode(bmp.Canvas.Handle, PrevStretchBltMode);// Восстанавливаем предыдущий ражим сглаживания
end;
finally
bmp.Free;
end;
// PrevStretchBltMode := SetStretchBltMode(MainForm.imgEncounter.Picture.Bitmap.Canvas.Handle, STRETCH_HALFTONE);// устанавливаем режим сглаживания
// StretchBlt(MainForm.imgEncounter.Canvas.Handle, 0, 0, 300, 300, bmp.Canvas.handle,
// 0, 0, MainForm.imgEncounter.Width, MainForm.imgEncounter.Height, SRCCOPY);
// Canvas.CopyRect(
// rect(0, 0, ClientWidth, ClientHeight),
// Image1.Picture.Bitmap.Canvas,
// Rect(0,0, Image1.Picture.Bitmap.Width, Image1.Picture.Bitmap.Height));
//
// SetStretchBltMode(Canvas.Handle, PrevStretchBltMode );// Восстанавливаем предыдущий ражим сглаживания
c_node := card.crd_head;
for i := 0 to c_node.mnChildCount-1 do
processnode(c_node.mnChild[i]);
end
else
MessageDlg('Карта почему-то пустая :('+#10+#13+'Или вы не перешли на локацию.', mtError, [mbOK], 0);
//Arkham_Streets[GetStreetIndxByLokID(gCurrentPlayer.Location)].deck.Shuffle;
end;
// Берет назв. локи из массива LocationsNames
function GetLokIDByName(lok_name: string): integer;
var
i: integer;
begin
result := 0;
for i := 1 to NUMBER_OF_STREETS do
begin
if (AnsiCompareText(aNeighborhoodsNames[i, 2], lok_name) = 0) then
if (StrToInt(aNeighborhoodsNames[i, 1]) >= 1000) then
begin
result := StrToInt(aNeighborhoodsNames[i, 1]);
break;
Exit;
end
else
result := 0; // TODO: Move to nowhere
end;
for i := 1 to NUMBER_OF_LOCATIONS do
begin
if (AnsiCompareText(aLocationsNames[i, 2], lok_name) = 0) then
if (StrToInt(aLocationsNames[i, 1]) > 1000) then
begin
result := StrToInt(aLocationsNames[i, 1]);
break;
Exit;
end
else
result := 0; // TODO: Move to nowhere
end;
end;
function GetStreetIDByName(street_name: string): integer;
var
i: integer;
begin
for i := 1 to NUMBER_OF_LOCATIONS do
if ((aLocationsNames[i, 2] = street_name) AND (StrToInt(aLocationsNames[i, 1]) > 1000)) then
begin
result := StrToInt(aLocationsNames[i, 1]);
break;
end
else
result := 1100;
end;
function GetLokNameByID(id: integer): string;
var
i: integer;
begin
Result := 'Undefined';
if id mod 1000 = 0 then // Streets.. right
begin
Result := aNeighborhoodsNames[ton(id), 2];
Exit;
end;
if id < 1000 then // Other worlds
begin
for i := 1 to NUMBER_OF_OW_LOCATIONS do
if StrToInt(aOtherWorldsNames[i, 1]) = id then
begin
Result := aOtherWorldsNames[i, 2];
break;
end;
Exit;
end;
for i := 1 to NUMBER_OF_LOCATIONS do
if StrToInt(aLocationsNames[i, 1]) = id then
begin
Result := aLocationsNames[i, 2];
break;
end;
end;
// Searches the array for location that matches the id param
{function GetStreetIndxByLokID(id: integer): integer;
var
i: integer;
st: integer;
begin
st := ton(id) * 1000;
for i := 1 to NUMBER_OF_STREETS do
if Arkham_Streets[i].fId = st then
begin
result := i;
break;
end;
end; }
function GetStreetNameByID(id: integer): string;
var
i: integer;
begin
for i := 1 to NUMBER_OF_STREETS do
if StrToInt(aNeighborhoodsNames[i, 1]) = id then
GetStreetNameByID := aNeighborhoodsNames[i, 2];
end;
function TStreet.AddMonster(to_lok: integer; mob: TMonster): Boolean;
var
i, lok_num: integer;
begin
if mob = nil then
begin
ShowMessage('Невозможно добавить моба! Nil');
Result := false;
exit;
end;
if not (mob is TMonster) then
begin
ShowMessage('Alarm!!!');
end;
try
if to_lok mod 1000 = 0 then
begin
fStreetMonsterCount := fStreetMonsterCount + 1;
fMonsters[fStreetMonsterCount] := mob;
mob.LocationId := to_lok;
uMonster.DeckMobCount := uMonster.DeckMobCount - 1;
// ShowMessage('Добавлен на локацию: ' + IntToStr(to_lok));
end
else
begin
lok_num := hon(to_lok);
fLok[lok_num].lok_mon_count := fLok[lok_num].lok_mon_count + 1;
fLok[lok_num].lok_monsters[fLok[lok_num].lok_mon_count] := mob;
mob.LocationId := to_lok;
uMonster.DeckMobCount := uMonster.DeckMobCount - 1;
// ShowMessage('Добавлен на локацию: ' + IntToStr(to_lok));
end;
result := true;
except
ShowMessage('Невозможно добавить монстра! Except');
Result := false;
end;
end;
function TStreet.AddClue(lok_id: integer; n: integer): Boolean;
begin
result := true;
try
fLok[hon(lok_id)].clues := fLok[hon(lok_id)].clues + n;
except
ShowMessage('Невозможно добавить улику!');
Result := false;
end;
end;
procedure TStreet.RemoveClue(lok_id: integer; n: integer);
begin
fLok[hon(lok_id)].clues := fLok[hon(lok_id)].clues - n;
end;
function TStreet.SpawnGate(lok_id: integer; gate: TGate): boolean;
begin
try
fLok[hon(lok_id)] := GetLokByID(lok_id);
fLok[hon(lok_id)].gate.other_world := gate.other_world;
fLok[hon(lok_id)].gate.modif := gate.modif;
fLok[hon(lok_id)].gate.dimension := gate.dimension;
fLok[hon(lok_id)].HasGate := true;
result := true;
except
ShowMessage('Невозможно добавить врата!');
Result := false;
end;
end;
procedure TStreet.TakeAwayMonster(from_lok: integer; mob: TMonster);
var
i, j: integer;
lok_num: integer;
mob_count: Integer;
procedure AlignArray(var mobs: array of TMonster);
var
k, l: Integer;
begin
for k := 0 to MONSTER_MAX_ON_LOK - 2 do
if (mobs[k] = nil) then
for l := k to MONSTER_MAX_ON_LOK - 2 do
if (mobs[l + 1] <> nil) then
begin
mobs[l] := mobs[l + 1];
mobs[l + 1] := nil;
end;
end;
begin
if from_lok mod 1000 = 0 then // Street
begin
mob_count := fStreetMonsterCount;
for i := 1 to mob_count do
begin
if fMonsters[i] = mob then
begin
fMonsters[i].LocationId := 0;
fMonsters[i] := nil;
mob.LocationId := 0;
fStreetMonsterCount := fStreetMonsterCount - 1;
uMonster.DeckMobCount := uMonster.DeckMobCount + 1;
// ShowMessage('Убран с локации: ' + IntToStr(from_lok));
end;
end;
AlignArray(Self.fMonsters);
// ShowMessage('s');
//AlignArray(Self.fMonsters);
end
else // Location
begin
lok_num := hon(from_lok);
mob_count := fLok[lok_num].lok_mon_count;
for i := 1 to mob_count do
begin
if fLok[lok_num].lok_monsters[i] = mob then
begin
fLok[lok_num].lok_monsters[i].LocationId := 0;
fLok[lok_num].lok_monsters[i] := nil;
mob.LocationId := 0;
fLok[lok_num].lok_mon_count := fLok[lok_num].lok_mon_count - 1;
uMonster.DeckMobCount := uMonster.DeckMobCount + 1;
// ShowMessage('Убран с локации: ' + IntToStr(from_lok));
end;
end;
AlignArray(fLok[lok_num].lok_monsters);
// ShowMessage('s');
//AlignArray(fLok[lok_num].lok_monsters);
end;
end;
procedure TStreet.CloseGate(lok_id: integer);
var
lokk: TLocation;
begin
fLok[hon(lok_id)] := GetLokByID(lok_id);
fLok[hon(lok_id)].gate.other_world := 0;
fLok[hon(lok_id)].gate.modif := 0;
fLok[hon(lok_id)].gate.dimension := 0;
fLok[hon(lok_id)].HasGate := false;
end;
procedure TStreet.MoveMonsters();
begin
end;
end.
|
unit rhlPJW;
interface
uses
rhlCore;
type
{ TrhlPJW }
TrhlPJW = class(TrhlHash)
private
const
BitsInUnsignedInt = SizeOf(DWord) * 8;
ThreeQuarters = (BitsInUnsignedInt * 3) div 4;
OneEighth = BitsInUnsignedInt div 8;
HighBits = High(DWord) shl (BitsInUnsignedInt - OneEighth);
var
m_hash: DWord;
protected
procedure UpdateBytes(const ABuffer; ASize: LongWord); override;
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlPJW }
procedure TrhlPJW.UpdateBytes(const ABuffer; ASize: LongWord);
var
b: PByte;
test: DWord;
begin
b := @ABuffer;
while ASize > 0 do
begin
m_hash := (m_hash shl OneEighth) + b^;
test := m_hash and HighBits;
if (test <> 0) then
m_hash := ((m_hash xor (test shr ThreeQuarters)) and (not HighBits));
Inc(b);
Dec(ASize);
end;
end;
constructor TrhlPJW.Create;
begin
HashSize := 4;
BlockSize := 1;
end;
procedure TrhlPJW.Init;
begin
inherited Init;
m_hash := 0;
end;
procedure TrhlPJW.Final(var ADigest);
begin
Move(m_hash, ADigest, 4);
end;
end.
|
unit DW.iOSapi.Foundation;
{*******************************************************}
{ }
{ Kastri Free }
{ }
{ DelphiWorlds Cross-Platform Library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// Mac
Macapi.ObjectiveC,
// iOS
iOSapi.Foundation;
type
NSLocaleKey = NSString;
NSLocale = interface(NSObject)
['{6D772B7D-BE16-4960-A10B-D5BCEE8D3B94}']
function alternateQuotationBeginDelimiter: NSString; cdecl;
function alternateQuotationEndDelimiter: NSString; cdecl;
function calendarIdentifier: NSString; cdecl;
function collationIdentifier: NSString; cdecl;
function collatorIdentifier: NSString; cdecl;
function countryCode: NSString; cdecl;
function currencyCode: NSString; cdecl;
function currencySymbol: NSString; cdecl;
function decimalSeparator: NSString; cdecl;
[MethodName('displayNameForKey:value:')]
function displayNameForKey(key: NSLocaleKey; value: Pointer): NSString; cdecl;
function exemplarCharacterSet: NSCharacterSet; cdecl;
function groupingSeparator: NSString; cdecl;
function init: Pointer; cdecl;
function initWithCoder(aDecoder: NSCoder): Pointer; cdecl;
function initWithLocaleIdentifier(&string: NSString): Pointer; cdecl;
function languageCode: NSString; cdecl;
function localeIdentifier: NSString; cdecl;
function localizedStringForCalendarIdentifier(calendarIdentifier: NSString): NSString; cdecl;
function localizedStringForCollationIdentifier(collationIdentifier: NSString): NSString; cdecl;
function localizedStringForCollatorIdentifier(collatorIdentifier: NSString): NSString; cdecl;
function localizedStringForCountryCode(countryCode: NSString): NSString; cdecl;
function localizedStringForCurrencyCode(currencyCode: NSString): NSString; cdecl;
function localizedStringForLanguageCode(languageCode: NSString): NSString; cdecl;
function localizedStringForLocaleIdentifier(localeIdentifier: NSString): NSString; cdecl;
function localizedStringForScriptCode(scriptCode: NSString): NSString; cdecl;
function localizedStringForVariantCode(variantCode: NSString): NSString; cdecl;
function objectForKey(key: NSLocaleKey): Pointer; cdecl;
function quotationBeginDelimiter: NSString; cdecl;
function quotationEndDelimiter: NSString; cdecl;
function scriptCode: NSString; cdecl;
function usesMetricSystem: Boolean; cdecl;
function variantCode: NSString; cdecl;
end;
TNSLocale = class(TOCGenericImport<NSLocaleClass, NSLocale>) end;
implementation
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{ *************************************************************************** }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
unit Web.ApacheHTTP;
interface
uses System.SysUtils, System.Classes, Web.HTTPDMethods, Web.HTTPApp;
{$WARN IMPLICIT_STRING_CAST OFF}
type
TApacheRequest = class(TWebRequest)
private
FBytesContent: TBytes;
FContentType: string;
FRequest_rec: PHTTPDRequest;
protected
function GetStringVariable(Index: Integer): string; override;
function GetDateVariable(Index: Integer): TDateTime; override;
function GetIntegerVariable(Index: Integer): Integer; override;
function GetRawContent: TBytes; override;
procedure DoReadTotalContent; override;
public
constructor Create(r: PHTTPDRequest);
function GetFieldByName(const Name: string): string; override;
function ReadClient(var Buffer; Count: Integer): Integer; override;
function ReadString(Count: Integer): string; override;
function TranslateURI(const URI: string): string; override;
function WriteClient(var Buffer; Count: Integer): Integer; override;
function WriteString(const AString: string): Boolean; override;
function WriteHeaders(StatusCode: Integer; const StatusString, Headers: string): Boolean; override;
property HTTPDRequest: PHTTPDRequest read FRequest_rec;
end;
TApacheResponse = class(TWebResponse)
private
FStatusCode: integer;
FReturnCode: integer;
FStringVariables: array[0..MAX_STRINGS - 1] of string;
FIntegerVariables: array[0..MAX_INTEGERS - 1] of Integer;
FDateVariables: array[0..MAX_DATETIMES - 1] of TDateTime;
FBytesContent: TBytes;
FLogMsg: string;
FSent: Boolean;
protected
function GetContent: string; override;
function GetDateVariable(Index: Integer): TDateTime; override;
function GetIntegerVariable(Index: Integer): Integer; override;
function GetLogMessage: string; override;
function GetStatusCode: Integer; override;
function GetStringVariable(Index: Integer): string; override;
procedure SetContent(const Value: string); override;
procedure SetDateVariable(Index: Integer; const Value: TDateTime); override;
procedure SetIntegerVariable(Index: Integer; Value: Integer); override;
procedure SetLogMessage(const Value: string); override;
procedure SetStatusCode(Value: Integer); override;
procedure SetStringVariable(Index: Integer; const Value: string); override;
procedure InitResponse; virtual;
public
constructor Create(HTTPRequest: TWebRequest);
procedure SendResponse; override;
procedure SendRedirect(const URI: string); override;
procedure SendStream(AStream: TStream); override;
function Sent: Boolean; override;
property ReturnCode: integer read FReturnCode write FReturnCode;
end;
implementation
uses System.Math;
constructor TApacheRequest.Create(r: PHTTPDRequest);
begin
FRequest_rec := r; //@r;
FContentType := THTTPDMethods.get_ContentType(FRequest_rec);
FBytesContent := THTTPDMethods.get_Content(FRequest_rec);
// The ancestor's constructor must be called after fRequest_rec is initialized
inherited Create;
end;
function TApacheRequest.GetFieldByName(const Name: string): string;
begin
//Result := apr_table_getx(FRequest_rec^.headers_in, PUTF8Char(UTF8String(Name)));
Result := THTTPDMethods.get_Field(FRequest_rec, Name)
end;
function TApacheRequest.GetStringVariable(Index: Integer): string;
var
len: Integer;
p: pchar;
value: string;
begin
case Index of
0: value := THTTPDMethods.get_method(FRequest_rec); //FRequest_rec^.method;
1: value := THTTPDMethods.get_protocol(FRequest_rec); //FRequest_rec^.protocol;
2: value := THTTPDMethods.get_unparsed_uri(FRequest_rec); //FRequest_rec^.unparsed_uri;
3: value := THTTPDMethods.get_args(FRequest_rec); //FRequest_rec^.args;
4: value := THTTPDMethods.get_path_info(FRequest_rec); //FRequest_rec^.path_info;
5: value := THTTPDMethods.get_filename(FRequest_rec); //FRequest_rec^.filename;
7: value := ''; // Request Date
8: value := THTTPDMethods.get_headers_in_Accept(FRequest_rec); //apr_table_getx(FRequest_rec^.headers_in, 'Accept');
9: value := THTTPDMethods.get_headers_in_From(FRequest_rec); //apr_table_getx(FRequest_rec^.headers_in, 'From');
10: value := THTTPDMethods.get_hostname(FRequest_rec); //FRequest_rec^.hostname;
12: value := THTTPDMethods.get_headers_in_Referer(FRequest_rec); //apr_table_getx(FRequest_rec^.headers_in, 'Referer');
13: value := THTTPDMethods.get_headers_in_UserAgent(FRequest_rec); //apr_table_getx(FRequest_rec^.headers_in, 'User-Agent');
14: value := THTTPDMethods.get_content_encoding(FRequest_rec); //FRequest_rec^.content_encoding;
15: value := THTTPDMethods.get_headers_in_ContentType(FRequest_rec); //apr_table_getx(FRequest_rec^.headers_in, 'Content-Type');
16: value := THTTPDMethods.get_headers_in_ContentLength(FRequest_rec); //apr_table_getx(FRequest_rec^.headers_in, 'Content-Length');
19: value := ''; // Expires
20: value := THTTPDMethods.get_headers_in_Title(FRequest_rec); //apr_table_getx(FRequest_rec^.headers_in, 'Title');
21: value := THTTPDMethods.get_connection_ClientIP(FRequest_rec); //Request_Connection_ClientIP(FRequest_rec^.connection);
22: value := THTTPDMethods.get_connection_RemoteHost(FRequest_rec); //ap_get_remote_hostx(FRequest_rec^.connection,FRequest_rec^.per_dir_config, REMOTE_HOSTx, nil);
23: begin
value := THTTPDMethods.get_unparsed_uri(FRequest_rec); //FRequest_rec^.unparsed_uri;
p := StrScan(pchar(value), '?');
if p <> nil then
len := p - PChar(value)
else
len := length(value);
value := copy(value, 1, len - length(PathInfo));
end;
24: value := THTTPDMethods.get_ServerPort(FRequest_rec); //string(IntToStr(ap_get_server_portx(FRequest_rec)));
25: begin
ReadTotalContent;
value := DefaultCharSetEncoding.GetString(FBytesContent);
end;
26: value := THTTPDMethods.get_headers_in_Connection(FRequest_rec); //apr_table_getx(FRequest_rec^.headers_in, 'Connection');
27: value := THTTPDMethods.get_headers_in_Cookie(FRequest_rec); //apr_table_getx(FRequest_rec^.headers_in, 'Cookie');
28: value := THTTPDMethods.get_headers_in_Authorization(FRequest_rec);
else
value := '';
end;
Result := value;
end;
function TApacheRequest.GetDateVariable(Index: Integer): TDateTime;
var
Value: string;
begin
Value := GetStringVariable(Index);
if Value <> '' then
Result := ParseDate(Value)
else Result := -1;
end;
function TApacheRequest.GetIntegerVariable(Index: Integer): Integer;
var
Value: string;
begin
Value := GetStringVariable(Index);
if Value <> '' then
Result := StrToInt(Value)
else Result := -1;
end;
function TApacheRequest.GetRawContent: TBytes;
begin
Result := FBytesContent;
end;
procedure TApacheRequest.DoReadTotalContent;
var
ReadNow: Integer;
Size: Integer;
Count: Integer;
begin
Count := ContentLength;
ReadNow := Length(FBytesContent);
if ReadNow < Count then
begin
SetLength(FBytesContent, Count);
Size := Count - ReadNow;
while Size > 0 do
begin
ReadNow := ReadClient(FBytesContent[Count-Size], Size);
// FileRead returns -1 when there is an error so we should break out of
// this loop in that case as well as when there is no data left to read.
if ReadNow <= 0 then break;
Dec(Size, ReadNow);
end;
end;
end;
function TApacheRequest.ReadClient(var Buffer; Count: Integer): Integer;
begin
Result := THTTPDMethods.get_client_block(FRequest_rec, @Buffer, Count);
end;
function TApacheRequest.ReadString(Count: Integer): string;
var
Len: Integer;
LResult: TBytes;
begin
SetLength(LResult, Count);
Len := ReadClient(LResult[0], Count);
if Len > 0 then
SetLength(LResult, Len)
else SetLength(LResult, 0);
Result := DefaultCharSetEncoding.GetString(LResult);
end;
function TApacheRequest.TranslateURI(const URI: string): string;
begin
Result := string(THTTPDMethods.server_root_relative(FRequest_rec, URI));
{$IFDEF MSWINDOWS}
Result := UnixPathToDosPath(Result);
{$ENDIF}
end;
{buffer is void type, hence: var Buffer}
function TApacheRequest.WriteClient(var Buffer; Count: Integer): Integer;
begin
Result := 0;
if Count > 0 then
//Result := ap_rwritex(Buffer, Count, FRequest_rec)
Result := THTTPDMethods.write_buffer(FRequest_rec, Buffer, Count);
end;
function TApacheRequest.WriteHeaders(StatusCode: Integer; const StatusString, Headers: string): Boolean;
begin
THTTPDMethods.set_status(FRequest_rec, StatusCode); // FRequest_rec.status := StatusCode;
// ap_send_http_header(FRequest_rec); // Not needed in apache 2.0
Result := true;
end;
function TApacheRequest.WriteString(const AString: string): Boolean;
begin
Result:= true;
if Astring <> '' then
Result := THTTPDMethods.write_string(FRequest_rec, Astring) = length(Astring);
end;
// TApacheResponse methods
constructor TApacheResponse.Create(HTTPRequest: TWebRequest);
begin
inherited Create(HTTPRequest);
InitResponse;
end;
procedure TApacheResponse.InitResponse;
begin
if FHTTPRequest.ProtocolVersion = '' then
Version := '1.0';
StatusCode := 200; // HTTP_OKx;
ReturnCode := THTTPDMethods.get_AP_OK; //AP_OKx;
LastModified := -1;
Expires := -1;
Date := -1;
ContentType := 'text/html';
end;
function TApacheResponse.GetContent: string;
begin
Result := DefaultCharSetEncoding.GetString(FBytesContent);
end;
function TApacheResponse.GetDateVariable(Index: Integer): TDateTime;
begin
if (Index >= Low(FDateVariables)) and (Index <= High(FDateVariables)) then
Result := FDateVariables[Index]
else Result := 0.0;
end;
function TApacheResponse.GetIntegerVariable(Index: Integer): Integer;
begin
if (Index >= Low(FIntegerVariables)) and (Index <= High(FIntegerVariables)) then
Result := FIntegerVariables[Index]
else Result := -1;
end;
function TApacheResponse.GetLogMessage: string;
begin
Result := fLogMsg;
end;
function TApacheResponse.GetStatusCode: Integer;
begin
result := FStatusCode;
end;
function TApacheResponse.GetStringVariable(Index: Integer): string;
begin
if (Index >= Low(FStringVariables)) and (Index <= High(FStringVariables)) then
Result := FStringVariables[Index];
end;
function TApacheResponse.Sent: Boolean;
begin
Result := FSent;
end;
procedure TApacheResponse.SetContent(const Value: string);
begin
FBytesContent := DefaultCharSetEncoding.GetBytes(Value);
if ContentStream = nil then
ContentLength := Length(FBytesContent);
end;
procedure TApacheResponse.SetDateVariable(Index: Integer; const Value: TDateTime);
begin
if (Index >= Low(FDateVariables)) and (Index <= High(FDateVariables)) then
if Value <> FDateVariables[Index] then
FDateVariables[Index] := Value;
end;
procedure TApacheResponse.SetIntegerVariable(Index: Integer; Value: Integer);
begin
if (Index >= Low(FIntegerVariables)) and (Index <= High(FIntegerVariables)) then
if Value <> FIntegerVariables[Index] then
FIntegerVariables[Index] := Value;
end;
procedure TApacheResponse.SetLogMessage(const Value: string);
begin
FLogMsg := Value;
end;
procedure TApacheResponse.SetStatusCode(Value: Integer);
begin
if FStatusCode <> Value then
begin
FStatusCode := Value;
ReasonString := StatusString(Value);
end;
end;
procedure TApacheResponse.SetStringVariable(Index: Integer; const Value: string);
begin
if (Index >= Low(FStringVariables)) and (Index <= High(FStringVariables)) then
FStringVariables[Index] := Value;
end;
procedure TApacheResponse.SendResponse;
var
i: Integer;
ServerMsg: string;
//embedded
procedure AddHeaderItem(const Key, Value: string); overload;
begin
if (Key <> '') and (Value <> '') then
with TApacheRequest(FHTTPRequest) do
THTTPDMethods.set_headers_out(FRequest_rec, Key, Value);
end;
//embedded
procedure AddCustomHeaders;
var
i: integer;
Name: string;
begin
for i := 0 to FCustomHeaders.Count - 1 do
begin
Name := FCustomHeaders.Names[I];
addHeaderItem(Name, FCustomHeaders.values[Name]);
end;
end;
begin
if HTTPRequest.ProtocolVersion <> '' then
begin
if StatusCode > 0 then
ServerMsg := Format('%d %s', [StatusCode, ReasonString]);
AddHeaderItem('Allow', Allow); {do not localize}
for I := 0 to Cookies.Count - 1 do
begin
if (Cookies[I].HeaderValue <> '') then
with TApacheRequest(FHTTPRequest) do
THTTPDMethods.add_headers_out(FRequest_rec, 'Set-Cookie', {do not localize}
PUTF8Char(UTF8String(Cookies[I].HeaderValue)));
end;
AddHeaderItem('Derived-From', DerivedFrom); {do not localize}
if Expires > 0 then
AddHeaderItem('Expires', Format(FormatDateTime(sDateFormat + ' "GMT"', {do not localize}
Expires), [DayOfWeekStr(Expires), MonthStr(Expires)])); {do not localize}
if LastModified > 0 then
AddHeaderItem('Last-Modified', Format(FormatDateTime(sDateFormat +
' "GMT"', LastModified), [DayOfWeekStr(LastModified), {do not localize}
MonthStr(LastModified)])); {do not localize}
AddHeaderItem('Title', Title); {do not localize}
AddHeaderItem('WWW-Authenticate', WWWAuthenticate); {do not localize}
AddCustomHeaders;
AddHeaderItem('Content-Version', ContentVersion); {do not localize}
if ContentType <> '' then
THTTPDMethods.set_headers_out_ContentType(TApacheRequest(FHTTPRequest).FRequest_rec, ContentType);
if ContentEncoding <> '' then
THTTPDMethods.set_headers_out_ContentEncoding(TApacheRequest(FHTTPRequest).FRequest_rec, ContentEncoding);
if (Length(FBytesContent) <> 0) or (ContentStream <> nil) then
begin
Assert((Length(FBytesContent) = 0) or (Length(FBytesContent) = ContentLength));
AddHeaderItem('Content-Length', IntToStr(ContentLength)); {do not localize}
end;
HTTPRequest.WriteHeaders(StatusCode, ServerMsg, '');
end;
if (ContentStream = nil) and (Length(FBytesContent) > 0) then
HTTPRequest.WriteClient(FBytesContent[0], Length(FBytesContent))
else if ContentStream <> nil then
begin
SendStream(ContentStream);
ContentStream := nil; // Drop the stream - memory leak?
end;
//ContentStream.Free; //no need stream is destroyed in destructor TWebResponse.Destroy;
FSent := True;
end;
procedure TApacheResponse.SendRedirect(const URI: string);
begin
with TApacheRequest(FHTTPRequest) do
begin
THTTPDMethods.set_location(FRequest_rec, URI);
FStatusCode := 302; // HTTP_MOVED_TEMPORARILYx;
end;
FSent := False;
end;
procedure TApacheResponse.SendStream(AStream: TStream);
var
Buffer: array[0..8191] of Byte;
BytesToSend: Integer;
begin
while AStream.Position < AStream.Size do
begin
BytesToSend := AStream.Read(Buffer, SizeOf(Buffer));
FHTTPRequest.WriteClient(Buffer, BytesToSend);
end;
end;
end.
|
unit MeasureUnit.Time;
interface
uses
SysUtils, Math,
Global.LanguageString;
type
TimeUnit = record
FPowerOfSUnit: Integer;
end;
const
UnittimePerHigherUnittime = 60;
HourUnit: TimeUnit = (FPowerOfSUnit: 2);
MinuteUnit: TimeUnit = (FPowerOfSUnit: 1);
SecondUnit: TimeUnit = (FPowerOfSUnit: 0);
function FormatTimeInSecond(TimeInSecond: Double): String;
implementation
function GetTimeUnitString
(var TimeInSecond: Double;
UnitToTest: TimeUnit;
const UnitName: String): String;
var
UnitSizeInSecond: Int64;
TimeInThisUnit: Integer;
begin
result := '';
UnitSizeInSecond :=
Floor(Power(UnittimePerHigherUnittime, UnitToTest.FPowerOfSUnit));
TimeInThisUnit := Floor(TimeInSecond / UnitSizeInSecond);
if TimeInThisUnit > 0 then
begin
TimeInSecond := TimeInSecond - (TimeInThisUnit * UnitSizeInSecond);
result := IntToStr(TimeInThisUnit) + UnitName;
if TimeInThisUnit > 1 then
result := result + CapMultiple[CurrLang];
end;
end;
function FormatTimeInSecond(TimeInSecond: Double): String;
var
CurrStr: String;
begin
result := '';
CurrStr :=
GetTimeUnitString(TimeInSecond, HourUnit, CapHour[CurrLang]);
if CurrStr <> '' then
result := CurrStr + ' ';
CurrStr :=
GetTimeUnitString(TimeInSecond, MinuteUnit, CapMin[CurrLang]);
if CurrStr <> '' then
result := result + CurrStr + ' ';
CurrStr :=
GetTimeUnitString(TimeInSecond, SecondUnit, CapSec[CurrLang]);
if CurrStr <> '' then
result := result + CurrStr + ' ';
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.