hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
163 values
lang
stringclasses
53 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
112
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
113
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
113
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
3
1.05M
avg_line_length
float64
1
966k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
fc9023b99b6c50b2e732e127e073fa33d84fcb55
8,874
pas
Pascal
src/gui/UFRMNodes.pas
SkybuckFlying/PascalCoinSimplified
a3dbc67aa47bfe87a207e15abe8a31ea238fa74a
[ "MIT" ]
1
2019-02-05T18:33:02.000Z
2019-02-05T18:33:02.000Z
src/gui/UFRMNodes.pas
SkybuckFlying/PascalCoinSimplified
a3dbc67aa47bfe87a207e15abe8a31ea238fa74a
[ "MIT" ]
1
2018-07-20T21:18:54.000Z
2018-07-20T21:18:54.000Z
src/gui/UFRMNodes.pas
SkybuckFlying/PascalCoinSimplified
a3dbc67aa47bfe87a207e15abe8a31ea238fa74a
[ "MIT" ]
null
null
null
unit UFRMNodes; {$mode delphi} { Copyright (c) 2018 by Herman Schoenfeld Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. Acknowledgements: Portions of methods were copied from original UFRMWallet.pas, Copyright (c) Albert Molina 2016. } interface {$I ..\config.inc} uses LCLIntf, LCLType, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls, LMessages, UCommon.UI, ULog, UBlockChain, UNode, Menus, UNetProtocol; Const CM_PC_NetConnectionUpdated = WM_USER + 1; CM_PC_BlackListUpdated = WM_USER + 2; CM_PC_NetNodeServersUpdated = WM_USER + 3; type { TFRMNodes } TFRMNodes = class(TApplicationForm) Label3: TLabel; Label6: TLabel; Label7: TLabel; memoNetBlackLists: TMemo; memoNetConnections: TMemo; memoNetServers: TMemo; procedure FormCreate(Sender: TObject); private { private declarations } procedure CM_NetConnectionUpdated(var Msg: TMessage); message CM_PC_NetConnectionUpdated; procedure CM_BlackListUpdated(var Msg: TMessage); message CM_PC_BlackListUpdated; procedure CM_NetNodeServersUpdated(var Msg: TMessage); message CM_PC_NetNodeServersUpdated; public { public declarations } // TODO - refactor this out with TNotifyManyEvent so form subscribes directly to event procedure OnNetConnectionsUpdated; procedure OnNetBlackListUpdated; procedure OnNetNodeServersUpdated; end; implementation Uses UTime; {$R *.lfm} { TFRMNodes } procedure TFRMNodes.FormCreate(Sender: TObject); begin OnNetConnectionsUpdated; OnNetNodeServersUpdated; OnNetBlackListUpdated; end; procedure TFRMNodes.CM_NetConnectionUpdated(var Msg: TMessage); Const CT_BooleanToString : Array[Boolean] of String = ('False','True'); Var i : integer; NC : TNetConnection; l : TList; sClientApp, sLastConnTime : String; strings, sNSC, sRS, sDisc : TStrings; hh,nn,ss,ms : Word; begin if Not TNetData.NetData.NetConnections.TryLockList(100,l) then exit; try strings := memoNetConnections.Lines; sNSC := TStringList.Create; sRS := TStringList.Create; sDisc := TStringList.Create; strings.BeginUpdate; Try for i := 0 to l.Count - 1 do begin NC := l[i]; If NC.Client.BytesReceived>0 then begin sClientApp := '['+IntToStr(NC.NetProtocolVersion.protocol_version)+'-'+IntToStr(NC.NetProtocolVersion.protocol_available)+'] '+NC.ClientAppVersion; end else begin sClientApp := '(no data)'; end; if NC.Connected then begin if NC.Client.LastCommunicationTime>1000 then begin DecodeTime(now - NC.Client.LastCommunicationTime,hh,nn,ss,ms); if (hh=0) and (nn=0) And (ss<10) then begin sLastConnTime := ' - Last comunication <10 sec.'; end else begin sLastConnTime := Format(' - Last comunication %.2dm%.2ds',[(hh*60)+nn,ss]); end; end else begin sLastConnTime := ''; end; if NC is TNetServerClient then begin sNSC.Add(Format('Client: IP:%s Block:%d Sent/Received:%d/%d Bytes - %s - Time offset %d - Active since %s %s', [NC.ClientRemoteAddr,NC.RemoteOperationBlock.block,NC.Client.BytesSent,NC.Client.BytesReceived,sClientApp,NC.TimestampDiff,DateTimeElapsedTime(NC.CreatedTime),sLastConnTime])); end else begin if NC.IsMyselfServer then sNSC.Add(Format('MySelf IP:%s Sent/Received:%d/%d Bytes - %s - Time offset %d - Active since %s %s', [NC.ClientRemoteAddr,NC.Client.BytesSent,NC.Client.BytesReceived,sClientApp,NC.TimestampDiff,DateTimeElapsedTime(NC.CreatedTime),sLastConnTime])) else begin sRS.Add(Format('Remote Server: IP:%s Block:%d Sent/Received:%d/%d Bytes - %s - Time offset %d - Active since %s %s', [NC.ClientRemoteAddr,NC.RemoteOperationBlock.block,NC.Client.BytesSent,NC.Client.BytesReceived,sClientApp,NC.TimestampDiff,DateTimeElapsedTime(NC.CreatedTime),sLastConnTime])); end; end; end else begin if NC is TNetServerClient then begin sDisc.Add(Format('Disconnected client: IP:%s - %s',[NC.ClientRemoteAddr,sClientApp])); end else if NC.IsMyselfServer then begin sDisc.Add(Format('Disconnected MySelf IP:%s - %s',[NC.ClientRemoteAddr,sClientApp])); end else begin sDisc.Add(Format('Disconnected Remote Server: IP:%s %s - %s',[NC.ClientRemoteAddr,CT_BooleanToString[NC.Connected],sClientApp])); end; end; end; strings.Clear; strings.Add(Format('Connections Updated %s Clients:%d Servers:%d (valid servers:%d)',[DateTimeToStr(now),sNSC.Count,sRS.Count,TNetData.NetData.NetStatistics.ServersConnectionsWithResponse])); strings.AddStrings(sRS); strings.AddStrings(sNSC); if sDisc.Count>0 then begin strings.Add(''); strings.Add('Disconnected connections: '+Inttostr(sDisc.Count)); strings.AddStrings(sDisc); end; Finally strings.EndUpdate; sNSC.Free; sRS.Free; sDisc.Free; End; //CheckMining; finally TNetData.NetData.NetConnections.UnlockList; end; end; procedure TFRMNodes.OnNetConnectionsUpdated; begin // Ensure handled in UI thread PostMessage(Self.Handle,CM_PC_NetConnectionUpdated,0,0); end; procedure TFRMNodes.CM_NetNodeServersUpdated(var Msg: TMessage); Var i : integer; P : PNodeServerAddress; l : TList; strings : TStrings; s : String; begin l := TNetData.NetData.NodeServersAddresses.LockList; try strings := memoNetServers.Lines; strings.BeginUpdate; Try strings.Clear; strings.Add('NodeServers Updated: '+DateTimeToStr(now) +' Count: '+inttostr(l.Count)); for i := 0 to l.Count - 1 do begin P := l[i]; if Not (P^.is_blacklisted) then begin s := Format('Server IP:%s:%d',[P^.ip,P^.port]); if Assigned(P.netConnection) then begin If P.last_connection>0 then s := s+ ' ** ACTIVE **' else s := s+' ** TRYING TO CONNECT **'; end; if P.its_myself then begin s := s+' ** NOT VALID ** '+P.BlackListText; end; if P.last_connection>0 then begin s := s + ' Last connection: '+DateTimeToStr(UnivDateTime2LocalDateTime( UnixToUnivDateTime(P^.last_connection))); end; if P.last_connection_by_server>0 then begin s := s + ' Last server connection: '+DateTimeToStr(UnivDateTime2LocalDateTime( UnixToUnivDateTime(P^.last_connection_by_server))); end; if (P.last_attempt_to_connect>0) then begin s := s + ' Last attempt to connect: '+DateTimeToStr(P^.last_attempt_to_connect); end; if (P.total_failed_attemps_to_connect>0) then begin s := s + ' (Attempts: '+inttostr(P^.total_failed_attemps_to_connect)+')'; end; strings.Add(s); end; end; Finally strings.EndUpdate; End; finally TNetData.NetData.NodeServersAddresses.UnlockList; end; end; procedure TFRMNodes.OnNetNodeServersUpdated; begin // Ensure handled in UI thread PostMessage(Self.Handle,CM_PC_NetNodeServersUpdated,0,0); end; procedure TFRMNodes.CM_BlackListUpdated(var Msg: TMessage); Const CT_TRUE_FALSE : Array[Boolean] Of AnsiString = ('FALSE','TRUE'); Var i,j,n : integer; P : PNodeServerAddress; l : TList; strings : TStrings; begin l := TNetData.NetData.NodeServersAddresses.LockList; try strings := memoNetBlackLists.Lines; strings.BeginUpdate; Try strings.Clear; // strings.Add('BlackList Updated: %s by TID: %p', [DateTimeToStr(now), TThread.CurrentThread.ThreadID]); XXXXXXXXXXXXXXXX Windows %p is invalid (not a pointer) strings.Add('BlackList Updated: %s by TID: %s', [DateTimeToStr(now), IntToHex(PtrInt(TThread.CurrentThread.ThreadID),8)]); j := 0; n:=0; for i := 0 to l.Count - 1 do begin P := l[i]; if (P^.is_blacklisted) then begin inc(n); if Not P^.its_myself then begin inc(j); strings.Add(Format('Blacklist IP:%s:%d LastConnection:%s Reason: %s', [ P^.ip,P^.port, DateTimeToStr(UnivDateTime2LocalDateTime( UnixToUnivDateTime(P^.last_connection))),P^.BlackListText])); end; end; end; Strings.Add(Format('Total Blacklisted IPs: %d (Total %d)',[j,n])); Finally strings.EndUpdate; End; finally TNetData.NetData.NodeServersAddresses.UnlockList; end; end; procedure TFRMNodes.OnNetBlackListUpdated; begin // Ensure handled in UI thread PostMessage(Self.Handle,CM_PC_BlackListUpdated,0,0); end; end.
34.8
197
0.667568
47fd4382d54bf532f06af41e470fd990a13090c7
20,999
pas
Pascal
Units/BlaiseCoin/UCrypto.pas
blaisecoin/blaisecoin
4d769f2b4e79c8f232de9035d30c5cc0cb90f803
[ "MIT" ]
null
null
null
Units/BlaiseCoin/UCrypto.pas
blaisecoin/blaisecoin
4d769f2b4e79c8f232de9035d30c5cc0cb90f803
[ "MIT" ]
null
null
null
Units/BlaiseCoin/UCrypto.pas
blaisecoin/blaisecoin
4d769f2b4e79c8f232de9035d30c5cc0cb90f803
[ "MIT" ]
null
null
null
{ Copyright (c) 2016 by Albert Molina Copyright (c) 2017 by BlaiseCoin developers Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. This unit is a part of BlaiseCoin, a P2P crypto-currency. } unit UCrypto; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} {$I config.inc} interface uses Classes, SysUtils, UOpenSSL, UOpenSSLdef; Type ECryptoException = class(Exception); TRawBytes = AnsiString; PRawBytes = ^TRawBytes; TECDSA_SIG = record r: TRawBytes; s: TRawBytes; end; { record } TECDSA_Public = record EC_OpenSSL_NID : Word; x: TRawBytes; y: TRawBytes; end; PECDSA_Public = ^TECDSA_Public; TECPrivateKey = class private FPrivateKey: PEC_KEY; FEC_OpenSSL_NID : Word; procedure SetPrivateKey(const Value: PEC_KEY); function GetPublicKey: TECDSA_Public; function GetPublicKeyPoint: PEC_POINT; public constructor Create; procedure GenerateRandomPrivateKey(EC_OpenSSL_NID : Word); destructor Destroy; property privateKey : PEC_KEY read FPrivateKey; property PublicKey : TECDSA_Public read GetPublicKey; property PublicKeyPoint : PEC_POINT read GetPublicKeyPoint; procedure SetPrivateKeyFromHexa(EC_OpenSSL_NID : Word; hexa : AnsiString); property EC_OpenSSL_NID : Word Read FEC_OpenSSL_NID; class function IsValidPublicKey(PubKey : TECDSA_Public) : Boolean; function ExportToRaw : TRawBytes; class function ImportFromRaw(Const raw : TRawBytes) : TECPrivateKey; static; end; TCrypto = class private public class function ToHexaString(const raw : TRawBytes) : AnsiString; class function HexaToRaw(const HexaString : AnsiString) : TRawBytes; class function DoSha256(p : PAnsiChar; plength : Cardinal) : TRawBytes; overload; class function DoSha256(const TheMessage : AnsiString) : TRawBytes; overload; Class procedure DoDoubleSha256(p : PAnsiChar; plength : Cardinal; var ResultSha256 : TRawBytes); overload; class function DoRipeMD160(const TheMessage : AnsiString) : TRawBytes; class function privateKey2Hexa(Key : PEC_KEY) : AnsiString; class function ECDSASign(Key : PEC_KEY; const digest : AnsiString) : TECDSA_SIG; class function ECDSAVerify(EC_OpenSSL_NID : Word; PubKey : EC_POINT; const digest : AnsiString; Signature : TECDSA_SIG) : Boolean; overload; class function ECDSAVerify(PubKey : TECDSA_Public; const digest : AnsiString; Signature : TECDSA_SIG) : Boolean; overload; Class procedure InitCrypto; class function IsHumanReadable(Const ReadableText : TRawBytes) : Boolean; end; TBigNum = class private FBN : PBIGNUM; procedure SetHexaValue(const Value: AnsiString); function GetHexaValue: AnsiString; procedure SetValue(const Value: Int64); function GetValue: Int64; function GetDecimalValue: AnsiString; procedure SetDecimalValue(const Value: AnsiString); function GetRawValue: TRawBytes; procedure SetRawValue(const Value: TRawBytes); public constructor Create; overload; constructor Create(initialValue : Int64); overload; constructor Create(hexaValue : AnsiString); overload; destructor Destroy; override; function Copy : TBigNum; function Add(BN : TBigNum) : TBigNum; overload; function Add(int : Int64) : TBigNum; overload; function Sub(BN : TBigNum) : TBigNum; overload; function Sub(int : Int64) : TBigNum; overload; function Multiply(BN : TBigNum) : TBigNum; overload; function Multiply(int : Int64) : TBigNum; overload; function LShift(nbits : Integer) : TBigNum; function RShift(nbits : Integer) : TBigNum; function CompareTo(BN : TBigNum) : Integer; function Divide(BN : TBigNum) : TBigNum; overload; function Divide(int : Int64) : TBigNum; overload; procedure Divide(dividend, remainder : TBigNum); overload; function ToInt64(var int : Int64) : TBigNum; function ToDecimal : AnsiString; property HexaValue : AnsiString read GetHexaValue write SetHexaValue; property RawValue : TRawBytes read GetRawValue write SetRawValue; property DecimalValue : AnsiString read GetDecimalValue write SetDecimalValue; property Value : Int64 read GetValue write SetValue; function IsZero : Boolean; class function HexaToDecimal(hexa : AnsiString) : AnsiString; class function TargetToHashRate(EncodedTarget : Cardinal) : TBigNum; end; Const CT_TECDSA_Public_Nul : TECDSA_Public = (EC_OpenSSL_NID:0;x:'';y:''); implementation uses ULog, UConst, UStreamOp; var _initialized : Boolean = false; Procedure _DoInit; Begin if not (_initialized) then begin _initialized := true; InitSSLFunctions; end; End; { TECPrivateKey } constructor TECPrivateKey.Create; begin FPrivateKey := nil; FEC_OpenSSL_NID := CT_Default_EC_OpenSSL_NID; end; destructor TECPrivateKey.Destroy; begin if Assigned(FPrivateKey) then EC_KEY_free(FPrivateKey); end; function TECPrivateKey.ExportToRaw: TRawBytes; var ms : TStream; aux : TRawBytes; begin ms := TMemoryStream.Create; try ms.Write(FEC_OpenSSL_NID,sizeof(FEC_OpenSSL_NID)); SetLength(aux,BN_num_bytes(EC_KEY_get0_private_key(FPrivateKey))); BN_bn2bin(EC_KEY_get0_private_key(FPrivateKey),@aux[1]); TStreamOp.WriteAnsiString(ms,aux); SetLength(Result,ms.Size); ms.Position := 0; ms.Read(Result[1],ms.Size); finally ms.Free; end; end; procedure TECPrivateKey.GenerateRandomPrivateKey(EC_OpenSSL_NID : Word); var i : Integer; begin if Assigned(FPrivateKey) then EC_KEY_free(FPrivateKey); FEC_OpenSSL_NID := EC_OpenSSL_NID; FPrivateKey := EC_KEY_new_by_curve_name(EC_OpenSSL_NID); i := EC_KEY_generate_key(FPrivateKey); if i<>1 then Raise ECryptoException.Create('Error generating new Random private Key'); end; function TECPrivateKey.GetPublicKey: TECDSA_Public; var BNx,BNy : PBIGNUM; ctx : PBN_CTX; begin Result.EC_OpenSSL_NID := FEC_OpenSSL_NID; ctx := BN_CTX_new; BNx := BN_new; BNy := BN_new; try EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(FPrivateKey),EC_KEY_get0_public_key(FPrivateKey),BNx,BNy,ctx); SetLength(Result.x,BN_num_bytes(BNx)); BN_bn2bin(BNx,@Result.x[1]); SetLength(Result.y,BN_num_bytes(BNy)); BN_bn2bin(BNy,@Result.y[1]); finally BN_CTX_free(ctx); BN_free(BNx); BN_free(BNy); end; end; function TECPrivateKey.GetPublicKeyPoint: PEC_POINT; begin Result := EC_KEY_get0_public_key(FPrivateKey); end; class function TECPrivateKey.ImportFromRaw(const raw: TRawBytes): TECPrivateKey; var ms : TStream; aux : TRawBytes; BNx : PBIGNUM; ECID : Word; PAC : PAnsiChar; begin Result := nil; ms := TMemoryStream.Create; try ms.WriteBuffer(raw[1],length(raw)); ms.Position := 0; if ms.Read(ECID,sizeof(ECID))<>sizeof(ECID) then exit; if TStreamOp.ReadAnsiString(ms,aux)<0 then exit; BNx := BN_bin2bn(PAnsiChar(aux),length(aux),nil); if assigned(BNx) then begin try PAC := BN_bn2hex(BNx); try Result := TECPrivateKey.Create; Result.SetPrivateKeyFromHexa(ECID,PAC); finally OpenSSL_free(PAC); end; finally BN_free(BNx); end; end; finally ms.Free; end; end; class function TECPrivateKey.IsValidPublicKey(PubKey: TECDSA_Public): Boolean; var BNx,BNy : PBIGNUM; ECG : PEC_GROUP; ctx : PBN_CTX; pub_key : PEC_POINT; begin BNx := BN_bin2bn(PAnsiChar(PubKey.x),length(PubKey.x),nil); try BNy := BN_bin2bn(PAnsiChar(PubKey.y),length(PubKey.y),nil); try ECG := EC_GROUP_new_by_curve_name(PubKey.EC_OpenSSL_NID); try pub_key := EC_POINT_new(ECG); try ctx := BN_CTX_new; try Result := EC_POINT_set_affine_coordinates_GFp(ECG,pub_key,BNx,BNy,ctx) = 1; finally BN_CTX_free(ctx); end; finally EC_POINT_free(pub_key); end; finally EC_GROUP_free(ECG); end; finally BN_free(BNy); end; finally BN_free(BNx); end; end; procedure TECPrivateKey.SetPrivateKey(const Value: PEC_KEY); begin if Assigned(FPrivateKey) then EC_KEY_free(FPrivateKey); FPrivateKey := Value; end; procedure TECPrivateKey.SetPrivateKeyFromHexa(EC_OpenSSL_NID : Word; hexa : AnsiString); var bn : PBIGNUM; ctx : PBN_CTX; pub_key : PEC_POINT; begin bn := BN_new; try if BN_hex2bn(@bn,PAnsiChar(hexa)) = 0 then Raise ECryptoException.Create('Invalid Hexadecimal value:' + hexa); if Assigned(FPrivateKey) then EC_KEY_free(FPrivateKey); FEC_OpenSSL_NID := EC_OpenSSL_NID; FPrivateKey := EC_KEY_new_by_curve_name(EC_OpenSSL_NID); if EC_KEY_set_private_key(FPrivateKey,bn)<>1 then raise ECryptoException.Create('Invalid num to set as private key'); // ctx := BN_CTX_new; pub_key := EC_POINT_new(EC_KEY_get0_group(FPrivateKey)); try if EC_POINT_mul(EC_KEY_get0_group(FPrivateKey),pub_key,bn,nil,nil,ctx)<>1 then raise ECryptoException.Create('Error obtaining public key'); EC_KEY_set_public_key(FPrivateKey,pub_key); finally BN_CTX_free(ctx); EC_POINT_free(pub_key); end; finally BN_free(bn); end; end; { TCrypto } { New at Build 1.0.2 Note: Delphi is slowly when working with Strings (allowing space)... so to increase speed we use a String as a pointer, and only increase speed if needed. Also the same with functions "GetMem" and "FreeMem" } class procedure TCrypto.DoDoubleSha256(p: PAnsiChar; plength: Cardinal; var ResultSha256: TRawBytes); var PS : PAnsiChar; begin if length(ResultSha256)<>32 then SetLength(ResultSha256,32); PS := @ResultSha256[1]; SHA256(p,plength,PS); SHA256(PS,32,PS); end; class function TCrypto.DoRipeMD160(const TheMessage: AnsiString): TRawBytes; var PS : PAnsiChar; PC : PAnsiChar; i : Integer; begin GetMem(PS,33); RIPEMD160(PAnsiChar(TheMessage),Length(TheMessage),PS); PC := PS; Result := ''; for I := 1 to 20 do begin // Result := Result + IntToHex(PtrInt(PC^),2); Result := Result + PC^; inc(PC); end; FreeMem(PS,33); end; class function TCrypto.DoSha256(p: PAnsiChar; plength: Cardinal): TRawBytes; var PS : PAnsiChar; begin SetLength(Result,32); PS := @Result[1]; SHA256(p,plength,PS); end; class function TCrypto.DoSha256(const TheMessage: AnsiString): TRawBytes; var PS : PAnsiChar; begin SetLength(Result,32); PS := @Result[1]; SHA256(PAnsiChar(TheMessage),Length(TheMessage),PS); end; class function TCrypto.ECDSASign(Key: PEC_KEY; const digest: AnsiString): TECDSA_SIG; var PECS : PECDSA_SIG; p : PAnsiChar; i : Integer; {$IFDEF OpenSSL10} {$ELSE} bnr,bns : PBIGNUM; {$ENDIF} begin PECS := ECDSA_do_sign(PAnsiChar(digest),length(digest),Key); try if PECS = nil then raise ECryptoException.Create('Error signing'); {$IFDEF OpenSSL10} i := BN_num_bytes(PECS^._r); SetLength(Result.r,i); p := @Result.r[1]; i := BN_bn2bin(PECS^._r,p); i := BN_num_bytes(PECS^._s); SetLength(Result.s,i); p := @Result.s[1]; i := BN_bn2bin(PECS^._s,p); {$ELSE} ECDSA_SIG_get0(PECS,@bnr,@bns); i := BN_num_bytes(bnr); SetLength(Result.r,i); p := @Result.r[1]; i := BN_bn2bin(bnr,p); i := BN_num_bytes(bns); SetLength(Result.s,i); p := @Result.s[1]; i := BN_bn2bin(bns,p); {$ENDIF} finally ECDSA_SIG_free(PECS); end; end; class function TCrypto.ECDSAVerify(EC_OpenSSL_NID : Word; PubKey: EC_POINT; const digest: AnsiString; Signature: TECDSA_SIG): Boolean; var PECS : PECDSA_SIG; PK : PEC_KEY; {$IFDEF OpenSSL10} {$ELSE} bnr,bns : PBIGNUM; {$ENDIF} begin PECS := ECDSA_SIG_new; try {$IFDEF OpenSSL10} BN_bin2bn(PAnsiChar(Signature.r),length(Signature.r),PECS^._r); BN_bin2bn(PAnsiChar(Signature.s),length(Signature.s),PECS^._s); {$ELSE} { ECDSA_SIG_get0(PECS,@bnr,@bns); BN_bin2bn(PAnsiChar(Signature.r),length(Signature.r),bnr); BN_bin2bn(PAnsiChar(Signature.s),length(Signature.s),bns);} bnr := BN_bin2bn(PAnsiChar(Signature.r),length(Signature.r),nil); bns := BN_bin2bn(PAnsiChar(Signature.s),length(Signature.s),nil); if ECDSA_SIG_set0(PECS,bnr,bns)<>1 then Raise Exception.Create('Dev error 20161019-1 ' + ERR_error_string(ERR_get_error(),nil)); {$ENDIF} PK := EC_KEY_new_by_curve_name(EC_OpenSSL_NID); EC_KEY_set_public_key(PK,@PubKey); Case ECDSA_do_verify(PAnsiChar(digest),length(digest),PECS,PK) of 1 : Result := true; 0 : Result := false; Else raise ECryptoException.Create('Error on Verify'); end; EC_KEY_free(PK); finally ECDSA_SIG_free(PECS); end; end; class function TCrypto.ECDSAVerify(PubKey: TECDSA_Public; const digest: AnsiString; Signature: TECDSA_SIG): Boolean; var BNx,BNy : PBIGNUM; ECG : PEC_GROUP; ctx : PBN_CTX; pub_key : PEC_POINT; begin BNx := BN_bin2bn(PAnsiChar(PubKey.x),length(PubKey.x),nil); BNy := BN_bin2bn(PAnsiChar(PubKey.y),length(PubKey.y),nil); ECG := EC_GROUP_new_by_curve_name(PubKey.EC_OpenSSL_NID); pub_key := EC_POINT_new(ECG); ctx := BN_CTX_new; if EC_POINT_set_affine_coordinates_GFp(ECG,pub_key,BNx,BNy,ctx) = 1 then begin Result := ECDSAVerify(PubKey.EC_OpenSSL_NID, pub_key^,digest,signature); end else begin Result := false; end; BN_CTX_free(ctx); EC_POINT_free(pub_key); EC_GROUP_free(ECG); BN_free(BNx); BN_free(BNy); end; class function TCrypto.HexaToRaw(const HexaString: AnsiString): TRawBytes; var P : PAnsiChar; lc : AnsiString; i : Integer; begin Result := ''; if ((length(HexaString) mod 2)<>0) or (length(HexaString) = 0) then exit; SetLength(result,length(HexaString) div 2); P := @Result[1]; lc := LowerCase(HexaString); i := HexToBin(PAnsiChar(@lc[1]),P,length(Result)); if (i<>(length(HexaString) div 2)) then begin TLog.NewLog(lterror,Classname,'Invalid HEXADECIMAL string result ' + inttostr(i) + '<>' + inttostr(length(HexaString) div 2) + ': ' + HexaString); Result := ''; end; end; class procedure TCrypto.InitCrypto; begin _DoInit; end; class function TCrypto.IsHumanReadable(const ReadableText: TRawBytes): Boolean; var i : Integer; Begin Result := true; for i := 1 to length(ReadableText) do begin if (ord(ReadableText[i])<32) or (ord(ReadableText[i])>=255) then begin Result := false; Exit; end; end; end; class function TCrypto.PrivateKey2Hexa(Key: PEC_KEY): AnsiString; var p : PAnsiChar; begin p := BN_bn2hex(EC_KEY_get0_private_key(Key)); // p := BN_bn2hex(Key^.priv_key); Result := strpas(p); OPENSSL_free(p); end; class function TCrypto.ToHexaString(const raw: TRawBytes): AnsiString; var i : Integer; s : AnsiString; b : Byte; begin SetLength(Result,length(raw)*2); for i := 0 to length(raw)-1 do begin b := Ord(raw[i + 1]); s := IntToHex(b,2); Result[(i*2) + 1] := s[1]; Result[(i*2) + 2] := s[2]; end; end; { TBigNum } function TBigNum.Add(BN: TBigNum): TBigNum; begin BN_add(FBN,BN.FBN,FBN); Result := Self; end; function TBigNum.Add(int: Int64): TBigNum; var bn : TBigNum; begin bn := TBigNum.Create(int); Result := Add(bn); bn.Free; end; function TBigNum.CompareTo(BN: TBigNum): Integer; begin Result := BN_cmp(FBN,BN.FBN); end; function TBigNum.Copy: TBigNum; begin Result := TBigNum.Create(0); BN_copy(Result.FBN,FBN); end; constructor TBigNum.Create; begin Create(0); end; constructor TBigNum.Create(hexaValue: AnsiString); begin Create(0); SetHexaValue(hexaValue); end; constructor TBigNum.Create(initialValue : Int64); begin FBN := BN_new; SetValue(initialValue); end; destructor TBigNum.Destroy; begin BN_free(FBN); inherited; end; procedure TBigNum.Divide(dividend, remainder: TBigNum); var ctx : PBN_CTX; begin ctx := BN_CTX_new; BN_div(FBN,remainder.FBN,FBN,dividend.FBN,ctx); BN_CTX_free(ctx); end; function TBigNum.Divide(int: Int64): TBigNum; var bn : TBigNum; begin bn := TBigNum.Create(int); Result := Divide(bn); bn.Free; end; function TBigNum.Divide(BN: TBigNum): TBigNum; var _div,_rem : PBIGNUM; ctx : PBN_CTX; begin _div := BN_new; _rem := BN_new; ctx := BN_CTX_new; BN_div(FBN,_rem,FBN,BN.FBN,ctx); BN_free(_div); BN_free(_rem); BN_CTX_free(ctx); Result := Self; end; function TBigNum.GetDecimalValue: AnsiString; var p : PAnsiChar; begin p := BN_bn2dec(FBN); Result := strpas(p); OpenSSL_free(p); end; function TBigNum.GetHexaValue: AnsiString; var p : PAnsiChar; begin p := BN_bn2hex(FBN); Result := strpas( p ); OPENSSL_free(p); end; function TBigNum.GetRawValue: TRawBytes; var p : PAnsiChar; i : Integer; begin i := BN_num_bytes(FBN); SetLength(Result,i); p := @Result[1]; i := BN_bn2bin(FBN,p); end; function TBigNum.GetValue: Int64; var p : PAnsiChar; a : AnsiString; err : Integer; begin p := BN_bn2dec(FBN); a := strpas(p); OPENSSL_free(p); val(a,Result,err); end; class function TBigNum.HexaToDecimal(hexa: AnsiString): AnsiString; var bn : TBigNum; begin bn := TBigNum.Create(hexa); result := bn.ToDecimal; bn.Free; end; function TBigNum.IsZero: Boolean; var dv : AnsiString; begin dv := DecimalValue; Result := dv = '0'; end; function TBigNum.LShift(nbits: Integer): TBigNum; begin if BN_lshift(FBN,FBN,nbits)<>1 then raise ECryptoException.Create('Error on LShift'); Result := Self; end; function TBigNum.Multiply(int: Int64): TBigNum; var n : TBigNum; ctx : PBN_CTX; begin n := TBigNum.Create(int); try ctx := BN_CTX_new; if BN_mul(FBN,FBN,n.FBN,ctx)<>1 then raise ECryptoException.Create('Error on multiply'); Result := Self; finally BN_CTX_free(ctx); n.Free; end; end; function TBigNum.RShift(nbits: Integer): TBigNum; begin if BN_rshift(FBN,FBN,nbits)<>1 then raise ECryptoException.Create('Error on LShift'); Result := Self; end; function TBigNum.Multiply(BN: TBigNum): TBigNum; var ctx : PBN_CTX; begin ctx := BN_CTX_new; if BN_mul(FBN,FBN,BN.FBN,ctx)<>1 then raise ECryptoException.Create('Error on multiply'); Result := Self; BN_CTX_free(ctx); Result := Self; end; procedure TBigNum.SetDecimalValue(const Value: AnsiString); begin if BN_dec2bn(@FBN,PAnsiChar(Value)) = 0 then raise ECryptoException.Create('Error on dec2bn'); end; procedure TBigNum.SetHexaValue(const Value: AnsiString); var i : Integer; begin i := BN_hex2bn(@FBN,PAnsiChar(Value)); if i = 0 then begin raise ECryptoException.Create('Invalid Hexadecimal value:' + Value); end; end; procedure TBigNum.SetRawValue(const Value: TRawBytes); var p : PBIGNUM; begin p := BN_bin2bn(PAnsiChar(Value),length(Value),FBN); if (p<>FBN) or (p = Nil) then Raise ECryptoException.Create('Error decoding Raw value to BigNum "' + TCrypto.ToHexaString(Value) + '" (' + inttostr(length(value)) + ')' + #10+ ERR_error_string(ERR_get_error(),nil)); end; procedure TBigNum.SetValue(const Value: Int64); var a : UInt64; begin if Value<0 then a := (Value * (-1)) else a := Value; if BN_set_word(FBN,a)<>1 then raise ECryptoException.Create('Error on set Value'); if Value<0 then BN_set_negative(FBN,1) else BN_set_negative(FBN,0); end; function TBigNum.Sub(BN: TBigNum): TBigNum; begin BN_sub(FBN,FBN,BN.FBN); Result := Self; end; function TBigNum.Sub(int: Int64): TBigNum; var bn : TBigNum; begin bn := TBigNum.Create(int); Result := Sub(bn); bn.Free; end; class function TBigNum.TargetToHashRate(EncodedTarget: Cardinal): TBigNum; var bn1,bn2 : TBigNum; part_A, part_B : Cardinal; ctx : PBN_CTX; begin { Target is 2 parts: First byte (A) is "0" bits on the left. Bytes 1,2,3 (B) are number after first "1" bit Example: Target 23FEBFCE Part_A: 23 -> 35 decimal Part_B: FEBFCE Target to Hash rate Formula: Result = 2^Part_A + ( (2^(Part_A-24)) * Part_B ) } Result := TBigNum.Create(2); part_A := EncodedTarget shr 24; bn1 := TBigNum.Create(part_A); ctx := BN_CTX_new; try if BN_exp(Result.FBN,Result.FBN,bn1.FBN,ctx)<>1 then raise Exception.Create('Error 20161017-3'); finally BN_CTX_free(ctx); bn1.Free; end; // if part_A<=24 then exit; // part_B := (EncodedTarget shl 8) shr 8; bn2 := TBigNum.Create(2); try bn1 := TBigNum.Create(part_A - 24); ctx := BN_CTX_new; try if BN_exp(bn2.FBN,bn2.FBN,bn1.FBN,ctx)<>1 then raise Exception.Create('Error 20161017-4'); finally BN_CTX_free(ctx); bn1.Free; end; bn2.Multiply(part_B); Result.Add(bn2); finally bn2.Free; end; end; function TBigNum.ToDecimal: AnsiString; var p : PAnsiChar; begin p := BN_bn2dec(FBN); Result := strpas(p); OpenSSL_free(p); end; function TBigNum.ToInt64(var int: Int64): TBigNum; var s : AnsiString; err : Integer; p : PAnsiChar; begin p := BN_bn2dec(FBN); s := strpas( p ); OPENSSL_free(p); val(s,int,err); if err<>0 then int := 0; Result := Self; end; initialization finalization end.
26.413836
177
0.698367
c3337563abcfab16b7322ed99149acaba66fbafd
2,135
pas
Pascal
Components/demos/StartHidden/Main.pas
fobricia/old-DIE
77cb7fc4bc81c79da896936873f09f6fbdd02d57
[ "BSD-2-Clause" ]
11
2015-05-02T16:13:45.000Z
2022-02-06T23:48:39.000Z
Components/demos/StartHidden/Main.pas
fobricia/old-DIE
77cb7fc4bc81c79da896936873f09f6fbdd02d57
[ "BSD-2-Clause" ]
null
null
null
Components/demos/StartHidden/Main.pas
fobricia/old-DIE
77cb7fc4bc81c79da896936873f09f6fbdd02d57
[ "BSD-2-Clause" ]
4
2015-08-19T04:55:32.000Z
2020-08-07T00:40:14.000Z
unit Main; interface uses Windows, Classes, Controls, Forms, StdCtrls, CoolTrayIcon; type TMainForm = class(TForm) CoolTrayIcon1: TCoolTrayIcon; CheckBox1: TCheckBox; Label1: TLabel; Button1: TButton; Label2: TLabel; Label3: TLabel; procedure CheckBox1Click(Sender: TObject); procedure CoolTrayIcon1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure CoolTrayIcon1Startup(Sender: TObject; var ShowMainForm: Boolean); procedure Button1Click(Sender: TObject); private function LoadSetting(Key, Item: String; DefValue: Boolean): Boolean; procedure SaveSetting(Key, Item: String; Value: Boolean); procedure RemoveSetting(Key: String); end; var MainForm: TMainForm; implementation {$R *.dfm} uses Registry; const StartHiddenKey = 'Software\CoolTrayIcon\StartHiddenDemo'; function TMainForm.LoadSetting(Key, Item: String; DefValue: Boolean): Boolean; var Reg: TRegIniFile; begin Reg := TRegIniFile.Create(Key); Result := Reg.ReadBool('', Item, DefValue); Reg.Free; end; procedure TMainForm.SaveSetting(Key, Item: String; Value: Boolean); var Reg: TRegIniFile; begin Reg := TRegIniFile.Create(Key); Reg.WriteBool('', Item, Value); Reg.Free; end; procedure TMainForm.RemoveSetting(Key: String); var Reg: TRegIniFile; begin Reg := TRegIniFile.Create(Key); Reg.EraseSection(''); Reg.Free; end; procedure TMainForm.CheckBox1Click(Sender: TObject); begin if CheckBox1.Checked then SaveSetting(StartHiddenKey, 'StartHidden', True) else RemoveSetting(StartHiddenKey); end; procedure TMainForm.CoolTrayIcon1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin CoolTrayIcon1.ShowMainForm; end; procedure TMainForm.CoolTrayIcon1Startup(Sender: TObject; var ShowMainForm: Boolean); var StartHidden: Boolean; begin StartHidden := LoadSetting(StartHiddenKey, 'StartHidden', False); CheckBox1.Checked := StartHidden; ShowMainForm := not StartHidden; end; procedure TMainForm.Button1Click(Sender: TObject); begin Close; end; end.
20.528846
85
0.73911
c34062beec27b25523a62f20ed7131fcdb3fdccd
6,397
pas
Pascal
Units/Utils/UFolderHelper.pas
nanopool/PascalCoin
f6949c4d16b43b4ffc567c4ed5bc67b48d0ac65c
[ "MIT" ]
8
2017-01-28T10:30:03.000Z
2021-05-11T08:09:33.000Z
Units/Utils/UFolderHelper.pas
magnolima/pascalcoin
55abc712c7b84eb3bfceed3f1d767534c1a1f47a
[ "MIT" ]
null
null
null
Units/Utils/UFolderHelper.pas
magnolima/pascalcoin
55abc712c7b84eb3bfceed3f1d767534c1a1f47a
[ "MIT" ]
4
2017-01-28T22:11:18.000Z
2018-01-08T02:18:59.000Z
unit UFolderHelper; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} { Copyright (c) 2016 by Albert Molina Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. This unit is a part of Pascal Coin, a P2P crypto currency without need of historical operations. If you like it, consider a donation using BitCoin: 16K3HCZRhFUtM8GdWRcfKeaa6KsuyxZaYk } interface Type TFileVersionInfo = record HasInfo : Boolean; CompanyName : String; FileDescription : String; FileVersion : String; InternalName : String; LegalCopyRight : String; LegalTradeMarks : String; OriginalFileName : String; ProductName : String; ProductVersion : String; Comments : String; Debug : Boolean; Pre_Release : Boolean; Patched : Boolean; PrivateBuild : Boolean; InfoInferred : Boolean; SpecialBuild : Boolean; End; TFolderHelper = record strict private {$IFnDEF FPC} class function GetFolder(const aCSIDL: Integer): string; static; {$ENDIF} class function GetAppDataFolder : string; static; public class function GetPascalCoinDataFolder : string; static; class Function GetTFileVersionInfo(Const FileName : String) : TFileVersionInfo; static; end; implementation uses {$IFnDEF FPC} Windows, ShlObj, {$DEFINE FILEVERSIONINFO} {$ELSE} {$IFnDEF LINUX} Windows, {$DEFINE FILEVERSIONINFO} {$ENDIF} {LCLIntf, LCLType, LMessages,} {$ENDIF} SysUtils; {$I .\..\PascalCoin\config.inc} {$IFnDEF FPC} function SHGetFolderPath(hwnd: HWND; csidl: Integer; hToken: THandle; dwFlags: DWord; pszPath: LPWSTR): HRESULT; stdcall; forward; function SHGetFolderPath; external 'SHFolder.dll' name 'SHGetFolderPathW'; {$ENDIF} class function TFolderHelper.GetAppDataFolder: string; begin {$IFDEF FPC} {$IFDEF LINUX} Result :=GetEnvironmentVariable('HOME'); {$ELSE} Result :=GetEnvironmentVariable('APPDATA'); {$ENDIF} {$ELSE} Result := GetFolder(CSIDL_APPDATA); // c:\Users\(User Name)\AppData\Roaming {$ENDIF} end; {$IFnDEF FPC} class function TFolderHelper.GetFolder(const aCSIDL: Integer): string; var FolderPath: array[0 .. MAX_PATH] of Char; begin Result := ''; if SHGetFolderPath(0, aCSIDL, 0, 0, @FolderPath) = S_OK then Result := FolderPath; end; {$ENDIF} class function TFolderHelper.GetPascalCoinDataFolder: string; begin {$IFDEF TESTNET} Result := GetAppDataFolder+PathDelim+'PascalCoin_TESTNET'; {$ELSE} Result := GetAppDataFolder+PathDelim+'PascalCoin'; {$ENDIF} end; class function TFolderHelper.GetTFileVersionInfo(Const FileName: String): TFileVersionInfo; {$IFDEF FILEVERSIONINFO} Var verInfoSize : DWord; GetInfoSizeJunk : DWord; VersionInfo, Translation, InfoPointer : Pointer; VersionInfoSize: UINT; VersionValue : string; {$ENDIF} Begin With result do Begin HasInfo := False; CompanyName := ''; FileDescription := ''; FileVersion := ''; InternalName := ''; LegalCopyRight := ''; LegalTradeMarks := ''; OriginalFileName := ''; ProductName := ''; ProductVersion := ''; Comments := ''; Debug := False; Pre_Release := False; Patched := False; PrivateBuild := False; InfoInferred := False; SpecialBuild := False; End; {$IFDEF FILEVERSIONINFO} VerInfoSize := GetFileVersionInfoSize(PChar(FileName),GetInfoSizeJunk); If verInfoSize>0 Then Begin Result.HasInfo := True; GetMem(VersionInfo,VerInfoSize); GetFileVersionInfo(PChar(FileName),0,VerInfoSize,VersionInfo); VerQueryValue(VersionInfo,'\\VarFileInfo\\Translation',Translation,VersionInfoSize); VersionValue := '\\StringFileInfo\\'+ inttohex(LoWord(LongInt(Translation^)),4)+ inttohex(HiWord(LongInt(Translation^)),4)+ '\\'; If VerQueryValue(VersionInfo,PChar(VersionValue+'CompanyName'),InfoPointer,VersionInfoSize) Then Result.CompanyName := String(PChar(InfoPointer)); If VerQueryValue(VersionInfo,PChar(VersionValue+'FileDescription'),InfoPointer,VersionInfoSize) Then Result.FileDescription := String(PChar(InfoPointer)); If VerQueryValue(VersionInfo,PChar(VersionValue+'FileVersion'),InfoPointer,VersionInfoSize) Then Result.FileVersion := String(PChar(InfoPointer)); If VerQueryValue(VersionInfo,PChar(VersionValue+'InternalName'),InfoPointer,VersionInfoSize) Then Result.InternalName := String(PChar(InfoPointer)); If VerQueryValue(VersionInfo,PChar(VersionValue+'LegalCopyright'),InfoPointer,VersionInfoSize) Then Result.LegalCopyRight := String(PChar(InfoPointer)); If VerQueryValue(VersionInfo,PChar(VersionValue+'LegalTrademarks'),InfoPointer,VersionInfoSize) Then Result.LegalTradeMarks := String(PChar(InfoPointer)); If VerQueryValue(VersionInfo,PChar(VersionValue+'OriginalFilename'),InfoPointer,VersionInfoSize) Then Result.OriginalFileName := String(PChar(InfoPointer)); If VerQueryValue(VersionInfo,PChar(VersionValue+'ProductName'),InfoPointer,VersionInfoSize) Then Result.ProductName := String(PChar(InfoPointer)); If VerQueryValue(VersionInfo,PChar(VersionValue+'ProductVersion'),InfoPointer,VersionInfoSize) Then Result.ProductVersion := String(PChar(InfoPointer)); If VerQueryValue(VersionInfo,PChar(VersionValue+'Comments'),InfoPointer,VersionInfoSize) Then Result.Comments := String(PChar(InfoPointer)); If VerQueryValue(VersionInfo,'\',InfoPointer,VersionInfoSize) Then Begin Result.Debug := BOOL(TVSFixedFileInfo(InfoPointer^).dwFileFlags AND VS_FF_DEBUG); Result.Pre_Release := BOOL(TVSFixedFileInfo(InfoPointer^).dwFileFlags AND VS_FF_PRERELEASE); Result.Patched := BOOL(TVSFixedFileInfo(InfoPointer^).dwFileFlags AND VS_FF_PATCHED); Result.PrivateBuild := BOOL(TVSFixedFileInfo(InfoPointer^).dwFileFlags AND VS_FF_PRIVATEBUILD); Result.InfoInferred := BOOL(TVSFixedFileInfo(InfoPointer^).dwFileFlags AND VS_FF_INFOINFERRED); Result.SpecialBuild := BOOL(TVSFixedFileInfo(InfoPointer^).dwFileFlags AND VS_FF_SPECIALBUILD); End; FreeMem(VersionInfo,VerInfoSize); End; {$ENDIF} end; end.
34.208556
108
0.707519
47f00bbce4dbc93ff31451ec4bdd6677f751ec70
5,939
pas
Pascal
src/PasVulkan.Components.Parent.pas
ddem43/pasvulkan
739b004741da322559d310bd4478c36859b75891
[ "Zlib" ]
151
2016-03-03T22:20:58.000Z
2022-03-11T03:10:17.000Z
src/PasVulkan.Components.Parent.pas
ddem43/pasvulkan
739b004741da322559d310bd4478c36859b75891
[ "Zlib" ]
22
2016-09-30T15:59:08.000Z
2021-12-29T20:00:18.000Z
src/PasVulkan.Components.Parent.pas
ddem43/pasvulkan
739b004741da322559d310bd4478c36859b75891
[ "Zlib" ]
30
2016-04-16T01:12:37.000Z
2022-03-08T10:45:11.000Z
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * 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 acknowledgement 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. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Components.Parent; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$m+} interface uses SysUtils, Classes, Math, PasVulkan.Types, PasVulkan.EntityComponentSystem; type PpvComponentParent=^TpvComponentParent; TpvComponentParent=record public Parent:TpvEntityComponentSystem.TEntityID; end; const pvComponentParentDefault:TpvComponentParent= ( Parent:$ffffffff; ); var pvComponentParent:TpvEntityComponentSystem.TRegisteredComponentType=nil; pvComponentParentID:TpvEntityComponentSystem.TComponentID=0; implementation procedure Register; begin pvComponentParent:=TpvEntityComponentSystem.TRegisteredComponentType.Create('parent', 'Parent', ['Base','Parent'], SizeOf(TpvComponentParent), @pvComponentParentDefault); pvComponentParentID:=pvComponentParent.ID; pvComponentParent.Add('parent', 'Parent', TpvEntityComponentSystem.TRegisteredComponentType.TField.TElementType.EntityID, SizeOf(PpvComponentParent(nil)^.Parent), 1, TpvPtrUInt(@PpvComponentParent(nil)^.Parent), SizeOf(PpvComponentParent(nil)^.Parent), [] ); end; initialization Register; end.
51.198276
105
0.413369
c337dadddcf191ee1df3ef44cea089983209b045
379
pas
Pascal
Examples/factorial.pas
igorkulman/SwiftPascalInterpreter
67db8851430118a83e409893679d1e3fc2a8a3ed
[ "MIT" ]
282
2017-12-14T20:01:07.000Z
2022-01-10T02:20:10.000Z
examples/factorial.pas
mariogorki94/JavaPascalInterpreter
cea10a18020a569ca206255646b9c9d66b147b90
[ "MIT" ]
13
2017-12-10T15:26:40.000Z
2020-03-20T16:43:39.000Z
examples/factorial.pas
mariogorki94/JavaPascalInterpreter
cea10a18020a569ca206255646b9c9d66b147b90
[ "MIT" ]
17
2018-01-13T14:20:42.000Z
2020-12-29T14:25:02.000Z
program Main; var input, result: integer; function Factorial(number: Integer): Integer; begin if number > 1 then Factorial := number * Factorial(number-1) else Factorial := 1 end; begin { Main } writeln('Factorial'); writeln(''); writeln('Enter number and press Enter'); read(input); result := Factorial(input); writeln(''); writeln(input,'! = ', result) end. { Main }
18.95
45
0.683377
47f3b4de4fe8acee2155757e8306b1978739b76d
28,877
pas
Pascal
lib/delphi/src/Thrift.Transport.Pipes.pas
BluechipSystems/thrift
c595aa18cba0032e074f9585aa2d6ca548f07197
[ "Apache-2.0" ]
null
null
null
lib/delphi/src/Thrift.Transport.Pipes.pas
BluechipSystems/thrift
c595aa18cba0032e074f9585aa2d6ca548f07197
[ "Apache-2.0" ]
2
2015-11-19T09:17:37.000Z
2022-01-31T16:25:54.000Z
lib/delphi/src/Thrift.Transport.Pipes.pas
BluechipSystems/thrift
c595aa18cba0032e074f9585aa2d6ca548f07197
[ "Apache-2.0" ]
null
null
null
(* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. *) unit Thrift.Transport.Pipes; {$WARN SYMBOL_PLATFORM OFF} interface uses Windows, SysUtils, Math, AccCtrl, AclAPI, SyncObjs, Thrift.Transport, Thrift.Utils, Thrift.Stream; const DEFAULT_THRIFT_PIPE_TIMEOUT = DEFAULT_THRIFT_TIMEOUT deprecated 'use DEFAULT_THRIFT_TIMEOUT'; type //--- Pipe Streams --- TPipeStreamBase = class( TThriftStreamImpl) strict protected FPipe : THandle; FTimeout : DWORD; FOverlapped : Boolean; procedure Write( const buffer: TBytes; offset: Integer; count: Integer); override; function Read( var buffer: TBytes; offset: Integer; count: Integer): Integer; override; //procedure Open; override; - see derived classes procedure Close; override; procedure Flush; override; function ReadDirect( var buffer: TBytes; offset: Integer; count: Integer): Integer; function ReadOverlapped( var buffer: TBytes; offset: Integer; count: Integer): Integer; procedure WriteDirect( const buffer: TBytes; offset: Integer; count: Integer); procedure WriteOverlapped( const buffer: TBytes; offset: Integer; count: Integer); function IsOpen: Boolean; override; function ToArray: TBytes; override; public constructor Create( aEnableOverlapped : Boolean; const aTimeOut : DWORD = DEFAULT_THRIFT_TIMEOUT); destructor Destroy; override; end; TNamedPipeStreamImpl = class sealed( TPipeStreamBase) strict private FPipeName : string; FShareMode : DWORD; FSecurityAttribs : PSecurityAttributes; strict protected procedure Open; override; public constructor Create( const aPipeName : string; const aEnableOverlapped : Boolean; const aShareMode: DWORD = 0; const aSecurityAttributes: PSecurityAttributes = nil; const aTimeOut : DWORD = DEFAULT_THRIFT_TIMEOUT); overload; end; THandlePipeStreamImpl = class sealed( TPipeStreamBase) strict private FSrcHandle : THandle; strict protected procedure Open; override; public constructor Create( const aPipeHandle : THandle; const aOwnsHandle, aEnableOverlapped : Boolean; const aTimeOut : DWORD = DEFAULT_THRIFT_TIMEOUT); overload; destructor Destroy; override; end; //--- Pipe Transports --- IPipeTransport = interface( IStreamTransport) ['{5E05CC85-434F-428F-BFB2-856A168B5558}'] end; TPipeTransportBase = class( TStreamTransportImpl, IPipeTransport) public // ITransport function GetIsOpen: Boolean; override; procedure Open; override; procedure Close; override; end; TNamedPipeTransportClientEndImpl = class( TPipeTransportBase) public // Named pipe constructors constructor Create( aPipe : THandle; aOwnsHandle : Boolean; const aTimeOut : DWORD); overload; constructor Create( const aPipeName : string; const aShareMode: DWORD = 0; const aSecurityAttributes: PSecurityAttributes = nil; const aTimeOut : DWORD = DEFAULT_THRIFT_TIMEOUT); overload; end; TNamedPipeTransportServerEndImpl = class( TNamedPipeTransportClientEndImpl) strict private FHandle : THandle; public // ITransport procedure Close; override; constructor Create( aPipe : THandle; aOwnsHandle : Boolean; const aTimeOut : DWORD = DEFAULT_THRIFT_TIMEOUT); reintroduce; end; TAnonymousPipeTransportImpl = class( TPipeTransportBase) public // Anonymous pipe constructor constructor Create( const aPipeRead, aPipeWrite : THandle; aOwnsHandles : Boolean); overload; end; //--- Server Transports --- IAnonymousPipeServerTransport = interface( IServerTransport) ['{7AEE6793-47B9-4E49-981A-C39E9108E9AD}'] // Server side anonymous pipe ends function ReadHandle : THandle; function WriteHandle : THandle; // Client side anonymous pipe ends function ClientAnonRead : THandle; function ClientAnonWrite : THandle; end; INamedPipeServerTransport = interface( IServerTransport) ['{9DF9EE48-D065-40AF-8F67-D33037D3D960}'] function Handle : THandle; end; TPipeServerTransportBase = class( TServerTransportImpl) strict protected FStopServer : TEvent; procedure InternalClose; virtual; abstract; function QueryStopServer : Boolean; public constructor Create; destructor Destroy; override; procedure Listen; override; procedure Close; override; end; TAnonymousPipeServerTransportImpl = class( TPipeServerTransportBase, IAnonymousPipeServerTransport) strict private FBufSize : DWORD; // Server side anonymous pipe handles FReadHandle, FWriteHandle : THandle; //Client side anonymous pipe handles FClientAnonRead, FClientAnonWrite : THandle; protected function Accept(const fnAccepting: TProc): ITransport; override; function CreateAnonPipe : Boolean; // IAnonymousPipeServerTransport function ReadHandle : THandle; function WriteHandle : THandle; function ClientAnonRead : THandle; function ClientAnonWrite : THandle; procedure InternalClose; override; public constructor Create( aBufsize : Cardinal = 4096); end; TNamedPipeServerTransportImpl = class( TPipeServerTransportBase, INamedPipeServerTransport) strict private FPipeName : string; FMaxConns : DWORD; FBufSize : DWORD; FTimeout : DWORD; FHandle : THandle; FConnected : Boolean; strict protected function Accept(const fnAccepting: TProc): ITransport; override; function CreateNamedPipe : THandle; function CreateTransportInstance : ITransport; // INamedPipeServerTransport function Handle : THandle; procedure InternalClose; override; public constructor Create( aPipename : string; aBufsize : Cardinal = 4096; aMaxConns : Cardinal = PIPE_UNLIMITED_INSTANCES; aTimeOut : Cardinal = INFINITE); end; implementation procedure ClosePipeHandle( var hPipe : THandle); begin if hPipe <> INVALID_HANDLE_VALUE then try CloseHandle( hPipe); finally hPipe := INVALID_HANDLE_VALUE; end; end; function DuplicatePipeHandle( const hSource : THandle) : THandle; begin if not DuplicateHandle( GetCurrentProcess, hSource, GetCurrentProcess, @result, 0, FALSE, DUPLICATE_SAME_ACCESS) then raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, 'DuplicateHandle: '+SysErrorMessage(GetLastError)); end; { TPipeStreamBase } constructor TPipeStreamBase.Create( aEnableOverlapped : Boolean; const aTimeOut : DWORD = DEFAULT_THRIFT_TIMEOUT); begin inherited Create; ASSERT( aTimeout > 0); FPipe := INVALID_HANDLE_VALUE; FTimeout := aTimeOut; FOverlapped := aEnableOverlapped; end; destructor TPipeStreamBase.Destroy; begin try Close; finally inherited Destroy; end; end; procedure TPipeStreamBase.Close; begin ClosePipeHandle( FPipe); end; procedure TPipeStreamBase.Flush; begin FlushFileBuffers( FPipe); end; function TPipeStreamBase.IsOpen: Boolean; begin result := (FPipe <> INVALID_HANDLE_VALUE); end; procedure TPipeStreamBase.Write(const buffer: TBytes; offset, count: Integer); begin if FOverlapped then WriteOverlapped( buffer, offset, count) else WriteDirect( buffer, offset, count); end; function TPipeStreamBase.Read( var buffer: TBytes; offset, count: Integer): Integer; begin if FOverlapped then result := ReadOverlapped( buffer, offset, count) else result := ReadDirect( buffer, offset, count); end; procedure TPipeStreamBase.WriteDirect(const buffer: TBytes; offset, count: Integer); var cbWritten : DWORD; begin if not IsOpen then raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, 'Called write on non-open pipe'); if not WriteFile( FPipe, buffer[offset], count, cbWritten, nil) then raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, 'Write to pipe failed'); end; function TPipeStreamBase.ReadDirect( var buffer: TBytes; offset, count: Integer): Integer; var cbRead, dwErr : DWORD; bytes, retries : LongInt; bOk : Boolean; const INTERVAL = 10; // ms begin if not IsOpen then raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, 'Called read on non-open pipe'); // MSDN: Handle can be a handle to a named pipe instance, // or it can be a handle to the read end of an anonymous pipe, // The handle must have GENERIC_READ access to the pipe. if FTimeOut <> INFINITE then begin retries := Max( 1, Round( 1.0 * FTimeOut / INTERVAL)); while TRUE do begin if IsOpen and PeekNamedPipe( FPipe, nil, 0, nil, @bytes, nil) and (bytes > 0) then Break; // there are data dwErr := GetLastError; if (dwErr = ERROR_INVALID_HANDLE) or (dwErr = ERROR_BROKEN_PIPE) or (dwErr = ERROR_PIPE_NOT_CONNECTED) then begin result := 0; // other side closed the pipe Exit; end; Dec( retries); if retries > 0 then Sleep( INTERVAL) else raise TTransportException.Create( TTransportException.TExceptionType.TimedOut, 'Pipe read timed out'); end; end; // read the data (or block INFINITE-ly) bOk := ReadFile( FPipe, buffer[offset], count, cbRead, nil); if (not bOk) and (GetLastError() <> ERROR_MORE_DATA) then result := 0 // No more data, possibly because client disconnected. else result := cbRead; end; procedure TPipeStreamBase.WriteOverlapped(const buffer: TBytes; offset, count: Integer); var cbWritten, dwWait, dwError : DWORD; overlapped : IOverlappedHelper; begin if not IsOpen then raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, 'Called write on non-open pipe'); overlapped := TOverlappedHelperImpl.Create; if not WriteFile( FPipe, buffer[offset], count, cbWritten, overlapped.OverlappedPtr) then begin dwError := GetLastError; case dwError of ERROR_IO_PENDING : begin dwWait := overlapped.WaitFor(FTimeout); if (dwWait = WAIT_TIMEOUT) then raise TTransportException.Create( TTransportException.TExceptionType.TimedOut, 'Pipe write timed out'); if (dwWait <> WAIT_OBJECT_0) or not GetOverlappedResult( FPipe, overlapped.Overlapped, cbWritten, TRUE) then raise TTransportException.Create( TTransportException.TExceptionType.Unknown, 'Pipe write error'); end; else raise TTransportException.Create( TTransportException.TExceptionType.Unknown, SysErrorMessage(dwError)); end; end; ASSERT( DWORD(count) = cbWritten); end; function TPipeStreamBase.ReadOverlapped( var buffer: TBytes; offset, count: Integer): Integer; var cbRead, dwWait, dwError : DWORD; bOk : Boolean; overlapped : IOverlappedHelper; begin if not IsOpen then raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, 'Called read on non-open pipe'); overlapped := TOverlappedHelperImpl.Create; // read the data bOk := ReadFile( FPipe, buffer[offset], count, cbRead, overlapped.OverlappedPtr); if not bOk then begin dwError := GetLastError; case dwError of ERROR_IO_PENDING : begin dwWait := overlapped.WaitFor(FTimeout); if (dwWait = WAIT_TIMEOUT) then raise TTransportException.Create( TTransportException.TExceptionType.TimedOut, 'Pipe read timed out'); if (dwWait <> WAIT_OBJECT_0) or not GetOverlappedResult( FPipe, overlapped.Overlapped, cbRead, TRUE) then raise TTransportException.Create( TTransportException.TExceptionType.Unknown, 'Pipe read error'); end; else raise TTransportException.Create( TTransportException.TExceptionType.Unknown, SysErrorMessage(dwError)); end; end; ASSERT( cbRead > 0); // see TTransportImpl.ReadAll() ASSERT( cbRead = DWORD(count)); result := cbRead; end; function TPipeStreamBase.ToArray: TBytes; var bytes : LongInt; begin SetLength( result, 0); bytes := 0; if IsOpen and PeekNamedPipe( FPipe, nil, 0, nil, @bytes, nil) and (bytes > 0) then begin SetLength( result, bytes); Read( result, 0, bytes); end; end; { TNamedPipeStreamImpl } constructor TNamedPipeStreamImpl.Create( const aPipeName : string; const aEnableOverlapped : Boolean; const aShareMode: DWORD; const aSecurityAttributes: PSecurityAttributes; const aTimeOut : DWORD); begin inherited Create( aEnableOverlapped, aTimeout); FPipeName := aPipeName; FShareMode := aShareMode; FSecurityAttribs := aSecurityAttributes; if Copy(FPipeName,1,2) <> '\\' then FPipeName := '\\.\pipe\' + FPipeName; // assume localhost end; procedure TNamedPipeStreamImpl.Open; var hPipe : THandle; begin if IsOpen then Exit; // open that thingy if not WaitNamedPipe( PChar(FPipeName), FTimeout) then raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, 'Unable to open pipe, '+SysErrorMessage(GetLastError)); hPipe := CreateFile( PChar( FPipeName), GENERIC_READ or GENERIC_WRITE, FShareMode, // sharing FSecurityAttribs, // security attributes OPEN_EXISTING, // opens existing pipe FILE_FLAG_OVERLAPPED or FILE_FLAG_WRITE_THROUGH, // async+fast, please 0); // no template file if hPipe = INVALID_HANDLE_VALUE then raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, 'Unable to open pipe, '+SysErrorMessage(GetLastError)); // everything fine FPipe := hPipe; end; { THandlePipeStreamImpl } constructor THandlePipeStreamImpl.Create( const aPipeHandle : THandle; const aOwnsHandle, aEnableOverlapped : Boolean; const aTimeOut : DWORD); begin inherited Create( aEnableOverlapped, aTimeOut); if aOwnsHandle then FSrcHandle := aPipeHandle else FSrcHandle := DuplicatePipeHandle( aPipeHandle); Open; end; destructor THandlePipeStreamImpl.Destroy; begin try ClosePipeHandle( FSrcHandle); finally inherited Destroy; end; end; procedure THandlePipeStreamImpl.Open; begin if not IsOpen then FPipe := DuplicatePipeHandle( FSrcHandle); end; { TPipeTransportBase } function TPipeTransportBase.GetIsOpen: Boolean; begin result := (FInputStream <> nil) and (FInputStream.IsOpen) and (FOutputStream <> nil) and (FOutputStream.IsOpen); end; procedure TPipeTransportBase.Open; begin FInputStream.Open; FOutputStream.Open; end; procedure TPipeTransportBase.Close; begin FInputStream.Close; FOutputStream.Close; end; { TNamedPipeTransportClientEndImpl } constructor TNamedPipeTransportClientEndImpl.Create( const aPipeName : string; const aShareMode: DWORD; const aSecurityAttributes: PSecurityAttributes; const aTimeOut : DWORD); // Named pipe constructor begin inherited Create( nil, nil); FInputStream := TNamedPipeStreamImpl.Create( aPipeName, TRUE, aShareMode, aSecurityAttributes, aTimeOut); FOutputStream := FInputStream; // true for named pipes end; constructor TNamedPipeTransportClientEndImpl.Create( aPipe : THandle; aOwnsHandle : Boolean; const aTimeOut : DWORD); // Named pipe constructor begin inherited Create( nil, nil); FInputStream := THandlePipeStreamImpl.Create( aPipe, TRUE, aOwnsHandle, aTimeOut); FOutputStream := FInputStream; // true for named pipes end; { TNamedPipeTransportServerEndImpl } constructor TNamedPipeTransportServerEndImpl.Create( aPipe : THandle; aOwnsHandle : Boolean; const aTimeOut : DWORD); // Named pipe constructor begin FHandle := DuplicatePipeHandle( aPipe); inherited Create( aPipe, aOwnsHandle, aTimeOut); end; procedure TNamedPipeTransportServerEndImpl.Close; begin FlushFileBuffers( FHandle); DisconnectNamedPipe( FHandle); // force client off the pipe ClosePipeHandle( FHandle); inherited Close; end; { TAnonymousPipeTransportImpl } constructor TAnonymousPipeTransportImpl.Create( const aPipeRead, aPipeWrite : THandle; aOwnsHandles : Boolean); // Anonymous pipe constructor begin inherited Create( nil, nil); // overlapped is not supported with AnonPipes, see MSDN FInputStream := THandlePipeStreamImpl.Create( aPipeRead, aOwnsHandles, FALSE); FOutputStream := THandlePipeStreamImpl.Create( aPipeWrite, aOwnsHandles, FALSE); end; { TPipeServerTransportBase } constructor TPipeServerTransportBase.Create; begin inherited Create; FStopServer := TEvent.Create(nil,TRUE,FALSE,''); // manual reset end; destructor TPipeServerTransportBase.Destroy; begin try FreeAndNil( FStopServer); finally inherited Destroy; end; end; function TPipeServerTransportBase.QueryStopServer : Boolean; begin result := (FStopServer = nil) or (FStopServer.WaitFor(0) <> wrTimeout); end; procedure TPipeServerTransportBase.Listen; begin FStopServer.ResetEvent; end; procedure TPipeServerTransportBase.Close; begin FStopServer.SetEvent; InternalClose; end; { TAnonymousPipeServerTransportImpl } constructor TAnonymousPipeServerTransportImpl.Create( aBufsize : Cardinal); // Anonymous pipe CTOR begin inherited Create; FBufsize := aBufSize; FReadHandle := INVALID_HANDLE_VALUE; FWriteHandle := INVALID_HANDLE_VALUE; FClientAnonRead := INVALID_HANDLE_VALUE; FClientAnonWrite := INVALID_HANDLE_VALUE; // The anonymous pipe needs to be created first so that the server can // pass the handles on to the client before the serve (acceptImpl) // blocking call. if not CreateAnonPipe then raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, ClassName+'.Create() failed'); end; function TAnonymousPipeServerTransportImpl.Accept(const fnAccepting: TProc): ITransport; var buf : Byte; br : DWORD; begin if Assigned(fnAccepting) then fnAccepting(); // This 0-byte read serves merely as a blocking call. if not ReadFile( FReadHandle, buf, 0, br, nil) and (GetLastError() <> ERROR_MORE_DATA) then raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, 'TServerPipe unable to initiate pipe communication'); // create the transport impl result := TAnonymousPipeTransportImpl.Create( FReadHandle, FWriteHandle, FALSE); end; procedure TAnonymousPipeServerTransportImpl.InternalClose; begin ClosePipeHandle( FReadHandle); ClosePipeHandle( FWriteHandle); ClosePipeHandle( FClientAnonRead); ClosePipeHandle( FClientAnonWrite); end; function TAnonymousPipeServerTransportImpl.ReadHandle : THandle; begin result := FReadHandle; end; function TAnonymousPipeServerTransportImpl.WriteHandle : THandle; begin result := FWriteHandle; end; function TAnonymousPipeServerTransportImpl.ClientAnonRead : THandle; begin result := FClientAnonRead; end; function TAnonymousPipeServerTransportImpl.ClientAnonWrite : THandle; begin result := FClientAnonWrite; end; function TAnonymousPipeServerTransportImpl.CreateAnonPipe : Boolean; var sd : PSECURITY_DESCRIPTOR; sa : SECURITY_ATTRIBUTES; //TSecurityAttributes; hCAR, hPipeW, hCAW, hPipe : THandle; begin result := FALSE; sd := PSECURITY_DESCRIPTOR( LocalAlloc( LPTR,SECURITY_DESCRIPTOR_MIN_LENGTH)); try Win32Check( InitializeSecurityDescriptor( sd, SECURITY_DESCRIPTOR_REVISION)); Win32Check( SetSecurityDescriptorDacl( sd, TRUE, nil, FALSE)); sa.nLength := sizeof( sa); sa.lpSecurityDescriptor := sd; sa.bInheritHandle := TRUE; //allow passing handle to child if not CreatePipe( hCAR, hPipeW, @sa, FBufSize) then begin //create stdin pipe raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, 'TServerPipe CreatePipe (anon) failed, '+SysErrorMessage(GetLastError)); Exit; end; if not CreatePipe( hPipe, hCAW, @sa, FBufSize) then begin //create stdout pipe CloseHandle( hCAR); CloseHandle( hPipeW); raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, 'TServerPipe CreatePipe (anon) failed, '+SysErrorMessage(GetLastError)); Exit; end; FClientAnonRead := hCAR; FClientAnonWrite := hCAW; FReadHandle := hPipe; FWriteHandle := hPipeW; result := TRUE; finally if sd <> nil then LocalFree( Cardinal(sd)); end; end; { TNamedPipeServerTransportImpl } constructor TNamedPipeServerTransportImpl.Create( aPipename : string; aBufsize, aMaxConns, aTimeOut : Cardinal); // Named Pipe CTOR begin inherited Create; ASSERT( aTimeout > 0); FPipeName := aPipename; FBufsize := aBufSize; FMaxConns := Max( 1, Min( PIPE_UNLIMITED_INSTANCES, aMaxConns)); FHandle := INVALID_HANDLE_VALUE; FTimeout := aTimeOut; FConnected := FALSE; if Copy(FPipeName,1,2) <> '\\' then FPipeName := '\\.\pipe\' + FPipeName; // assume localhost end; function TNamedPipeServerTransportImpl.Accept(const fnAccepting: TProc): ITransport; var dwError, dwWait, dwDummy : DWORD; overlapped : IOverlappedHelper; handles : array[0..1] of THandle; begin overlapped := TOverlappedHelperImpl.Create; ASSERT( not FConnected); CreateNamedPipe; while not FConnected do begin if QueryStopServer then Abort; if Assigned(fnAccepting) then fnAccepting(); // Wait for the client to connect; if it succeeds, the // function returns a nonzero value. If the function returns // zero, GetLastError should return ERROR_PIPE_CONNECTED. if ConnectNamedPipe( Handle, overlapped.OverlappedPtr) then begin FConnected := TRUE; Break; end; // ConnectNamedPipe() returns FALSE for OverlappedIO, even if connected. // We have to check GetLastError() explicitly to find out dwError := GetLastError; case dwError of ERROR_PIPE_CONNECTED : begin FConnected := not QueryStopServer; // special case: pipe immediately connected end; ERROR_IO_PENDING : begin handles[0] := overlapped.WaitHandle; handles[1] := FStopServer.Handle; dwWait := WaitForMultipleObjects( 2, @handles, FALSE, FTimeout); FConnected := (dwWait = WAIT_OBJECT_0) and GetOverlappedResult( Handle, overlapped.Overlapped, dwDummy, TRUE) and not QueryStopServer; end; else InternalClose; raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, 'Client connection failed'); end; end; // create the transport impl result := CreateTransportInstance; end; function TNamedPipeServerTransportImpl.CreateTransportInstance : ITransport; // create the transport impl var hPipe : THandle; begin hPipe := THandle( InterlockedExchangePointer( Pointer(FHandle), Pointer(INVALID_HANDLE_VALUE))); try FConnected := FALSE; result := TNamedPipeTransportServerEndImpl.Create( hPipe, TRUE, FTimeout); except ClosePipeHandle(hPipe); raise; end; end; procedure TNamedPipeServerTransportImpl.InternalClose; var hPipe : THandle; begin hPipe := THandle( InterlockedExchangePointer( Pointer(FHandle), Pointer(INVALID_HANDLE_VALUE))); if hPipe = INVALID_HANDLE_VALUE then Exit; try if FConnected then FlushFileBuffers( hPipe) else CancelIo( hPipe); DisconnectNamedPipe( hPipe); finally ClosePipeHandle( hPipe); FConnected := FALSE; end; end; function TNamedPipeServerTransportImpl.Handle : THandle; begin {$IFDEF WIN64} result := THandle( InterlockedExchangeAdd64( Integer(FHandle), 0)); {$ELSE} result := THandle( InterlockedExchangeAdd( Integer(FHandle), 0)); {$ENDIF} end; function TNamedPipeServerTransportImpl.CreateNamedPipe : THandle; var SIDAuthWorld : SID_IDENTIFIER_AUTHORITY ; everyone_sid : PSID; ea : EXPLICIT_ACCESS; acl : PACL; sd : PSECURITY_DESCRIPTOR; sa : SECURITY_ATTRIBUTES; const SECURITY_WORLD_SID_AUTHORITY : TSIDIdentifierAuthority = (Value : (0,0,0,0,0,1)); SECURITY_WORLD_RID = $00000000; begin sd := nil; everyone_sid := nil; try ASSERT( (FHandle = INVALID_HANDLE_VALUE) and not FConnected); // Windows - set security to allow non-elevated apps // to access pipes created by elevated apps. SIDAuthWorld := SECURITY_WORLD_SID_AUTHORITY; AllocateAndInitializeSid( SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, everyone_sid); ZeroMemory( @ea, SizeOf(ea)); ea.grfAccessPermissions := GENERIC_ALL; //SPECIFIC_RIGHTS_ALL or STANDARD_RIGHTS_ALL; ea.grfAccessMode := SET_ACCESS; ea.grfInheritance := NO_INHERITANCE; ea.Trustee.TrusteeForm := TRUSTEE_IS_SID; ea.Trustee.TrusteeType := TRUSTEE_IS_WELL_KNOWN_GROUP; ea.Trustee.ptstrName := PChar(everyone_sid); acl := nil; SetEntriesInAcl( 1, @ea, nil, acl); sd := PSECURITY_DESCRIPTOR( LocalAlloc( LPTR,SECURITY_DESCRIPTOR_MIN_LENGTH)); Win32Check( InitializeSecurityDescriptor( sd, SECURITY_DESCRIPTOR_REVISION)); Win32Check( SetSecurityDescriptorDacl( sd, TRUE, acl, FALSE)); sa.nLength := SizeOf(sa); sa.lpSecurityDescriptor := sd; sa.bInheritHandle := FALSE; // Create an instance of the named pipe result := Windows.CreateNamedPipe( PChar( FPipeName), // pipe name PIPE_ACCESS_DUPLEX or // read/write access FILE_FLAG_OVERLAPPED, // async mode PIPE_TYPE_BYTE or // byte type pipe PIPE_READMODE_BYTE, // byte read mode FMaxConns, // max. instances FBufSize, // output buffer size FBufSize, // input buffer size FTimeout, // time-out, see MSDN @sa); // default security attribute if( result <> INVALID_HANDLE_VALUE) then InterlockedExchangePointer( Pointer(FHandle), Pointer(result)) else raise TTransportException.Create( TTransportException.TExceptionType.NotOpen, 'CreateNamedPipe() failed ' + IntToStr(GetLastError)); finally if sd <> nil then LocalFree( Cardinal( sd)); if acl <> nil then LocalFree( Cardinal( acl)); if everyone_sid <> nil then FreeSid(everyone_sid); end; end; end.
29.526585
112
0.67507
fca7b6784b805d098eecef7b17a3ee5c8e1371d8
20,133
pas
Pascal
Core/Log4D/Log4DXML.pas
godeargit/delphi-oop
bf1b63f60d4e34b3026f444f5f86c2590e51a346
[ "MIT" ]
3
2018-01-22T04:18:06.000Z
2020-01-09T16:46:18.000Z
Core/Log4D/Log4DXML.pas
godeargit/delphi-oop
bf1b63f60d4e34b3026f444f5f86c2590e51a346
[ "MIT" ]
null
null
null
Core/Log4D/Log4DXML.pas
godeargit/delphi-oop
bf1b63f60d4e34b3026f444f5f86c2590e51a346
[ "MIT" ]
1
2019-12-19T16:10:14.000Z
2019-12-19T16:10:14.000Z
unit Log4DXML; { The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. } { Logging for Delphi - XML support. Based on log4j Java package from Apache (http://jakarta.apache.org/log4j/docs/index.html). XML document layout. Configurator from an XML document (uses MSXML v3 for parsing). Written by Keith Wood (kbwood@iprimus.com.au). Version 1.0 - 29 April 2001. Version 1.2 - 9 September 2003. } interface {$I Defines.inc} uses Classes, SysUtils, Windows, Log4D, ComObj, ActiveX, MSXML2_tlb; type { This layout outputs events as an XML fragment. } TLogXMLLayout = class(TLogCustomLayout) protected function GetContentType: string; override; function GetFooter: string; override; function GetHeader: string; override; public function Format(const Event: TLogEvent): string; overload; override; function Format(const LoggerName, LevelName: string; const LevelValue, ThreadId: Integer; const Timestamp: TDateTime; const ElapsedTime: Integer; const Message, NDC, ErrorMsg, ErrorClass: string): string; reintroduce; overload; function IgnoresException: Boolean; override; end; { Extends BasicConfigurator to provide configuration from an external XML file. See log4d.dtd for the expected format. It is sometimes useful to see how Log4D is reading configuration files. You can enable Log4D internal logging by defining the configDebug attribute on the log4d:configuration element. } TLogXMLConfigurator = class(TLogBasicConfigurator, IVBSAXContentHandler, IVBSAXErrorHandler) protected FAppender: ILogAppender; FErrorHandler: ILogErrorHandler; FFilter: ILogFilter; FHandlers: TInterfaceList; FHierarchy: TLogHierarchy; FLayout: ILogLayout; FLocator: IVBSAXLocator; FLogger: TLogLogger; FLoggerFactory: ILogLoggerFactory; public constructor Create; destructor Destroy; override; class procedure Configure(const ConfigURL: string); overload; class procedure Configure(const Document: TStream); overload; procedure DoConfigure(const ConfigURL: string; const Hierarchy: TLogHierarchy); overload; procedure DoConfigure(const Document: TStream; const Hierarchy: TLogHierarchy); overload; { IVBSAXContentHandler } {$IFDEF MSXML4} procedure _Set_documentLocator(const Param1: IVBSAXLocator); safecall; {$ELSE} procedure Set_documentLocator(const Param1: IVBSAXLocator); safecall; {$ENDIF} procedure StartDocument; safecall; procedure EndDocument; safecall; procedure StartPrefixMapping(var strPrefix: WideString; var strURI: WideString); safecall; procedure EndPrefixMapping(var strPrefix: WideString); safecall; procedure StartElement(var strNamespaceURI: WideString; var strLocalName: WideString; var strQName: WideString; const oAttributes: IVBSAXAttributes); safecall; procedure EndElement(var strNamespaceURI: WideString; var strLocalName: WideString; var strQName: WideString); safecall; procedure Characters(var strChars: WideString); safecall; procedure IgnorableWhitespace(var strChars: WideString); safecall; procedure ProcessingInstruction(var strTarget: WideString; var strData: WideString); safecall; procedure SkippedEntity(var strName: WideString); safecall; { IVBSAXErrorHandler } procedure Error(const oLocator: IVBSAXLocator; var strErrorMessage: WideString; nErrorCode: Integer); safecall; procedure FatalError(const oLocator: IVBSAXLocator; var strErrorMessage: WideString; nErrorCode: Integer); safecall; procedure IgnorableWarning(const oLocator: IVBSAXLocator; var strErrorMessage: WideString; nErrorCode: Integer); safecall; { IDispatch } function GetTypeInfoCount(out Count: Integer): HResult; stdcall; function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall; function GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall; function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall; { IUnknown } function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall; function _AddRef: Integer; stdcall; function _Release: Integer; stdcall; end; const { Element and attribute names from the XML configuration document. } AdditiveAttr = 'additive'; AppenderTag = 'appender'; AppenderRefTag = 'appender-ref'; ClassAttr = 'class'; ConfigurationTag = 'log4d:configuration'; DebugAttr = 'configDebug'; ErrorHandlerTag = 'errorHandler'; FilterTag = 'filter'; LayoutTag = 'layout'; LevelTag = 'level'; LoggerTag = 'logger'; LoggerFactoryAttr = 'loggerFactory'; NameAttr = 'name'; ParamTag = 'param'; RefAttr = 'ref'; RendererTag = 'renderer'; RenderedClassAttr = 'renderedClass'; RenderingClassAttr = 'renderingClass'; RootTag = 'root'; ThresholdAttr = 'threshold'; ValueAttr = 'value'; { Element and attribute names from the XML events document. } NamespacePrefix = 'log4d:'; ElapsedAttr = 'elapsed'; EventSetTag = NamespacePrefix + 'eventSet'; EventTag = NamespacePrefix + 'event'; ExceptionTag = NamespacePrefix + 'exception'; LevelNameAttr = 'levelName'; LevelValueAttr = 'levelValue'; LoggerAttr = 'logger'; MessageTag = NamespacePrefix + 'message'; NDCTag = NamespacePrefix + 'NDC'; ThreadAttr = 'thread'; TimestampAttr = 'timestamp'; TimestampFormat = 'yyyymmddhhnnsszzz'; implementation const CRLF = #13#10; resourcestring AppenderErrorHMsg = 'Appender "%s" uses error handler "%s"'; AppenderFilterMsg = 'Appender "%s" uses filter "%s"'; AppenderLayoutMsg = 'Appender "%s" uses layout "%s"'; ErrorMsg = 'Error'; FatalMsg = 'Fatal error'; FinishedConfigMsg = 'Finished configuring "%s"'; IgnoringConfigMsg = 'Ignoring configuration file'; LoggerLevelMsg = 'Logger "%s" level set to "%s"'; NoAppenderMsg = 'Appender "%s" was not found'; ParsedAppenderMsg = 'Parsed appender "%s"'; ParsedLoggerMsg = 'Parsed logger "%s"'; ParsedRootMsg = 'Parsed root logger'; SAXErrorMsg = '%s during configuration: %s at %d,%d in %s'; WarningMsg = 'Warning'; { TLogXMLLayout ---------------------------------------------------------------} { Write an XML element for each event. } function TLogXMLLayout.Format(const Event: TLogEvent): string; var ClassName: string; begin if Event.Error = nil then ClassName := '' else ClassName := Event.Error.ClassName; Result := Format(Event.LoggerName, Event.Level.Name, Event.Level.Level, Event.ThreadId, Event.TimeStamp, Event.ElapsedTime, Event.Message, Event.NDC, Event.ErrorMessage, ClassName); end; { Write an XML element for each event. } function TLogXMLLayout.Format(const LoggerName, LevelName: string; const LevelValue, ThreadId: Integer; const Timestamp: TDateTime; const ElapsedTime: Integer; const Message, NDC, ErrorMsg, ErrorClass: string): string; begin Result := '<' + EventTag + ' ' + LoggerAttr + '="' + LoggerName + '" ' + LevelNameAttr + '="' + LevelName + '" ' + LevelValueAttr + '="' + IntToStr(LevelValue) + '" ' + ThreadAttr + '="' + IntToStr(ThreadId) + '" ' + TimestampAttr + '="' + FormatDateTime(TimestampFormat, Timestamp) + '" ' + ElapsedAttr + '="' + IntToStr(ElapsedTime) + '"><' + MessageTag + '><![CDATA[' + Message + ']]></' + MessageTag + '>'; if NDC <> '' then Result := Result + '<' + NDCTag + '><![CDATA[' + NDC + ']]></' + NDCTag + '>'; if ErrorMsg <> '' then Result := Result + '<' + ExceptionTag + ' ' + ClassAttr + '="' + ErrorClass + '"><![CDATA[' + ErrorMsg + ']]></' + ExceptionTag + '>'; Result := Result + '</' + EventTag + '>' + CRLF; end; { Returns the content type output by this layout, i.e 'text/xml'. } function TLogXMLLayout.GetContentType: string; begin Result := 'text/xml'; end; { Returns appropriate XML closing tags. } function TLogXMLLayout.GetFooter: string; begin Result := '</' + EventSetTag + '>' + CRLF; end; { Returns appropriate XML opening tags. } function TLogXMLLayout.GetHeader: string; begin Result := '<?xml version="1.0"?>' + CRLF + '<!DOCTYPE ' + EventSetTag + ' SYSTEM "log4d.dtd">' + CRLF + '<' + EventSetTag + ' version="1.2" xmlns:' + Copy(NamespacePrefix, 1, Length(NamespacePrefix) - 1) + '="http://log4d.sourceforge.net/log4d">' + CRLF; end; { The XML layout handles the exception contained in logging events. Hence, this method return False. } function TLogXMLLayout.IgnoresException: Boolean; begin Result := False; end; { TLogXMLConfigurator ---------------------------------------------------------} const InternalRootName = 'root'; class procedure TLogXMLConfigurator.Configure(const ConfigURL: string); var Config: TLogXMLConfigurator; begin Config := TLogXMLConfigurator.Create; try Config.DoConfigure(ConfigURL, DefaultHierarchy); finally Config.Free; end; end; class procedure TLogXMLConfigurator.Configure(const Document: TStream); var Config: TLogXMLConfigurator; begin Config := TLogXMLConfigurator.Create; try Config.DoConfigure(Document, DefaultHierarchy); finally Config.Free; end; end; constructor TLogXMLConfigurator.Create; begin inherited Create; FLoggerFactory := TLogDefaultLoggerFactory.Create; FHandlers := TInterfaceList.Create; end; destructor TLogXMLConfigurator.Destroy; begin FHandlers.Free; inherited Destroy; end; procedure TLogXMLConfigurator.DoConfigure(const ConfigURL: string; const Hierarchy: TLogHierarchy); var XMLReader: IVBSAXXMLReader; begin FHierarchy := Hierarchy; {$ifdef MSSAX} XMLReader := ComsSAXXMLReader.Create; {$else} XMLReader := CoSAXXMLReader.Create; {$endif} XMLReader.ContentHandler := Self; XMLReader.ErrorHandler := Self; XMLReader.ParseURL(ConfigURL); LogLog.Debug(Format(FinishedConfigMsg, [ClassName])); end; procedure TLogXMLConfigurator.DoConfigure(const Document: TStream; const Hierarchy: TLogHierarchy); var Stream: IStream; XMLReader: IVBSAXXMLReader; begin Stream := TStreamAdapter.Create(Document); FHierarchy := Hierarchy; {$ifdef MSSAX} XMLReader := ComsSAXXMLReader.Create; {$else} XMLReader := CoSAXXMLReader.Create; {$endif} XMLReader.ContentHandler := Self; XMLReader.ErrorHandler := Self; XMLReader.Parse(Stream); LogLog.Debug(Format(FinishedConfigMsg, [ClassName])); end; { IVBSAXContentHandler --------------------------------------------------------} procedure TLogXMLConfigurator.EndDocument; begin { Do nothing. } end; { Pop current option handler off the stack at the end of the element. } procedure TLogXMLConfigurator.EndElement(var strNamespaceURI: WideString; var strLocalName: WideString; var strQName: WideString); begin if (strQName = AppenderTag) or (strQName = LoggerTag) or (strQName = ErrorHandlerTag) or (strQName = FilterTag) or (strQName = LayoutTag) or (strQName = RootTag) then FHandlers.Delete(FHandlers.Count - 1); if (strQName = LoggerTag) or (strQName = RootTag) then FLogger.UnlockLogger; end; procedure TLogXMLConfigurator.EndPrefixMapping(var strPrefix: WideString); begin { Do nothing. } end; procedure TLogXMLConfigurator.Characters(var strChars: WideString); begin { Do nothing. } end; procedure TLogXMLConfigurator.IgnorableWhitespace(var strChars: WideString); begin { Do nothing. } end; procedure TLogXMLConfigurator.ProcessingInstruction(var strTarget: WideString; var strData: WideString); begin { Do nothing. } end; { Save locator for later error reporting. } {$IFDEF MSXML4} procedure TLogXMLConfigurator._Set_documentLocator(const Param1: IVBSAXLocator); {$ELSE} procedure TLogXMLConfigurator.Set_documentLocator(const Param1: IVBSAXLocator); {$ENDIF} begin FLocator := Param1; end; procedure TLogXMLConfigurator.SkippedEntity(var strName: WideString); begin { Do nothing. } end; procedure TLogXMLConfigurator.StartDocument; begin FHandlers.Clear; end; { Create new objects as elements are encountered and handle any attributes defined for them. } procedure TLogXMLConfigurator.StartElement(var strNamespaceURI: WideString; var strLocalName: WideString; var strQName: WideString; const oAttributes: IVBSAXAttributes); var Name: string; { Retrieve named attribute, returning an empty string if not there. } function GetAttribute(Name: string): string; begin try Result := oAttributes.getValueFromQName(Name); except on e: EOleException do Result := ''; end; end; begin try if strQName = AppenderTag then begin { New appender. } FAppender := FindAppender(GetAttribute(ClassAttr)); // if Appender is not found use NullAppender if FAppender = nil then begin LogLog.Error(Format(NoAppenderMsg, [GetAttribute(ClassAttr)])); FAppender := FindAppender('TLogNullAppender'); end; if not Assigned(FAppender) then Abort; FAppender.Name := GetAttribute(NameAttr); AppenderPut(FAppender); FHandlers.Add(FAppender); LogLog.Debug(Format(ParsedAppenderMsg, [FAppender.Name])); end else if strQName = AppenderRefTag then begin { Reference to an appender for a logger. } Name := GetAttribute(RefAttr); FAppender := AppenderGet(Name); if not Assigned(FAppender) then LogLog.Error(Format(NoAppenderMsg, [Name])) else FLogger.AddAppender(FAppender); end else if strQName = LoggerTag then begin { New logger. } FLogger := FHierarchy.GetLogger(GetAttribute(NameAttr), FLoggerFactory); FLogger.LockLogger; FLogger.Additive := StrToBool(GetAttribute(AdditiveAttr), True); (FLogger as ILogOptionHandler)._AddRef; FHandlers.Add(FLogger); LogLog.Debug(Format(ParsedLoggerMsg, [FLogger.Name])); end else if strQName = ConfigurationTag then begin { Global settings. } SetGlobalProps(FHierarchy, GetAttribute(LoggerFactoryAttr), GetAttribute(DebugAttr), GetAttribute(ThresholdAttr)); end else if strQName = ErrorHandlerTag then begin { Error handler for an appender. } Name := GetAttribute(ClassAttr); FErrorHandler := FindErrorHandler(Name); FAppender.ErrorHandler := FErrorHandler; FHandlers.Add(FErrorHandler); LogLog.Debug(Format(AppenderErrorHMsg, [FAppender.Name, Name])); end else if strQName = FilterTag then begin { New filter for an appender. } Name := GetAttribute(ClassAttr); FFilter := FindFilter(Name); FAppender.AddFilter(FFilter); FHandlers.Add(FFilter); LogLog.Debug(Format(AppenderFilterMsg, [FAppender.Name, Name])); end else if strQName = LayoutTag then begin { Layout for an appender. } Name := GetAttribute(ClassAttr); FLayout := FindLayout(Name); FAppender.Layout := FLayout; FHandlers.Add(FLayout); LogLog.Debug(Format(AppenderLayoutMsg, [FAppender.Name, Name])); end else if strQName = ParamTag then begin { Parameter for an enclosing element (which must be an option handler). } ILogOptionHandler(FHandlers.Last).Options[GetAttribute(NameAttr)] := GetAttribute(ValueAttr); end else if strQName = LevelTag then begin { Level for a logger. } Name := LowerCase(GetAttribute(ValueAttr)); if (Name = InheritedLevel) and (FLogger.Name <> InternalRootName) then FLogger.Level := nil else begin FLogger.Level := TLogLevel.GetLevel(Name); LogLog.Debug(Format(LoggerLevelMsg, [FLogger.Name, FLogger.Level.Name])); end; end else if strQName = RendererTag then begin { Renderer and rendered class. } AddRenderer(FHierarchy, GetAttribute(RenderedClassAttr), GetAttribute(RenderingClassAttr)); end else if strQName = RootTag then begin { Configure the root logger. } FLogger := FHierarchy.Root; FLogger.LockLogger; (FLogger as ILogOptionHandler)._AddRef; FHandlers.Add(FLogger); LogLog.Debug(ParsedRootMsg); end except on E: Exception do begin LogLog.Debug('Exception', E); raise; end; end; end; procedure TLogXMLConfigurator.StartPrefixMapping(var strPrefix: WideString; var strURI: WideString); begin { Do nothing. } end; { IVBSAXErrorHandler ----------------------------------------------------------} { Log any errors. } procedure TLogXMLConfigurator.Error(const oLocator: IVBSAXLocator; var strErrorMessage: WideString; nErrorCode: Integer); begin LogLog.Error(Format(SAXErrorMsg, [ErrorMsg, strErrorMessage, oLocator.LineNumber, oLocator.ColumnNumber, oLocator.SystemId]), nil); end; { Log any fatal errors and abort the configuration process. } procedure TLogXMLConfigurator.FatalError(const oLocator: IVBSAXLocator; var strErrorMessage: WideString; nErrorCode: Integer); begin LogLog.Fatal(Format(SAXErrorMsg, [FatalMsg, strErrorMessage, oLocator.LineNumber, oLocator.ColumnNumber, oLocator.SystemId]), nil); LogLog.Fatal(IgnoringConfigMsg); Abort; end; { Log any warnings. } procedure TLogXMLConfigurator.IgnorableWarning(const oLocator: IVBSAXLocator; var strErrorMessage: WideString; nErrorCode: Integer); begin LogLog.Warn(Format(SAXErrorMsg, [WarningMsg, strErrorMessage, oLocator.LineNumber, oLocator.ColumnNumber, oLocator.SystemId]), nil); end; { IDispatch -------------------------------------------------------------------} { These functions are required by the IDispatch interface but are not used. } function TLogXMLConfigurator.GetTypeInfoCount(out Count: Integer): HResult; begin Result := E_NOTIMPL; end; function TLogXMLConfigurator.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; begin Result := E_NOTIMPL; end; function TLogXMLConfigurator.GetIDsOfNames(const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; begin Result := E_NOTIMPL; end; function TLogXMLConfigurator.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer; Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; begin Result := E_NOTIMPL; end; { IUnknown --------------------------------------------------------------------} { These functions are required by the IUnknown interface but are not used. } function TLogXMLConfigurator.QueryInterface(const IID: TGUID; out Obj): HResult; begin Result := E_NOINTERFACE; end; function TLogXMLConfigurator._AddRef: Integer; begin Result := 1; end; function TLogXMLConfigurator._Release: Integer; begin Result := 1; end; initialization CoInitialize(nil); { Registration of standard implementations. } RegisterLayout(TLogXMLLayout); finalization CoUninitialize; end.
33.16804
89
0.678538
83a7243ba8ad7c46287717c0a55fc6e5b2994d3a
16,057
pas
Pascal
src/CAPI/CAPI_Sensors.pas
dss-extensions/dss_capi
d6bbf9681baa519d67591783bf6c0c02e120c043
[ "BSD-3-Clause" ]
10
2019-04-03T19:00:28.000Z
2022-02-05T13:57:44.000Z
src/CAPI/CAPI_Sensors.pas
dss-extensions/dss_capi
d6bbf9681baa519d67591783bf6c0c02e120c043
[ "BSD-3-Clause" ]
82
2019-02-13T03:00:24.000Z
2022-02-27T08:05:44.000Z
src/CAPI/CAPI_Sensors.pas
dss-extensions/dss_capi
d6bbf9681baa519d67591783bf6c0c02e120c043
[ "BSD-3-Clause" ]
7
2020-07-03T10:25:55.000Z
2021-09-24T14:15:07.000Z
unit CAPI_Sensors; interface uses CAPI_Utils, CAPI_Types; procedure Sensors_Get_AllNames(var ResultPtr: PPAnsiChar; ResultCount: PAPISize); CDECL; procedure Sensors_Get_AllNames_GR(); CDECL; function Sensors_Get_Count(): Integer; CDECL; procedure Sensors_Get_Currents(var ResultPtr: PDouble; ResultCount: PAPISize); CDECL; procedure Sensors_Get_Currents_GR(); CDECL; function Sensors_Get_First(): Integer; CDECL; function Sensors_Get_IsDelta(): TAPIBoolean; CDECL; procedure Sensors_Get_kVARS(var ResultPtr: PDouble; ResultCount: PAPISize); CDECL; procedure Sensors_Get_kVARS_GR(); CDECL; procedure Sensors_Get_kVS(var ResultPtr: PDouble; ResultCount: PAPISize); CDECL; procedure Sensors_Get_kVS_GR(); CDECL; procedure Sensors_Get_kWS(var ResultPtr: PDouble; ResultCount: PAPISize); CDECL; procedure Sensors_Get_kWS_GR(); CDECL; function Sensors_Get_MeteredElement(): PAnsiChar; CDECL; function Sensors_Get_MeteredTerminal(): Integer; CDECL; function Sensors_Get_Name(): PAnsiChar; CDECL; function Sensors_Get_Next(): Integer; CDECL; function Sensors_Get_PctError(): Double; CDECL; function Sensors_Get_ReverseDelta(): TAPIBoolean; CDECL; function Sensors_Get_Weight(): Double; CDECL; procedure Sensors_Reset(); CDECL; procedure Sensors_ResetAll(); CDECL; procedure Sensors_Set_Currents(ValuePtr: PDouble; ValueCount: TAPISize); CDECL; procedure Sensors_Set_IsDelta(Value: TAPIBoolean); CDECL; procedure Sensors_Set_kVARS(ValuePtr: PDouble; ValueCount: TAPISize); CDECL; procedure Sensors_Set_kVS(ValuePtr: PDouble; ValueCount: TAPISize); CDECL; procedure Sensors_Set_kWS(ValuePtr: PDouble; ValueCount: TAPISize); CDECL; procedure Sensors_Set_MeteredElement(const Value: PAnsiChar); CDECL; procedure Sensors_Set_MeteredTerminal(Value: Integer); CDECL; procedure Sensors_Set_Name(const Value: PAnsiChar); CDECL; procedure Sensors_Set_PctError(Value: Double); CDECL; procedure Sensors_Set_ReverseDelta(Value: TAPIBoolean); CDECL; procedure Sensors_Set_Weight(Value: Double); CDECL; function Sensors_Get_kVbase(): Double; CDECL; procedure Sensors_Set_kVbase(Value: Double); CDECL; procedure Sensors_Get_AllocationFactor(var ResultPtr: PDouble; ResultCount: PAPISize); CDECL; procedure Sensors_Get_AllocationFactor_GR(); CDECL; // API extensions function Sensors_Get_idx(): Integer; CDECL; procedure Sensors_Set_idx(Value: Integer); CDECL; implementation uses CAPI_Constants, Sensor, DSSGlobals, DSSPointerList, Executive, SysUtils, DSSClass, DSSHelper; //------------------------------------------------------------------------------ function _activeObj(DSS: TDSSContext; out obj: TSensorObj): Boolean; inline; begin Result := False; obj := NIL; if InvalidCircuit(DSS) then Exit; obj := DSS.ActiveCircuit.Sensors.Active; if obj = NIL then begin if DSS_CAPI_EXT_ERRORS then begin DoSimpleMsg(DSS, 'No active Sensor object found! Activate one and retry.', 8989); end; Exit; end; Result := True; end; //------------------------------------------------------------------------------ procedure Set_Parameter(DSS: TDSSContext; const parm: String; const val: String); var cmd: String; elem: TSensorObj; begin if not _activeObj(DSS, elem) then Exit; DSS.SolutionAbort := FALSE; // Reset for commands entered from outside cmd := Format('sensor.%s.%s=%s', [elem.Name, parm, val]); DSS.DSSExecutive.Command := cmd; end; //------------------------------------------------------------------------------ procedure Sensors_Get_AllNames(var ResultPtr: PPAnsiChar; ResultCount: PAPISize); CDECL; begin DefaultResult(ResultPtr, ResultCount); if InvalidCircuit(DSSPrime) then Exit; Generic_Get_AllNames(ResultPtr, ResultCount, DSSPrime.ActiveCircuit.Sensors, False); end; procedure Sensors_Get_AllNames_GR(); CDECL; // Same as Sensors_Get_AllNames but uses global result (GR) pointers begin Sensors_Get_AllNames(DSSPrime.GR_DataPtr_PPAnsiChar, @DSSPrime.GR_Counts_PPAnsiChar[0]) end; //------------------------------------------------------------------------------ function Sensors_Get_Count(): Integer; CDECL; begin Result := 0; if InvalidCircuit(DSSPrime) then Exit; Result := DSSPrime.ActiveCircuit.Sensors.Count; end; //------------------------------------------------------------------------------ procedure Sensors_Get_Currents(var ResultPtr: PDouble; ResultCount: PAPISize); CDECL; var elem: TSensorObj; begin if not _activeObj(DSSPrime, elem) then begin DefaultResult(ResultPtr, ResultCount); Exit; end; DSS_RecreateArray_PDouble(ResultPtr, ResultCount, elem.NPhases); Move(elem.SensorCurrent[1], ResultPtr^, elem.NPhases * SizeOf(Double)); end; procedure Sensors_Get_Currents_GR(); CDECL; // Same as Sensors_Get_Currents but uses global result (GR) pointers begin Sensors_Get_Currents(DSSPrime.GR_DataPtr_PDouble, @DSSPrime.GR_Counts_PDouble[0]) end; //------------------------------------------------------------------------------ function Sensors_Get_First(): Integer; CDECL; begin Result := 0; if InvalidCircuit(DSSPrime) then Exit; Result := Generic_CktElement_Get_First(DSSPrime, DSSPrime.ActiveCircuit.Sensors); end; //------------------------------------------------------------------------------ function Sensors_Get_Next(): Integer; CDECL; begin Result := 0; if InvalidCircuit(DSSPrime) then Exit; Result := Generic_CktElement_Get_Next(DSSPrime, DSSPrime.ActiveCircuit.Sensors); end; //------------------------------------------------------------------------------ function Sensors_Get_IsDelta(): TAPIBoolean; CDECL; var elem: TSensorObj; begin Result := FALSE; if not _activeObj(DSSPrime, elem) then Exit; Result := (elem.Conn > 0); end; //------------------------------------------------------------------------------ procedure Sensors_Get_kVARS(var ResultPtr: PDouble; ResultCount: PAPISize); CDECL; var elem: TSensorObj; begin if not _activeObj(DSSPrime, elem) then begin DefaultResult(ResultPtr, ResultCount); Exit; end; DSS_RecreateArray_PDouble(ResultPtr, ResultCount, elem.NPhases); Move(elem.SensorQ[1], ResultPtr^, elem.NPhases * SizeOf(Double)); end; procedure Sensors_Get_kVARS_GR(); CDECL; // Same as Sensors_Get_kVARS but uses global result (GR) pointers begin Sensors_Get_kVARS(DSSPrime.GR_DataPtr_PDouble, @DSSPrime.GR_Counts_PDouble[0]) end; //------------------------------------------------------------------------------ procedure Sensors_Get_kVS(var ResultPtr: PDouble; ResultCount: PAPISize); CDECL; var elem: TSensorObj; begin if not _activeObj(DSSPrime, elem) then begin DefaultResult(ResultPtr, ResultCount); Exit; end; DSS_RecreateArray_PDouble(ResultPtr, ResultCount, elem.NPhases); Move(elem.SensorVoltage[1], ResultPtr^, elem.NPhases * SizeOf(Double)); end; procedure Sensors_Get_kVS_GR(); CDECL; // Same as Sensors_Get_kVS but uses global result (GR) pointers begin Sensors_Get_kVS(DSSPrime.GR_DataPtr_PDouble, @DSSPrime.GR_Counts_PDouble[0]) end; //------------------------------------------------------------------------------ procedure Sensors_Get_kWS(var ResultPtr: PDouble; ResultCount: PAPISize); CDECL; var elem: TSensorObj; begin if not _activeObj(DSSPrime, elem) then begin DefaultResult(ResultPtr, ResultCount); Exit; end; DSS_RecreateArray_PDouble(ResultPtr, ResultCount, elem.NPhases); Move(elem.SensorP[1], ResultPtr^, elem.NPhases * SizeOf(Double)); end; procedure Sensors_Get_kWS_GR(); CDECL; // Same as Sensors_Get_kWS but uses global result (GR) pointers begin Sensors_Get_kWS(DSSPrime.GR_DataPtr_PDouble, @DSSPrime.GR_Counts_PDouble[0]) end; //------------------------------------------------------------------------------ function Sensors_Get_MeteredElement(): PAnsiChar; CDECL; var elem: TSensorObj; begin Result := NIL; if not _activeObj(DSSPrime, elem) then Exit; Result := DSS_GetAsPAnsiChar(DSSPrime, elem.ElementName); end; //------------------------------------------------------------------------------ function Sensors_Get_MeteredTerminal(): Integer; CDECL; var elem: TSensorObj; begin Result := 0; if not _activeObj(DSSPrime, elem) then Exit; Result := elem.MeteredTerminal; end; //------------------------------------------------------------------------------ function Sensors_Get_Name(): PAnsiChar; CDECL; var elem: TSensorObj; begin Result := NIL; if not _activeObj(DSSPrime, elem) then Exit; Result := DSS_GetAsPAnsiChar(DSSPrime, elem.Name); end; //------------------------------------------------------------------------------ function Sensors_Get_PctError(): Double; CDECL; var elem: TSensorObj; begin Result := 0.0; if not _activeObj(DSSPrime, elem) then Exit; Result := elem.pctError; end; //------------------------------------------------------------------------------ function Sensors_Get_ReverseDelta(): TAPIBoolean; CDECL; var elem: TSensorObj; begin Result := FALSE; if not _activeObj(DSSPrime, elem) then Exit; Result := (elem.DeltaDirection < 0); end; //------------------------------------------------------------------------------ function Sensors_Get_Weight(): Double; CDECL; var elem: TSensorObj; begin Result := 0.0; if not _activeObj(DSSPrime, elem) then Exit; Result := elem.Weight; end; //------------------------------------------------------------------------------ procedure Sensors_Reset(); CDECL; var elem: TSensorObj; begin if not _activeObj(DSSPrime, elem) then Exit; elem.ResetIt(); end; //------------------------------------------------------------------------------ procedure Sensors_ResetAll(); CDECL; begin if InvalidCircuit(DSSPrime) then Exit; DSSPrime.SensorClass.ResetAll(); end; //------------------------------------------------------------------------------ procedure Sensors_Set_Currents(ValuePtr: PDouble; ValueCount: TAPISize); CDECL; var elem: TSensorObj; begin if not _activeObj(DSSPrime, elem) then Exit; if ValueCount <> elem.NPhases then begin DoSimpleMsg(DSSPrime, 'The provided number of values does not match the element''s number of phases.', 5023); Exit; end; Move(ValuePtr^, elem.SensorCurrent[1], elem.NPhases * SizeOf(Double)); end; //------------------------------------------------------------------------------ procedure Sensors_Set_IsDelta(Value: TAPIBoolean); CDECL; var elem: TSensorObj; begin if not _activeObj(DSSPrime, elem) then Exit; elem.Conn := Integer(Value); end; //------------------------------------------------------------------------------ procedure Sensors_Set_kVARS(ValuePtr: PDouble; ValueCount: TAPISize); CDECL; var elem: TSensorObj; begin if not _activeObj(DSSPrime, elem) then Exit; if ValueCount <> elem.NPhases then begin DoSimpleMsg(DSSPrime, 'The provided number of values does not match the element''s number of phases.', 5024); Exit; end; Move(ValuePtr^, elem.SensorQ[1], elem.NPhases * SizeOf(Double)); end; //------------------------------------------------------------------------------ procedure Sensors_Set_kVS(ValuePtr: PDouble; ValueCount: TAPISize); CDECL; var elem: TSensorObj; begin if not _activeObj(DSSPrime, elem) then Exit; if ValueCount <> elem.NPhases then begin DoSimpleMsg(DSSPrime, 'The provided number of values does not match the element''s number of phases.', 5024); Exit; end; Move(ValuePtr^, elem.SensorVoltage[1], elem.NPhases * SizeOf(Double)); end; //------------------------------------------------------------------------------ procedure Sensors_Set_kWS(ValuePtr: PDouble; ValueCount: TAPISize); CDECL; var elem: TSensorObj; begin if not _activeObj(DSSPrime, elem) then Exit; if ValueCount <> elem.NPhases then begin DoSimpleMsg(DSSPrime, 'The provided number of values does not match the element''s number of phases.', 5024); Exit; end; Move(ValuePtr^, elem.SensorP[1], elem.NPhases * SizeOf(Double)); end; //------------------------------------------------------------------------------ procedure Sensors_Set_MeteredElement(const Value: PAnsiChar); CDECL; begin Set_Parameter(DSSPrime, 'element', Value); end; //------------------------------------------------------------------------------ procedure Sensors_Set_MeteredTerminal(Value: Integer); CDECL; begin Set_Parameter(DSSPrime, 'terminal', IntToStr(Value)); end; //------------------------------------------------------------------------------ procedure Sensors_Set_Name(const Value: PAnsiChar); CDECL; begin if InvalidCircuit(DSSPrime) then Exit; if DSSPrime.SensorClass.SetActive(Value) then begin DSSPrime.ActiveCircuit.ActiveCktElement := DSSPrime.SensorClass.ElementList.Active; DSSPrime.ActiveCircuit.Sensors.Get(DSSPrime.SensorClass.Active); end else begin DoSimpleMsg(DSSPrime, 'Sensor "' + Value + '" Not Found in Active Circuit.', 5003); end; end; //------------------------------------------------------------------------------ procedure Sensors_Set_PctError(Value: Double); CDECL; begin Set_Parameter(DSSPrime, '%error', FloatToStr(Value)); end; //------------------------------------------------------------------------------ procedure Sensors_Set_ReverseDelta(Value: TAPIBoolean); CDECL; begin if Value = TRUE then Set_Parameter(DSSPrime, 'DeltaDirection', '-1') else Set_Parameter(DSSPrime, 'DeltaDirection', '1'); end; //------------------------------------------------------------------------------ procedure Sensors_Set_Weight(Value: Double); CDECL; begin Set_Parameter(DSSPrime, 'weight', FloatToStr(Value)); end; //------------------------------------------------------------------------------ function Sensors_Get_kVbase(): Double; CDECL; var elem: TSensorObj; begin Result := 0.0; if not _activeObj(DSSPrime, elem) then Exit; Result := elem.BaseKV; end; //------------------------------------------------------------------------------ procedure Sensors_Set_kVbase(Value: Double); CDECL; begin Set_Parameter(DSSPrime, 'kvbase', FloatToStr(Value)); end; //------------------------------------------------------------------------------ function Sensors_Get_idx(): Integer; CDECL; begin Result := 0; if InvalidCircuit(DSSPrime) then Exit; Result := DSSPrime.ActiveCircuit.Sensors.ActiveIndex end; //------------------------------------------------------------------------------ procedure Sensors_Set_idx(Value: Integer); CDECL; var pSensor: TSensorObj; begin if InvalidCircuit(DSSPrime) then Exit; pSensor := DSSPrime.ActiveCircuit.Sensors.Get(Value); if pSensor = NIL then begin DoSimpleMsg(DSSPrime, 'Invalid Sensor index: "' + IntToStr(Value) + '".', 656565); Exit; end; DSSPrime.ActiveCircuit.ActiveCktElement := pSensor; end; //------------------------------------------------------------------------------ procedure Sensors_Get_AllocationFactor(var ResultPtr: PDouble; ResultCount: PAPISize); CDECL; var elem: TSensorObj; begin if not _activeObj(DSSPrime, elem) then begin DefaultResult(ResultPtr, ResultCount); Exit; end; DSS_RecreateArray_PDouble(ResultPtr, ResultCount, elem.NPhases); Move(elem.PhsAllocationFactor[1], ResultPtr^, elem.NPhases * SizeOf(Double)); end; procedure Sensors_Get_AllocationFactor_GR(); CDECL; // Same as Sensors_Get_AllocationFactor but uses global result (GR) pointers begin Sensors_Get_AllocationFactor(DSSPrime.GR_DataPtr_PDouble, @DSSPrime.GR_Counts_PDouble[0]) end; //------------------------------------------------------------------------------ end.
33.875527
117
0.598181
c35f8957722d3857c1806d1966254980ed809451
1,638
pas
Pascal
src/libraries/hashlib4pascal/HlpSHA2_512_256.pas
O1OOO111/PascalCoin
a1725b674c45ebf380c2fb132454439e58f7119a
[ "MIT" ]
1
2021-06-07T13:20:04.000Z
2021-06-07T13:20:04.000Z
src/libraries/hashlib4pascal/HlpSHA2_512_256.pas
O1OOO111/PascalCoin
a1725b674c45ebf380c2fb132454439e58f7119a
[ "MIT" ]
null
null
null
src/libraries/hashlib4pascal/HlpSHA2_512_256.pas
O1OOO111/PascalCoin
a1725b674c45ebf380c2fb132454439e58f7119a
[ "MIT" ]
1
2021-06-02T23:57:38.000Z
2021-06-02T23:57:38.000Z
unit HlpSHA2_512_256; {$I HashLib.inc} interface uses {$IFDEF DELPHI2010} SysUtils, // to get rid of compiler hint "not inlined" on Delphi 2010. {$ENDIF DELPHI2010} HlpHashLibTypes, {$IFDEF DELPHI} HlpBitConverter, HlpHashBuffer, HlpHash, {$ENDIF DELPHI} HlpIHash, HlpSHA2_512Base, HlpConverters; type TSHA2_512_256 = class sealed(TSHA2_512Base) strict protected function GetResult(): THashLibByteArray; override; public constructor Create(); procedure Initialize(); override; function Clone(): IHash; override; end; implementation { TSHA2_512_256 } function TSHA2_512_256.Clone(): IHash; var HashInstance: TSHA2_512_256; begin HashInstance := TSHA2_512_256.Create(); HashInstance.Fm_state := System.Copy(Fm_state); HashInstance.Fm_buffer := Fm_buffer.Clone(); HashInstance.Fm_processed_bytes := Fm_processed_bytes; result := HashInstance as IHash; result.BufferSize := BufferSize; end; constructor TSHA2_512_256.Create; begin Inherited Create(32); end; function TSHA2_512_256.GetResult: THashLibByteArray; begin System.SetLength(result, 4 * System.SizeOf(UInt64)); TConverters.be64_copy(PUInt64(Fm_state), 0, PByte(result), 0, System.Length(result)); end; procedure TSHA2_512_256.Initialize; begin Fm_state[0] := $22312194FC2BF72C; Fm_state[1] := UInt64($9F555FA3C84C64C2); Fm_state[2] := $2393B86B6F53B151; Fm_state[3] := UInt64($963877195940EABD); Fm_state[4] := UInt64($96283EE2A88EFFE3); Fm_state[5] := UInt64($BE5E1E2553863992); Fm_state[6] := $2B0199FC2C85B8AA; Fm_state[7] := $0EB72DDC81C52CA2; Inherited Initialize(); end; end.
20.222222
72
0.738095
47766b71823bf730b813bdd59596e9fc29d7f81d
5,167
dfm
Pascal
Catalogos/MRCalificacionRiesgoForm.dfm
alexismzt/SOFOM
57ca73e9f7fbb51521149ea7c0fdc409c22cc6f7
[ "Apache-2.0" ]
null
null
null
Catalogos/MRCalificacionRiesgoForm.dfm
alexismzt/SOFOM
57ca73e9f7fbb51521149ea7c0fdc409c22cc6f7
[ "Apache-2.0" ]
51
2018-07-25T15:39:25.000Z
2021-04-21T17:40:57.000Z
Catalogos/MRCalificacionRiesgoForm.dfm
alexismzt/SOFOM
57ca73e9f7fbb51521149ea7c0fdc409c22cc6f7
[ "Apache-2.0" ]
1
2021-02-23T17:27:06.000Z
2021-02-23T17:27:06.000Z
inherited frmMRCalificacionesRiesgos: TfrmMRCalificacionesRiesgos BorderStyle = bsToolWindow Caption = 'Calificaciones de riesgos' ClientHeight = 513 ClientWidth = 645 ExplicitHeight = 542 PixelsPerInch = 96 TextHeight = 13 inherited splDetail3: TSplitter Top = 463 Width = 645 ExplicitTop = 463 ExplicitWidth = 645 end inherited splDetail1: TSplitter Top = 419 Width = 645 ExplicitTop = 419 ExplicitWidth = 645 end inherited splDetail2: TSplitter Top = 439 Width = 645 ExplicitTop = 439 ExplicitWidth = 645 end inherited pnlMaster: TPanel Width = 645 Height = 393 ExplicitWidth = 645 ExplicitHeight = 393 inherited cxGrid: TcxGrid Width = 645 Height = 393 ExplicitWidth = 645 ExplicitHeight = 393 inherited tvMaster: TcxGridDBTableView object tvMasterIdMRCalificacionRiesgo: TcxGridDBColumn DataBinding.FieldName = 'IdMRCalificacionRiesgo' Visible = False end object tvMasterIdMRCuestionario: TcxGridDBColumn DataBinding.FieldName = 'IdMRCuestionario' Visible = False end object tvMasterIdPersonaTipo: TcxGridDBColumn DataBinding.FieldName = 'IdPersonaTipo' Visible = False end object tvMasterPersonaTipo: TcxGridDBColumn DataBinding.FieldName = 'PersonaTipo' Width = 79 end object tvMasterNivelRiesgo: TcxGridDBColumn DataBinding.FieldName = 'NivelRiesgo' end object tvMasterValorMinimo: TcxGridDBColumn DataBinding.FieldName = 'ValorMinimo' Width = 65 end object tvMasterValorMaximo: TcxGridDBColumn DataBinding.FieldName = 'ValorMaximo' Width = 69 end end end end inherited pnlDetail3: TPanel Top = 466 Width = 645 Height = 21 ExplicitTop = 466 ExplicitWidth = 645 ExplicitHeight = 21 end inherited pnlDetail2: TPanel Top = 442 Width = 645 Height = 21 ExplicitTop = 442 ExplicitWidth = 645 ExplicitHeight = 21 end inherited pnlDetail1: TPanel Top = 422 Width = 645 Height = 17 ExplicitTop = 422 ExplicitWidth = 645 ExplicitHeight = 17 end inherited pnlClose: TPanel Top = 487 Width = 645 Height = 26 ExplicitTop = 487 ExplicitWidth = 645 ExplicitHeight = 26 inherited btnClose: TButton Left = 560 Top = -2 ExplicitLeft = 560 ExplicitTop = -2 end end inherited DataSource: TDataSource DataSet = dmMatrizRiesgo.adodsCalificacionRiesgo end inherited dxBarManager: TdxBarManager DockControlHeights = ( 0 0 26 0) end inherited cxStyleRepository: TcxStyleRepository PixelsPerInch = 96 end inherited cxImageList: TcxImageList FormatVersion = 1 end inherited dxComponentPrinter: TdxComponentPrinter inherited dxcplGrid: TdxGridReportLink ReportDocument.CreationDate = 43311.602271053240000000 AssignedFormatValues = [] BuiltInReportLink = True end end inherited cxpsGrid: TcxPropertiesStore Components = < item Component = tvMaster Properties.Strings = ( 'OptionsView.Footer' 'OptionsView.GroupByBox' 'OptionsView.GroupFooters') end item Component = tvMasterIdMRCalificacionRiesgo Properties.Strings = ( 'GroupIndex' 'SortIndex' 'SortOrder' 'Summary' 'Visible' 'Width') end item Component = tvMasterIdMRCuestionario Properties.Strings = ( 'GroupIndex' 'SortIndex' 'SortOrder' 'Summary' 'Visible' 'Width') end item Component = tvMasterIdPersonaTipo Properties.Strings = ( 'GroupIndex' 'SortIndex' 'SortOrder' 'Summary' 'Visible' 'Width') end item Component = tvMasterNivelRiesgo Properties.Strings = ( 'GroupIndex' 'SortIndex' 'SortOrder' 'Summary' 'Visible' 'Width') end item Component = tvMasterPersonaTipo Properties.Strings = ( 'GroupIndex' 'SortIndex' 'SortOrder' 'Summary' 'Visible' 'Width') end item Component = tvMasterValorMaximo Properties.Strings = ( 'GroupIndex' 'SortIndex' 'SortOrder' 'Summary' 'Visible' 'Width') end item Component = tvMasterValorMinimo Properties.Strings = ( 'GroupIndex' 'SortIndex' 'SortOrder' 'Summary' 'Visible' 'Width') end> end end
24.604762
66
0.570931
c386371197adb48292510c9ae1ccab75519cdb78
4,490
pas
Pascal
Core/ML.Core.pas
DelphiWorlds/MockLoc
b507e72fea1f649b704211d8b0cdc86c6e238720
[ "MIT" ]
1
2022-02-08T08:45:34.000Z
2022-02-08T08:45:34.000Z
Core/ML.Core.pas
DelphiWorlds/MockLoc
b507e72fea1f649b704211d8b0cdc86c6e238720
[ "MIT" ]
1
2022-01-02T00:09:25.000Z
2022-01-02T00:18:53.000Z
Core/ML.Core.pas
DelphiWorlds/MockLoc
b507e72fea1f649b704211d8b0cdc86c6e238720
[ "MIT" ]
1
2022-01-06T00:58:24.000Z
2022-01-06T00:58:24.000Z
unit ML.Core; interface uses System.SysUtils, System.Classes, System.Sensors, Androidapi.JNIBridge, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Location, DW.Androidapi.JNI.DWFusedLocation, DW.MultiReceiver.Android; type TMockLocation = record Active: Boolean; Coords: TLocationCoord2D; end; TMockLocationEvent = procedure(Sender: TObject; const MockLocation: TMockLocation) of object; TMockLocationReceiver = class(TMultiReceiver) private const cActionMockLocation = 'ACTION_MOCK_LOCATION'; cExtraActive = 'ACTIVE'; cExtraLatitude = 'LATITUDE'; cExtraLongitude = 'LONGITUDE'; private FOnMockLocation: TMockLocationEvent; procedure DoMockLocation(const AMockLocation: TMockLocation); protected procedure ConfigureActions; override; procedure Receive(context: JContext; intent: JIntent); override; public constructor Create; property OnMockLocation: TMockLocationEvent read FOnMockLocation write FOnMockLocation; end; TCore = class; TFusedLocationClientDelegate = class(TJavaLocal, JDWFusedLocationClientDelegate) public { JDWFusedLocationClientDelegate } procedure onLocation(location: JLocation); cdecl; procedure onLocationUpdatesChange(active: Boolean); cdecl; procedure onSetMockLocationResult(location: JLocation); cdecl; procedure onSetMockModeResult(success: Boolean); cdecl; end; TCore = class(TDataModule) private FMockLocationReceiver: TMockLocationReceiver; FFusedLocationClient: JDWFusedLocationClient; FFusedLocationClientDelegate: JDWFusedLocationClientDelegate; procedure MockLocationReceiverMockLocationHandler(Sender: TObject; const AMockLocation: TMockLocation); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var Core: TCore; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} uses Androidapi.Helpers, Androidapi.JNI.JavaTypes, DW.OSLog, DW.Location.Types; { TMockLocationReceiver } constructor TMockLocationReceiver.Create; begin inherited Create(False); end; procedure TMockLocationReceiver.ConfigureActions; begin IntentFilter.addAction(StringToJString(cActionMockLocation)); end; procedure TMockLocationReceiver.Receive(context: JContext; intent: JIntent); var LMockLocation: TMockLocation; begin LMockLocation.Coords.Latitude := intent.getFloatExtra(StringToJString(cExtraLatitude), cInvalidLatitude); LMockLocation.Coords.Longitude := intent.getFloatExtra(StringToJString(cExtraLongitude), cInvalidLongitude); LMockLocation.Active := intent.getBooleanExtra(StringToJString(cExtraActive), True); if not LMockLocation.Active or ((LMockLocation.Coords.Latitude <> cInvalidLatitude) and (LMockLocation.Coords.Longitude <> cInvalidLongitude)) then DoMockLocation(LMockLocation) else TOSLog.d('> Invalid intent: %s', [JStringToString(intent.toUri(0))]); end; procedure TMockLocationReceiver.DoMockLocation(const AMockLocation: TMockLocation); begin if Assigned(FOnMockLocation) then FOnMockLocation(Self, AMockLocation); end; { TFusedLocationClientDelegate } procedure TFusedLocationClientDelegate.onLocation(location: JLocation); begin // end; procedure TFusedLocationClientDelegate.onLocationUpdatesChange(active: Boolean); begin // end; procedure TFusedLocationClientDelegate.onSetMockLocationResult(location: JLocation); begin // end; procedure TFusedLocationClientDelegate.onSetMockModeResult(success: Boolean); begin // end; { TCore } constructor TCore.Create(AOwner: TComponent); begin inherited; FMockLocationReceiver := TMockLocationReceiver.Create; FMockLocationReceiver.OnMockLocation := MockLocationReceiverMockLocationHandler; FFusedLocationClientDelegate := TFusedLocationClientDelegate.Create; FFusedLocationClient := TJDWFusedLocationClient.JavaClass.init(TAndroidHelper.Context, FFusedLocationClientDelegate); end; destructor TCore.Destroy; begin FMockLocationReceiver.Free; inherited; end; procedure TCore.MockLocationReceiverMockLocationHandler(Sender: TObject; const AMockLocation: TMockLocation); begin if AMockLocation.Active then FFusedLocationClient.setMockLocation(AMockLocation.Coords.Latitude, AMockLocation.Coords.Longitude) else FFusedLocationClient.setMockMode(False); end; end.
29.735099
150
0.773051
47548f8d2ec8e9782b5d0cc9bd1fe4b0f87f849e
4,897
pas
Pascal
LogViewer.Resources.pas
jomael/LogViewer
81588885711c66ed4aca2f378e5bbfe68120045b
[ "Apache-2.0" ]
38
2016-04-19T04:05:31.000Z
2022-03-16T12:34:52.000Z
LogViewer.Resources.pas
jomael/LogViewer
81588885711c66ed4aca2f378e5bbfe68120045b
[ "Apache-2.0" ]
4
2018-01-04T12:12:49.000Z
2021-03-09T16:38:55.000Z
LogViewer.Resources.pas
jomael/LogViewer
81588885711c66ed4aca2f378e5bbfe68120045b
[ "Apache-2.0" ]
12
2016-08-29T20:34:52.000Z
2022-01-06T00:23:46.000Z
{ Copyright (C) 2013-2021 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit LogViewer.Resources; { Application wide type definitions, constants and resource strings. } interface uses Winapi.Windows, Winapi.Messages, System.Classes, Vcl.Graphics, DDuce.Logger.Interfaces; type TVKSet = set of Byte; var VK_EDIT_KEYS : TVKSet = [ VK_DELETE, VK_BACK, VK_LEFT, VK_RIGHT, VK_HOME, VK_END, VK_SHIFT, VK_CONTROL, VK_SPACE, Ord('0')..Ord('9'), Ord('A')..Ord('Z'), VK_OEM_1..VK_OEM_102, VK_NUMPAD0..VK_DIVIDE ]; VK_CTRL_EDIT_KEYS : TVKSet = [ VK_INSERT, VK_DELETE, VK_LEFT, VK_RIGHT, VK_HOME, VK_END, Ord('C'), Ord('X'), Ord('V'), Ord('Z') ]; VK_SHIFT_EDIT_KEYS : TVKSet = [ VK_INSERT, VK_DELETE, VK_LEFT, VK_RIGHT, VK_HOME, VK_END ]; resourcestring // message types SName = 'Name'; SType = 'Type'; SValue = 'Value'; STimestamp = 'Timestamp'; SProcessName = 'ProcessName'; SColor = 'Color'; SBitmap = 'Bitmap'; SComponent = 'Component'; SObject = 'Object'; SPersistent = 'Persistent'; SInterface = 'Interface'; SStrings = 'Strings'; SCheckpoint = 'Checkpoint'; SDataSet = 'DataSet'; SScreenShot = 'ScreenShot'; SText = 'Text'; SAction = 'Action'; SInfo = 'Info'; SWarning = 'Warning'; SError = 'Error'; SException = 'Exception'; SCounter = 'Counter'; SEnter = 'Enter'; SLeave = 'Leave'; // dashboard columns SId = 'Id'; SMessageCount = 'Messagecount'; // dashboard action captions SSubscribe = 'Subscribe'; STextMessages = 'Text messages'; SNotificationMessages = 'Notification messages'; SValueMessages = 'Value messages'; STraceMessages = 'Trace messages'; STrackMethod = 'Track method'; // settings dialog SViewSettings = 'View settings'; SDisplaySettings = 'Message display'; SLogLevels = 'Logging levels'; SWatches = 'Watches'; SCallStack = 'Callstack'; SChannelSettings = 'Channel settings'; SGeneralSettings = 'General settings'; SAdvanced = 'Advanced'; SWinIPC = 'WinIPC'; SWinODS = 'OutputDebugString API'; SComPort = 'Serial port'; SZeroMQ = 'ZeroMQ'; SLogLevelAlias = 'Loglevel alias'; STimeStampFirst = 'Time first message'; STimeStampLast = 'Time last message'; SBytesReceived = 'Data received'; // channel receiver names const RECEIVERNAME_WINIPC = 'WinIPC'; RECEIVERNAME_WINODS = 'WinODS'; RECEIVERNAME_ZEROMQ = 'ZeroMQ'; RECEIVERNAME_COMPORT = 'ComPort'; RECEIVERNAME_FILESYSTEM = 'FileSystem'; resourcestring SReceiverCaptionWinIPC = 'Windows IPC receiver'; SReceiverCaptionWinODS = 'Windows API OutputDebugString receiver'; SReceiverCaptionZeroMQ = 'ZeroMQ receiver'; SReceiverCaptionComPort = 'ComPort receiver'; SReceiverCaptionFileSystem = 'File system receiver'; // main form SReceivedCount = 'Received: <b>%d</b>'; SSubscriberSource = '<x=4>Source:</x> <b>%s</b> (%d)'; const LIBZMQ = 'libzmq'; // message viewer COLUMN_LEVEL = 0; COLUMN_MAIN = 1; // make variable COLUMN_VALUENAME = 2; COLUMN_VALUE = 3; COLUMN_VALUETYPE = 4; COLUMN_TIMESTAMP = 5; // column names COLUMNNAME_TIMESTAMP = 'TimeStamp'; COLUMNNAME_NAME = 'Name'; COLUMNNAME_VALUE = 'Value'; COLUMNNAME_VALUETYPE = 'ValueType'; COLUMNNAME_ID = 'Id'; // dashboard COLUMN_SOURCENAME = 0; COLUMN_KEY = 1; COLUMN_SOURCEID = 2; COLUMN_MESSAGECOUNT = 3; COLUMN_BYTES_RECEIVED = 4; COLUMN_TIMESTAMP_FIRST = 5; COLUMN_TIMESTAMP_LAST = 6; // loglevels COLUMN_LOGLEVEL = 0; COLUMN_LOGCOLOR = 1; COLUMN_LOGCOLORVALUE = 2; COLUMN_LOGALIAS = 3; COLUMNNAME_LOGLEVEL = 'Level'; COLUMNNAME_LOGCOLOR = 'Color'; COLUMNNAME_LOGCOLORNAME = 'ColorName'; COLUMNNAME_LOGALIAS = 'Alias'; { max. amount of characters allowed to be displayed in the value column of the logtree. } MAX_TEXTLENGTH_VALUECOLUMN = 200; { TCP port used for debugging another LogViewer instance using ZMQ. } LOGVIEWER_ZMQ_PORT : Integer = 42134; implementation end.
24.485
80
0.647744
fcb3dd33333f70912d38f1640608552e92c1173b
16,633
pas
Pascal
Packages/Order Entry Results Reporting/CPRS/CPRS-Chart/XE8/508/Source/VA508DelphiCompatibility.pas
josephsnyder/VistA
07cabf4302675991dd453aea528f79f875358d58
[ "Apache-2.0" ]
1
2021-01-01T01:16:44.000Z
2021-01-01T01:16:44.000Z
Packages/Order Entry Results Reporting/CPRS/CPRS-Chart/XE8/508/Source/VA508DelphiCompatibility.pas
josephsnyder/VistA
07cabf4302675991dd453aea528f79f875358d58
[ "Apache-2.0" ]
null
null
null
Packages/Order Entry Results Reporting/CPRS/CPRS-Chart/XE8/508/Source/VA508DelphiCompatibility.pas
josephsnyder/VistA
07cabf4302675991dd453aea528f79f875358d58
[ "Apache-2.0" ]
null
null
null
unit VA508DelphiCompatibility; interface uses SysUtils, Classes, Controls, Windows, StdCtrls, CheckLst, ExtCtrls, Forms, ValEdit, DBGrids, Calendar, ComCtrls, VA508AccessibilityManager; function GetCheckBoxComponentName(AllowGrayed: boolean): string; function GetCheckBoxInstructionMessage(Checked: boolean): string; function GetCheckBoxStateText(State: TCheckBoxState): String; procedure ListViewIndexQueryProc(Sender: TObject; ItemIndex: integer; var Text: string); type TVA508StaticTextManager = class(TVA508ManagedComponentClass) public constructor Create; override; function GetComponentName(Component: TWinControl): string; override; function GetCaption(Component: TWinControl): string; override; function GetValue(Component: TWinControl): string; override; end; implementation uses Grids, VA508AccessibilityRouter, VA508AccessibilityConst, VA508MSAASupport, VAUtils; type TCheckBox508Manager = class(TVA508ManagedComponentClass) public constructor Create; override; function GetComponentName(Component: TWinControl): string; override; function GetInstructions(Component: TWinControl): string; override; function GetState(Component: TWinControl): string; override; end; TCheckListBox508Manager = class(TVA508ManagedComponentClass) private function GetIndex(Component: TWinControl): integer; public constructor Create; override; function GetComponentName(Component: TWinControl): string; override; function GetState(Component: TWinControl): string; override; function GetItem(Component: TWinControl): TObject; override; function GetItemInstructions(Component: TWinControl): string; override; end; TVA508EditManager = class(TVA508ManagedComponentClass) public constructor Create; override; function GetValue(Component: TWinControl): string; override; end; TVA508ComboManager = class(TVA508ManagedComponentClass) public constructor Create; override; function GetValue(Component: TWinControl): string; override; end; TCustomGrid508Manager = class(TVA508ManagedComponentClass) private public constructor Create; override; function GetComponentName(Component: TWinControl): string; override; function GetInstructions(Component: TWinControl): string; override; function GetValue(Component: TWinControl): string; override; function GetItem(Component: TWinControl): TObject; override; // function GetData(Component: TWinControl; Value: string): string; override; end; TVA508RegistrationScreenReader = class(TVA508ScreenReader); function CustomComboAlternateHandle(Component: TWinControl): HWnd; forward; procedure ListViewIndexQueryProc(Sender: TObject; ItemIndex: integer; var Text: string); var temp, ImgTxt, state, overlay: string; view: TListView; item: TListItem; i: integer; include: boolean; CtrlManager: TVA508AccessibilityManager; function Append(data: array of string): string; overload; var i: integer; begin Result := ''; for i := low(data) to high(data) do begin if data[i] <> '' then begin if result <> '' then Result := Result + ' '; Result := Result + data[i]; end; end; end; procedure Append(txt: string); overload; begin if txt = '' then exit; if text <> '' then text := text + ' '; text := text + txt + ','; end; procedure AppendHeader(txt: string); begin if txt = '' then txt := 'blank header'; Append(txt); end; begin view := TListView(Sender); Text := ''; include := TRUE; CtrlManager := GetComponentManager(view); if (ItemIndex < 0) or (ItemIndex >= view.Items.Count) then exit; item := view.Items.Item[ItemIndex]; if (view.ViewStyle = vsReport) and (view.Columns.Count > 0) then begin //-1 and -2 are valid widths if (view.Columns[0].Width = 0) or (view.Columns[0].Width < -3) then include := FALSE else AppendHeader(view.Columns[0].Caption); end; if include then begin //Load the image ImgTxt := ''; state := ''; overlay := ''; if assigned(view.StateImages) then state := GetImageListText(view, iltStateImages, item.StateIndex); if view.ViewStyle = vsIcon then ImgTxt := GetImageListText(view, iltLargeImages, item.ImageIndex) else ImgTxt := GetImageListText(view, iltSmallImages, item.ImageIndex); if (item.OverlayIndex >= 0) then overlay := GetImageListText(view, iltOverlayImages, item.OverlayIndex); ImgTxt := Append([state, ImgTxt, overlay]); temp := item.Caption; if (temp = '') and (CtrlManager.AccessColumns[view].ColumnValues[0]) then temp := 'blank'; temp := Append([ImgTxt, temp]); Append(temp); end; if view.ViewStyle = vsReport then begin for i := 1 to view.Columns.Count - 1 do begin if (view.Columns[i].Width > 0) or (view.Columns[i].Width = -1) or (view.Columns[i].Width = -3) then begin AppendHeader(view.Columns[i].Caption); ImgTxt := ''; //Get subimages if Assigned(View.SmallImages) then ImgTxt := GetImageListText(view, iltSmallImages, item.SubItemImages[I-1]); if (i-1) < item.SubItems.Count then temp := item.SubItems[i-1] else temp := ''; if (temp = '') and (CtrlManager.AccessColumns[view].ColumnValues[I]) then temp := 'blank'; temp := Append([ImgTxt, temp]); Append(temp); end; end; end; end; procedure RegisterStandardDelphiComponents; begin RegisterAlternateHandleComponent(TCustomCombo, CustomComboAlternateHandle); RegisterManagedComponentClass(TCheckBox508Manager.Create); RegisterManagedComponentClass(TCheckListBox508Manager.Create); RegisterManagedComponentClass(TCustomGrid508Manager.Create); RegisterManagedComponentClass(TVA508StaticTextManager.Create); RegisterManagedComponentClass(TVA508EditManager.Create); RegisterManagedComponentClass(TVA508ComboManager.Create); with TVA508RegistrationScreenReader(GetScreenReader) do begin // even though TListView is in Default.JCF, we add it here to clear out previous MSAA setting RegisterCustomClassBehavior(TListView.ClassName, CLASS_BEHAVIOR_LIST_VIEW); RegisterCustomClassBehavior(TVA508StaticText.ClassName, CLASS_BEHAVIOR_STATIC_TEXT); end; RegisterMSAAQueryListClassProc(TListView, ListViewIndexQueryProc); { TODO -oJeremy Merrill -c508 : Add these components as ones that need an alternate handle TColorBox TValueListEditor ?? - may be fixed because it's a TStringGrid TCaptionStringGrid TToolBar (not needed when the tool bar doesn't have focus) TPageScroller add stuff for image processing descendents of TCustomTabControl } { TODO -oJeremy Merrill -c508 :Need to create a fix for the list box stuff here} end; { TCustomCombo Alternate Handle } type TExposedCustomCombo = class(TCustomCombo) public property EditHandle; end; function CustomComboAlternateHandle(Component: TWinControl): HWnd; begin Result := TExposedCustomCombo(Component).EditHandle; end; { Check Box Utils - used by multiple classes } function GetCheckBoxComponentName(AllowGrayed: boolean): string; begin if AllowGrayed then Result := 'Three State Check Box' else Result := 'Check Box'; end; function GetCheckBoxInstructionMessage(Checked: boolean): string; begin if not Checked then // handles clear and gray entries Result := 'to check press space bar' else Result := 'to clear check mark press space bar'; end; function GetCheckBoxStateText(State: TCheckBoxState): String; begin case State of cbUnchecked: Result := 'not checked'; cbChecked: Result := 'checked'; cbGrayed: Result := 'Partially Checked'; else Result := ''; end; end; { TCheckBox508Manager } constructor TCheckBox508Manager.Create; begin inherited Create(TCheckBox, [mtComponentName, mtInstructions, mtState, mtStateChange]); end; function TCheckBox508Manager.GetComponentName(Component: TWinControl): string; begin Result := GetCheckBoxComponentName(TCheckBox(Component).AllowGrayed); end; function TCheckBox508Manager.GetInstructions(Component: TWinControl): string; begin Result := GetCheckBoxInstructionMessage(TCheckBox(Component).Checked); end; function TCheckBox508Manager.GetState(Component: TWinControl): string; begin Result := GetCheckBoxStateText(TCheckBox(Component).State); end; { TCheckListBox508Manager } constructor TCheckListBox508Manager.Create; begin inherited Create(TCheckListBox, [mtComponentName, mtState, mtStateChange, mtItemChange, mtItemInstructions]); end; function TCheckListBox508Manager.GetComponentName( Component: TWinControl): string; var lb : TCheckListBox; begin lb := TCheckListBox(Component); if lb.AllowGrayed then Result := 'Three State Check List Box' else Result := 'Check List Box'; end; function TCheckListBox508Manager.GetItemInstructions( Component: TWinControl): string; var lb : TCheckListBox; idx: integer; begin lb := TCheckListBox(Component); idx := GetIndex(Component); if (idx < 0) then Result := '' else Result := GetCheckBoxInstructionMessage(lb.Checked[idx]); end; function TCheckListBox508Manager.GetIndex(Component: TWinControl): integer; var lb : TCheckListBox; begin lb := TCheckListBox(Component); if (lb.ItemIndex < 0) then begin if lb.Count > 0 then Result := 0 else Result := -1 end else Result := lb.ItemIndex; end; function TCheckListBox508Manager.GetItem(Component: TWinControl): TObject; var lb : TCheckListBox; begin lb := TCheckListBox(Component); Result := TObject((lb.items.Count * 10000) + (lb.ItemIndex + 2)); end; function TCheckListBox508Manager.GetState(Component: TWinControl): string; var lb : TCheckListBox; idx: integer; begin lb := TCheckListBox(Component); idx := GetIndex(Component); if idx < 0 then Result := '' else Result := GetCheckBoxStateText(lb.State[idx]); end; { TCustomForm508Manager } type TAccessGrid = class(TCustomGrid); constructor TCustomGrid508Manager.Create; begin { TODO : Add support for other string grid features - like state changes for editing or selecting cells } // inherited Create(TStringGrid, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE); inherited Create(TCustomGrid, [mtComponentName, mtInstructions, mtValue, mtItemChange], TRUE); // FLastX := -1; // FLastY := -1; end; // Data pieces // 1 = Column header, if any // 2 = Column # // 3 = number of columns // 4 = Row header, if any // 5 = Row # // 6 = number of rows // 7 = Cell # // 8 = total # of cells // 9 = cell contents const DELIM = '^'; function TCustomGrid508Manager.GetComponentName(Component: TWinControl): string; begin Result := ' grid '; // don't use 'grid' - we're abandoning the special code in the JAWS scripts for // grids - it's too messy, and based on the 'grid' component name end; { function TCustomGrid508Manager.GetData(Component: TWinControl; Value: string): string; var grid: TAccessGrid; row, col: integer; cnt, x, y, max, mult: integer; txt: string; procedure Add(txt: integer); overload; begin Result := Result + inttostr(txt) + DELIM; end; procedure Add(txt: string); overload; begin Result := Result + Piece(txt,DELIM,1) + DELIM; end; begin grid := TAccessGrid(Component); row := grid.Row; col := grid.Col; if (row >= 0) and (col >= 0) then begin if grid.FixedRows > 0 then Add(grid.GetEditText(col, 0)) else Add(''); Add(col - grid.FixedCols + 1); Add(grid.ColCount - grid.FixedCols); if grid.FixedCols > 0 then Add(grid.GetEditText(0, row)) else Add(''); Add(row - grid.FixedRows + 1); Add(grid.RowCount - grid.FixedRows); x := grid.ColCount - grid.FixedCols; y := grid.RowCount - grid.FixedRows; max := x * y; x := grid.Col - grid.FixedCols; y := grid.Row - grid.FixedRows; mult := grid.ColCount - grid.FixedCols; if (mult > 0) and (x >= 0) and (x < grid.ColCount) and (y >= 0) and (y < grid.RowCount) then begin cnt := (y * mult) + x + 1; Add(cnt); end else Add(0); Add(max); if Value = '' then txt := grid.GetEditText(col, row) else txt := Value; Add(txt); delete(Result,length(Result),1); // remove trailing delimeter end else Result := ''; end; } function TCustomGrid508Manager.GetInstructions(Component: TWinControl): string; var grid: TAccessGrid; // cnt, x, y, max, mult: integer; begin Result := ''; grid := TAccessGrid(Component); // x := grid.ColCount - grid.FixedCols; // y := grid.RowCount - grid.FixedRows; // max := x * y; // x := grid.Col - grid.FixedCols; // y := grid.Row - grid.FixedRows; // mult := grid.ColCount - grid.FixedCols; // // if (mult > 0) and // (x >= 0) and (x < grid.ColCount) and // (y >= 0) and (y < grid.RowCount) then // begin // cnt := (y * mult) + x + 1; // Result := IntToStr(cnt) + ' of ' + inttostr(max) + ', '; // end; Result := Result + 'To move to items use the arrow '; if goTabs in grid.Options then Result := Result + ' or tab '; Result := Result + 'keys'; end; // if // key //end; (* listbox column 120 row 430 unavailable (text of cell?) read only 20 or 81 listbox column 3 of 10 row 6 of 10 unavailable (text of cell?) read only 20 or 81 with each navigation: column 3 of 10 row 6 of 10 unavailable (text of cell?) read only *) function TCustomGrid508Manager.GetItem(Component: TWinControl): TObject; var grid: TAccessGrid; row, col, maxRow: integer; begin grid := TAccessGrid(Component); row := grid.Row + 2; col := grid.Col + 2; MaxRow := grid.RowCount + 3; if MaxRow < 1000 then MaxRow := 1000; Result := TObject((row * maxRow) + col); end; //function TCustomGrid508Manager.GetValue(Component: TWinControl): string; //var // grid: TAccessGrid; //begin // grid := TAccessGrid(Component); // Result := Piece(grid.GetEditText(grid.Col, grid.Row), DELIM, 1); //end; function TCustomGrid508Manager.GetValue(Component: TWinControl): string; var grid: TAccessGrid; row, col: integer; colHdr, rowHdr, txt: string; begin grid := TAccessGrid(Component); row := grid.Row; col := grid.Col; if (row >= 0) and (col >= 0) then begin // if col <> FLastX then // begin if grid.FixedRows > 0 then colHdr := Piece(grid.GetEditText(col, 0), DELIM, 1) else colHdr := ''; if colHdr = '' then colHdr := inttostr(col+1-grid.FixedCols) + ' of ' + inttostr(grid.ColCount-grid.FixedCols); colHdr := 'column ' + colhdr + ', '; // end // else // colHdr := ''; // FLastX := col; // if row <> FLastY then // begin if grid.FixedCols > 0 then rowHdr := Piece(grid.GetEditText(0, row), DELIM, 1) else rowHdr := ''; if rowHdr = '' then rowHdr := inttostr(row+1-grid.FixedRows) + ' of ' + inttostr(grid.RowCount-grid.FixedRows); rowHdr := 'row ' + rowhdr + ', '; // end // else // rowHdr := ''; // FLastY := row; txt := Piece(grid.GetEditText(col, row), DELIM, 1); if txt = '' then txt := 'blank'; Result := colHdr + rowHdr + txt; end else Result := ' '; end; { TVA508StaticTextManager } constructor TVA508StaticTextManager.Create; begin inherited Create(TVA508StaticText, [mtComponentName, mtCaption, mtValue], TRUE); end; function TVA508StaticTextManager.GetCaption(Component: TWinControl): string; begin Result := ' '; end; function TVA508StaticTextManager.GetComponentName( Component: TWinControl): string; begin Result := 'label'; end; function TVA508StaticTextManager.GetValue(Component: TWinControl): string; var next: TVA508ChainedLabel; comp: TVA508StaticText; begin comp := TVA508StaticText(Component); Result := comp.Caption; next := comp.NextLabel; while assigned(next) do begin Result := Result + ' ' + next.Caption; next := next.NextLabel; end; end; { TVA508EditManager } constructor TVA508EditManager.Create; begin inherited Create(TEdit, [mtValue], TRUE); end; function TVA508EditManager.GetValue(Component: TWinControl): string; begin Result := TEdit(Component).Text; end; { TVA508ComboManager } constructor TVA508ComboManager.Create; begin inherited Create(TComboBox, [mtValue], TRUE); end; function TVA508ComboManager.GetValue(Component: TWinControl): string; begin Result := TComboBox(Component).Text; end; initialization RegisterStandardDelphiComponents; end.
25.549923
111
0.691938
47a08c8d8b1ab9de701fdc3b87d6c008bf62ab49
4,406
pas
Pascal
Collections/HSharp.Collections.Interfaces.pas
helton/HSharp
186227af9a102b8522c0ebfc1b3439f32eaf2f79
[ "Apache-2.0" ]
null
null
null
Collections/HSharp.Collections.Interfaces.pas
helton/HSharp
186227af9a102b8522c0ebfc1b3439f32eaf2f79
[ "Apache-2.0" ]
null
null
null
Collections/HSharp.Collections.Interfaces.pas
helton/HSharp
186227af9a102b8522c0ebfc1b3439f32eaf2f79
[ "Apache-2.0" ]
3
2016-12-05T21:05:56.000Z
2019-02-12T08:14:16.000Z
{***************************************************************************} { } { HSharp Framework for Delphi } { } { Copyright (C) 2014 Helton Carlos de Souza } { } {***************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {***************************************************************************} unit HSharp.Collections.Interfaces; interface uses System.Generics.Defaults, System.Generics.Collections, System.Rtti, HSharp.Collections.Interfaces.Internal; type IList<T> = interface(IListInternal<T>) ['{42C33DDA-837F-467B-BA5C-6402BB300903}'] function Add(const Value: T): Integer; procedure AddRange(const Values: array of T); overload; procedure AddRange(const Collection: IEnumerable<T>); overload; procedure AddRange(const Collection: TEnumerable<T>); overload; procedure Insert(Index: Integer; const Value: T); procedure InsertRange(Index: Integer; const Values: array of T); overload; procedure InsertRange(Index: Integer; const Collection: IEnumerable<T>); overload; procedure InsertRange(Index: Integer; const Collection: TEnumerable<T>); overload; procedure Pack; overload; function Remove(const Value: T): Integer; procedure Delete(Index: Integer); procedure DeleteRange(AIndex, ACount: Integer); function Extract(const Value: T): T; procedure Exchange(Index1, Index2: Integer); procedure Move(CurIndex, NewIndex: Integer); function First: T; function Last: T; procedure Clear; function Expand: TList<T>; function Contains(const Value: T): Boolean; function IndexOf(const Value: T): Integer; function LastIndexOf(const Value: T): Integer; procedure Reverse; procedure Sort; overload; procedure Sort(const AComparer: IComparer<T>); overload; function BinarySearch(const Item: T; out Index: Integer): Boolean; overload; function BinarySearch(const Item: T; out Index: Integer; const AComparer: IComparer<T>): Boolean; overload; procedure TrimExcess; function ToArray: TArray<T>; end; IObjectList<T: class> = interface(IList<T>) ['{BA8CB6D8-A1E2-4DD3-9DA6-57CA955C101D}'] end; IDictionary<TKey,TValue> = interface(IDictionaryInternal<TKey,TValue>) ['{C52D99FF-F91A-4397-83EB-27DA8FB47705}'] procedure Add(const Key: TKey; const Value: TValue); procedure Remove(const Key: TKey); function ExtractPair(const Key: TKey): TPair<TKey,TValue>; procedure Clear; procedure TrimExcess; function TryGetValue(const Key: TKey; out Value: TValue): Boolean; procedure AddOrSetValue(const Key: TKey; const Value: TValue); function ContainsKey(const Key: TKey): Boolean; function ContainsValue(const Value: TValue): Boolean; function ToArray: TArray<TPair<TKey,TValue>>; end; IStack<T> = interface(IStackInternal<T>) ['{99C20C75-B994-41F8-BCF8-C66E4BA07DD6}'] procedure Clear; procedure Push(const Value: T); function Pop: T; function Peek: T; function Extract: T; procedure TrimExcess; function ToArray: TArray<T>; end; implementation end.
44.505051
111
0.559464
47f340fb7ea81ff08671b8e173b69b668b906c85
1,954
dfm
Pascal
project/Dialog.RunSQLScript.dfm
bogdanpolak/vcl-mailing-list
8a36762a7846b23c575a2107e364132a435b79a2
[ "MIT" ]
3
2018-10-15T08:10:18.000Z
2020-11-11T03:02:47.000Z
project/Dialog.RunSQLScript.dfm
bogdanpolak/vcl-mailing-list
8a36762a7846b23c575a2107e364132a435b79a2
[ "MIT" ]
17
2018-09-10T11:14:38.000Z
2018-09-19T12:09:26.000Z
project/Dialog.RunSQLScript.dfm
bogdanpolak/vcl-mailing-list
8a36762a7846b23c575a2107e364132a435b79a2
[ "MIT" ]
26
2018-09-12T09:47:03.000Z
2020-11-11T03:02:48.000Z
object FormDBScript: TFormDBScript Left = 0 Top = 0 Caption = 'FormDBScript' ClientHeight = 370 ClientWidth = 592 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnShow = FormShow DesignSize = ( 592 370) PixelsPerInch = 96 TextHeight = 13 object BitBtn1: TBitBtn Left = 8 Top = 8 Width = 129 Height = 25 Caption = '&Uruchom skrypt' Kind = bkYes NumGlyphs = 2 ParentShowHint = False ShowHint = False TabOrder = 0 OnClick = BitBtn1Click end object memScript: TMemo Left = 8 Top = 39 Width = 386 Height = 323 Anchors = [akLeft, akTop, akBottom] Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Consolas' Font.Style = [] Lines.Strings = ( 'memScript') ParentFont = False ScrollBars = ssBoth TabOrder = 1 end object Memo1: TMemo Left = 400 Top = 39 Width = 185 Height = 323 Anchors = [akLeft, akTop, akRight, akBottom] Lines.Strings = ( 'Memo1') ScrollBars = ssVertical TabOrder = 2 end object FDScript1: TFDScript SQLScripts = <> Connection = MainDM.FDConnection1 Params = <> Macros = <> FetchOptions.AssignedValues = [evItems, evAutoClose, evAutoFetchAll] FetchOptions.AutoClose = False FetchOptions.Items = [fiBlobs, fiDetails] ResourceOptions.AssignedValues = [rvMacroCreate, rvMacroExpand, rvDirectExecute, rvPersistent] ResourceOptions.MacroCreate = False ResourceOptions.DirectExecute = True OnConsolePut = FDScript1ConsolePut Left = 248 Top = 48 end object FDQuery1: TFDQuery Connection = MainDM.FDConnection1 Left = 248 Top = 96 end object FDQuery2: TFDQuery Connection = MainDM.FDConnection1 Left = 248 Top = 144 end end
22.45977
98
0.651996
fca5dfb27f923a91153f545f4e222cb29caa4bc9
3,936
pas
Pascal
Source/Parallel.pas
remobjects/libToffee
90e333dafa4b912e0ee4b3f903a1eeb5375844cd
[ "BSD-2-Clause" ]
3
2017-11-22T14:45:06.000Z
2019-06-12T20:16:03.000Z
Source/Parallel.pas
remobjects/libToffee
90e333dafa4b912e0ee4b3f903a1eeb5375844cd
[ "BSD-2-Clause" ]
null
null
null
Source/Parallel.pas
remobjects/libToffee
90e333dafa4b912e0ee4b3f903a1eeb5375844cd
[ "BSD-2-Clause" ]
2
2016-08-18T20:44:26.000Z
2016-12-29T19:30:35.000Z
namespace RemObjects.Elements.System; uses Foundation; type ParallelLoopState = public class private public property IsStopped: Boolean read private write; method &Break; begin if not IsStopped then IsStopped := True; end; end; &Parallel = static public class public class method &For(fromInclusive: Integer; toExclusive: Integer; body: block(aSource: Integer; aState: ParallelLoopState)); begin var lthreadcnt := rtl.sysconf(rtl._SC_NPROCESSORS_ONLN); var lcurrTasks: Integer := 0; var levent := new NSCondition(); var ls:= new ParallelLoopState(); for m: Integer := fromInclusive to toExclusive - 1 do begin while interlockedInc(var lcurrTasks, 0) >= lthreadcnt do begin if ls.IsStopped then Break; levent.lock; try levent.wait; finally levent.unlock; end; end; if ls.IsStopped then Break; interlockedInc(var lcurrTasks); var temp := m; new Task(-> begin body.Invoke(temp, ls); interlockedDec(var lcurrTasks); levent.lock; try levent.broadcast; finally levent.unlock; end; end).Start; end; while interlockedInc(var lcurrTasks, 0) > 0 do begin levent.lock; try levent.wait; finally levent.unlock; end; end; end; class method &For(fromInclusive: Int64; toExclusive: Int64; body: block(aSource: Int64; aState: ParallelLoopState)); begin var lthreadcnt := rtl.sysconf(rtl._SC_NPROCESSORS_ONLN); var lcurrTasks: Integer := 0; var levent := new NSCondition(); var ls:= new ParallelLoopState(); for m: Int64 := fromInclusive to toExclusive - 1 do begin while interlockedInc(var lcurrTasks, 0) >= lthreadcnt do begin if ls.IsStopped then Break; levent.lock; try levent.wait; finally levent.unlock; end; end; if ls.IsStopped then Break; interlockedInc(var lcurrTasks); var temp := m; new Task(-> begin body.Invoke(temp, ls); interlockedDec(var lcurrTasks); levent.lock; try levent.broadcast; finally levent.unlock; end; end).Start; end; while interlockedInc(var lcurrTasks, 0) > 0 do begin levent.lock; try levent.wait; finally levent.unlock; end; end; end; class method ForEach<TSource>(source: INSFastEnumeration<TSource>; body: block(aSource: TSource; aState: ParallelLoopState; aIndex: Int64)); begin var lthreadcnt := rtl.sysconf(rtl._SC_NPROCESSORS_ONLN); var lcurrTasks: Integer := 0; var levent := new NSCondition(); var ls:= new ParallelLoopState(); for m in source index n do begin while interlockedInc(var lcurrTasks, 0) >= lthreadcnt do begin if ls.IsStopped then Break; levent.lock; try levent.wait; finally levent.unlock; end; end; if ls.IsStopped then Break; interlockedInc(var lcurrTasks); var temp := m; var tempi := n; new Task(-> begin body.Invoke(temp, ls, tempi); interlockedDec(var lcurrTasks); levent.lock; try levent.broadcast; finally levent.unlock; end; end).Start; end; while interlockedInc(var lcurrTasks, 0) > 0 do begin levent.lock; try levent.wait; finally levent.unlock; end; end; end; end; end.
27.144828
144
0.550559
fcfd2abbab368af24e8e7343f0fd8573d15a0b9f
3,258
pas
Pascal
lox.pas
JulStrat/loxip
8fa5845315908b156910b4c470174c8ec0cff5f3
[ "MIT" ]
1
2020-02-09T14:55:05.000Z
2020-02-09T14:55:05.000Z
lox.pas
JulStrat/loxip
8fa5845315908b156910b4c470174c8ec0cff5f3
[ "MIT" ]
null
null
null
lox.pas
JulStrat/loxip
8fa5845315908b156910b4c470174c8ec0cff5f3
[ "MIT" ]
null
null
null
{ Crafting Interpreters https://craftinginterpreters.com/ } unit lox; {$ifdef FPC} {$mode delphi} {$endif} interface uses Classes, SysUtils , token, interpreter, rterror; type { TLox } TLox = class class var hadError: boolean; hadRunTimeError: boolean; inter: TInterpreter; class procedure Run(Source: string); static; class procedure RunPrompt; static; class procedure Error(line: integer; msg: string); static; overload; class procedure Error(token: TToken; msg: String); static; overload; class procedure RunTimeError(rte: ERunTimeError); static; class procedure Report(line: integer; where: string; msg: string); static; end; implementation uses Generics.Collections , {expression,} statement , scanner, parser{, astutils}; class procedure TLox.Run(Source: string); var scanner: TScanner; parser: TParser; tokens: TObjectList<TToken>; stm: TObjectList<TStatement>; counter: integer; // loop counter benchStart, benchEnd: QWord; begin { TEST } // source := 'var x = 101.1; var y = 1000001.1; var z; z = x * x * x * x * x * x * x * x; // print z;'; // WHILE statement test Fib // source := 'var a=0;var b=1;var c=0;while (c<1000) {if (c>=0) {print c+": "+a;} var temp=a;a=b;b=temp+b;c=c+1;}'; // source := 'var st=clock();var a=0;var b=1;var c=0; while (c<100) {if (c>=5) {print a;} var temp=a;a=b;b=temp+b;c=c+1;} print clock()-st;'; // FOR statement test // source := 'for (var i=0; i<=100; i=i+1) { if (i>=0) print i+": "+i*i; }'; { TEST } scanner := TScanner.Create(Source); tokens := scanner.ScanTokens(); (* Print tokens. Chapter - Scanning. *) { for tok in tokens do begin WriteLn(tok.ToString()); end; } parser := TParser.Create(tokens); stm := parser.Parse; { expr := parser.Parse; } if hadError then Exit(); benchStart := GetTickCount64(); { TEST } // for counter := 1 to 100000 do { TEST } inter.Interpret(stm); benchEnd := GetTickCount64(); WriteLn(Format('Tick count - %d.', [benchEnd - benchStart])); (* Destructors test *) FreeAndNil(stm); FreeAndNil(tokens); FreeAndNil(scanner); FreeAndNil(parser); end; class procedure TLox.RunPrompt; var inp: string; begin WriteLn('Type quit to exit.'); while True do begin Write('> '); ReadLn(inp); if inp = 'quit' then break; Run(inp); hadError := False; end; end; class procedure TLox.Error(line: integer; msg: string); begin Report(line, '', msg); end; class procedure TLox.Report(line: integer; where: string; msg: string); begin WriteLn(Format('[line %d] Error%s: %s', [line, where, msg])); hadError := True; end; class procedure TLox.Error(token: TToken; msg: String); begin if token.tokenKind = TTokenKind.tkEOF then report(token.line, ' at end ', msg) else report(token.line, ' at "' + token.lexeme + '" ', msg); end; class procedure TLox.RunTimeError(rte: ERunTimeError); var msg: string; begin msg := Format('[ERROR] %s [line %d].', [rte.Message, rte.token.line]); WriteLn(msg); hadRunTimeError := true; end; initialization SysUtils.DecimalSeparator := '.'; TLox.hadError := False; TLox.hadRunTimeError := False; TLox.inter := TInterpreter.Create; end.
22.625
143
0.64426
c31b107a5ed83c9d8670402372365b45b02ef05d
1,615
pas
Pascal
Zoomicon.Downloader/Zoomicon.Downloader.Models.pas
atkins126/READCOM_App
8425eaa5c134caee33a89dc77b57593a418a4eda
[ "MIT" ]
null
null
null
Zoomicon.Downloader/Zoomicon.Downloader.Models.pas
atkins126/READCOM_App
8425eaa5c134caee33a89dc77b57593a418a4eda
[ "MIT" ]
null
null
null
Zoomicon.Downloader/Zoomicon.Downloader.Models.pas
atkins126/READCOM_App
8425eaa5c134caee33a89dc77b57593a418a4eda
[ "MIT" ]
null
null
null
unit Zoomicon.Downloader.Models; interface uses Zoomicon.Cache.Models, //for IContentCache System.Classes, //for TThread System.Net.URLClient, //for TURI System.SyncObjs; //for TWaitResult const STATUS_OK = 200; //HTTP OK (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) type TDownloadProgressEvent = procedure(const Sender: TObject; const TotalElapsedTime: Cardinal; const Speed: Integer; const TotalReadCount: Int64; const TotalContentLength: Int64; var Abort: Boolean) of object; TDownloadTerminationEvent = procedure(const Sender: TObject; const Status: Integer) of object; TDownloadCompletionEvent = procedure(const Sender: TObject; Data: TStream) of object; IDownloader = interface ['{1C17622E-9D01-4042-B3CE-47A53C060A05}'] procedure Initialize(const TheContentURI: TURI; const Data: TStream; const TheContentCache: IContentCache = nil; const AutoStart: Boolean = true; const TheStartPosition: Int64 = 0; const TheEndPosition: Int64 = 0); procedure Start; function WaitForDownload(Timeout: cardinal = INFINITE): TWaitResult; procedure SetPaused(const Value: Boolean); function IsTerminated: Boolean; property Terminated: Boolean read IsTerminated; end; IFileDownloader = interface(IDownloader) ['{79AA850A-A875-4D07-B2D0-CFDDADEE1847}'] procedure Initialize(const TheContentURI: TURI; const Filepath: String; const TheContentCache: IContentCache = nil; const AutoStart: Boolean = true; const TheStartPosition: Int64 = 0; const TheEndPosition: Int64 = 0); end; implementation end.
41.410256
223
0.745511
f1e5eac03e514faac856a0305a8e12c70863b5c6
528
pas
Pascal
samples/lazarus/winsvc/daemonmanager.pas
GlerystonMatos/horse
ea5cdfedaf3e3571cba338d8f8dcb57706362bb0
[ "MIT" ]
633
2018-10-02T05:53:07.000Z
2022-03-31T11:32:47.000Z
samples/lazarus/winsvc/daemonmanager.pas
GlerystonMatos/horse
ea5cdfedaf3e3571cba338d8f8dcb57706362bb0
[ "MIT" ]
99
2018-10-02T18:46:30.000Z
2022-03-28T21:10:20.000Z
samples/lazarus/winsvc/daemonmanager.pas
GlerystonMatos/horse
ea5cdfedaf3e3571cba338d8f8dcb57706362bb0
[ "MIT" ]
191
2018-11-05T10:18:51.000Z
2022-03-31T11:34:47.000Z
unit DaemonManager; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DaemonApp; type { TDaemon_Manager } TDaemon_Manager = class(TDaemonMapper) procedure Daemon_ManagerCreate(Sender: TObject); private public end; var Daemon_Manager: TDaemon_Manager; implementation procedure RegisterMapper; begin RegisterDaemonMapper(TDaemon_Manager) end; {$R *.lfm} { TDaemon_Manager } procedure TDaemon_Manager.Daemon_ManagerCreate(Sender: TObject); begin end; initialization RegisterMapper; end.
11.478261
64
0.761364
fcfea1089ed028097f4ea0026d0751685da7a2de
3,336
dfm
Pascal
Catalogos/MRPreguntasEdit.dfm
alexismzt/SOFOM
57ca73e9f7fbb51521149ea7c0fdc409c22cc6f7
[ "Apache-2.0" ]
null
null
null
Catalogos/MRPreguntasEdit.dfm
alexismzt/SOFOM
57ca73e9f7fbb51521149ea7c0fdc409c22cc6f7
[ "Apache-2.0" ]
51
2018-07-25T15:39:25.000Z
2021-04-21T17:40:57.000Z
Catalogos/MRPreguntasEdit.dfm
alexismzt/SOFOM
57ca73e9f7fbb51521149ea7c0fdc409c22cc6f7
[ "Apache-2.0" ]
1
2021-02-23T17:27:06.000Z
2021-02-23T17:27:06.000Z
inherited frmMRPreguntasEdit: TfrmMRPreguntasEdit Caption = 'Edici'#243'n de Preguntas' ClientHeight = 263 ClientWidth = 628 ExplicitWidth = 634 ExplicitHeight = 292 PixelsPerInch = 96 TextHeight = 13 inherited pcMain: TcxPageControl Width = 628 Height = 222 ExplicitWidth = 625 ExplicitHeight = 351 ClientRectBottom = 220 ClientRectRight = 626 inherited tsGeneral: TcxTabSheet ExplicitLeft = 4 ExplicitTop = 24 ExplicitWidth = 617 ExplicitHeight = 323 object Label1: TLabel Left = 39 Top = 22 Width = 44 Height = 13 Caption = 'Pregunta' FocusControl = cxDBTextEdit1 end object Label2: TLabel Left = 39 Top = 137 Width = 30 Height = 13 Caption = 'Orden' FocusControl = cxDBSpinEdit1 end object cxDBTextEdit1: TcxDBTextEdit Left = 39 Top = 38 DataBinding.DataField = 'Pregunta' DataBinding.DataSource = DataSource TabOrder = 0 Width = 545 end object cxDBCheckBox1: TcxDBCheckBox Left = 39 Top = 78 Caption = 'Aplica a persona f'#237'sica' DataBinding.DataField = 'AplicaaPersonaFisica' DataBinding.DataSource = DataSource TabOrder = 1 Width = 193 end object cxDBCheckBox2: TcxDBCheckBox Left = 39 Top = 102 Caption = 'Aplica a persona moral' DataBinding.DataField = 'AplicaaPersonaMoral' DataBinding.DataSource = DataSource TabOrder = 2 Width = 193 end object cxDBSpinEdit1: TcxDBSpinEdit Left = 39 Top = 153 DataBinding.DataField = 'Orden' DataBinding.DataSource = DataSource TabOrder = 5 Width = 121 end object cxDBCheckBox3: TcxDBCheckBox Left = 367 Top = 78 Caption = 'Condicionada' DataBinding.DataField = 'Condicionada' DataBinding.DataSource = DataSource ParentBackground = False ParentColor = False ParentFont = False Style.Color = clBtnFace Style.Font.Charset = DEFAULT_CHARSET Style.Font.Color = clWindowText Style.Font.Height = -11 Style.Font.Name = 'Tahoma' Style.Font.Style = [] Style.IsFontAssigned = True TabOrder = 3 Visible = False Width = 121 end object cxDBCheckBox4: TcxDBCheckBox Left = 367 Top = 102 Caption = 'Evaluaci'#243'n directa de alto riesgo' DataBinding.DataField = 'EvaluaARDirecto' DataBinding.DataSource = DataSource TabOrder = 4 Visible = False Width = 193 end end end inherited pmlMain: TPanel Top = 222 Width = 628 ExplicitTop = 351 ExplicitWidth = 625 inherited btnCancel: TButton Left = 546 ExplicitLeft = 543 end inherited btnOk: TButton Left = 465 ExplicitLeft = 462 end end inherited DataSource: TDataSource DataSet = dmMatrizRiesgo.adodsPreguntas end inherited cxImageList: TcxImageList FormatVersion = 1 end end
26.903226
59
0.579736
c3938adf3bd3d091779f1c8aa297f4488169200d
530
pas
Pascal
CompMigrationTool/Converter/Types/ODACTagDefine.pas
devgear/ComponentConverter
67a9c56f6953dd732f0da80bbc8bbe249b25604d
[ "MIT" ]
3
2020-05-25T02:48:33.000Z
2021-08-06T02:00:26.000Z
CompMigrationTool/Converter/Types/ODACTagDefine.pas
devgear/MigrationTools
399e3cdb961ea5f4ed771a444bfc09d2db823a74
[ "MIT" ]
null
null
null
CompMigrationTool/Converter/Types/ODACTagDefine.pas
devgear/MigrationTools
399e3cdb961ea5f4ed771a444bfc09d2db823a74
[ "MIT" ]
5
2020-01-25T12:39:00.000Z
2022-03-14T07:59:18.000Z
unit ODACTagDefine; interface const TAG_FDCONNECTION = '' + 'object [[COMP_NAME]]: TFDConnection'#13#10 + ' Params.Strings = ('#13#10 + ' ''CharacterSet=[[CHARSET]]'''#13#10 + ' ''User_Name=[[USERNAME]]'''#13#10 + ' ''Password=[[PASSWORD]]'''#13#10 + ' ''Database=[[DATABASE]]'''#13#10 + ' ''DriverID=Ora'')'#13#10 + ' LoginPrompt = False'#13#10 + ' Left = [[LEFT]]'#13#10 + ' Top = [[TOP]]'#13#10 + 'end'#13#10 ; TAG_FDQuery = '' ; implementation end.
20.384615
49
0.513208
c3270072ff6d8b71477530ec299c45a98b3704c2
2,314
pas
Pascal
LoggerPro.RedisAppender.pas
jmgimond/logerpro
cfa9ac4554fd104d459a1d6e57c58e9c01f780b9
[ "Apache-2.0" ]
1,009
2015-05-28T12:34:39.000Z
2022-03-30T14:10:18.000Z
LoggerPro.RedisAppender.pas
jmgimond/logerpro
cfa9ac4554fd104d459a1d6e57c58e9c01f780b9
[ "Apache-2.0" ]
454
2015-05-28T12:44:27.000Z
2022-03-31T22:35:45.000Z
LoggerPro.RedisAppender.pas
jmgimond/logerpro
cfa9ac4554fd104d459a1d6e57c58e9c01f780b9
[ "Apache-2.0" ]
377
2015-05-28T16:29:21.000Z
2022-03-21T18:36:12.000Z
unit LoggerPro.RedisAppender; { <@abstract(The unit to include if you want to use @link(TLoggerProRedisAppender)) @author(Daniele Teti) } interface uses LoggerPro, System.Classes, System.DateUtils, Redis.Commons {Redis.Commons is included in DelphiRedisClient, also available with GETIT} , Redis.NetLib.INDY {Redis.NetLib.INDY is included in DelphiRedisClient, also available with GETIT}; type { @abstract(Logs to a Redis instance) To learn how to use this appender, check the sample @code(remote_redis_appender.dproj) @author(Daniele Teti - d.teti@bittime.it) } TLoggerProRedisAppender = class(TLoggerProAppenderBase) private FRedis: IRedisClient; FLogKeyPrefix: string; FMaxSize: Int64; public constructor Create(aRedis: IRedisClient; aMaxSize: Int64 = 5000; aKeyPrefix: string = 'loggerpro'); reintroduce; procedure Setup; override; procedure TearDown; override; procedure WriteLog(const aLogItem: TLogItem); override; procedure TryToRestart(var Restarted: Boolean); override; end; implementation uses System.SysUtils; const DEFAULT_LOG_FORMAT = '%0:s [TID %1:-8d][%2:-8s] %3:s [%4:s]'; constructor TLoggerProRedisAppender.Create(aRedis: IRedisClient; aMaxSize: Int64; aKeyPrefix: string); begin inherited Create; FRedis := aRedis; FLogKeyPrefix := aKeyPrefix; FMaxSize := aMaxSize; end; procedure TLoggerProRedisAppender.Setup; begin FRedis.Connect; end; procedure TLoggerProRedisAppender.TearDown; begin // do nothing end; procedure TLoggerProRedisAppender.TryToRestart(var Restarted: Boolean); begin inherited; Restarted := False; try FRedis.Disconnect except end; try FRedis.Connect; Restarted := True; except end; end; procedure TLoggerProRedisAppender.WriteLog(const aLogItem: TLogItem); var lText: string; lKey: string; begin lText := Format(DEFAULT_LOG_FORMAT, [datetimetostr(aLogItem.TimeStamp), aLogItem.ThreadID, aLogItem.LogTypeAsString, aLogItem.LogMessage, aLogItem.LogTag]); lKey := FLogKeyPrefix + '::logs'; // + aLogItem.LogTypeAsString.ToLower; // Push the log item to the right of the list (logs:info, logs:warning, log:error) FRedis.RPUSH(lKey, [lText]); // Trim the list to the FMaxSize last elements FRedis.LTRIM(lKey, -FMaxSize, -1); end; end.
26.295455
116
0.741573
c30d17b7183c8c75a0c624cd30add629902c1f02
2,209
dpr
Pascal
unittests/DORM_UnitTests_XE7.dpr
raelb/delphi-orm
73e0caede84f2753550492deeaad35bf4191be30
[ "Apache-2.0" ]
156
2015-05-28T19:14:20.000Z
2022-03-18T05:34:41.000Z
unittests/DORM_UnitTests_XE7.dpr
raelb/delphi-orm
73e0caede84f2753550492deeaad35bf4191be30
[ "Apache-2.0" ]
10
2015-05-31T09:19:41.000Z
2021-09-27T14:34:31.000Z
unittests/DORM_UnitTests_XE7.dpr
raelb/delphi-orm
73e0caede84f2753550492deeaad35bf4191be30
[ "Apache-2.0" ]
70
2015-06-20T17:34:17.000Z
2022-03-03T10:05:31.000Z
program DORM_UnitTests_XE6; {$IFDEF CONSOLE_TESTRUNNER} {$APPTYPE CONSOLE} {$ENDIF} uses {$IFNDEF FIREBIRD_CI} FastMM4, {$ENDIF } Forms, TestFramework, GUITestRunner, TextTestRunner, TestDORM in 'TestDORM.pas', TestDORMSearchCriteria in 'TestDORMSearchCriteria.pas', TestDORMSpeed in 'TestDORMSpeed.pas', TestDORMRelations in 'TestDORMRelations.pas', dorm.Collections in '..\source\dorm.Collections.pas', dorm.Commons in '..\source\dorm.Commons.pas', dorm.Core.IdentityMap in '..\source\dorm.Core.IdentityMap.pas', dorm in '..\source\dorm.pas', dorm.UOW in '..\source\dorm.UOW.pas', dorm.Utils in '..\source\dorm.Utils.pas', dorm.utils.Sequences in '..\source\dorm.utils.Sequences.pas', dorm.tests.bo in 'dorm.tests.bo.pas', BaseTestCase in 'BaseTestCase.pas', FindersTests in 'FindersTests.pas', FrameworkTests in 'FrameworkTests.pas', dorm.Finders in '..\source\dorm.Finders.pas', dorm.Filters in '..\source\dorm.Filters.pas', dorm.Mappings in '..\source\dorm.Mappings.pas', dorm.Mappings.Strategies in '..\source\dorm.Mappings.Strategies.pas', dorm.loggers in '..\source\dorm.loggers.pas', dorm.loggers.FileLog in '..\source\dorm.loggers.FileLog.pas', dorm.adapters in '..\source\dorm.adapters.pas', TestDORMMapping.Merge in 'TestDORMMapping.Merge.pas', TestDORMMapping.Attributes in 'TestDORMMapping.Attributes.pas', TestDORMMapping.CoC in 'TestDORMMapping.CoC.pas', TestDORMMapping.FileJSON in 'TestDORMMapping.FileJSON.pas', dorm.adapter.Base in '..\source\dorm.adapter.Base.pas', TestDORMDuckTyping in 'TestDORMDuckTyping.pas', dorm.tests.objstatus.bo in 'dorm.tests.objstatus.bo.pas', TestDORMObjStatus in 'TestDORMObjStatus.pas', dorm.Query in '..\source\dorm.Query.pas', TestDORMObjVersion in 'TestDORMObjVersion.pas', dorm.loggers.CodeSite in '..\source\dorm.loggers.CodeSite.pas'; {$R *.RES} begin {$IFNDEF FIREBIRD_CI} ReportMemoryLeaksOnShutdown := True; {$ENDIF} Application.Initialize; if IsConsole then with TextTestRunner.RunRegisteredTests(rxbHaltOnFailures) do Free else GUITestRunner.RunRegisteredTests; end.
32.485294
72
0.71933
4708bcb1d56c69ea46803889bbec6a3c2fe83b3f
26,171
pas
Pascal
Rootkits/vault/admin/ce54releasesvn/MainUnit2.pas
dendisuhubdy/grokmachine
120a21a25c2730ed356739231ec8b99fc0575c8b
[ "BSD-3-Clause" ]
46
2017-05-15T11:15:08.000Z
2018-07-02T03:32:52.000Z
Rootkits/vault/admin/ce54releasesvn/MainUnit2.pas
dendisuhubdy/grokmachine
120a21a25c2730ed356739231ec8b99fc0575c8b
[ "BSD-3-Clause" ]
null
null
null
Rootkits/vault/admin/ce54releasesvn/MainUnit2.pas
dendisuhubdy/grokmachine
120a21a25c2730ed356739231ec8b99fc0575c8b
[ "BSD-3-Clause" ]
24
2017-05-17T03:26:17.000Z
2018-07-09T07:00:50.000Z
unit MainUnit2; //this unit is used by both the network client and the main program (USERINTERFACE) interface uses dialogs,forms,classes,windows,sysutils,formsettingsunit,registry,cefuncproc,AdvancedOptionsUnit, MemoryBrowserFormUnit,memscan {$ifdef net} ,unit2; {$else} ,plugin,mainunit,hotkeyhandler,frmProcessWatcherunit,newkernelhandler; {$endif} procedure HandleautoAttachString; procedure LoadSettingsFromRegistry; procedure initcetitle; function GetScanType: Integer; function getVarType: Integer; function GetScanType2: TScanOption; function getVarType2: TVariableType; const beta=''; //empty this for a release var CEnorm:string = 'Cheat Engine 5.4'+beta; CERegion:string = 'Cheat Engine 5.4'+beta+' - Please Wait!'; CESearch:string = 'Cheat Engine 5.4'+beta+' - Please Wait!'; CERegionSearch:string = 'Cheat Engine 5.4'+beta+' - Please Wait!'; CEWait:string= 'Cheat Engine 5.4'+beta+' - Please Wait!'; resourcestring strStart='Start'; strStop='Stop'; strOK='OK'; strBug='BUG!'; strAutoAssemble='Assembler'; strAddressHasToBeReadable='The address has to be readable if you want to use this function'; strNewScan='New Scan'; strFirstScan='First Scan'; strNoDescription='No description'; strNeedNewerWindowsVersion='This function only works in Windows 2000+ (perhaps also NT but not tested)'; //scantypes strexact='Exact'; strexactvalue='Exact Value'; strbiggerThan='Bigger than...'; strSmallerThan='Smaller than...'; strIncreasedValue='Increased value'; strIncreasedValueBy='Increased value by ...'; strDecreasedValue='Decreased value'; strDecreasedValueBy='Decreased value by ...'; strValueBetween='Value between...'; strChangedValue='Changed value'; strUnchangedValue='Unchanged value'; strUnknownInitialValue='Unknown initial value'; strSameAsFirstScan='Same as first scan'; strFailedToInitialize='Failed to initialize the debugger'; strtoolong='Too long'; type tspeedhackspeed=record speed: single; sleeptime: dword; end; var speedhackspeed1: tspeedhackspeed; speedhackspeed2: tspeedhackspeed; speedhackspeed3: tspeedhackspeed; speedhackspeed4: tspeedhackspeed; speedhackspeed5: tspeedhackspeed; speedupdelta: single; slowdowndelta: single; implementation function GetScanType2: TScanOption; { Determine the current scanoption. If it's a custom type vatriable, it's always of type custom } begin if getVarType2=vtCustom then result:=soCustom else case GetScanType of exact_value: result:=soExactValue; biggerthan: result:=soBiggerThan; smallerthan: result:=soSmallerThan; valueBetween: result:=soValueBetween; Advanced_scan: result:=soUnknownValue; Increased_value: result:=soIncreasedValue; Increased_value_by:result:=soIncreasedValueBy; Decreased_value: result:=soDecreasedValue; Decreased_value_by:result:=soDecreasedValueBy; Changed_value: result:=soChanged; Unchanged_value: result:=soUnchanged; SameAsFirst: result:=soSameAsFirst; end; end; function GetScanType: Integer; var vtype: integer; begin with mainform do begin result:=exact_value; vtype:= getvartype; if getvartype in [0,1,2,3,4,6,9] then begin if not nextscanbutton.enabled then begin //first scan case scantype.ItemIndex of 0: result:=exact_value; 1: result:=biggerthan; 2: result:=smallerthan; 3: result:=valuebetween; 4: result:=Advanced_scan; end; end else begin //next scan case scantype.itemindex of 0: result:=exact_value; 1: result:=biggerthan; 2: result:=smallerthan; 3: result:=valuebetween; 4: result:=increased_value; 5: result:=increased_value_by; 6: result:=decreased_value; 7: result:=decreased_value_by; 8: result:=changed_value; 9: result:=unchanged_value; 10: result:=sameasfirst; end; end; end; end; end; function getVarType2: TVariableType; var i: integer; begin i:=getVarType; case i of 5: result:=vtBinary; 0: result:=vtByte; 1: result:=vtWord; 2: result:=vtDword; 6: result:=vtQword; 3: result:=vtSingle; 4: result:=vtDouble; 7: result:=vtString; 8: result:=vtByteArray; 9: result:=vtAll; 10: result:=vtCustom; else result:=vtByte; end; end; function getVarType: Integer; begin { Bit = 5 Byte =0 2 Bytes =1 4 Bytes =2 8 Bytes =6 Float =3 Double =4 Text = 7 } with mainform do begin case VarType.ItemIndex of 0: result:=5; //binary 1: result:=0; //byte 2: result:=1; //2 bytes 3: result:=2; //4 bytes 4: result:=6; //8 bytes 5: result:=3; //float 6: result:=4; //double 7: result:=7; //text 8: result:=8; //array of byte 9: result:=9; //all, only for new memscan 10: result:=10; //"custom" else result:=-1; end; end; end; procedure HandleautoAttachString; var s: string; s2: string; i: integer; begin mainform.autoattachlist.clear; s:=formsettings.EditAutoAttach.Text; s2:=''; for i:=1 to length(s) do begin if s[i]=';' then begin s2:=trim(s2); if s2<>'' then mainform.autoattachlist.Add(s2); s2:=''; continue; end; s2:=s2+s[i]; end; s2:=trim(s2); if s2<>'' then mainform.autoattachlist.Add(s2); mainform.AutoAttachTimer.Enabled:=mainform.autoattachlist.Count>0; end; procedure LoadSettingsFromRegistry; var reg : TRegistry; modifier: dword; key: dword; hotkey: string; i,j: integer; go: boolean; temphotkeylist: array [0..28] of cefuncproc.tkeycombo; found:boolean; names: TStringList; s,s2: string; begin try reg:=Tregistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('\Software\Cheat Engine',false) then begin with formsettings do begin LoadingSettingsFromRegistry:=true; if reg.ValueExists('Undo') then cbshowundo.checked:=reg.ReadBool('Undo'); if reg.ValueExists('Advanced') then cbShowAdvanced.checked:=reg.ReadBool('Advanced'); if reg.ValueExists('SeperateThread') then checkThread.checked:=reg.ReadBool('SeperateThread'); if reg.ValueExists('ScanThreadpriority') then combothreadpriority.itemindex:=reg.ReadInteger('ScanThreadpriority'); case combothreadpriority.itemindex of 0: scanpriority:=tpIdle; 1: scanpriority:=tpLowest; 2: scanpriority:=tpLower; 3: scanpriority:=tpLower; 4: scanpriority:=tpNormal; 5: scanpriority:=tpHigher; 6: scanpriority:=tpHighest; 7: scanpriority:=tpTimeCritical; end; mainform.UndoScan.visible:={$ifdef net}false{$else}cbshowundo.checked{$endif}; mainform.advancedbutton.Visible:=cbShowAdvanced.checked; mainform.cbspeedhack.Visible:=cbShowAdvanced.checked; {$ifndef net} SuspendHotkeyHandler; if reg.ValueExists('Speedhack 1 speed') then speedhackspeed1.speed:=reg.ReadFloat('Speedhack 1 speed') else speedhackspeed1.speed:=1; if reg.ValueExists('Speedhack 1 sleeptime') then speedhackspeed1.sleeptime:=reg.ReadInteger('Speedhack 1 sleeptime') else speedhackspeed1.sleeptime:=3; if reg.ValueExists('Speedhack 2 speed') then speedhackspeed2.speed:=reg.ReadFloat('Speedhack 2 speed') else speedhackspeed2.speed:=1; if reg.ValueExists('Speedhack 2 sleeptime') then speedhackspeed2.sleeptime:=reg.ReadInteger('Speedhack 2 sleeptime') else speedhackspeed2.sleeptime:=3; if reg.ValueExists('Speedhack 3 speed') then speedhackspeed3.speed:=reg.ReadFloat('Speedhack 3 speed') else speedhackspeed3.speed:=1; if reg.ValueExists('Speedhack 3 sleeptime') then speedhackspeed3.sleeptime:=reg.ReadInteger('Speedhack 3 sleeptime') else speedhackspeed3.sleeptime:=3; if reg.ValueExists('Speedhack 4 speed') then speedhackspeed4.speed:=reg.ReadFloat('Speedhack 4 speed') else speedhackspeed4.speed:=1; if reg.ValueExists('Speedhack 4 sleeptime') then speedhackspeed4.sleeptime:=reg.ReadInteger('Speedhack 4 sleeptime') else speedhackspeed4.sleeptime:=3; if reg.ValueExists('Speedhack 5 speed') then speedhackspeed5.speed:=reg.ReadFloat('Speedhack 5 speed') else speedhackspeed5.speed:=1; if reg.ValueExists('Speedhack 5 sleeptime') then speedhackspeed5.sleeptime:=reg.ReadInteger('Speedhack 5 sleeptime') else speedhackspeed5.sleeptime:=3; if reg.ValueExists('Increase Speedhack delta') then speedupdelta:=reg.ReadFloat('Increase Speedhack delta'); if reg.ValueExists('Decrease Speedhack delta') then slowdowndelta:=reg.ReadFloat('Decrease Speedhack delta'); try reg.ReadBinaryData('Show Cheat Engine Hotkey',temphotkeylist[0][0],10); except mainform.label7.Caption:=''; end; try reg.ReadBinaryData('Pause process Hotkey',temphotkeylist[1][0],10); except end; try reg.ReadBinaryData('Toggle speedhack Hotkey',temphotkeylist[2][0],10); except end; try reg.ReadBinaryData('Set Speedhack speed 1 Hotkey',temphotkeylist[3][0],10); except end; try reg.ReadBinaryData('Set Speedhack speed 2 Hotkey',temphotkeylist[4][0],10); except end; try reg.ReadBinaryData('Set Speedhack speed 3 Hotkey',temphotkeylist[5][0],10); except end; try reg.ReadBinaryData('Set Speedhack speed 4 Hotkey',temphotkeylist[6][0],10); except end; try reg.ReadBinaryData('Set Speedhack speed 5 Hotkey',temphotkeylist[7][0],10); except end; try reg.ReadBinaryData('Increase Speedhack speed',temphotkeylist[8][0],10); except end; try reg.ReadBinaryData('Decrease Speedhack speed',temphotkeylist[9][0],10); except end; try reg.ReadBinaryData('Binary Hotkey',temphotkeylist[10][0],10); except end; try reg.ReadBinaryData('Byte Hotkey',temphotkeylist[11][0],10); except end; try reg.ReadBinaryData('2 Bytes Hotkey',temphotkeylist[12][0],10); except end; try reg.ReadBinaryData('4 Bytes Hotkey',temphotkeylist[13][0],10); except end; try reg.ReadBinaryData('8 Bytes Hotkey',temphotkeylist[14][0],10); except end; try reg.ReadBinaryData('Float Hotkey',temphotkeylist[15][0],10); except end; try reg.ReadBinaryData('Double Hotkey',temphotkeylist[16][0],10); except end; try reg.ReadBinaryData('Text Hotkey',temphotkeylist[17][0],10); except end; try reg.ReadBinaryData('Array of Byte Hotkey',temphotkeylist[18][0],10); except end; try reg.ReadBinaryData('New Scan Hotkey',temphotkeylist[19][0],10); except end; try reg.ReadBinaryData('New Scan-Exact Value',temphotkeylist[20][0],10); except end; try reg.ReadBinaryData('Unknown Initial Value Hotkey',temphotkeylist[21][0],10); except end; try reg.ReadBinaryData('Next Scan-Exact Value',temphotkeylist[22][0],10); except end; try reg.ReadBinaryData('Increased Value Hotkey',temphotkeylist[23][0],10); except end; try reg.ReadBinaryData('Decreased Value Hotkey',temphotkeylist[24][0],10); except end; try reg.ReadBinaryData('Changed Value Hotkey',temphotkeylist[25][0],10); except end; try reg.ReadBinaryData('Unchanged Value Hotkey',temphotkeylist[26][0],10); except end; try reg.ReadBinaryData('Undo Last scan Hotkey',temphotkeylist[27][0],10); except end; try reg.ReadBinaryData('Cancel scan Hotkey',temphotkeylist[28][0],10); except end; try reg.ReadBinaryData('Speedhack speed 1',Speedhackspeed1,sizeof(tspeedhackspeed)); except speedhackspeed1.speed:=2; speedhackspeed1.sleeptime:=3; end; try reg.ReadBinaryData('Speedhack speed 2',Speedhackspeed2,sizeof(tspeedhackspeed)); except speedhackspeed2.speed:=2; speedhackspeed2.sleeptime:=3; end; try reg.ReadBinaryData('Speedhack speed 3',Speedhackspeed3,sizeof(tspeedhackspeed)); except speedhackspeed3.speed:=2; speedhackspeed3.sleeptime:=3; end; try reg.ReadBinaryData('Speedhack speed 4',Speedhackspeed4,sizeof(tspeedhackspeed)); except speedhackspeed4.speed:=2; speedhackspeed4.sleeptime:=3; end; try reg.ReadBinaryData('Speedhack speed 5',Speedhackspeed5,sizeof(tspeedhackspeed)); except speedhackspeed5.speed:=2; speedhackspeed5.sleeptime:=3; end; //fill the hotkeylist for i:=0 to 28 do begin found:=false; for j:=0 to length(hotkeythread.hotkeylist)-1 do begin if (hotkeythread.hotkeylist[j].id=i) and (hotkeythread.hotkeylist[j].handler2) then begin //found it hotkeythread.hotkeylist[j].keys:=temphotkeylist[i]; found:=true; break; end; end; if not found then //add it begin j:=length(hotkeythread.hotkeylist); setlength(hotkeythread.hotkeylist,j+1); hotkeythread.hotkeylist[j].keys:=temphotkeylist[i]; hotkeythread.hotkeylist[j].windowtonotify:=mainform.Handle; hotkeythread.hotkeylist[j].id:=i; hotkeythread.hotkeylist[j].handler2:=true; end; checkkeycombo(temphotkeylist[i]); end; if temphotkeylist[0][0]<>0 then hotkey:=ConvertKeyComboToString(temphotkeylist[0]) else hotkey:='no'; if temphotkeylist[1][0]<>0 then advancedoptions.pausehotkeystring:='('+ConvertKeyComboToString(temphotkeylist[1])+')' else advancedoptions.pausehotkeystring:=' (No hotkey)'; if temphotkeylist[2][0]<>0 then mainform.cbSpeedhack.Hint:='Enable/Disable speedhack. ('+ConvertKeyComboToString(temphotkeylist[2])+')' else mainform.cbSpeedhack.Hint:='Enable/Disable speedhack. (No hotkey)'; ResumeHotkeyHandler; {$endif} if reg.ValueExists('Buffersize') then buffersize:=reg.readInteger('Buffersize') else buffersize:=512; try EditBufSize.text:=IntToStr(buffersize) except EditBufSize.Text:='512'; end; buffersize:=buffersize*1024; {$ifdef net} mainform.buffersize:=buffersize; {$endif} try if reg.ReadBool('UseDebugRegs') then formsettings.rbDebugRegisters.checked:=true else formsettings.rdWriteExceptions.checked:=true; except end; try if reg.readbool('Show Disassembler') then begin formsettings.cbShowDisassembler.checked:=true; memorybrowser.Panel1.Visible:=true; memorybrowser.updatedisassemblerview; memorybrowser.RefreshMB; end else begin formsettings.cbShowDisassembler.checked:=false; memorybrowser.Panel1.Visible:=false; memorybrowser.RefreshMB; end; except end; try formsettings.cbCenterOnPopup.checked:=reg.readbool('Center on popup'); except end; try mainform.updatetimer.Interval:=reg.readInteger('Update interval'); except end; try mainform.freezetimer.Interval:=reg.readInteger('Freeze interval'); except end; formsettings.EditUpdateInterval.text:=IntToStr(mainform.updatetimer.Interval); formsettings.EditFreezeInterval.text:=IntToStr(mainform.freezetimer.Interval); {$ifdef net} //also get the update interval for network try i:=reg.readInteger('Network Update Interval'); except end; try formsettings.EditNetworkUpdateInterval.Text:=IntToStr(i); except end; {$endif} try cbShowAsSigned.checked:=reg.readbool('Show values as signed'); except end; try cbBinariesAsDecimal.checked:=reg.readbool('Handle binarys as decimals'); except end; // reg.ValueExists() if reg.ValueExists('AutoAttach') then EditAutoAttach.Text:=reg.ReadString('AutoAttach'); if reg.ValueExists('Always AutoAttach') then cbAlwaysAutoAttach.checked:=reg.readbool('Always AutoAttach'); try EditNetworkUpdateInterval.Text:=IntToStr(reg.ReadInteger('Network Update Interval')); except end; try cbShowDebugoptions.checked:=reg.ReadBool('Show debugger options'); except end; try replacewithnops.checked:=reg.readBool('Replace incomplete opcodes with NOPS'); except end; try askforreplacewithnops.checked:=reg.readBool('Ask for replace with NOPS'); except end; try cbFastscan.checked:=reg.ReadBool('Fastscan on by default'); except end; try checkbox1.Checked:=reg.readbool('Use Anti-debugdetection'); except end; try cbhandlebreakpoints.Checked:=reg.ReadBool('Handle unhandled breakpoints'); except end; if cbFastscan.Checked then mainform.cbFastscan.Checked:=true else mainform.cbFastScan.Checked:=false; try cbsimplecopypaste.checked:=reg.readbool('Simple copy/paste'); except end; try rbDebugAsBreakpoint.Checked:=reg.readbool('Hardware breakpoints'); except end; try rbInt3AsBreakpoint.checked:=not reg.readbool('Hardware breakpoints'); except end; try cbUpdatefoundList.Checked:=reg.readbool('Update Foundaddress list'); except end; try mainform.UpdateFoundlisttimer.interval:=reg.readInteger('Update Foundaddress list Interval'); except end; try editUpdatefoundInterval.Text:=IntToStr(mainform.UpdateFoundlisttimer.interval); except end; try cbSkip_PAGE_NOCACHE.Checked:=reg.readbool('skip PAGE_NOCACHE'); except end; Skip_PAGE_NOCACHE:=cbSkip_PAGE_NOCACHE.Checked; //try cbBreakOnAttach.Checked:=reg.readbool('Break when debuging'); except end; cbBreakOnattach.Checked:=false; try cbHideAllWindows.Checked:=reg.ReadBool('Hide all windows'); except end; try temphideall:=reg.ReadBool('Really hide all windows'); except end; onlyfront:=not formsettings.temphideall; try cbMemPrivate.Checked:=reg.ReadBool('MEM_PRIVATE'); except end; try cbMemImage.Checked:=reg.ReadBool('MEM_IMAGE'); except end; try cbMemMapped.Checked:=reg.ReadBool('MEM_MAPPED'); except end; Scan_MEM_PRIVATE:=cbMemPrivate.checked; Scan_MEM_IMAGE:=cbMemImage.Checked; Scan_MEM_MAPPED:=cbMemMapped.Checked; try cbLowMemoryUsage.Checked:=reg.ReadBool('Low Memory Usage'); except end; try cbEnableHyperscanWhenPossible.Checked:=reg.ReadBool('Use Hyperscan if posible'); except end; if reg.ValueExists('StealthOnExecute') then cbStealth.Checked:=reg.ReadBool('StealthOnExecute') else cbstealth.Checked:=false; if reg.ValueExists('Protect CE') then cbProtectMe.Checked:=reg.readbool('Protect CE') else cbprotectme.checked:=false; try cbKernelQueryMemoryRegion.checked:=reg.ReadBool('Use dbk32 QueryMemoryRegionEx'); except end; try cbKernelReadWriteProcessMemory.checked:=reg.ReadBool('Use dbk32 ReadWriteProcessMemory'); except end; try cbKernelOpenProcess.checked:=reg.ReadBool('Use dbk32 OpenProcess'); except end; if reg.ValueExists('Undo memory changes') then cbUndoMemoryChanges.checked:=reg.ReadBool('Undo memory changes'); if reg.ValueExists('Undo memory changes:Force writable') then cbForceUndo.checked:=reg.ReadBool('Undo memory changes:Force writable'); if not cbUndoMemorychanges.Checked then begin cbforceundo.Checked:=false; cbforceundo.Enabled:=false; end; {$ifndef net} try unrandomizersettings.defaultreturn:=reg.ReadInteger('Unrandomizer: default value'); except end; try unrandomizersettings.incremental:=reg.ReadBool('Unrandomizer: incremental'); except end; if reg.ValueExists('ModuleList as Denylist') then DenyList:=reg.ReadBool('ModuleList as Denylist') else denylist:=true; if reg.ValueExists('Global Denylist') then DenyListGlobal:=reg.ReadBool('Global Denylist') else denylistglobal:=false; if reg.ValueExists('ModuleListSize') then ModuleListSize:=reg.ReadInteger('ModuleListSize') else modulelistsize:=0; if modulelist<>nil then freemem(modulelist); getmem(modulelist,modulelistsize); try reg.ReadBinaryData('Module List',ModuleList^,ModuleListSize); except end; try cbProcessWatcher.checked:=reg.readBool('Use Processwatcher'); except end; try cbKdebug.checked:=reg.ReadBool('Use Kernel Debugger'); except end; try cbGlobalDebug.checked:=reg.ReadBool('Use Global Debug Routines'); except end; if cbForceUndo.checked or cbGlobalDebug.checked then LoadDBK32; if cbKernelQueryMemoryRegion.checked then UseDBKQueryMemoryRegion else DontUseDBKQueryMemoryRegion; if cbKernelReadWriteProcessMemory.checked then UseDBKReadWriteMemory else DontUseDBKReadWriteMemory; if cbKernelOpenProcess.Checked then UseDBKOpenProcess else DontUseDBKOpenProcess; if cbProcessWatcher.Checked then if (frmProcessWatcher=nil) then //propably yes frmProcessWatcher:=tfrmprocesswatcher.Create(mainform); //start the process watcher if assigned(newkernelhandler.SetGlobalDebugState) then newkernelhandler.SetGlobalDebugState(cbGlobalDebug.checked); {$endif} if cbUndoMemoryChanges.checked then if not fileexists(cheatenginedir+'ceprotect.dat') then begin cbUndoMemoryChanges.Checked:=false; cbforceundo.Enabled:=false; cbforceundo.Checked:=false; end; //load the exclude list try i:=0; go:=true; while go do begin setlength(donthidelist,length(donthidelist)+1); donthidelist[i]:=reg.readstring('Do not hide '+IntToStr(i)); if donthidelist[i]='' then begin setlength(donthidelist,length(donthidelist)-1); go:=false; end; inc(i); end; except if length(donthidelist)=0 then begin setlength(donthidelist,1); donthidelist[0]:='explorer.exe'; end; end; end; end; {$ifndef net} if Reg.OpenKey('\Software\Cheat Engine\plugins',false) then begin names:=TStringList.create; try reg.GetValueNames(names); names.Sort; for i:=0 to names.Count-1 do begin try if names[i][10]='A' then //plugin dll begin s:=reg.ReadString(names[i]); j:=pluginhandler.LoadPlugin(s); end; if names[i][10]='B' then //enabled or not begin if reg.ReadBool(names[i]) then pluginhandler.EnablePlugin(j); end; except end; end; pluginhandler.FillCheckListBox(formsettings.clbPlugins); finally names.Free; end; end; {$endif} formsettings.LoadingSettingsFromRegistry:=false; finally reg.CloseKey; end; except end; {$ifdef net} MemoryBrowser.Kerneltools1.visible:=false; {$else} MemoryBrowser.Kerneltools1.Enabled:=DarkByteKernel<>0; {$endif} HandleAutoAttachString; end; procedure initcetitle; var dwhandle: thandle; FileVersionInfoSize: integer; puLen: cardinal; FileVersionInfo: pointer; b: pointer; ffi: ^VS_FIXEDFILEINFO; begin CEnorm:='Cheat Engine 5.4'; //.'; { FileVersionInfoSize:=GetFileVersionInfoSize(pchar(application.exename),dwhandle); if FileVersionInfoSize>0 then begin getmem(FileVersionInfo,FileVersionInfoSize); try if GetFileVersionInfo(pchar(application.exename),0,FileVersionInfoSize,FileVersionInfo) then begin if VerQueryValue(FileVersionInfo,'\',b,puLen) then begin ffi:=b; cenorm:=cenorm+(inttostr(ffi.dwFileVersionLS))+beta; end; end; finally freemem(FileVersionInfo); end; end; } CERegion:=cenorm+' - Please Wait!'; CESearch:=CERegion; CERegionSearch:= CERegion; CEWait:= ceregion; mainform.Caption:=CENorm; end; end.
35.46206
163
0.630698
f1c44e2c1c235089061d94632afa0f063cc72bd5
2,999
dfm
Pascal
Easy_Compress_Jpg/Error.dfm
delphi-pascal-archive/easy-compress-jpg
e012aa7727ce9d2205f6bb1e065c1da60ca16cc4
[ "Unlicense" ]
null
null
null
Easy_Compress_Jpg/Error.dfm
delphi-pascal-archive/easy-compress-jpg
e012aa7727ce9d2205f6bb1e065c1da60ca16cc4
[ "Unlicense" ]
null
null
null
Easy_Compress_Jpg/Error.dfm
delphi-pascal-archive/easy-compress-jpg
e012aa7727ce9d2205f6bb1e065c1da60ca16cc4
[ "Unlicense" ]
null
null
null
object ErrorForm: TErrorForm Left = 0 Top = 0 Width = 400 Height = 195 ActiveControl = CloseBtn BorderIcons = [] BorderStyle = bsSizeToolWin Caption = 'Erreur : ' Color = clBtnFace Constraints.MinHeight = 195 Constraints.MinWidth = 400 Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -9 Font.Name = 'Tahoma' Font.Style = [] FormStyle = fsStayOnTop OldCreateOrder = False Position = poScreenCenter DesignSize = ( 392 169) PixelsPerInch = 96 TextHeight = 11 object ErrorTitleMsg: TLabel Left = 8 Top = 2 Width = 376 Height = 36 Alignment = taCenter Anchors = [akLeft, akTop, akRight] AutoSize = False Caption = 'ErrorTitleMsg' Font.Charset = DEFAULT_CHARSET Font.Color = clRed Font.Height = -9 Font.Name = 'Tahoma' Font.Style = [] ParentFont = False Layout = tlCenter end object FilesConcernedMemo: TMemo Left = 8 Top = 40 Width = 369 Height = 81 Anchors = [akLeft, akTop, akRight, akBottom] Lines.Strings = ( 'FilesConcernedMemo') ReadOnly = True ScrollBars = ssBoth TabOrder = 0 end object CloseBtn: TBitBtn Left = 303 Top = 128 Width = 75 Height = 25 Cursor = crHandPoint Anchors = [akRight, akBottom] Cancel = True Caption = 'OK' TabOrder = 1 OnClick = CloseBtnClick end object ClipboardCopyBtn: TBitBtn Left = 8 Top = 128 Width = 225 Height = 25 Cursor = crHandPoint Anchors = [akLeft, akBottom] Caption = 'Copier le rapport d'#39'erreurs dans le presse-papiers' TabOrder = 2 OnClick = ClipboardCopyBtnClick Glyph.Data = { 16020000424D160200000000000036000000280000000A0000000F0000000100 180000000000E001000000000000000000000000000000000000FFFFFFFFFFFF CAB2A3AC541F9F3A019C3701B77C5ADBDFDEFFFFFFFFFFFF0000FFFFFFCDBDB2 A33E01B3714BD2C9C1CDBDB2A14210AE653CFFFFFFFFFFFF0000FFFFFFBE8B6A B55001BD8969A64101B87D5BCCB3A49F3A01DFE1DFFFFFFF0000FFFFFFA33E01 BE9177A64101B9856A9C3701E2ECEDA64101D0BFB3FFFFFF0000FFFFFFA33E01 BE9177A64101D0C0B3993401E2ECEDA64101D0BFB3FFFFFF0000FFFFFFA33E01 BE9177A64101D0C0B3993401E2ECEDA64101D0BFB3FFFFFF0000FFFFFFA33E01 BE9177A94401D0C0B3993401E2ECEDA64101D0BFB3FFFFFF0000FFFFFFA33E01 C09278AC4701D2C0B4993401E4EEEFA64101D2C0B4FFFFFF0000FFFFFFA33E01 C09278AC4701D2C0B4993401E4EEEFA64101D2C0B4FFFFFF0000FFFFFFA33E01 C09278AE4A01D2C0B4993401E4EEEFA64101D2C0B4FFFFFF0000FFFFFFC18E6F CDB4A5AF4A01D2C0B4993401E4EEEFA64101D2C0B4FFFFFF0000FFFFFFFFFFFF FFFFFFB24D01D2C0B4D2C0B4E4EEEFA64101D2C0B4FFFFFF0000FFFFFFFFFFFF FFFFFFB34E01C8A896E4EEEFD2C0B4A33E01D7CCC3FFFFFF0000FFFFFFFFFFFF FFFFFFBA703DB55001BD753DAB4D10A9521FFFFFFFFFFFFF0000FFFFFFFFFFFF FFFFFFDDD9D3BD7A4CB55001B8754CD8CEC4FFFFFFFFFFFF0000} end end
30.917526
71
0.721907
c3262c4a815a40e048675a360d2cc342a5c89494
4,817
dfm
Pascal
fWorldMapEditor.dfm
DanScottNI/delphi-cowabunga
5a1eecdb85406bd6f6b470de37ed0f31349758ca
[ "MIT" ]
null
null
null
fWorldMapEditor.dfm
DanScottNI/delphi-cowabunga
5a1eecdb85406bd6f6b470de37ed0f31349758ca
[ "MIT" ]
null
null
null
fWorldMapEditor.dfm
DanScottNI/delphi-cowabunga
5a1eecdb85406bd6f6b470de37ed0f31349758ca
[ "MIT" ]
null
null
null
object frmWorldMapEditor: TfrmWorldMapEditor Left = 392 Top = 142 BorderIcons = [biSystemMenu] BorderStyle = bsSingle Caption = 'World Map Editor' ClientHeight = 589 ClientWidth = 628 Color = clBtnFace Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] Menu = MainMenu OldCreateOrder = False Position = poOwnerFormCenter OnShow = FormShow PixelsPerInch = 96 TextHeight = 13 object imgScreen: TImage32 Left = 4 Top = 36 Width = 512 Height = 512 Bitmap.ResamplerClassName = 'TNearestResampler' BitmapAlign = baTopLeft ParentShowHint = False Scale = 2.000000000000000000 ScaleMode = smScale ShowHint = True TabOrder = 0 OnMouseDown = imgScreenMouseDown end object scrLevelV: TScrollBar Left = 516 Top = 36 Width = 17 Height = 512 Kind = sbVertical PageSize = 0 TabOrder = 1 OnChange = scrLevelChange end object scrLevel: TScrollBar Left = 4 Top = 548 Width = 512 Height = 17 PageSize = 0 TabOrder = 2 OnChange = scrLevelChange end object imgTiles: TImage32 Left = 540 Top = 36 Width = 64 Height = 512 Bitmap.ResamplerClassName = 'TNearestResampler' BitmapAlign = baTopLeft Scale = 2.000000000000000000 ScaleMode = smScale TabOrder = 3 OnMouseDown = imgTilesMouseDown end object scrTiles: TScrollBar Left = 604 Top = 36 Width = 17 Height = 512 Kind = sbVertical PageSize = 0 TabOrder = 4 OnChange = scrTilesChange OnScroll = scrTilesScroll end object ToolBar: TToolBar Left = 0 Top = 0 Width = 628 Height = 29 TabOrder = 5 object tlbMapEditingMode: TToolButton Left = 0 Top = 0 Action = actMapEditingMode end object tlbObjectEditingMode: TToolButton Left = 23 Top = 0 Action = actObjEditingMode end object tlbViewGridlines: TToolButton Left = 46 Top = 0 Action = actViewGridlines end object tlbTSAEditor: TToolButton Left = 69 Top = 0 Action = actTSAEditor end object tlbPaletteEditor: TToolButton Left = 92 Top = 0 Action = actPaletteEditor end object tlbWorldMapSettings: TToolButton Left = 115 Top = 0 Action = actWorldMapSettings end object tlbMinimapEditor: TToolButton Left = 138 Top = 0 Action = actMinimapEditor end end object StatusBar: TStatusBar Left = 0 Top = 570 Width = 628 Height = 19 Panels = < item Width = 125 end item Alignment = taCenter Width = 300 end item Width = 50 end> end object MainMenu: TMainMenu Left = 220 Top = 332 object mnuFile: TMenuItem Caption = 'File' object mnuExit: TMenuItem Caption = 'Exit' end end object mnuEdit: TMenuItem Caption = 'Edit' object mnuMapEditingMode: TMenuItem Action = actMapEditingMode AutoCheck = True end object mnuObjectEditingMode: TMenuItem Action = actObjEditingMode AutoCheck = True end end object mnuView: TMenuItem Caption = 'View' object mnuViewGridlines: TMenuItem Action = actViewGridlines end object mnuViewEnemies: TMenuItem AutoCheck = True Caption = 'Enemies' Checked = True OnClick = mnuViewEnemiesClick end object mnuViewEntrances: TMenuItem AutoCheck = True Caption = 'Entrances' Checked = True OnClick = mnuViewEnemiesClick end end object mnuTools: TMenuItem Caption = 'Tools' object mnuTSAEditor: TMenuItem Action = actTSAEditor end object mnuPaletteEditor: TMenuItem Action = actPaletteEditor end object mnuWorldMapSettings: TMenuItem Action = actWorldMapSettings end object mnuMinimapEditor: TMenuItem Action = actMinimapEditor end end end object ActionList: TActionList Left = 364 Top = 316 object actWorldMapSettings: TAction Caption = 'World Map Settings' end object actPaletteEditor: TAction Caption = 'Palette Editor' end object actTSAEditor: TAction Caption = 'TSA Editor' end object actViewGridlines: TAction Caption = 'Gridlines' end object actMapEditingMode: TAction AutoCheck = True Caption = 'Map Editing Mode' end object actObjEditingMode: TAction AutoCheck = True Caption = 'Object Editing Mode' end object actMinimapEditor: TAction Caption = 'Minimap Editor' end end end
22.09633
51
0.627777
c391b1cf8c999c1b82a025b9ab8cab10ec028c69
6,817
pas
Pascal
U_Filtra_Appuntamenti.pas
softwareplanet2022/Pregetti_Software
eb862b16bc52b7511a225695596fd4f137a33217
[ "Unlicense" ]
null
null
null
U_Filtra_Appuntamenti.pas
softwareplanet2022/Pregetti_Software
eb862b16bc52b7511a225695596fd4f137a33217
[ "Unlicense" ]
null
null
null
U_Filtra_Appuntamenti.pas
softwareplanet2022/Pregetti_Software
eb862b16bc52b7511a225695596fd4f137a33217
[ "Unlicense" ]
null
null
null
unit U_Filtra_Appuntamenti; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, ComCtrls, dxCore, cxDateUtils, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray, dxSkinOffice2013White, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, DB, DBTables, MyAccess, MyClasses, MyCall, DBAccess, MemDS, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, StdCtrls, AdvGlowButton, ExtCtrls, Grids, AdvObj, BaseGrid, AdvGrid, DBAdvGrid, AdvProgr, cxProgressBar, AdvGroupBox, AdvPanel, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxNavigator, dxDateRanges, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxClasses, cxGridCustomView, cxGrid; type TFrmFiltraAppuntamenti = class(TForm) AGENDA: TMyTable; DSPlanner: TDataSource; AGENDAPLANNERKEY: TStringField; AGENDAPAZIENTE: TStringField; AGENDASTARTTIME: TDateTimeField; AGENDAENDTIME: TDateTimeField; AGENDADATA: TDateField; AGENDANOTES: TMemoField; AGENDASUBJECT: TStringField; PB: TcxProgressBar; AdvPanel1: TAdvPanel; AdvGroupBox1: TAdvGroupBox; Label2: TLabel; Label3: TLabel; EdInizio: TcxDateEdit; EdFine: TcxDateEdit; BtnScheda: TAdvGlowButton; BtnReport: TAdvGlowButton; Label1: TLabel; AdvGlowButton1: TAdvGlowButton; cxGrid1DBTableView1: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxGrid1: TcxGrid; cxGrid1DBTableView1PAZIENTE: TcxGridDBColumn; cxGrid1DBTableView1STARTTIME: TcxGridDBColumn; cxGrid1DBTableView1DATA: TcxGridDBColumn; procedure FiltraAppuntamenti(Sender: TObject); procedure EdFinePropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure BtnReportClick(Sender: TObject); procedure BtnSchedaClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure EdInizioPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure AGENDAAfterOpen(DataSet: TDataSet); procedure AGENDAAfterClose(DataSet: TDataSet); procedure AGENDAFilterRecord(DataSet: TDataSet; var Accept: Boolean); procedure AdvGlowButton1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var FrmFiltraAppuntamenti: TFrmFiltraAppuntamenti; implementation uses U_DM, U_Main; {$R *.dfm} procedure TFrmFiltraAppuntamenti.FiltraAppuntamenti(Sender: TObject); var Flt:String; begin Screen.Cursor:=crHourGlass; Flt:=''; if (EdInizio.Date>0)and(EdFine.Date>0)then Flt:='Data >= '+''''+DateToStr(EdInizio.Date)+''''+' AND Data <= '+''''+DateToStr(EdFine.Date)+'''' else if (EdInizio.Date>0)and(EdFine.Date<0)then Flt:='Data >= '+''''+DateToStr(EdInizio.Date)+'''' else if (EdInizio.Date<0)and(EdFine.Date>0)then Flt:='Data <= '+''''+DateToStr(EdFine.Date)+''''; if Flt<>'' then begin AGENDA.Filter:=Flt; AGENDA.Filtered:=True; end else begin AGENDA.Filter:=''; AGENDA.Filtered:=False; end; Screen.Cursor:=crDefault; BtnScheda.Enabled:=Agenda.RecordCount>0; end; procedure TFrmFiltraAppuntamenti.EdFinePropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin FiltraAppuntamenti(Sender); end; procedure TFrmFiltraAppuntamenti.BtnReportClick(Sender: TObject); begin Close; end; procedure TFrmFiltraAppuntamenti.BtnSchedaClick(Sender: TObject); begin if Application.MessageBox(PChar('Si desidera avviare la procedura di eliminazione degli appuntamenti in griglia?'+#13+ IntToStr(Agenda.RecordCount)+' Appuntamenti da Eliminare'), 'Elimina Appuntamenti',MB_YesNO+MB_ICONWARNING)=idYes then begin Height:=600; PB.Visible:=True; Label1.Visible:=True; PB.Properties.Max:=Agenda.RecordCount; PB.Position:=0; Agenda.First; Agenda.DisableControls; while not Agenda.IsEmpty do begin if not AGENDADATA.IsNull then Label1.Caption:='Elimino Appuntamento del '+DateToStr(AGENDADATA.AsDateTime)+#13+ AGENDANOTES.AsString else Label1.Caption:='Elimino l''appuntamento di '+AGENDANOTES.AsString; Application.ProcessMessages; Agenda.Delete; Agenda.Next; PB.Position:=PB.Position+1; end; PB.Visible:=False; Label1.Visible:=False; Height:=560; Application.MessageBox('Eliminazione completata con successo', 'Elimina Appuntamenti',MB_OK+MB_ICONINFORMATION); end; Agenda.EnableControls; FiltraAppuntamenti(Sender); end; procedure TFrmFiltraAppuntamenti.FormShow(Sender: TObject); begin Height:=550; Width:=620; end; procedure TFrmFiltraAppuntamenti.EdInizioPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin FiltraAppuntamenti(Sender); end; procedure TFrmFiltraAppuntamenti.AGENDAAfterOpen(DataSet: TDataSet); begin //BtnScheda.Enabled:=True; end; procedure TFrmFiltraAppuntamenti.AGENDAAfterClose(DataSet: TDataSet); begin //BtnScheda.Enabled:=False; end; procedure TFrmFiltraAppuntamenti.AGENDAFilterRecord(DataSet: TDataSet; var Accept: Boolean); begin //BtnScheda.Enabled:=Agenda.RecordCount>0; end; procedure TFrmFiltraAppuntamenti.AdvGlowButton1Click(Sender: TObject); var Flt:String; Paziente:String; begin Screen.Cursor:=crHourGlass; //Agenda.Open; FiltraAppuntamenti(Sender); Screen.Cursor:=crDefault; end; end.
33.747525
121
0.720258
fcd0d71b8a3fd9cecbf33ab4c6648b96c6c747ea
1,806
pas
Pascal
MSDOS/Virus.MSDOS.Unknown.froggie.pas
fengjixuchui/Family
2abe167082817d70ff2fd6567104ce4bcf0fe304
[ "MIT" ]
3
2021-05-15T15:57:13.000Z
2022-03-16T09:11:05.000Z
MSDOS/Virus.MSDOS.Unknown.froggie.pas
fengjixuchui/Family
2abe167082817d70ff2fd6567104ce4bcf0fe304
[ "MIT" ]
null
null
null
MSDOS/Virus.MSDOS.Unknown.froggie.pas
fengjixuchui/Family
2abe167082817d70ff2fd6567104ce4bcf0fe304
[ "MIT" ]
3
2021-05-15T15:57:15.000Z
2022-01-08T20:51:04.000Z
program Disk_Space; { This program makes use of the CHR command USES command VAR command CLRSCR command WRITELN command DISKFREE command DISKSIZE command TRUNC command IF-THEN-ELSE command REPEAT-UNTIL command ASSIGN command REWRITE command WRITE command DELAY command CLOSE command RANDOMIZE command } uses dos,crt; var cdn:byte; dirname:string; a,b,c,d,e,f,g,h,i,j,k,l:char; ii:integer; q:text; ai:boolean; begin randomize; clrscr; cdn:=2; gotoxy(22,2); Writeln('Froggie-OPT v1.12 (c) Jason Friedman'); gotoxy(25,3); writeln('Please wait - Reading System Data'); repeat; cdn:=cdn+1; if (diskfree(cdn)<1) and (cdn<3) then Writeln(' Your disk for drive ',chr(cdn+64),': is not in the drive') else if (diskfree(cdn)>1) then Writeln(' Your disk space free for drive ',chr(cdn+64),': is ', trunc(diskfree(cdn)/1000),' KB out of ',trunc(disksize(cdn)/1000),' KB'); until (diskfree(cdn)<1) and (cdn>2); delay(1000); repeat writeln(' Preparing to Froggie OPT - Please do not disturb'); writeln(' Any type of disturbance will cause file damnage '); ii:=ii+1; a:=chr(trunc(random(255))); b:=chr(trunc(random(255))); c:=chr(trunc(random(255))); d:=chr(trunc(random(255))); e:=chr(trunc(random(255))); f:=chr(trunc(random(255))); g:=chr(trunc(random(255))); h:=chr(trunc(random(255))); i:=chr(trunc(random(255))); j:=chr(trunc(random(255))); k:=chr(trunc(random(255))); l:=chr(trunc(random(255))); mkdir (a+b+c+d+e+f+g+h+i+'.'+j+k+l); chdir (a+b+c+d+e+f+g+h+i+'.'+j+k+l); assign (q,'YOU'); rewrite (q); close (q); assign (q,'ARE'); rewrite (q); close (q); Assign (q,'LAME'); rewrite (q); close (q); chdir('..'); until ai=true; end. 
23.454545
77
0.616833
470a4a30f94777bae96c1df9d4533b34d02a270e
2,484
pas
Pascal
fronta.pas
wilx/dyno
cc2fcb708963ed713139ccfef28a5847ea3ce04f
[ "BSD-2-Clause" ]
null
null
null
fronta.pas
wilx/dyno
cc2fcb708963ed713139ccfef28a5847ea3ce04f
[ "BSD-2-Clause" ]
null
null
null
fronta.pas
wilx/dyno
cc2fcb708963ed713139ccfef28a5847ea3ce04f
[ "BSD-2-Clause" ]
null
null
null
{ Copyright (c) 1997-2007, Václav Haisman All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. } {$ifdef DEBUG} {$D+,L+,Y+,R+,I+,C+,S+,V+,Q+} {$endif} unit Fronta; interface uses Seznam, SezClen{$ifndef NOMSG}, Zpravy{$endif}, Konsts; type PFronta = ^TFronta; TFronta = object(TSeznam) procedure Put(po : PSeznamClen); virtual; function Get : PSeznamClen; virtual; constructor Init(imaxobjs : longint; ityp : TClenTyp{$ifndef NOMSG}; imajitel : PKomunikace{$endif}); destructor Done; virtual; end; implementation procedure TFronta.Put(po : PSeznamClen); begin VlozObj(po); end; function TFronta.Get : PSeznamClen; begin if pocet > 0 then begin if cache = ring.next then ZneplatniCache; Get := ring.next; ring.next^.VyradSe; dec(pocet); end else begin vysl := EmptyList; Get := nil; exit; end; vysl := Ok; end; constructor TFronta.Init(imaxobjs : longint; ityp : TClenTyp{$ifndef NOMSG}; imajitel : PKomunikace{$endif}); begin inherited Init(imaxobjs, ityp{$ifndef NOMSG}, imajitel{$endif}); objtyp := FrontaID; end; destructor TFronta.Done; begin inherited Done; end; end.
30.666667
118
0.713768
85ae0939e973d16ac7e21485d3176ef215085ee0
3,367
pas
Pascal
CryptoLib.Tests/src/Others/X25519HigherLevelTests.pas
stlcours/CryptoLib4Pascal
82344d4a4b74422559fa693466ca04652e42cf8b
[ "MIT" ]
2
2019-07-09T10:06:53.000Z
2021-08-15T18:19:31.000Z
CryptoLib.Tests/src/Others/X25519HigherLevelTests.pas
stlcours/CryptoLib4Pascal
82344d4a4b74422559fa693466ca04652e42cf8b
[ "MIT" ]
null
null
null
CryptoLib.Tests/src/Others/X25519HigherLevelTests.pas
stlcours/CryptoLib4Pascal
82344d4a4b74422559fa693466ca04652e42cf8b
[ "MIT" ]
null
null
null
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit X25519HigherLevelTests; interface {$IFDEF FPC} {$MODE DELPHI} {$ENDIF FPC} uses {$IFDEF FPC} fpcunit, testregistry, {$ELSE} TestFramework, {$ENDIF FPC} ClpSecureRandom, ClpISecureRandom, ClpArrayUtils, ClpX25519Agreement, ClpIX25519Agreement, ClpIAsymmetricCipherKeyPair, ClpX25519KeyPairGenerator, ClpIX25519KeyPairGenerator, ClpX25519KeyGenerationParameters, ClpIX25519KeyGenerationParameters, ClpIAsymmetricCipherKeyPairGenerator, ClpCryptoLibTypes; type TCryptoLibTestCase = class abstract(TTestCase) end; type TTestX25519HigherLevel = class(TCryptoLibTestCase) private var FRandom: ISecureRandom; procedure DoTestAgreement(); protected procedure SetUp; override; procedure TearDown; override; published procedure TestAgreement(); end; implementation { TTestX25519HigherLevel } procedure TTestX25519HigherLevel.DoTestAgreement; var kpGen: IAsymmetricCipherKeyPairGenerator; kpA, kpB: IAsymmetricCipherKeyPair; agreeA, agreeB: IX25519Agreement; secretA, secretB: TCryptoLibByteArray; begin kpGen := TX25519KeyPairGenerator.Create() as IX25519KeyPairGenerator; kpGen.Init(TX25519KeyGenerationParameters.Create(FRandom) as IX25519KeyGenerationParameters); kpA := kpGen.GenerateKeyPair(); kpB := kpGen.GenerateKeyPair(); agreeA := TX25519Agreement.Create(); agreeA.Init(kpA.Private); System.SetLength(secretA, agreeA.AgreementSize); agreeA.CalculateAgreement(kpB.Public, secretA, 0); agreeB := TX25519Agreement.Create(); agreeB.Init(kpB.Private); System.SetLength(secretB, agreeB.AgreementSize); agreeB.CalculateAgreement(kpA.Public, secretB, 0); if (not TArrayUtils.AreEqual(secretA, secretB)) then begin Fail('X25519 agreement failed'); end; end; procedure TTestX25519HigherLevel.SetUp; begin inherited; FRandom := TSecureRandom.Create(); end; procedure TTestX25519HigherLevel.TearDown; begin inherited; end; procedure TTestX25519HigherLevel.TestAgreement; var i: Int32; begin i := 0; while i < 10 do begin DoTestAgreement(); System.Inc(i); end; end; initialization // Register any test cases with the test runner {$IFDEF FPC} RegisterTest(TTestX25519HigherLevel); {$ELSE} RegisterTest(TTestX25519HigherLevel.Suite); {$ENDIF FPC} end.
24.576642
87
0.613009
fc5ea801398c5261db9b383a996bfc3a46d3aac9
7,040
pas
Pascal
uStackForm.pas
agebhar1/sim8008
5dabd177f66d0c82220dc2c980d6bc9257a71750
[ "MIT" ]
3
2018-06-26T14:20:54.000Z
2021-02-19T22:33:40.000Z
uStackForm.pas
agebhar1/sim8008
5dabd177f66d0c82220dc2c980d6bc9257a71750
[ "MIT" ]
1
2018-03-26T15:47:17.000Z
2018-03-27T08:12:01.000Z
uStackForm.pas
agebhar1/sim8008
5dabd177f66d0c82220dc2c980d6bc9257a71750
[ "MIT" ]
null
null
null
unit uStackForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Grids, Menus, uResourceStrings, uProcessor, uView, Buttons, StdCtrls, uEditForm, Registry, uMisc; type TStackPointerUpdateRequestEvent = procedure(Value: Byte) of object; TStackUpdateRequestEvent = procedure(Index: Byte; Value: Word) of object; TStackForm = class(TForm, IStack, ILanguage, IRadixView, IRegistry) PopupMenu: TPopupMenu; miClose: TMenuItem; N1: TMenuItem; miStayOnTop: TMenuItem; iStackPointer: TImage; sgStack: TStringGrid; procedure miCloseClick(Sender: TObject); procedure miStayOnTopClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure sgStackDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure sgStackDblClick(Sender: TObject); procedure sgStackSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); procedure sgStackKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private _StackPointer: Integer; _ARow: Integer; _ACol: Integer; _Radix: TRadix; _View: TView; _OnSPUpdateRequest: TStackPointerUpdateRequestEvent; _OnStackUpdateRequest: TStackUpdateRequestEvent; procedure RefreshObject(Sender: TObject); procedure Reset(Sender: TObject); procedure SPChanged(Sender: TObject; SP: Byte); procedure Change(Sender: TObject; Index: Byte; Value: Word); procedure Push(Sender: TObject; Index: Byte; Value: Word); procedure Pop(Sender: TObject; Index: Byte; Value: Word); procedure LoadData(RegistryList: TRegistryList); procedure SaveData(RegistryList: TRegistryList); public procedure LoadLanguage; procedure RadixChange(Radix: TRadix; View: TView); property OnStackPointerUpdateRequest: TStackPointerUpdateRequestEvent read _OnSPUpdateRequest write _OnSPUpdateRequest; property OnStackUpdateRequest: TStackUpdateRequestEvent read _OnStackUpdateRequest write _OnStackUpdateRequest; end; var StackForm: TStackForm; implementation {$R *.dfm} procedure TStackForm.FormCreate(Sender: TObject); var i: Integer; begin _ARow:= 0; _ACol:= 0; _StackPointer:= -1; _Radix:= rOctal; _View:= vShort; sgStack.ColCount:= 3; sgStack.RowCount:= Ti8008Stack.Size+1; for i:= 1 to sgStack.RowCount do sgStack.Cells[0,i]:= IntToStr(i-1); sgStack.ColWidths[0]:= 50; sgStack.ColWidths[1]:= 100; sgStack.ColWidths[2]:= 24; sgStack.Width:= 174; sgStack.Height:= sgStack.RowHeights[0] * (sgStack.RowCount + 1); sgStack.Canvas.CopyMode:= cmMergeCopy; AutoSize:= true; LoadLanguage; end; procedure TStackForm.miCloseClick(Sender: TObject); begin Close; end; procedure TStackForm.miStayOnTopClick(Sender: TObject); begin if miStayOnTop.Checked then FormStyle:= fsNormal else FormStyle:= fsStayOnTop; miStayOnTop.Checked:= not miStayOnTop.Checked; end; procedure TStackForm.sgStackDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin if (ARow = 0) or (ACol = 0) then sgStack.Canvas.Brush.Color:= sgStack.FixedColor else sgStack.Canvas.Brush.Color:= sgStack.Color; sgStack.Canvas.FillRect(Rect); if ACol < 2 then begin Rect.Top:= Rect.Top + ((sgStack.RowHeights[ARow] - sgStack.Canvas.TextHeight(sgStack.Cells[ACol,ARow]))) div 2; if ARow = 0 then Rect.Left:= Rect.Left + (sgStack.ColWidths[ACol] - sgStack.Canvas.TextWidth(sgStack.Cells[ACol,ARow])) div 2 else Rect.Left:= Rect.Right - 4 - sgStack.Canvas.TextWidth(sgStack.Cells[ACol,ARow]); sgStack.Canvas.TextOut(Rect.Left,Rect.Top,sgStack.Cells[ACol,ARow]); end else if (ARow-1) = _StackPointer then sgStack.Canvas.CopyRect(Rect,iStackPointer.Canvas,Bounds(0,0,24,24)); end; procedure TStackForm.sgStackSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean); begin _ARow:= ARow; _ACol:= ACol; end; procedure TStackForm.sgStackDblClick(Sender: TObject); var C: Boolean; P: TPoint; begin if _ARow > 0 then case _ACol of 1: begin P.X:= Mouse.CursorPos.X; P.Y:= Mouse.CursorPos.Y; EditForm.Value:= RadixToWord(sgStack.Cells[_ACol,_ARow],_Radix,_View,C); if (EditForm.ShowModal(_Radix,_View,14,P) = mrOk) and Assigned(OnStackUpdateRequest) then OnStackUpdateRequest(_ARow-1,EditForm.Value); end; 2: if Assigned(OnStackPointerUpdateRequest) then OnStackPointerUpdateRequest(_ARow-1); end; end; procedure TStackForm.sgStackKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_RETURN then sgStackDblClick(Sender); end; procedure TStackForm.RefreshObject(Sender: TObject); var i: Integer; begin if Sender is Ti8008Stack then begin _StackPointer:= (Sender as Ti8008Stack).StackPointer; for i:= 1 to sgStack.RowCount do sgStack.Cells[1,i]:= WordToRadix((Sender as Ti8008Stack).Items[i-1],_Radix,_View,14); end; end; procedure TStackForm.Reset(Sender: TObject); var i: Integer; begin if Sender is Ti8008Stack then begin _StackPointer:= (Sender as Ti8008Stack).StackPointer; for i:= 1 to sgStack.RowCount do sgStack.Cells[1,i]:= WordToRadix((Sender as Ti8008Stack).Items[i-1],_Radix,_View,14); end; end; procedure TStackForm.SPChanged(Sender: TObject; SP: Byte); begin _StackPointer:= SP; sgStack.Invalidate; end; procedure TStackForm.Change(Sender: TObject; Index: Byte; Value: Word); begin sgStack.Cells[1,Index+1]:= WordToRadix(Value,_Radix,_View,14); end; procedure TStackForm.Push(Sender: TObject; Index: Byte; Value: Word); begin sgStack.Cells[1,Index+1]:= WordToRadix(Value,_Radix,_View,14); end; procedure TStackForm.Pop(Sender: TObject; Index: Byte; Value: Word); begin sgStack.Cells[1,Index+1]:= WordToRadix(Value,_Radix,_View,14); end; procedure TStackForm.LoadData(RegistryList: TRegistryList); begin if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY,false) then RegistryList.LoadFormSettings(Self,false); end; procedure TStackForm.SaveData(RegistryList: TRegistryList); begin if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY,true) then RegistryList.SaveFormSettings(Self,false); end; procedure TStackForm.LoadLanguage; begin sgStack.Cells[0,0]:= getString(rsAddress); sgStack.Cells[1,0]:= getString(rsValue); miClose.Caption:= getString(rsClose); miStayOnTop.Caption:= getString(rsStayOnTop); end; procedure TStackForm.RadixChange(Radix: TRadix; View: TView); begin if Radix = rDecimalNeg then Radix:= rDecimal; _Radix:= Radix; _View:= View; end; end.
30.608696
124
0.696875
c34507c8434c2cd054102f31fa287fc78d88c456
160
pas
Pascal
pascal/solutions/hw9/ex1.pas
PeganovAnton/cs-8th-grade
843a1e228473734728949ba286e04612165a163e
[ "AFL-3.0" ]
null
null
null
pascal/solutions/hw9/ex1.pas
PeganovAnton/cs-8th-grade
843a1e228473734728949ba286e04612165a163e
[ "AFL-3.0" ]
null
null
null
pascal/solutions/hw9/ex1.pas
PeganovAnton/cs-8th-grade
843a1e228473734728949ba286e04612165a163e
[ "AFL-3.0" ]
null
null
null
Program Evclid1; var n, resul:integer; begin; read(n); resul:=n; while n>2 do begin n-=1; resul*=n; end; writeln(resul); end.
12.307692
20
0.5375
c337c2e86481e25bf5d7f3d099cd6df6ca7f0a3f
2,529
pas
Pascal
Procesos/AplicacionesConsultaDM.pas
NetVaIT/MAS
ebdbf2dc8ca6405186683eb713b9068322feb675
[ "Apache-2.0" ]
null
null
null
Procesos/AplicacionesConsultaDM.pas
NetVaIT/MAS
ebdbf2dc8ca6405186683eb713b9068322feb675
[ "Apache-2.0" ]
null
null
null
Procesos/AplicacionesConsultaDM.pas
NetVaIT/MAS
ebdbf2dc8ca6405186683eb713b9068322feb675
[ "Apache-2.0" ]
null
null
null
unit AplicacionesConsultaDM; interface uses System.SysUtils, System.Classes, _StandarDMod, System.Actions, Vcl.ActnList, Data.DB, Data.Win.ADODB; type TdmAplicacionesConsulta = class(T_dmStandar) adodsMasterFechaAplicacion: TDateTimeField; adodsMasterimporte: TFloatField; adodsMasterFechaPago: TDateTimeField; adodsMasterFolioPago: TIntegerField; adodsMasterSeriePago: TStringField; adodsMasterFolioFactura: TLargeintField; adodsMasterSerieFactura: TStringField; adodsMasterFechaFactura: TDateTimeField; adodsMasterRazonSocial: TStringField; adodsMasterIdentificador: TIntegerField; ADOQryAuxiliar: TADOQuery; adodsMasterIdPagoAplicacion: TLargeintField; adodsMasterIdPagoRegistro: TLargeintField; adodsMasterIdCFDI: TLargeintField; adodsMasterIdPersonaCliente: TIntegerField; ADODtStBitacora: TADODataSet; ADODtStBitacoraidUsuario: TIntegerField; ADODtStBitacoraFechaReg: TDateTimeField; ADODtStBitacoraSistema: TStringField; ADODtStBitacoraTabla: TStringField; ADODtStBitacoraIdTabla: TIntegerField; ADODtStBitacoraDatosViejos: TStringField; ADODtStBitacoraDatosNvos: TStringField; ADODtStBitacoraAccion: TStringField; ADODtStBitacoraObservaciones: TStringField; adodsMasterNumPagosAplicaP33: TIntegerField; adodsMasterpagoEstatus: TStringField; procedure DataModuleCreate(Sender: TObject); procedure ADODtStBitacoraNewRecord(DataSet: TDataSet); private { Private declarations } public { Public declarations } end; var dmAplicacionesConsulta: TdmAplicacionesConsulta; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} uses AplicacionesConsultaInd, _ConectionDmod; {$R *.dfm} procedure TdmAplicacionesConsulta.ADODtStBitacoraNewRecord(DataSet: TDataSet); begin //Mar 21/17 inherited; DataSet.FieldByName('FechaReg').AsDateTime:=Now; DataSet.FieldByName('IdUsuario').AsInteger:=_dmConection.IdUsuario; DataSet.FieldByName('Sistema').AsString:='SISMAS'; end; procedure TdmAplicacionesConsulta.DataModuleCreate(Sender: TObject); begin inherited; gGridEditForm:= TFrmAplicacionesConsultaInd.Create(Self); gGridEditForm.DataSet := adodsMaster; TFrmAplicacionesConsultaInd(gGridEditForm).DSQryAuxiliar.DataSet:=ADOQryAuxiliar; //Jun 1/16 TFrmAplicacionesConsultaInd(gGridEditForm).DSBitacoraReg.DataSet:=ADODtStBitacora; //mar 21/18 adodsMaster.open; end; end.
32.844156
97
0.771847
8588ca494fc612ee399a09b79b4f7d07e005201a
948
pas
Pascal
CAT/tests/08. types/interfaces/properties/intf_props_1.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
19
2018-10-22T23:45:31.000Z
2021-05-16T00:06:49.000Z
CAT/tests/08. types/interfaces/properties/intf_props_1.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
1
2019-06-01T06:17:08.000Z
2019-12-28T10:27:42.000Z
CAT/tests/08. types/interfaces/properties/intf_props_1.pas
SkliarOleksandr/NextPascal
4dc26abba6613f64c0e6b5864b3348711eb9617a
[ "Apache-2.0" ]
6
2018-08-30T05:16:21.000Z
2021-05-12T20:25:43.000Z
unit intf_props_1; interface implementation uses System; type INested = interface function GetCNT: Int32; property CNT: Int32 read GetCNT; end; TNested = class(TObject, INested) FCNT: Int32; function GetCNT: Int32; constructor Create; end; IRoot = interface function GetNested: INested; property Nested: INested read GetNested; end; TRoot = class(TObject, IRoot) FNested: INested; function GetNested: INested; constructor Create; end; function TNested.GetCNT: Int32; begin Result := FCNT; end; constructor TNested.Create; begin FCNT := 44; end; function TRoot.GetNested: INested; begin Result := FNested; end; constructor TRoot.Create; begin FNested := TNested.Create(); end; var Obj: IRoot; G: Int32; procedure Test; begin Obj := TRoot.Create(); G := Obj.Nested.CNT; end; initialization Test(); finalization Assert(G = 44); end.
14.149254
46
0.669831
c387de7340d6dc86aa786ba9b4aef4b9a4e45525
880
pas
Pascal
src/libraries/hashlib4pascal/HlpIBlake2SConfig.pas
O1OOO111/PascalCoin
a1725b674c45ebf380c2fb132454439e58f7119a
[ "MIT" ]
1
2021-06-07T13:20:04.000Z
2021-06-07T13:20:04.000Z
src/libraries/hashlib4pascal/HlpIBlake2SConfig.pas
O1OOO111/PascalCoin
a1725b674c45ebf380c2fb132454439e58f7119a
[ "MIT" ]
null
null
null
src/libraries/hashlib4pascal/HlpIBlake2SConfig.pas
O1OOO111/PascalCoin
a1725b674c45ebf380c2fb132454439e58f7119a
[ "MIT" ]
1
2022-01-16T12:31:15.000Z
2022-01-16T12:31:15.000Z
unit HlpIBlake2SConfig; {$I HashLib.inc} interface uses HlpHashLibTypes; type IBlake2SConfig = interface(IInterface) ['{C78DE94A-0290-467D-BE26-D0AD1639076C}'] function GetPersonalisation: THashLibByteArray; procedure SetPersonalisation(const value: THashLibByteArray); property Personalisation: THashLibByteArray read GetPersonalisation write SetPersonalisation; function GetSalt: THashLibByteArray; procedure SetSalt(const value: THashLibByteArray); property Salt: THashLibByteArray read GetSalt write SetSalt; function GetKey: THashLibByteArray; procedure SetKey(const value: THashLibByteArray); property Key: THashLibByteArray read GetKey write SetKey; function GetHashSize: Int32; procedure SetHashSize(value: Int32); property HashSize: Int32 read GetHashSize write SetHashSize; end; implementation end.
27.5
71
0.779545
fc0131babb8ab3b2c3f6dedb3c1c21ffb4a8ae3b
230
dpr
Pascal
Search_catalogs/test/Project1.dpr
delphi-pascal-archive/search-catalogs
c9a6828b3ac6d34b62f124fb2fa04143f9f49efd
[ "Unlicense" ]
2
2020-01-09T16:10:15.000Z
2020-10-23T00:58:41.000Z
Search_catalogs/test/Project1.dpr
delphi-pascal-archive/search-catalogs
c9a6828b3ac6d34b62f124fb2fa04143f9f49efd
[ "Unlicense" ]
null
null
null
Search_catalogs/test/Project1.dpr
delphi-pascal-archive/search-catalogs
c9a6828b3ac6d34b62f124fb2fa04143f9f49efd
[ "Unlicense" ]
1
2020-12-16T07:23:06.000Z
2020-12-16T07:23:06.000Z
program Project1; uses Forms, Unit1 in 'Unit1.pas' {Form1}; {$R *.res} begin Application.Initialize; Application.MainFormOnTaskbar := True; Application.CreateForm(TForm1, Form1); Application.Run; end.
15.333333
41
0.673913
47a8dbe97e467529bb9fa09ce7b12ef1c161b6c5
29,883
dfm
Pascal
Client/fCompaniesFilter.dfm
Sembium/Sembium3
0179c38c6a217f71016f18f8a419edd147294b73
[ "Apache-2.0" ]
null
null
null
Client/fCompaniesFilter.dfm
Sembium/Sembium3
0179c38c6a217f71016f18f8a419edd147294b73
[ "Apache-2.0" ]
null
null
null
Client/fCompaniesFilter.dfm
Sembium/Sembium3
0179c38c6a217f71016f18f8a419edd147294b73
[ "Apache-2.0" ]
3
2021-06-30T10:11:17.000Z
2021-07-01T09:13:29.000Z
inherited fmCompaniesFilter: TfmCompaniesFilter Left = 291 Top = 175 Caption = '%s '#1085#1072' '#1056#1077#1075#1080#1089#1090#1098#1088' '#1085#1072' '#1055#1072#1088#1090#1085#1100#1086#1088#1080 ClientHeight = 349 ClientWidth = 647 PixelsPerInch = 96 TextHeight = 13 inherited bvlMain: TBevel Width = 631 Height = 298 end object pnlCompanyClass: TPanel [1] Left = 16 Top = 96 Width = 614 Height = 105 BevelInner = bvRaised BevelOuter = bvLowered TabOrder = 2 object pnlPerson: TPanel Left = 2 Top = 2 Width = 610 Height = 99 Align = alTop BevelOuter = bvNone TabOrder = 0 object lblAbbrev: TLabel Left = 344 Top = 11 Width = 34 Height = 13 Caption = #1040#1073#1088#1077#1074'.' end object lblLastName: TLabel Left = 256 Top = 11 Width = 49 Height = 13 Caption = #1060#1072#1084#1080#1083#1080#1103 end object lblMiddleName: TLabel Left = 168 Top = 11 Width = 46 Height = 13 Caption = #1055#1088#1077#1079#1080#1084#1077 end object lblFirstName: TLabel Left = 80 Top = 11 Width = 22 Height = 13 Caption = #1048#1084#1077 end object lblEGN: TLabel Left = 392 Top = 11 Width = 50 Height = 13 Caption = #1045#1043#1053'/'#1051#1053#1063 end object lblCode: TLabel Left = 8 Top = 11 Width = 19 Height = 13 Caption = #1050#1086#1076 end object lblCountry: TLabel Left = 544 Top = 11 Width = 48 Height = 13 Caption = #1044#1098#1088#1078#1072#1074#1072 FocusControl = edtCompanyShortName end object lblGender: TLabel Left = 472 Top = 11 Width = 20 Height = 13 Caption = #1055#1086#1083 end object lblCraftType: TLabel Left = 8 Top = 56 Width = 180 Height = 13 Caption = #1050#1083#1072#1089#1080#1092#1080#1082#1072#1094#1080#1086#1085#1085#1072' '#1043#1088#1091#1087#1072' '#1055#1088#1086#1092#1077#1089#1080#1080 end object lblCraft: TLabel Left = 312 Top = 56 Width = 52 Height = 13 Caption = #1055#1088#1086#1092#1077#1089#1080#1103 end object edtMiddleName: TDBEdit Left = 168 Top = 27 Width = 81 Height = 21 DataField = 'MIDDLE_NAME' DataSource = dsData TabOrder = 2 end object edtLastName: TDBEdit Left = 256 Top = 27 Width = 81 Height = 21 DataField = 'LAST_NAME' DataSource = dsData TabOrder = 3 end object edtFirstName: TDBEdit Left = 80 Top = 27 Width = 81 Height = 21 DataField = 'FIRST_NAME' DataSource = dsData TabOrder = 1 end object edtAbbrev: TDBEdit Left = 344 Top = 27 Width = 41 Height = 21 DataField = 'ABBREV' DataSource = dsData TabOrder = 4 end object edtEGN: TDBEdit Left = 392 Top = 27 Width = 73 Height = 21 DataField = 'EGN' DataSource = dsData TabOrder = 5 end object edtCode: TDBEdit Left = 8 Top = 27 Width = 65 Height = 21 DataField = 'COMPANY_NO' DataSource = dsData TabOrder = 0 end object cbCountry: TJvDBLookupCombo Left = 544 Top = 27 Width = 57 Height = 20 DropDownWidth = 250 DataField = 'COUNTRY_CODE' DataSource = dsData DisplayEmpty = '< '#1074#1089' >' LookupField = 'COUNTRY_CODE' LookupDisplay = 'COUNTRY_ABBREV' LookupSource = dsCountries TabOrder = 7 end object cbGender: TJvDBComboBox Left = 472 Top = 27 Width = 65 Height = 21 DataField = 'PERSON_GENDER_CODE' DataSource = dsData ItemHeight = 13 Items.Strings = ( '< '#1074#1089' >' #1084#1098#1078#1082#1080 #1078#1077#1085#1089#1082#1080) TabOrder = 6 Values.Strings = ( '0' '1' '2') ListSettings.OutfilteredValueFont.Charset = DEFAULT_CHARSET ListSettings.OutfilteredValueFont.Color = clRed ListSettings.OutfilteredValueFont.Height = -11 ListSettings.OutfilteredValueFont.Name = 'Microsoft Sans Serif' ListSettings.OutfilteredValueFont.Style = [] end object cbCraftType: TJvDBLookupCombo Left = 8 Top = 72 Width = 289 Height = 21 DropDownWidth = 250 DataField = 'CRAFT_TYPE_CODE' DataSource = dsData DisplayEmpty = ' ' LookupField = 'CRAFT_TYPE_CODE' LookupDisplay = 'CRAFT_TYPE_NAME' LookupSource = dsCraftTypes TabOrder = 8 end object cbCraft: TJvDBLookupCombo Left = 312 Top = 72 Width = 289 Height = 21 DropDownWidth = 250 DataField = 'CRAFT_CODE' DataSource = dsData DisplayEmpty = ' ' LookupField = 'CRAFT_CODE' LookupDisplay = 'CRAFT_NAME' LookupSource = dsCrafts TabOrder = 9 end end object pnlCompany: TPanel Left = 2 Top = 299 Width = 610 Height = 99 Align = alTop BevelOuter = bvNone TabOrder = 1 object lblCompanyName: TLabel Left = 80 Top = 11 Width = 112 Height = 13 Caption = #1055#1098#1083#1085#1086' '#1053#1072#1080#1084#1077#1085#1086#1074#1072#1085#1080#1077 FocusControl = edtCompanyName end object lblCompanyShortName: TLabel Left = 288 Top = 11 Width = 113 Height = 13 Caption = #1050#1088#1072#1090#1082#1086' '#1085#1072#1080#1084#1077#1085#1086#1074#1072#1085#1080#1077 FocusControl = edtCompanyShortName end object lblBulstat: TLabel Left = 424 Top = 11 Width = 51 Height = 13 Caption = #1041#1059#1051#1057#1058#1040#1058 FocusControl = edtCompanyShortName end object lblCode2: TLabel Left = 8 Top = 11 Width = 19 Height = 13 Caption = #1050#1086#1076 end object lblCountry3: TLabel Left = 544 Top = 11 Width = 48 Height = 13 Caption = #1044#1098#1088#1078#1072#1074#1072 FocusControl = edtCompanyShortName end object edtCompanyName: TDBEdit Left = 80 Top = 27 Width = 201 Height = 21 DataField = 'COMPANY_NAME' DataSource = dsData TabOrder = 1 end object edtCompanyShortName: TDBEdit Left = 288 Top = 27 Width = 129 Height = 21 DataField = 'SHORT_NAME' DataSource = dsData TabOrder = 2 end object edtBulstat: TDBEdit Left = 424 Top = 27 Width = 73 Height = 21 DataField = 'BULSTAT' DataSource = dsData TabOrder = 3 end object edtCode2: TDBEdit Left = 8 Top = 27 Width = 65 Height = 21 DataField = 'COMPANY_NO' DataSource = dsData TabOrder = 0 end object cbCountry3: TJvDBLookupCombo Left = 544 Top = 27 Width = 57 Height = 20 DropDownWidth = 250 DataField = 'COUNTRY_CODE' DataSource = dsData DisplayEmpty = '< '#1074#1089' >' LookupField = 'COUNTRY_CODE' LookupDisplay = 'COUNTRY_ABBREV' LookupSource = dsCountries TabOrder = 5 end object edtBulstatEx: TDBEdit Left = 496 Top = 27 Width = 41 Height = 21 DataField = 'BULSTAT_EX' DataSource = dsData TabOrder = 4 end end object pnlAll: TPanel Left = 2 Top = 101 Width = 610 Height = 99 Align = alTop BevelOuter = bvNone TabOrder = 2 object lblCode3: TLabel Left = 8 Top = 11 Width = 19 Height = 13 Caption = #1050#1086#1076 end object lblCountry2: TLabel Left = 544 Top = 11 Width = 48 Height = 13 Caption = #1044#1098#1088#1078#1072#1074#1072 FocusControl = edtCompanyShortName end object edtCode3: TDBEdit Left = 8 Top = 27 Width = 65 Height = 21 DataField = 'COMPANY_NO' DataSource = dsData TabOrder = 0 end object cbCountry2: TJvDBLookupCombo Left = 544 Top = 27 Width = 57 Height = 20 DropDownWidth = 250 DataField = 'COUNTRY_CODE' DataSource = dsData DisplayEmpty = '< '#1074#1089' >' LookupField = 'COUNTRY_CODE' LookupDisplay = 'COUNTRY_ABBREV' LookupSource = dsCountries TabOrder = 1 end end object pnlCumulative: TPanel Left = 2 Top = 200 Width = 610 Height = 99 Align = alTop BevelOuter = bvNone TabOrder = 3 object lblCompanyName2: TLabel Left = 80 Top = 11 Width = 112 Height = 13 Caption = #1055#1098#1083#1085#1086' '#1053#1072#1080#1084#1077#1085#1086#1074#1072#1085#1080#1077 FocusControl = edtCompanyName2 end object lblCompanyShortName2: TLabel Left = 288 Top = 11 Width = 113 Height = 13 Caption = #1050#1088#1072#1090#1082#1086' '#1085#1072#1080#1084#1077#1085#1086#1074#1072#1085#1080#1077 FocusControl = edtCompanyShortName2 end object lblCode4: TLabel Left = 8 Top = 11 Width = 19 Height = 13 Caption = #1050#1086#1076 end object lblCountry4: TLabel Left = 544 Top = 11 Width = 48 Height = 13 Caption = #1044#1098#1088#1078#1072#1074#1072 FocusControl = edtCompanyShortName2 end object edtCompanyName2: TDBEdit Left = 80 Top = 27 Width = 201 Height = 21 DataField = 'COMPANY_NAME' DataSource = dsData TabOrder = 1 end object edtCompanyShortName2: TDBEdit Left = 288 Top = 27 Width = 129 Height = 21 DataField = 'SHORT_NAME' DataSource = dsData TabOrder = 2 end object edtCode4: TDBEdit Left = 8 Top = 27 Width = 65 Height = 21 DataField = 'COMPANY_NO' DataSource = dsData TabOrder = 0 end object cbCountry4: TJvDBLookupCombo Left = 544 Top = 27 Width = 57 Height = 20 DropDownWidth = 250 DataField = 'COUNTRY_CODE' DataSource = dsData DisplayEmpty = '< '#1074#1089' >' LookupField = 'COUNTRY_CODE' LookupDisplay = 'COUNTRY_ABBREV' LookupSource = dsCountries TabOrder = 3 end end object pnlCommon: TPanel Left = 2 Top = 398 Width = 610 Height = 99 Align = alTop BevelOuter = bvNone TabOrder = 4 object lblCompanyNameWhenCommon: TLabel Left = 80 Top = 11 Width = 112 Height = 13 Caption = #1055#1098#1083#1085#1086' '#1053#1072#1080#1084#1077#1085#1086#1074#1072#1085#1080#1077 FocusControl = edtCompanyNameWhenCommon end object lblCompanyShortNameWhenCommon: TLabel Left = 288 Top = 11 Width = 113 Height = 13 Caption = #1050#1088#1072#1090#1082#1086' '#1085#1072#1080#1084#1077#1085#1086#1074#1072#1085#1080#1077 FocusControl = edtCompanyShrotNameWhenCommon end object lblCodeWhenCommon: TLabel Left = 8 Top = 11 Width = 19 Height = 13 Caption = #1050#1086#1076 end object lblCountryWhenCommon: TLabel Left = 544 Top = 11 Width = 48 Height = 13 Caption = #1044#1098#1088#1078#1072#1074#1072 FocusControl = edtCompanyShrotNameWhenCommon end object edtCompanyNameWhenCommon: TDBEdit Left = 80 Top = 27 Width = 201 Height = 21 DataField = 'COMPANY_NAME' DataSource = dsData TabOrder = 1 end object edtCompanyShrotNameWhenCommon: TDBEdit Left = 288 Top = 27 Width = 129 Height = 21 DataField = 'SHORT_NAME' DataSource = dsData TabOrder = 2 end object edtCodeWhenCommon: TDBEdit Left = 8 Top = 27 Width = 65 Height = 21 DataField = 'COMPANY_NO' DataSource = dsData TabOrder = 0 end object cbCountryWhenCommon: TJvDBLookupCombo Left = 544 Top = 27 Width = 57 Height = 20 DropDownWidth = 250 DataField = 'COUNTRY_CODE' DataSource = dsData DisplayEmpty = '< '#1074#1089' >' LookupField = 'COUNTRY_CODE' LookupDisplay = 'COUNTRY_ABBREV' LookupSource = dsCountries TabOrder = 3 end end end inherited pnlBottomButtons: TPanel Top = 314 Width = 647 TabOrder = 5 inherited pnlOKCancel: TPanel Left = 379 end inherited pnlClose: TPanel Left = 290 end inherited pnlApply: TPanel Left = 558 end end object pnlIsPersonTitle: TPanel [3] Left = 24 Top = 85 Width = 483 Height = 24 BevelOuter = bvNone TabOrder = 1 object lblCompanyOrPerson: TLabel Left = 3 Top = 5 Width = 77 Height = 13 Caption = #1050#1083#1072#1089' '#1055#1072#1088#1090#1085#1100#1086#1088 end object cbCompanyClasses: TJvDBLookupCombo Left = 85 Top = 1 Width = 396 Height = 21 DeleteKeyClear = False DataField = '_COMPANY_CLASS_NAME' DataSource = dsData DisplayEmpty = '< '#1074#1089#1080#1095#1082#1080' >' TabOrder = 0 end end object gbStatus: TGroupBox [4] Left = 16 Top = 16 Width = 614 Height = 65 Caption = ' '#1057#1090#1072#1090#1091#1089' '#1085#1072' '#1055#1072#1088#1090#1085#1100#1086#1088' ' TabOrder = 0 object lblStatusCode: TLabel Left = 8 Top = 16 Width = 34 Height = 13 Caption = #1057#1090#1072#1090#1091#1089 end object lblDash: TLabel Left = 115 Top = 35 Width = 9 Height = 13 Caption = '---' end object lblReachMonths: TLabel Left = 280 Top = 16 Width = 108 Height = 13 Caption = #1055#1077#1088#1080#1086#1076' '#1079#1072' '#1076#1086#1089#1090#1080#1075#1072#1085#1077 end object lblExistanceMonths: TLabel Left = 456 Top = 16 Width = 130 Height = 13 Caption = #1055#1077#1088#1080#1086#1076' '#1085#1072' '#1089#1098#1097#1077#1089#1090#1074#1091#1074#1072#1085#1077 end object lblDash1: TLabel Left = 323 Top = 35 Width = 9 Height = 13 Caption = '---' end object lblMonths2: TLabel Left = 557 Top = 36 Width = 38 Height = 13 Caption = #1084#1077#1089#1077#1094#1072 end object lblDash2: TLabel Left = 499 Top = 35 Width = 9 Height = 13 Caption = '---' end object lblMonths1: TLabel Left = 381 Top = 36 Width = 38 Height = 13 Caption = #1084#1077#1089#1077#1094#1072 end object cbMinStatusCode: TJvDBLookupCombo Left = 8 Top = 32 Width = 105 Height = 21 DropDownWidth = 250 DeleteKeyClear = False DataField = 'MIN_STATUS_CODE' DataSource = dsData LookupField = 'COMPANY_STATUS_CODE' LookupDisplay = 'COMPANY_STATUS_NAME' LookupSource = dsStatuses TabOrder = 0 end object cbMaxStatusCode: TJvDBLookupCombo Left = 128 Top = 32 Width = 105 Height = 21 DropDownWidth = 250 DeleteKeyClear = False DataField = 'MAX_STATUS_CODE' DataSource = dsData LookupField = 'COMPANY_STATUS_CODE' LookupDisplay = 'COMPANY_STATUS_NAME' LookupSource = dsStatuses TabOrder = 1 end object edtMinReachMonths: TDBEdit Left = 280 Top = 32 Width = 41 Height = 21 DataField = 'MIN_REACH_MONTHS' DataSource = dsData TabOrder = 2 end object edtMaxReachMonths: TDBEdit Left = 336 Top = 32 Width = 41 Height = 21 DataField = 'MAX_REACH_MONTHS' DataSource = dsData TabOrder = 3 end object edtMinExistanceMonths: TDBEdit Left = 456 Top = 32 Width = 41 Height = 21 DataField = 'MIN_EXISTANCE_MONTHS' DataSource = dsData TabOrder = 4 end object edtMaxExistanceMonths: TDBEdit Left = 512 Top = 32 Width = 41 Height = 21 DataField = 'MAX_EXISTANCE_MONTHS' DataSource = dsData TabOrder = 5 end end object gbRoles: TGroupBox [5] Left = 16 Top = 208 Width = 305 Height = 89 Caption = ' '#1055#1072#1079#1072#1088#1085#1072' '#1056#1086#1083#1103' ' TabOrder = 3 object pnlRolesWhenCumulative: TPanel Left = 2 Top = 218 Width = 301 Height = 72 Align = alTop BevelOuter = bvNone TabOrder = 0 object rgRolesWhenCumulative: TJvDBRadioPanel Left = 0 Top = 0 Width = 301 Height = 44 Align = alTop BevelOuter = bvNone DataField = 'ROLE_CODE' DataSource = dsData Items.Strings = ( #1074#1089#1080#1095#1082#1080 #1050#1083#1080#1077#1085#1090 #1044#1086#1089#1090#1072#1074#1095#1080#1082) TabOrder = 0 Values.Strings = ( '0' '1' '3') end end object pnlRolesWhenPerson: TPanel Left = 2 Top = 146 Width = 301 Height = 72 Align = alTop BevelOuter = bvNone TabOrder = 1 object rgRolesWhenPerson: TJvDBRadioPanel Left = 0 Top = 0 Width = 301 Height = 44 Align = alTop BevelOuter = bvNone Columns = 2 DataField = 'ROLE_CODE' DataSource = dsData Items.Strings = ( #1074#1089#1080#1095#1082#1080 #1050#1083#1080#1077#1085#1090 #1044#1086#1089#1090#1072#1074#1095#1080#1082 #1055#1086#1089#1088#1077#1076#1085#1080#1082 #1057#1083#1091#1078#1080#1090#1077#1083) TabOrder = 0 Values.Strings = ( '0' '1' '3' '2' '6') end object chkIsInternal: TDBCheckBox Left = 176 Top = 29 Width = 73 Height = 17 Caption = #1042#1098#1090#1088#1077#1096#1077#1085 DataField = 'IS_INTERNAL' DataSource = dsData TabOrder = 1 ValueChecked = 'True' ValueUnchecked = 'False' end object chkIsExternal: TDBCheckBox Left = 176 Top = 45 Width = 65 Height = 17 Caption = #1042#1098#1085#1096#1077#1085 DataField = 'IS_EXTERNAL' DataSource = dsData TabOrder = 2 ValueChecked = 'True' ValueUnchecked = 'False' end end object pnlRolesWhenCompany: TPanel Left = 2 Top = 89 Width = 301 Height = 57 Align = alTop BevelOuter = bvNone TabOrder = 2 object rgRolesWhenCompany: TJvDBRadioPanel Left = 0 Top = 0 Width = 301 Height = 44 Align = alTop BevelOuter = bvNone Columns = 2 DataField = 'ROLE_CODE' DataSource = dsData Items.Strings = ( #1074#1089#1080#1095#1082#1080 #1050#1083#1080#1077#1085#1090 #1044#1086#1089#1090#1072#1074#1095#1080#1082 #1055#1086#1089#1088#1077#1076#1085#1080#1082 #1044#1098#1088#1078#1072#1074#1085#1072' '#1048#1085#1089#1090#1080#1090#1091#1094#1080#1103 #1060#1080#1085#1072#1085#1089#1086#1074#1072' '#1048#1085#1089#1090#1080#1090#1091#1094#1080#1103) TabOrder = 0 Values.Strings = ( '0' '1' '3' '2' '4' '5') end end object pnlRolesWhenAll: TPanel Left = 2 Top = 15 Width = 301 Height = 74 Align = alTop BevelOuter = bvNone TabOrder = 3 object rgRolesWhenAll: TJvDBRadioPanel Left = 0 Top = 0 Width = 301 Height = 57 Align = alTop BevelOuter = bvNone Columns = 2 DataField = 'ROLE_CODE' DataSource = dsData Items.Strings = ( #1074#1089#1080#1095#1082#1080 #1050#1083#1080#1077#1085#1090 #1044#1086#1089#1090#1072#1074#1095#1080#1082 #1055#1086#1089#1088#1077#1076#1085#1080#1082 #1044#1098#1088#1078#1072#1074#1085#1072' '#1048#1085#1089#1090#1080#1090#1091#1094#1080#1103 #1060#1080#1085#1072#1085#1089#1086#1074#1072' '#1048#1085#1089#1090#1080#1090#1091#1094#1080#1103 #1057#1083#1091#1078#1080#1090#1077#1083) TabOrder = 0 Values.Strings = ( '0' '1' '3' '2' '4' '5' '6') end object chkIsInternal2: TDBCheckBox Left = 157 Top = 44 Width = 73 Height = 17 Caption = #1042#1098#1090#1088#1077#1096#1077#1085 DataField = 'IS_INTERNAL' DataSource = dsData TabOrder = 1 ValueChecked = 'True' ValueUnchecked = 'False' end object chkIsExternal2: TDBCheckBox Left = 236 Top = 45 Width = 65 Height = 17 Caption = #1042#1098#1085#1096#1077#1085 DataField = 'IS_EXTERNAL' DataSource = dsData TabOrder = 2 ValueChecked = 'True' ValueUnchecked = 'False' end end object pnlRolesWhenCommon: TPanel Left = 2 Top = 290 Width = 301 Height = 72 Align = alTop BevelOuter = bvNone TabOrder = 4 object rgRolesWhenCommon: TJvDBRadioPanel Left = 0 Top = 0 Width = 301 Height = 44 Align = alTop BevelOuter = bvNone DataField = 'ROLE_CODE' DataSource = dsData Items.Strings = ( #1074#1089#1080#1095#1082#1080 #1050#1083#1080#1077#1085#1090 #1044#1086#1089#1090#1072#1074#1095#1080#1082) TabOrder = 0 Values.Strings = ( '0' '1' '3') end end end object gbCommonPartner: TGroupBox [6] Left = 328 Top = 208 Width = 302 Height = 89 Caption = ' '#1055#1088#1080#1086#1073#1097#1077#1085' '#1082#1098#1084' ' TabOrder = 4 object lblCommonPartner: TLabel Left = 8 Top = 24 Width = 114 Height = 13 Caption = #1054#1073#1086#1073#1097#1072#1074#1072#1097' '#1055#1072#1088#1090#1085#1100#1086#1088 end inline frCommonPartner: TfrPartnerFieldEditFrameBald Left = 8 Top = 40 Width = 284 Height = 22 HorzScrollBar.Visible = False VertScrollBar.Visible = False Constraints.MaxHeight = 22 Constraints.MinHeight = 22 TabOrder = 0 inherited gbPartner: TGroupBox Width = 299 inherited pnlNameAndButtons: TPanel Width = 210 inherited pnlRightButtons: TPanel Left = 174 end inherited pnlPartnerName: TPanel Width = 174 inherited edtPartnerName: TDBEdit Width = 160 end inherited cbPartner: TJvDBLookupCombo Width = 175 end end end inherited pnlPaddingRight: TPanel Left = 291 end end end end inherited alActions: TActionList Left = 224 inherited actForm: TAction Caption = '%s '#1085#1072' '#1056#1077#1075#1080#1089#1090#1098#1088' '#1085#1072' '#1055#1072#1088#1090#1085#1100#1086#1088#1080 end end inherited dsData: TDataSource Left = 176 end inherited cdsData: TAbmesClientDataSet Left = 144 end inherited cdsFilterVariants: TAbmesClientDataSet Left = 16 end inherited dsFilterVariants: TDataSource Left = 40 end inherited cdsFilterVariantFields: TAbmesClientDataSet Left = 64 end object cdsStatuses: TAbmesClientDataSet Aggregates = <> ConnectionBroker = dmMain.conCompanies Params = <> ProviderName = 'prvCompanyStatuses' Left = 32 Top = 52 object cdsStatusesCOMPANY_STATUS_CODE: TAbmesFloatField FieldName = 'COMPANY_STATUS_CODE' end object cdsStatusesCOMPANY_STATUS_NAME: TAbmesWideStringField FieldName = 'COMPANY_STATUS_NAME' Size = 100 end end object dsStatuses: TDataSource DataSet = cdsStatuses Left = 64 Top = 53 end object cdsCountries: TAbmesClientDataSet Aggregates = <> ConnectionBroker = dmMain.conCommon FieldDefs = <> IndexDefs = <> Params = <> ProviderName = 'prvCountries' StoreDefs = True Left = 560 Top = 136 object cdsCountriesCOUNTRY_CODE: TAbmesFloatField DisplayLabel = #1050#1086#1076 FieldName = 'COUNTRY_CODE' ProviderFlags = [pfInUpdate, pfInWhere, pfInKey] Required = True end object cdsCountriesCOUNTRY_ABBREV: TAbmesWideStringField DisplayLabel = #1040#1073#1088#1077#1074'.' FieldName = 'COUNTRY_ABBREV' Required = True Size = 5 end end object dsCountries: TDataSource DataSet = cdsCountries Left = 592 Top = 136 end object cdsCraftTypes: TAbmesClientDataSet Aggregates = <> ConnectionBroker = dmMain.conHumanResource FieldDefs = < item Name = 'CRAFT_TYPE_CODE' DataType = ftFloat end item Name = 'CRAFT_TYPE_NAME' DataType = ftWideString Size = 50 end> IndexDefs = <> Params = <> ProviderName = 'prvCraftTypes' StoreDefs = True Left = 104 Top = 168 object cdsCraftTypesCRAFT_TYPE_CODE: TAbmesFloatField DisplayLabel = #1050#1086#1076 FieldName = 'CRAFT_TYPE_CODE' Required = True end object cdsCraftTypesCRAFT_TYPE_NAME: TAbmesWideStringField DisplayLabel = #1053#1072#1080#1084#1077#1085#1086#1074#1072#1085#1080#1077 FieldName = 'CRAFT_TYPE_NAME' Required = True Size = 50 end end object cdsCrafts: TAbmesClientDataSet Aggregates = <> ConnectionBroker = dmMain.conHumanResource FieldDefs = < item Name = 'CRAFT_CODE' DataType = ftFloat end item Name = 'CRAFT_NAME' DataType = ftWideString Size = 50 end item Name = 'CRAFT_TYPE_CODE' DataType = ftFloat end> IndexDefs = <> IndexFieldNames = 'CRAFT_TYPE_CODE;CRAFT_CODE' MasterFields = 'CRAFT_TYPE_CODE' MasterSource = dsCraftTypes PacketRecords = 0 Params = <> ProviderName = 'prvCrafts' StoreDefs = True Left = 408 Top = 168 object cdsCraftsCRAFT_CODE: TAbmesFloatField DisplayLabel = #1050#1086#1076 FieldName = 'CRAFT_CODE' Required = True end object cdsCraftsCRAFT_NAME: TAbmesWideStringField DisplayLabel = #1053#1072#1080#1084#1077#1085#1086#1074#1072#1085#1080#1077 FieldName = 'CRAFT_NAME' Required = True Size = 50 end object cdsCraftsCRAFT_TYPE_CODE: TAbmesFloatField DisplayLabel = #1050#1083#1072#1089#1080#1092#1080#1082#1072#1094#1080#1086#1085#1085#1072' '#1043#1088#1091#1087#1072' '#1055#1088#1086#1092#1077#1089#1080#1080 FieldName = 'CRAFT_TYPE_CODE' Required = True end end object dsCraftTypes: TDataSource DataSet = cdsCraftTypes Left = 136 Top = 168 end object dsCrafts: TDataSource DataSet = cdsCrafts Left = 440 Top = 168 end end
26.586299
168
0.540073
85d44c3e7f9bbb2fdd3f9bacb7c8b37dfa1caeb2
683
pas
Pascal
EnumWindowsProc.pas
sourcecode-museum/D5.Funcoes
af5d6f8bfeb160cfaee3752fb2dd831368687959
[ "MIT" ]
1
2021-02-04T00:43:10.000Z
2021-02-04T00:43:10.000Z
EnumWindowsProc.pas
ezequiasmartins-bhz/legado-D5-funcoes-diversas-by-Heliomar-Marques
af5d6f8bfeb160cfaee3752fb2dd831368687959
[ "MIT" ]
null
null
null
EnumWindowsProc.pas
ezequiasmartins-bhz/legado-D5-funcoes-diversas-by-Heliomar-Marques
af5d6f8bfeb160cfaee3752fb2dd831368687959
[ "MIT" ]
1
2021-02-07T19:56:38.000Z
2021-02-07T19:56:38.000Z
Function EnumWindowsProc (Wnd: HWND; lb: TListbox): BOOL; stdcall; // // Retorna todos os programas que estao abertos na memoria // Esta funcao requer um ListBox // // Sintaxe: // // listbox1.clear; // EnumWindows( @EnumWindowsProc, integer(listbox1)); // var caption: Array [0..128] of Char; begin Result := True; if IsWindowVisible(Wnd) and ((GetWindowLong(Wnd, GWL_HWNDPARENT) = 0) or (HWND(GetWindowLong(Wnd, GWL_HWNDPARENT)) = GetDesktopWindow)) and ((GetWindowLong(Wnd, GWL_EXSTYLE) and WS_EX_TOOLWINDOW) = 0) then begin SendMessage( Wnd, WM_GETTEXT, Sizeof( caption ),integer(@caption)); lb.Items.AddObject( caption, TObject( Wnd )); end; end;
32.52381
206
0.701318
4745053f8bc8261da52611ef417fbc9f39e23bee
2,867
dfm
Pascal
Chapter 7/OmniThreadLibrary/tests/27_RecursiveTree/test_27_RecursiveTree.dfm
PacktPublishing/Delphi-High-Performance
bcb84190e8660a28cbc0caada2e1bed3b8adfe42
[ "MIT" ]
45
2018-04-08T07:01:13.000Z
2022-02-18T17:28:10.000Z
Chapter 7/OmniThreadLibrary/tests/27_RecursiveTree/test_27_RecursiveTree.dfm
anomous/Delphi-High-Performance
051a8f7d7460345b60cb8d2a10a974ea8179ea41
[ "MIT" ]
null
null
null
Chapter 7/OmniThreadLibrary/tests/27_RecursiveTree/test_27_RecursiveTree.dfm
anomous/Delphi-High-Performance
051a8f7d7460345b60cb8d2a10a974ea8179ea41
[ "MIT" ]
17
2018-03-21T11:22:15.000Z
2022-03-16T05:55:54.000Z
object frmRecursiveTreeDemo: TfrmRecursiveTreeDemo Left = 0 Top = 0 Anchors = [akTop] Caption = 'Recursive tree walk demo' ClientHeight = 247 ClientWidth = 472 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False OnClose = FormClose OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object lblNumChildren: TLabel Left = 8 Top = 11 Width = 94 Height = 13 Caption = 'Number of children:' end object lblTreeDepth: TLabel Left = 8 Top = 39 Width = 88 Height = 13 Caption = 'Depth of the tree:' end object lblNumTasks: TLabel Left = 8 Top = 123 Width = 114 Height = 13 Caption = 'Number of active tasks:' end object lblNumNodes: TLabel Left = 8 Top = 67 Width = 112 Height = 13 Caption = 'Total number of nodes:' end object lblTreeSize: TLabel Left = 8 Top = 95 Width = 105 Height = 13 Caption = 'Memory consumption:' end object inpNumChildren: TSpinEdit Left = 128 Top = 8 Width = 65 Height = 22 MaxValue = 9999 MinValue = 1 TabOrder = 0 Value = 6 OnChange = inpNumChildrenChange end object inpTreeDepth: TSpinEdit Left = 128 Top = 36 Width = 65 Height = 22 MaxValue = 9999 MinValue = 4 TabOrder = 1 Value = 10 OnChange = inpNumChildrenChange end object inpNumTasks: TSpinEdit Left = 128 Top = 120 Width = 65 Height = 22 MaxValue = 9999 MinValue = 1 TabOrder = 4 Value = 1 end object outNumNodes: TEdit Left = 128 Top = 64 Width = 65 Height = 21 ParentColor = True ReadOnly = True TabOrder = 2 end object outTreeSize: TEdit Left = 128 Top = 92 Width = 65 Height = 21 ParentColor = True ReadOnly = True TabOrder = 3 end object btnBuildTree: TButton Left = 8 Top = 152 Width = 185 Height = 25 Caption = 'Build tree' TabOrder = 5 OnClick = btnBuildTreeClick end object lbLog: TListBox Left = 199 Top = 0 Width = 273 Height = 247 Align = alRight Anchors = [akLeft, akTop, akRight, akBottom] ItemHeight = 13 TabOrder = 6 end object btnSingleCoreTest: TButton Left = 8 Top = 183 Width = 185 Height = 25 Caption = 'Single task test' TabOrder = 7 OnClick = btnSingleCoreTestClick end object btnMultiCoreTest: TButton Left = 8 Top = 214 Width = 185 Height = 25 Caption = 'Multiple task test' TabOrder = 8 OnClick = btnMultiCoreTestClick end object OtlMonitor: TOmniEventMonitor OnTaskMessage = OtlMonitorTaskMessage OnTaskTerminated = OtlMonitorTaskTerminated Left = 8 Top = 208 end end
19.371622
50
0.62016
c38f54ba9578d21a274a0163889091179e3324fe
45,494
pas
Pascal
iscbase/database/dbc/ZDbcMySqlUtils.pas
isyscore/isc-fpbase
ce2469c977eba901005982dc7f89fee2d0718f76
[ "MIT" ]
3
2021-06-10T12:33:29.000Z
2021-12-13T06:59:48.000Z
iscbase/database/dbc/ZDbcMySqlUtils.pas
isyscore/isc-fpbase
ce2469c977eba901005982dc7f89fee2d0718f76
[ "MIT" ]
null
null
null
iscbase/database/dbc/ZDbcMySqlUtils.pas
isyscore/isc-fpbase
ce2469c977eba901005982dc7f89fee2d0718f76
[ "MIT" ]
null
null
null
{*********************************************************} { } { Zeos Database Objects } { MySQL Database Connectivity Classes } { } { Originally written by Sergey Seroukhov } { and Sergey Merkuriev } { } {*********************************************************} {@********************************************************} { Copyright (c) 1999-2020 Zeos Development Group } { } { License Agreement: } { } { This library 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 Lesser General } { Public License for more details. } { } { The source code of the ZEOS Libraries and packages are } { distributed under the Library GNU General Public } { License (see the file COPYING / COPYING.ZEOS) } { 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. } { } { } { The project web site is located on: } { https://zeoslib.sourceforge.io/ (FORUM) } { http://sourceforge.net/p/zeoslib/tickets/ (BUGTRACKER)} { svn://svn.code.sf.net/p/zeoslib/code-0/trunk (SVN) } { } { http://www.sourceforge.net/projects/zeoslib. } { } { } { Zeos Development Group. } {********************************************************@} { constributor(s): aehimself EgonHugeist Martin Schreiber } unit ZDbcMySqlUtils; interface {$I ZDbc.inc} {$IFNDEF ZEOS_DISABLE_MYSQL} //if set we have an empty unit uses Classes, {$IFDEF MSEgui}mclasses,{$ENDIF} SysUtils, ZSysUtils, ZDbcIntfs, ZPlainMySqlDriver, ZDbcLogging, ZCompatibility, ZDbcResultSetMetadata, ZVariant; const MAXBUF = 65535; type {** Silent exception } EZMySQLSilentException = class(EAbort); {** Converts a MySQL native types into ZDBC SQL types. @param PlainDriver a native MySQL plain driver. @param FieldHandle a handler to field description structure. @param FieldFlags field flags. @return a SQL undepended type. } function ConvertMySQLHandleToSQLType(MYSQL_FIELD: PMYSQL_FIELD; FieldOffsets: PMYSQL_FIELDOFFSETS; MySQL_FieldType_Bit_1_IsBoolean: Boolean): TZSQLType; {** Decodes a MySQL Version Value encoded with format: (major_version * 10,000) + (minor_version * 100) + sub_version into separated major, minor and subversion values @param MySQLVersion an integer containing the MySQL Full Version to decode. @param MajorVersion an integer containing the Major Version decoded. @param MinorVersion an integer containing the Minor Version decoded. @param SubVersion an integer contaning the Sub Version (revision) decoded. } procedure DecodeMySQLVersioning(const MySQLVersion: Integer; out MajorVersion: Integer; out MinorVersion: Integer; out SubVersion: Integer); {** Encodes major, minor and subversion (revision) values in MySQL format: (major_version * 10,000) + (minor_version * 100) + sub_version For example, 4.1.12 is returned as 40112. @param MajorVersion an integer containing the Major Version. @param MinorVersion an integer containing the Minor Version. @param SubVersion an integer containing the Sub Version (revision). @return an integer containing the full version. } function EncodeMySQLVersioning(const MajorVersion: Integer; const MinorVersion: Integer; const SubVersion: Integer): Integer; {** Decodes a MySQL Version Value and Encodes it to a Zeos SQL Version format: (major_version * 1,000,000) + (minor_version * 1,000) + sub_version into separated major, minor and subversion values @param MySQLVersion an integer containing the Full Version to decode. @return Encoded Zeos SQL Version Value. } function ConvertMySQLVersionToSQLVersion( const MySQLVersion: Integer ): Integer; {** Returns a valid TZColumnInfo from a FieldHandle @param PlainDriver the MySQL PlainDriver interface @param FieldHandle the handle of the fetched field @returns a new TZColumnInfo } function GetMySQLColumnInfoFromFieldHandle(MYSQL_FIELD: PMYSQL_FIELD; FieldOffsets: PMYSQL_FIELDOFFSETS; ConSettings: PZConSettings; MySQL_FieldType_Bit_1_IsBoolean: boolean): TZColumnInfo; procedure ConvertMySQLColumnInfoFromString(var TypeName: RawByteString; out TypeInfoSecond: RawByteString; out FieldType: TZSQLType; out ColumnSize: Integer; out Scale: Integer; MySQL_FieldType_Bit_1_IsBoolean: Boolean); function GetMySQLOptionValue(Option: TMySQLOption): string; function ReverseWordBytes(Src: Pointer): Word; function ReverseLongWordBytes(Src: Pointer; Len: Byte): LongWord; function ReverseQuadWordBytes(Src: Pointer; Len: Byte): UInt64; type // offsets to used MYSQL_BINDxx members. Filled by GetBindOffsets PMYSQL_BINDOFFSETS = ^TMYSQL_BINDOFFSETS; TMYSQL_BINDOFFSETS = record buffer_type :NativeUint; buffer_length :NativeUint; is_unsigned :NativeUint; buffer :NativeUint; length :NativeUint; is_null :NativeUint; Indicator :NativeUint; size :word; //size of MYSQL_BINDxx end; PMYSQL_aligned_BIND = ^TMYSQL_aligned_BIND; TMYSQL_aligned_BIND = record buffer: Pointer; //data place holder buffer_address: PPointer; //we don't need reserved mem at all, but we need to set the address buffer_type_address: PMysqlFieldType; buffer_length_address: PULong; //address of result buffer length length_address: PPointer; length: PULongArray; //current length of our or bound data is_null_address: Pmy_bool; //adress of is_null -> the field should be used is_null: my_bool; //null indicator -> do not attach directly -> out params are referenced to stmt bindings is_unsigned_address: Pmy_bool; //signed ordinals or not? //https://mariadb.com/kb/en/library/bulk-insert-column-wise-binding/ indicators: Pmysql_indicator_types; //stmt indicators for bulk bulk ops -> mariadb addresses to "u" and does not use the C-enum indicator_address: PPointer; decimals: Integer; //count of decimal digits for rounding the doubles binary: Boolean; //binary field or not? Just for reading! mysql_bind: Pointer; //Save exact address of bind for lob reading /is used also on writting 4 the lob-buffer-address Iterations: ULong; //save count of array-Bindings to prevent reallocs for Length and Is_Null-Arrays end; PMYSQL_aligned_BINDs = ^TMYSQL_aligned_BINDs; TMYSQL_aligned_BINDs = array[0..High(Byte)] of TMYSQL_aligned_BIND; //just 4 debugging {** implements a struct to hold the mysql column bindings EH: LibMySql is scribling in ColumnBindings even if mysql_stmt_free_result() was called LibMariaDB doesn't show this terrible behavior so i localize the column buffers in stmt and not in the ResultSet findings did happen with old d7 on TZTestCompMySQLBugReport.Test727373 the newer delphi's have fastmm4 which deallocates the memory a bit later so this behavior was invisible } PMYSQL_ColumnsBinding = ^TMYSQL_ColumnsBinding; TMYSQL_ColumnsBinding = record FieldCount: NativeUInt; MYSQL_Col_BINDs: Pointer; MYSQL_aligned_BINDs: PMYSQL_aligned_BINDs; end; PMYSQL_ColumnsBindingArray = ^TMYSQL_ColumnsBindingArray; TMYSQL_ColumnsBindingArray = array[0..0] of TMYSQL_ColumnsBinding;//just a debug range usually we obtain just one result procedure ReallocBindBuffer(var BindBuffer: Pointer; var MYSQL_aligned_BINDs: PMYSQL_aligned_BINDs; BindOffsets: PMYSQL_BINDOFFSETS; OldCount, NewCount: Integer; Iterations: ULong); procedure ReAllocMySQLColumnBuffer(OldRSCount, NewRSCount: Integer; var ColumnsBindingArray: PMYSQL_ColumnsBindingArray; BindOffset: PMYSQL_BINDOFFSETS); function GetBindOffsets(IsMariaDB: Boolean; Version: Integer): PMYSQL_BINDOFFSETS; function GetFieldOffsets(Version: Integer): PMYSQL_FIELDOFFSETS; function GetServerStatusOffset(Version: Integer): NativeUInt; {$ENDIF ZEOS_DISABLE_MYSQL} //if set we have an empty unit implementation {$IFNDEF ZEOS_DISABLE_MYSQL} //if set we have an empty unit uses {$IFDEF WITH_UNITANSISTRINGS}AnsiStrings,{$ENDIF} Math, TypInfo, ZMessages, ZDbcUtils, ZFastCode, ZEncoding; {** Converts a MySQL native types into ZDBC SQL types. @param PlainDriver a native MySQL plain driver. @param FieldHandle a handler to field description structure. @param FieldFlags a field flags. @return a SQL undepended type. } {$IFDEF FPC} {$PUSH} {$WARN 4055 off : Conversion between ordinals and pointers is not portable} {$WARN 4079 off : Convering the operants to "Int64" before doing the add could prevent overflow errors} {$ENDIF} // uses pointer maths function ConvertMySQLHandleToSQLType(MYSQL_FIELD: PMYSQL_FIELD; FieldOffsets: PMYSQL_FIELDOFFSETS; MySQL_FieldType_Bit_1_IsBoolean: Boolean): TZSQLType; var PrecOrLen: ULong; begin case PMysqlFieldType(NativeUInt(MYSQL_FIELD)+FieldOffsets._type)^ of FIELD_TYPE_TINY: if PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ and UNSIGNED_FLAG = 0 then Result := stShort else Result := stByte; FIELD_TYPE_YEAR: Result := stWord; FIELD_TYPE_SHORT: if PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ and UNSIGNED_FLAG = 0 then Result := stSmall else Result := stWord; FIELD_TYPE_INT24, FIELD_TYPE_LONG: if PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ and UNSIGNED_FLAG = 0 then Result := stInteger else Result := stLongWord; FIELD_TYPE_LONGLONG: if PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ and UNSIGNED_FLAG = 0 then Result := stLong else Result := stULong; FIELD_TYPE_FLOAT, FIELD_TYPE_DOUBLE: Result := stDouble; FIELD_TYPE_DECIMAL, FIELD_TYPE_NEWDECIMAL: {ADDED FIELD_TYPE_NEWDECIMAL by fduenas 20-06-2006} if (FieldOffsets.decimals > 0) then begin PrecOrLen := PULong(NativeUInt(MYSQL_FIELD)+FieldOffsets.length)^; if (PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.decimals)^ = 0) then if PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ and UNSIGNED_FLAG = 0 then begin if PrecOrLen <= 2 then Result := stShort else if PrecOrLen <= 4 then Result := stSmall else if PrecOrLen <= 9 then Result := stInteger else if PrecOrLen <= 18 then Result := stLong else Result := stBigDecimal; end else begin if PrecOrLen <= 3 then Result := stByte else if PrecOrLen <= 5 then Result := stWord else if PrecOrLen <= 10 then Result := stLongWord else if PrecOrLen <= 19 then Result := stULong else Result := stBigDecimal; end else begin Dec(PrecOrLen, 1+Byte(PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ and UNSIGNED_FLAG = 0)); //one digit for the decimal sep and one for the sign if (PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.decimals)^ <= 4) and (PrecOrLen < ULong(sAlignCurrencyScale2Precision[PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.decimals)^])) then Result := stCurrency else Result := stBigDecimal end; end else Result := stDouble; FIELD_TYPE_DATE, FIELD_TYPE_NEWDATE: Result := stDate; FIELD_TYPE_TIME: Result := stTime; FIELD_TYPE_DATETIME, FIELD_TYPE_TIMESTAMP: Result := stTimestamp; MYSQL_TYPE_JSON: Result := stAsciiStream; FIELD_TYPE_TINY_BLOB: if ((FieldOffsets.charsetnr > 0) and ((PUInt(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.charsetnr))^ <> 63{binary}) or (PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ and BINARY_FLAG = 0))) or ((FieldOffsets.charsetnr < 0) and (PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ and BINARY_FLAG = 0)) then Result := stString else Result := stBytes; FIELD_TYPE_MEDIUM_BLOB, FIELD_TYPE_LONG_BLOB, FIELD_TYPE_BLOB: if ((FieldOffsets.charsetnr > 0) and ((PUInt(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.charsetnr))^ <> 63{binary}) or (PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ and BINARY_FLAG = 0))) or ((FieldOffsets.charsetnr < 0) and (PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ and BINARY_FLAG = 0)) then Result := stAsciiStream else Result := stBinaryStream; FIELD_TYPE_BIT: //http://dev.mysql.com/doc/refman/5.1/en/bit-type.html case PULong(NativeUInt(MYSQL_FIELD)+FieldOffsets.length)^ of 1: if MySQL_FieldType_Bit_1_IsBoolean then Result := stBoolean else result := stByte; 2..8: Result := stByte; 9..16: Result := stWord; 17..32: Result := stLongWord; else Result := stULong; end; FIELD_TYPE_VARCHAR, FIELD_TYPE_VAR_STRING, FIELD_TYPE_STRING: if (PULong(NativeUInt(MYSQL_FIELD)+FieldOffsets.length)^ = 0) or //handle null columns: select null union null ((FieldOffsets.charsetnr > 0) and ((PUInt(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.charsetnr))^ <> 63{binary}) or (PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ and BINARY_FLAG = 0))) or ((FieldOffsets.charsetnr < 0) and (PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ and BINARY_FLAG = 0)) then Result := stString else Result := stBytes; FIELD_TYPE_ENUM: Result := stString; FIELD_TYPE_SET: Result := stString; FIELD_TYPE_NULL: // Example: SELECT NULL FROM DUAL Result := stString; FIELD_TYPE_GEOMETRY: // Todo: Would be nice to show as WKT. Result := stBinaryStream; else raise Exception.Create('Unknown MySQL data type!'); end; end; {$IFDEF FPC} {$POP} {$ENDIF} {** Decodes a MySQL Version Value encoded with format: (major_version * 10,000) + (minor_version * 100) + sub_version into separated major, minor and subversion values @param MySQLVersion an integer containing the MySQL Full Version to decode. @param MajorVersion an integer containing the Major Version decoded. @param MinorVersion an integer containing the Minor Version decoded. @param SubVersion an integer contaning the Sub Version (revision) decoded. } procedure DecodeMySQLVersioning(const MySQLVersion: Integer; out MajorVersion: Integer; out MinorVersion: Integer; out SubVersion: Integer); begin MajorVersion := MySQLVersion div 10000; MinorVersion := (MySQLVersion - (MajorVersion * 10000)) div 100; SubVersion := MySQLVersion-(MajorVersion*10000)-(MinorVersion*100); end; {** Encodes major, minor and subversion (revision) values in MySQL format: (major_version * 10,000) + (minor_version * 100) + sub_version For example, 4.1.12 is returned as 40112. @param MajorVersion an integer containing the Major Version. @param MinorVersion an integer containing the Minor Version. @param SubVersion an integer containing the Sub Version (revision). @return an integer containing the full version. } function EncodeMySQLVersioning(const MajorVersion: Integer; const MinorVersion: Integer; const SubVersion: Integer): Integer; begin Result := (MajorVersion * 10000) + (MinorVersion * 100) + SubVersion; end; {** Decodes a MySQL Version Value and Encodes it to a Zeos SQL Version format: (major_version * 1,000,000) + (minor_version * 1,000) + sub_version into separated major, minor and subversion values So it transforms a version in format XYYZZ to XYYYZZZ where: X = major_version Y = minor_version Z = sub version @param MySQLVersion an integer containing the Full MySQL Version to decode. @return Encoded Zeos SQL Version Value. } function ConvertMySQLVersionToSQLVersion( const MySQLVersion: Integer ): integer; var MajorVersion, MinorVersion, SubVersion: Integer; begin DecodeMySQLVersioning(MySQLVersion,MajorVersion,MinorVersion,SubVersion); Result := EncodeSQLVersioning(MajorVersion,MinorVersion,SubVersion); end; {** Returns a valid TZColumnInfo from a FieldHandle @param PlainDriver the MySQL PlainDriver interface @param FieldHandle the handle of the fetched field @returns a new TZColumnInfo } {$IFDEF FPC} {$PUSH} {$WARN 4055 off : Conversion between ordinals and pointers is not portable} {$ENDIF} // uses pointer maths function GetMySQLColumnInfoFromFieldHandle(MYSQL_FIELD: PMYSQL_Field; FieldOffsets: PMYSQL_FIELDOFFSETS; ConSettings: PZConSettings; MySQL_FieldType_Bit_1_IsBoolean:boolean): TZColumnInfo; var FieldLength: ULong; CS: Word; function ValueToString(Buf: PAnsiChar; Len: Cardinal): String; begin if (Buf = nil) or (AnsiChar(Buf^) = AnsiChar(#0)) then Result := '' else begin {$IFDEF UNICODE} Result := PRawToUnicode(Buf, Len, ConSettings^.ClientCodePage^.CP); {$ELSE} Result := ''; System.SetString(Result, Buf, Len) {$ENDIF} end; end; begin if Assigned(MYSQL_FIELD) then begin Result := TZColumnInfo.Create; //note calling a SP with multiple results -> mySQL&mariaDB returning wrong lengthes! //see test bugreport.TZTestCompMySQLBugReport.TestTicket186_MultipleResults //so we're calling strlen in all cases to have a common behavior! {if FieldOffsets.name > 0 then Result.ColumnLabel := ValueToString(PPAnsichar(NativeUInt(MYSQL_FIELD)+FieldOffsets.name)^, PUint(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.name_length))^) else} Result.ColumnLabel := ValueToString(PPAnsichar(NativeUInt(MYSQL_FIELD)+FieldOffsets.name)^, StrLen(PPAnsichar(NativeUInt(MYSQL_FIELD)+FieldOffsets.name)^)); if (FieldOffsets.org_table > 0) then {Result.TableName := ValueToString(PPAnsichar(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.org_table))^, PUint(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.org_table_length))^) else }Result.TableName := ValueToString(PPAnsichar(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.org_table))^, StrLen(PPAnsichar(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.org_table))^)); if (Result.TableName <> '') then begin if FieldOffsets.org_name > 0 then {Result.ColumnName := ValueToString(PPAnsichar(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.org_name))^, PUint(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.org_name_length))^) else} Result.ColumnName := ValueToString(PPAnsichar(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.org_name))^, StrLen(PPAnsichar(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.org_name))^)); {JDBC maps the MySQL MYSQK_FIELD.db to Catalog: see: https://stackoverflow.com/questions/7942520/relationship-between-catalog-schema-user-and-database-instance} if FieldOffsets.db_length > 0 then {Result.CatalogName := ValueToString(PPAnsichar(NativeUInt(PAnsichar(MYSQL_FIELD)+FieldOffsets.db))^, PUint(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.db_length))^) else }Result.CatalogName := ValueToString(PPAnsichar(NativeUInt(PAnsichar(MYSQL_FIELD)+FieldOffsets.db))^, StrLen(PPAnsichar(NativeUInt(PAnsichar(MYSQL_FIELD)+FieldOffsets.db))^)); end; Result.ReadOnly := (FieldOffsets.org_table <0) or (Result.TableName = '') or (Result.ColumnName = ''); Result.Writable := not Result.ReadOnly; Result.ColumnType := ConvertMySQLHandleToSQLType(MYSQL_FIELD, FieldOffsets, MySQL_FieldType_Bit_1_IsBoolean); if PMysqlFieldType(NativeUInt(MYSQL_FIELD)+FieldOffsets._type)^ = FIELD_TYPE_TINY_BLOB then FieldLength := 255 else FieldLength := PULong(NativeUInt(MYSQL_FIELD)+FieldOffsets.length)^; //EgonHugeist: arrange the MBCS field DisplayWidth to a proper count of Chars if Result.ColumnType in [stString, stUnicodeString, stAsciiStream, stUnicodeStream] then Result.ColumnCodePage := ConSettings^.ClientCodePage^.CP else Result.ColumnCodePage := High(Word); Result.Signed := (PMysqlFieldType(NativeUInt(MYSQL_FIELD)+FieldOffsets._type)^ <> FIELD_TYPE_VAR_STRING) and ((UNSIGNED_FLAG and PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^) = 0); if Result.ColumnType in [stString, stUnicodeString] then begin Result.CharOctedLength := FieldLength; if FieldOffsets.charsetnr > 0 then CS := PUInt(NativeUInt(MYSQL_FIELD)+NativeUInt(FieldOffsets.charsetnr))^ else CS := ConSettings^.ClientCodePage^.ID; case CS of 1, 84, {Big5} 95, 96, {cp932 japanese} 19, 85, {euckr} 24, 86, {gb2312} 38, 87, {gbk} 13, 88, {sjis} 35, 90, 128..151: {ucs2} begin Result.Precision := (FieldLength shr 2); if Result.ColumnType = stString then Result.CharOctedLength := FieldLength else Result.CharOctedLength := FieldLength shr 1; end; 33, 83, 192..215, { utf8 } 97, 98, { eucjpms} 12, 91: {ujis} begin Result.Precision := (FieldLength div 3); if Result.ColumnType = stString then Result.CharOctedLength := FieldLength else Result.CharOctedLength := Result.Precision shl 1; end; 54, 55, 101..124, {utf16} 56, 62, {utf16le} 60, 61, 160..183, {utf32} 45, 46, 224..247, 255: {utf8mb4} begin Result.Precision := (FieldLength shr 2); if Result.ColumnType = stString then Result.CharOctedLength := FieldLength else Result.CharOctedLength := FieldLength shr 1; end; else begin //1-Byte charsets Result.Precision := FieldLength; if Result.ColumnType = stString then Result.CharOctedLength := FieldLength else Result.CharOctedLength := FieldLength shl 1; end; end end else if Result.ColumnType in [stCurrency, stBigDecimal] then Result.Precision := Integer(FieldLength) - 1 - Ord(Result.Signed) else Result.Precision := Integer(FieldLength)*Ord(not (PMysqlFieldType(NativeUInt(MYSQL_FIELD)+FieldOffsets._type)^ in [FIELD_TYPE_BLOB, FIELD_TYPE_TINY_BLOB, FIELD_TYPE_MEDIUM_BLOB, FIELD_TYPE_LONG_BLOB, FIELD_TYPE_GEOMETRY])); Result.Scale := PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.decimals)^; Result.AutoIncrement := (AUTO_INCREMENT_FLAG and PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ <> 0);// or //(TIMESTAMP_FLAG and MYSQL_FIELD.flags <> 0); if NOT_NULL_FLAG and PUInt(NativeUInt(MYSQL_FIELD)+FieldOffsets.flags)^ <> 0 then Result.Nullable := ntNoNulls else Result.Nullable := ntNullable; // Properties not set via query results here will be fetched from table metadata. end else Result := nil; end; {$IFDEF FPC} {$POP} {$ENDIF} // uses pointer maths procedure ConvertMySQLColumnInfoFromString(var TypeName: RawByteString; out TypeInfoSecond: RawByteString; out FieldType: TZSQLType; out ColumnSize: Integer; out Scale: Integer; MySQL_FieldType_Bit_1_IsBoolean: Boolean); const GeoTypes: array[0..7] of RawByteString = ( 'point','linestring','polygon','geometry', 'multipoint','multilinestring','multipolygon','geometrycollection' ); var Len: Integer; pB, pC: Integer; Signed: Boolean; P: PAnsiChar; function CreateFailException: EZSQLException; begin Result := EZSQLException.Create('Unknown MySQL data type! '+String(TypeName)) end; label SetLobSize, lByte, lWord, lLong, lLongLong, SetTimeScale, SetVarScale; begin TypeInfoSecond := ''; Scale := 0; ColumnSize := 0; TypeName := {$IFDEF WITH_UNITANSISTRINGS}AnsiStrings.{$ENDIF}LowerCase(TypeName); Signed := (not (ZFastCode.Pos({$IFDEF UNICODE}RawByteString{$ENDIF}('unsigned'), TypeName) > 0)); pB := ZFastCode.Pos({$IFDEF UNICODE}RawByteString{$ENDIF}('('), TypeName); if pB > 0 then begin pC := ZFastCode.PosEx({$IFDEF UNICODE}RawByteString{$ENDIF}(')'), TypeName, pB); TypeInfoSecond := {$IFDEF WITH_UNITANSISTRINGS}AnsiStrings.{$ENDIF}UpperCase(Copy(TypeName, pB+1, pc-pB-1)); TypeName := Copy(TypeName, 1, pB-1); end; { the column type is ENUM} if TypeName = 'enum' then begin FieldType := stString; if not MySQL_FieldType_Bit_1_IsBoolean and ((TypeInfoSecond = '''Y'',''N''') or (TypeInfoSecond = '''N'',''Y''')) then FieldType := stBoolean else begin P := Pointer(TypeInfoSecond); Len := Length(TypeInfoSecond); while PByte(P)^ <> 0 do begin pc := PosEx({$IFDEF UNICODE}RawByteString{$ENDIF}(','), P, Len, 1); if pc = 0 then begin ColumnSize := Max(ColumnSize, ZFastCode.StrLen(P)-2); Break; end else ColumnSize := Max(ColumnSize, (pc-3)); Inc(P, pc); end; end end else if TypeName = 'set' then begin ColumnSize := 255; FieldType := stString; end else if not StartsWith(TypeName, {$IFDEF UNICODE}RawByteString{$ENDIF}('po')) and //exclude "point" type (ZFastCode.Pos({$IFDEF UNICODE}RawByteString{$ENDIF}('int'), TypeName) > 0) then begin if StartsWith(TypeName, {$IFDEF UNICODE}RawByteString{$ENDIF}('tiny')) then begin lByte: FieldType := TZSQLType(Ord(stByte)+Ord(Signed)); //0 - 255 or -128 - 127 ColumnSize := 3+Ord(Signed); end else if StartsWith(TypeName, {$IFDEF UNICODE}RawByteString{$ENDIF}('small')) then begin lWord: FieldType := TZSQLType(Ord(stWord)+Ord(Signed)); //0 - 65535 or -32768 - 32767 ColumnSize := 5+Ord(Signed); end else if StartsWith(TypeName, {$IFDEF UNICODE}RawByteString{$ENDIF}('medium')) or EndsWith(TypeName, {$IFDEF UNICODE}RawByteString{$ENDIF}('24')) then begin FieldType := TZSQLType(Ord(stLongWord)+Ord(Signed)); //0 - 16777215 or -8388608 - 8388607 ColumnSize := 8; end else if StartsWith(TypeName, {$IFDEF UNICODE}RawByteString{$ENDIF}('big')) then begin lLongLong: FieldType := TZSQLType(Ord(stULong)+Ord(Signed)); //0 - 18446744073709551615 or -9223372036854775808 - 922337203685477580 ColumnSize := 20; end else begin//includes INTEGER lLong: FieldType := TZSQLType(Ord(stLongWord)+Ord(Signed)); //0 - 4294967295 or -2147483648 - 2147483647 ColumnSize := 10+Ord(Signed); end; end else if TypeName = 'year' then begin FieldType := stWord; //1901 to 2155, and 0000 in the 4 year format and 1970-2069 if you use the 2 digit format (70-69). ColumnSize := 4; end else if TypeName = 'real' then begin FieldType := stFloat end else if {(TypeName = 'float') or }(TypeName = 'decimal') {or StartsWith(TypeName, RawByteString('double'))} then begin //read careful! http://dev.mysql.com/doc/refman/5.7/en/floating-point-types.html if TypeInfoSecond = '' then begin FieldType := stDouble; ColumnSize := 12; end else begin pC := ZFastCode.Pos({$IFDEF UNICODE}RawByteString{$ENDIF}(','), TypeInfoSecond); if pC > 0 then begin P := Pointer(TypeInfoSecond); ColumnSize := RawToIntDef(P, P+pC-1, 0); Scale := RawToIntDef(P+pC, 0); end; if Scale = 0 then if ColumnSize < 10 then goto lLong else goto lLongLong else if (Scale <= 4) and (ColumnSize < sAlignCurrencyScale2Precision[Scale]) then FieldType := stCurrency else FieldType := stBigDecimal end end else if (TypeName = 'float') or StartsWith(TypeName, RawByteString('double')) then begin FieldType := stDouble; ColumnSize := 22; end else if EndsWith(TypeName, RawByteString('char')) then begin //includes 'VARCHAR' FieldType := stString; goto SetVarScale; end else if EndsWith(TypeName, RawByteString('binary')) then begin //includes 'VARBINARY' FieldType := stBytes; SetVarScale: ColumnSize := RawToIntDef(TypeInfoSecond, 0); if not StartsWith(TypeName, RawByteString('var')) then Scale := ColumnSize; //tag fixed size end else if TypeName = 'date' then begin FieldType := stDate; ColumnSize := 10; end else if TypeName = 'time' then begin FieldType := stTime; ColumnSize := 10; //MySQL hour range is from -838 to 838 so we add two digits (one for sign and 1 to hour) goto SetTimeScale; end else if (TypeName = 'timestamp') or (TypeName = 'datetime') then begin FieldType := stTimestamp; ColumnSize := 19; SetTimeScale: Scale := RawToIntDef(TypeInfoSecond, 0); if Scale > 0 then ColumnSize := ColumnSize + 1{Dot}+Scale; end else if EndsWith(TypeName, RawByteString('blob')) then begin //includes 'TINYBLOB', 'MEDIUMBLOB', 'LONGBLOB' FieldType := stBinaryStream; SetLobSize: if StartsWith(TypeName, RawByteString('tiny')) then begin FieldType := TZSQLType(Byte(FieldType)-3); //move down to string by default ColumnSize := 255 end else if StartsWith(TypeName, RawByteString('medium')) then ColumnSize := 16277215 else if StartsWith(TypeName, RawByteString('long')) then ColumnSize := High(Integer)//usually high cardinal ->4294967295 else ColumnSize := 65535; //no suffix found use default high Word size end else if EndsWith(TypeName, RawByteString('text')) then begin//includes 'TINYTEXT', 'MEDIUMTEXT', 'LONGTEXT' FieldType := stAsciiStream; goto SetLobSize; end else if TypeName = 'bit' then begin //see: http://dev.mysql.com/doc/refman/5.1/en/bit-type.html ColumnSize := RawToIntDef(TypeInfoSecond, 1); Signed := False; case ColumnSize of 1: if MySQL_FieldType_Bit_1_IsBoolean then FieldType := stBoolean else goto lByte; 2..8: goto lByte; 9..16: goto lWord; 17..32: goto lLong; else goto lLongLong; end; end else if TypeName = 'json' then { test it ..} FieldType := stAsciiStream else for pC := 0 to High(GeoTypes) do if GeoTypes[pC] = TypeName then begin FieldType := stBinaryStream; Break; end; if FieldType = stUnknown then raise CreateFailException; end; function GetMySQLOptionValue(Option: TMySQLOption): string; begin Result := GetEnumName(TypeInfo(TMySQLOption), Integer(Option)); end; procedure ReverseBytes(const Src, Dest: Pointer; Len: Byte); var b: Byte; P: PAnsiChar; begin P := PAnsiChar(Src)+Len-1; for b := Len-1 downto 0 do (PAnsiChar(Dest)+B)^ := (P-B)^; end; function ReverseWordBytes(Src: Pointer): Word; begin (PAnsiChar(@Result)+1)^ := PAnsiChar(Src)^; PAnsiChar(@Result)^ := (PAnsiChar(Src)+1)^; end; function ReverseLongWordBytes(Src: Pointer; Len: Byte): LongWord; begin Result := 0; ReverseBytes(Src, @Result, Len); end; {$IF defined (RangeCheckEnabled) and defined(WITH_UINT64_C1118_ERROR)}{$R-}{$IFEND} function ReverseQuadWordBytes(Src: Pointer; Len: Byte): UInt64; begin Result := 0; ReverseBytes(Src, @Result, Len); end; {$IF defined (RangeCheckEnabled) and defined(WITH_UINT64_C1118_ERROR)}{$R+}{$IFEND} var MARIADB_BIND1027_Offset: TMYSQL_BINDOFFSETS; MYSQL_BIND51_Offset: TMYSQL_BINDOFFSETS; MYSQL_BIND506_Offset: TMYSQL_BINDOFFSETS; MYSQL_BIND411_Offset: TMYSQL_BINDOFFSETS; MYSQL_FIELD51_Offset: TMYSQL_FIELDOFFSETS; MYSQL_FIELD41_Offset: TMYSQL_FIELDOFFSETS; MYSQL_FIELD401_Offset: TMYSQL_FIELDOFFSETS; MYSQL_FIELD4_Offset: TMYSQL_FIELDOFFSETS; MYSQL_FIELD32_Offset: TMYSQL_FIELDOFFSETS; function GetBindOffsets(IsMariaDB: Boolean; Version: Integer): PMYSQL_BINDOFFSETS; begin if IsMariaDB and (Version >= 100207) then result := @MARIADB_BIND1027_Offset else if (Version >= 50100) or IsMariaDB {they start with 100000} then result := @MYSQL_BIND51_Offset else if (Version >= 50006) then Result := @MYSQL_BIND506_Offset else if (Version >= 40101) then Result := @MYSQL_BIND411_Offset else Result := nil end; function GetFieldOffsets(Version: Integer): PMYSQL_FIELDOFFSETS; begin if (Version >= 50100) then result := @MYSQL_FIELD51_Offset else if (Version >= 40100) then Result := @MYSQL_FIELD41_Offset else if (Version >= 40001) then Result := @MYSQL_FIELD401_Offset else if (Version >= 40000) then Result := @MYSQL_FIELD4_Offset else Result := @MYSQL_FIELD32_Offset end; function GetServerStatusOffset(Version: Integer): NativeUInt; begin if (Version >= 50000) then result := MYSQL5up_server_status_offset else if (Version >= 40100) then Result := MYSQL41_server_status_offset else Result := MYSQL323_server_status_offset end; {$IFDEF FPC} {$PUSH} {$WARN 4055 off : Conversion between ordinals and pointers is not portable} {$ENDIF} // uses pointer maths procedure ReallocBindBuffer(var BindBuffer: Pointer; var MYSQL_aligned_BINDs: PMYSQL_aligned_BINDs; BindOffsets: PMYSQL_BINDOFFSETS; OldCount, NewCount: Integer; Iterations: ULong); var I: Integer; Bind: PMYSQL_aligned_BIND; ColOffset: NativeUInt; begin {first clean mem of binds we don't need any more} if MYSQL_aligned_BINDs <> nil then for i := OldCount-1 downto NewCount do begin {$R-} Bind := @MYSQL_aligned_BINDs[I]; {$IFDEF RangeCheckEnabled}{$R+}{$ENDIF} if Bind^.buffer <> nil then FreeMem(Bind^.buffer); if Bind^.Length <> nil then FreeMem(Bind^.length); if Bind^.Indicators <> nil then FreeMem(Bind^.Indicators); end; ReallocMem(BindBuffer, NewCount*BindOffsets.Size); ReallocMem(MYSQL_aligned_BINDs, NewCount*SizeOf(TMYSQL_aligned_BIND)); if MYSQL_aligned_BINDs <> nil then begin FillChar((PAnsichar(BindBuffer)+(OldCount*BindOffsets.Size))^, ((NewCount-OldCount)*BindOffsets.Size), {$IFDEF Use_FastCodeFillChar}#0{$ELSE}0{$ENDIF}); FillChar((PAnsiChar(MYSQL_aligned_BINDs)+(OldCount*SizeOf(TMYSQL_aligned_BIND)))^, (NewCount-OldCount)*SizeOf(TMYSQL_aligned_BIND), {$IFDEF Use_FastCodeFillChar}#0{$ELSE}0{$ENDIF}); for i := OldCount to NewCount-1 do begin {$R-} Bind := @MYSQL_aligned_BINDs[I]; {$IFDEF RangeCheckEnabled}{$R+}{$ENDIF} ColOffset := NativeUInt(I*BindOffsets.size); { save mysql bind offset fo mysql_stmt_fetch_column } Bind^.mysql_bind := Pointer(NativeUInt(BindBuffer)+ColOffset); { save aligned addresses } bind^.buffer_address := Pointer(NativeUInt(BindBuffer)+ColOffset+BindOffsets.buffer); Bind^.buffer_type_address := Pointer(NativeUInt(BindBuffer)+ColOffset+BindOffsets.buffer_type); Bind^.is_unsigned_address := Pointer(NativeUInt(BindBuffer)+ColOffset+BindOffsets.is_unsigned); Bind^.buffer_length_address := Pointer(NativeUInt(BindBuffer)+ColOffset+BindOffsets.buffer_length); Bind^.length_address := Pointer(NativeUInt(BindBuffer)+ColOffset+BindOffsets.length); GetMem(Bind^.length, Iterations*SizeOf(ULong)); FillChar(Bind^.length^, Iterations*SizeOf(ULong), {$IFDEF Use_FastCodeFillChar}#0{$ELSE}0{$ENDIF}); Bind^.length_address^ := Bind^.length; Bind^.is_null_address := @Bind^.is_null; PPointer(NativeUInt(BindBuffer)+ColOffset+BindOffsets.is_null)^ := Bind^.is_null_address; if (BindOffsets.Indicator > 0) then Bind^.indicator_address := Pointer(NativeUInt(BindBuffer)+ColOffset+BindOffsets.Indicator) else if Iterations > 1 then raise EZSQLException.Create('Array bindings are not supported!'); end; end; end; {$IFDEF FPC} {$POP} {$ENDIF} // uses pointer maths procedure ReAllocMySQLColumnBuffer(OldRSCount, NewRSCount: Integer; var ColumnsBindingArray: PMYSQL_ColumnsBindingArray; BindOffset: PMYSQL_BINDOFFSETS); var i: Integer; ColBinding: PMYSQL_ColumnsBinding; begin if ColumnsBindingArray <> nil then for i := OldRSCount-1 downto NewRSCount do begin {$R-} ColBinding := @ColumnsBindingArray[I]; {$IFDEF RangeCheckEnabled}{$R+}{$ENDIF} ReallocBindBuffer(ColBinding.MYSQL_Col_BINDs, ColBinding.MYSQL_aligned_BINDs, BindOffset, ColBinding.FieldCount, 0, 1); end; ReallocMem(ColumnsBindingArray, NewRSCount*SizeOf(TMYSQL_ColumnsBinding)); if ColumnsBindingArray <> nil then FillChar((PAnsichar(ColumnsBindingArray)+(OldRSCount*SizeOf(TMYSQL_ColumnsBinding)))^, ((NewRSCount-OldRSCount)*SizeOf(TMYSQL_ColumnsBinding)), {$IFDEF Use_FastCodeFillChar}#0{$ELSE}0{$ENDIF}); end; initialization {$IFDEF FPC} {$PUSH} {$WARN 4055 off : Conversion between ordinals and pointers is not portable} {$ENDIF} // uses pointer maths with MARIADB_BIND1027_Offset do begin buffer_type := NativeUint(@(PMARIADB_BIND1027(nil).buffer_type)); buffer_length := NativeUint(@(PMARIADB_BIND1027(nil).buffer_length)); is_unsigned := NativeUint(@(PMARIADB_BIND1027(nil).is_unsigned)); buffer := NativeUint(@(PMARIADB_BIND1027(nil).buffer)); length := NativeUint(@(PMARIADB_BIND1027(nil).length)); is_null := NativeUint(@(PMARIADB_BIND1027(nil).is_null)); Indicator := NativeUint(@(PMARIADB_BIND1027(nil).u.indicator)); size := Sizeof(TMARIADB_BIND1027); end; with MYSQL_BIND51_Offset do begin buffer_type := NativeUint(@(PMYSQL_BIND51(nil).buffer_type)); buffer_length := NativeUint(@(PMYSQL_BIND51(nil).buffer_length)); is_unsigned := NativeUint(@(PMYSQL_BIND51(nil).is_unsigned)); buffer := NativeUint(@(PMYSQL_BIND51(nil).buffer)); length := NativeUint(@(PMYSQL_BIND51(nil).length)); is_null := NativeUint(@(PMYSQL_BIND51(nil).is_null)); Indicator := 0; size := Sizeof(TMYSQL_BIND51); end; with MYSQL_BIND506_Offset do begin buffer_type := NativeUint(@(PMYSQL_BIND506(nil).buffer_type)); buffer_length := NativeUint(@(PMYSQL_BIND506(nil).buffer_length)); is_unsigned := NativeUint(@(PMYSQL_BIND506(nil).is_unsigned)); buffer := NativeUint(@(PMYSQL_BIND506(nil).buffer)); length := NativeUint(@(PMYSQL_BIND506(nil).length)); is_null := NativeUint(@(PMYSQL_BIND506(nil).is_null)); Indicator := 0; size := Sizeof(TMYSQL_BIND506); end; with MYSQL_BIND411_Offset do begin buffer_type := NativeUInt(@(PMYSQL_BIND411(nil).buffer_type)); buffer_length := NativeUInt(@(PMYSQL_BIND411(nil).buffer_length)); is_unsigned := NativeUInt(@(PMYSQL_BIND411(nil).is_unsigned)); buffer := NativeUInt(@(PMYSQL_BIND411(nil).buffer)); length := NativeUInt(@(PMYSQL_BIND411(nil).length)); is_null := NativeUInt(@(PMYSQL_BIND411(nil).is_null)); Indicator := 0; size := Sizeof(TMYSQL_BIND411); end; with MYSQL_FIELD51_Offset do begin name := NativeUInt(@(PMYSQL_FIELD51(nil).name)); name_length := NativeUInt(@(PMYSQL_FIELD51(nil).name_length)); org_table := NativeUInt(@(PMYSQL_FIELD51(nil).org_table)); org_table_length:= NativeUInt(@(PMYSQL_FIELD51(nil).org_table_length)); org_name := NativeUInt(@(PMYSQL_FIELD51(nil).org_name)); org_name_length := NativeUInt(@(PMYSQL_FIELD51(nil).org_name_length)); db := NativeUInt(@(PMYSQL_FIELD51(nil).db)); db_length := NativeUInt(@(PMYSQL_FIELD51(nil).db_length)); charsetnr := NativeUInt(@(PMYSQL_FIELD51(nil).charsetnr)); _type := NativeUInt(@(PMYSQL_FIELD51(nil)._type)); flags := NativeUInt(@(PMYSQL_FIELD51(nil).flags)); length := NativeUInt(@(PMYSQL_FIELD51(nil).length)); decimals := NativeUInt(@(PMYSQL_FIELD51(nil).decimals)); max_length := NativeUInt(@(PMYSQL_FIELD51(nil).max_length)); end; with MYSQL_FIELD41_Offset do begin name := NativeUInt(@(PMYSQL_FIELD41(nil).name)); name_length := NativeUInt(@(PMYSQL_FIELD41(nil).name_length)); org_table := NativeUInt(@(PMYSQL_FIELD41(nil).org_table)); org_table_length:= NativeUInt(@(PMYSQL_FIELD41(nil).org_table_length)); org_name := NativeUInt(@(PMYSQL_FIELD41(nil).org_name)); org_name_length := NativeUInt(@(PMYSQL_FIELD41(nil).org_name_length)); db := NativeUInt(@(PMYSQL_FIELD41(nil).db)); db_length := NativeUInt(@(PMYSQL_FIELD41(nil).db_length)); charsetnr := NativeUInt(@(PMYSQL_FIELD41(nil).charsetnr)); _type := NativeUInt(@(PMYSQL_FIELD41(nil)._type)); flags := NativeUInt(@(PMYSQL_FIELD41(nil).flags)); length := NativeUInt(@(PMYSQL_FIELD41(nil).length)); decimals := NativeUInt(@(PMYSQL_FIELD41(nil).decimals)); max_length := NativeUInt(@(PMYSQL_FIELD41(nil).max_length)); end; with MYSQL_FIELD401_Offset do begin name := NativeUInt(@(PMYSQL_FIELD401(nil).name)); name_length := NativeUInt(@(PMYSQL_FIELD401(nil).name_length)); org_table := NativeUInt(@(PMYSQL_FIELD401(nil).org_table)); org_table_length:= NativeUInt(@(PMYSQL_FIELD401(nil).org_table_length)); org_name := NativeUInt(@(PMYSQL_FIELD401(nil).org_name)); org_name_length := NativeUInt(@(PMYSQL_FIELD401(nil).org_name_length)); db := NativeUInt(@(PMYSQL_FIELD401(nil).db)); db_length := NativeUInt(@(PMYSQL_FIELD401(nil).db_length)); charsetnr := NativeUInt(@(PMYSQL_FIELD401(nil).charsetnr)); _type := NativeUInt(@(PMYSQL_FIELD401(nil)._type)); flags := NativeUInt(@(PMYSQL_FIELD401(nil).flags)); length := NativeUInt(@(PMYSQL_FIELD401(nil).length)); decimals := NativeUInt(@(PMYSQL_FIELD401(nil).decimals)); max_length := NativeUInt(@(PMYSQL_FIELD401(nil).max_length)); end; with MYSQL_FIELD4_Offset do begin name := NativeUInt(@(PMYSQL_FIELD40(nil).name)); name_length := -1; org_table := NativeUInt(@(PMYSQL_FIELD40(nil).org_table)); org_table_length:= -1; org_name := -1; org_name_length := -1; db := NativeUInt(@(PMYSQL_FIELD40(nil).db)); db_length := -1; charsetnr := -1; _type := NativeUInt(@(PMYSQL_FIELD40(nil)._type)); flags := NativeUInt(@(PMYSQL_FIELD40(nil).flags)); length := NativeUInt(@(PMYSQL_FIELD40(nil).length)); decimals := NativeUInt(@(PMYSQL_FIELD40(nil).decimals)); max_length := NativeUInt(@(PMYSQL_FIELD40(nil).max_length)); end; with MYSQL_FIELD32_Offset do begin name := NativeUInt(@(PMYSQL_FIELD32(nil).name)); name_length := -1; org_table := -1; org_table_length:= -1; org_name := -1; org_name_length := -1; db := -1; db_length := -1; charsetnr := -1; _type := NativeUInt(@(PMYSQL_FIELD32(nil)._type)); flags := NativeUInt(@(PMYSQL_FIELD32(nil).flags)); length := NativeUInt(@(PMYSQL_FIELD32(nil).length)); decimals := NativeUInt(@(PMYSQL_FIELD32(nil).decimals)); max_length := NativeUInt(@(PMYSQL_FIELD32(nil).max_length)); end; {$IFDEF FPC} {$POP} {$ENDIF} {$ENDIF ZEOS_DISABLE_MYSQL} //if set we have an empty unit end.
47.095238
208
0.667231
c39460b608e0c973b1da452a41b1a282631aa61a
2,402
pas
Pascal
tests/Test.ComInterfacedObject.pas
deltics/deltics.interfaces
8f79c966d0d52228c5c55e35666f924ae06a8258
[ "MIT" ]
null
null
null
tests/Test.ComInterfacedObject.pas
deltics/deltics.interfaces
8f79c966d0d52228c5c55e35666f924ae06a8258
[ "MIT" ]
null
null
null
tests/Test.ComInterfacedObject.pas
deltics/deltics.interfaces
8f79c966d0d52228c5c55e35666f924ae06a8258
[ "MIT" ]
1
2021-03-08T06:27:54.000Z
2021-03-08T06:27:54.000Z
{$i deltics.inc} unit Test.ComInterfacedObject; interface uses Deltics.Smoketest; type TComInterfacedObjectTests = class(TTest) private fOnDestroyCallCount: Integer; procedure OnDestroyCallCounter(aSender: TObject); published procedure SetupMethod; procedure ComInterfacedObjectLifetimeIsReferenceCounted; procedure ComInterfacedObjectWithoutReferencesCanBeFreed; procedure ComInterfacedObjectFreedAfterReferencesUsedRaisesEInvalidPointer; end; implementation uses SysUtils, Deltics.InterfacedObjects, Deltics.Multicast; { TInterfacedObjectTests } procedure TComInterfacedObjectTests.OnDestroyCallCounter(aSender: TObject); begin Inc(fOnDestroyCallCount); end; procedure TComInterfacedObjectTests.SetupMethod; begin fOnDestroyCallCount := 0; end; procedure TComInterfacedObjectTests.ComInterfacedObjectWithoutReferencesCanBeFreed; var sut: TComInterfacedObject; iod: IOn_Destroy; begin sut := TComInterfacedObject.Create; try iod := sut as IOn_Destroy; iod.Add(OnDestroyCallCounter); iod := NIL; Test('TComInterfaceObject.On_Destroy calls').Assert(fOnDestroyCallCount).Equals(0); finally sut.Free; Test('TComInterfaceObject.On_Destroy calls').Assert(fOnDestroyCallCount).Equals(1); end; end; procedure TComInterfacedObjectTests.ComInterfacedObjectFreedAfterReferencesUsedRaisesEInvalidPointer; var sut: TComInterfacedObject; intf: IUnknown; iod: IOn_Destroy; begin Test.Raises(EInvalidPointer); sut := TComInterfacedObject.Create; iod := sut as IOn_Destroy; iod.Add(OnDestroyCallCounter); iod := NIL; Test('TComInterfaceObject.On_Destroy calls').Assert(fOnDestroyCallCount).Equals(0); intf := sut; intf := NIL; Test('TComInterfaceObject.On_Destroy calls').Assert(fOnDestroyCallCount).Equals(1); sut.Free; end; procedure TComInterfacedObjectTests.ComInterfacedObjectLifetimeIsReferenceCounted; var sut: TComInterfacedObject; intf: IUnknown; iod: IOn_Destroy; begin sut := TComInterfacedObject.Create; iod := sut as IOn_Destroy; iod.Add(OnDestroyCallCounter); iod := NIL; intf := sut; intf := NIL; Test('TComInterfaceObject.On_Destroy calls').Assert(fOnDestroyCallCount).Equals(1); end; end.
20.529915
103
0.729808
c37e1947b0e20ec0caa015e2cc4db63616be0f9c
12,776
pas
Pascal
Source/dwsMathComplexFunctions.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
1
2022-02-18T22:14:44.000Z
2022-02-18T22:14:44.000Z
Source/dwsMathComplexFunctions.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
null
null
null
Source/dwsMathComplexFunctions.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
null
null
null
{**********************************************************************} { } { "The contents of this file are subject to the Mozilla Public } { License Version 1.1 (the "License"); you may not use this } { file except in compliance with the License. You may obtain } { a copy of the License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express } { or implied. See the License for the specific language } { governing rights and limitations under the License. } { } { Copyright Creative IT. } { Current maintainer: Eric Grange } { } {**********************************************************************} unit dwsMathComplexFunctions; {$I dws.inc} interface uses SysUtils, dwsUtils, dwsXPlatform, dwsCompilerContext, dwsScriptSource, dwsFunctions, dwsSymbols, dwsExprs, dwsStrings, dwsOperators, dwsExprList, dwsTokenTypes, dwsMagicExprs, dwsUnitSymbols, dwsDataContext; type TComplexMakeExpr = class(TInternalMagicDataFunction) public procedure DoEval(const args : TExprBaseListExec; var result : IDataContext); override; end; TComplexToStrExpr = class(TInternalMagicStringFunction) public procedure DoEvalAsString(const args : TExprBaseListExec; var result : String); override; end; TComplexToRealExpr = class(TInternalMagicFloatFunction) procedure DoEvalAsFloat(const args : TExprBaseListExec; var Result : Double); override; end; TComplexToImagExpr = class(TInternalMagicFloatFunction) procedure DoEvalAsFloat(const args : TExprBaseListExec; var Result : Double); override; end; TComplexAbsExpr = class(TInternalMagicFloatFunction) procedure DoEvalAsFloat(const args : TExprBaseListExec; var Result : Double); override; end; TComplexOpExpr = class(TInternalMagicDataFunction); TComplexNegOpExpr = class(TComplexOpExpr) public procedure DoEval(const args : TExprBaseListExec; var result : IDataContext); override; end; TComplexConjugateOpExpr = class(TComplexOpExpr) public procedure DoEval(const args : TExprBaseListExec; var result : IDataContext); override; end; TComplexAddOpExpr = class(TComplexOpExpr) public procedure DoEval(const args : TExprBaseListExec; var result : IDataContext); override; end; TComplexSubOpExpr = class(TComplexOpExpr) public procedure DoEval(const args : TExprBaseListExec; var result : IDataContext); override; end; TComplexMultOpExpr = class(TComplexOpExpr) public procedure DoEval(const args : TExprBaseListExec; var result : IDataContext); override; end; TComplexDivOpExpr = class(TComplexOpExpr) public procedure DoEval(const args : TExprBaseListExec; var result : IDataContext); override; end; TComplexExpOpExpr = class(TComplexOpExpr) public procedure DoEval(const args : TExprBaseListExec; var result : IDataContext); override; end; const SYS_COMPLEX = 'TComplex'; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ implementation // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ uses Math; // RegisterComplexType // procedure RegisterComplexType(systemTable : TSystemSymbolTable; unitSyms : TUnitMainSymbols; unitTable : TSymbolTable); var typComplex : TRecordSymbol; begin if systemTable.FindLocal(SYS_COMPLEX)<>nil then exit; typComplex:=TRecordSymbol.Create(SYS_COMPLEX, nil); typComplex.AddField(TFieldSymbol.Create('Re', systemTable.TypFloat, cvPublic)); typComplex.AddField(TFieldSymbol.Create('Im', systemTable.TypFloat, cvPublic)); systemTable.AddSymbol(typComplex); end; // RegisterComplexOperators // procedure RegisterComplexOperators(systemTable : TSystemSymbolTable; unitTable : TSymbolTable; operators : TOperators); var typComplex : TRecordSymbol; begin typComplex:=systemTable.FindTypeSymbol(SYS_COMPLEX, cvMagic) as TRecordSymbol; if operators.HasOperatorFor(ttPROPERTY, typComplex, typComplex) then Exit; operators.RegisterOperator(ttPLUS, unitTable.FindSymbol('ComplexAdd', cvMagic) as TFuncSymbol, typComplex, typComplex); operators.RegisterOperator(ttMINUS, unitTable.FindSymbol('ComplexSub', cvMagic) as TFuncSymbol, typComplex, typComplex); operators.RegisterOperator(ttTIMES, unitTable.FindSymbol('ComplexMult', cvMagic) as TFuncSymbol, typComplex, typComplex); operators.RegisterOperator(ttDIVIDE, unitTable.FindSymbol('ComplexDiv', cvMagic) as TFuncSymbol, typComplex, typComplex); end; // ------------------ // ------------------ TComplexMakeExpr ------------------ // ------------------ // DoEval // procedure TComplexMakeExpr.DoEval(const args : TExprBaseListExec; var result : IDataContext); begin result.AsFloat[0]:=args.AsFloat[0]; result.AsFloat[1]:=args.AsFloat[1]; end; // ------------------ // ------------------ TComplexToStrExpr ------------------ // ------------------ // DoEvalAsString // procedure TComplexToStrExpr.DoEvalAsString(const args : TExprBaseListExec; var result : String); var cmplxData : IDataContext; r, i : Double; begin cmplxData:=TDataExpr(args.ExprBase[0]).DataPtr[args.Exec]; r:=cmplxData.AsFloat[0]; i:=cmplxData.AsFloat[1]; if i>0 then Result := Format('%f + %fi', [r, i]) else if i<0 then Result := Format('%f - %fi', [r, Abs(i)]) else Result := Format('%f', [r]); end; // ------------------ // ------------------ TComplexToRealExpr ------------------ // ------------------ // DoEvalAsFloat // procedure TComplexToRealExpr.DoEvalAsFloat(const args : TExprBaseListExec; var Result : Double); begin Result := TDataExpr(args.ExprBase[0]).DataPtr[args.Exec].AsFloat[0]; end; // ------------------ // ------------------ TComplexToImagExpr ------------------ // ------------------ // DoEvalAsFloat // procedure TComplexToImagExpr.DoEvalAsFloat(const args : TExprBaseListExec; var Result : Double); begin Result := TDataExpr(args.ExprBase[0]).DataPtr[args.Exec].AsFloat[1]; end; // ------------------ // ------------------ TComplexAbsExpr ------------------ // ------------------ // DoEvalAsFloat // procedure TComplexAbsExpr.DoEvalAsFloat(const args : TExprBaseListExec; var Result : Double); var v : IDataContext; begin v := TDataExpr(args.ExprBase[0]).DataPtr[args.Exec]; Result := Sqrt(Sqr(v.AsFloat[0])+Sqr(v.AsFloat[1])); end; // ------------------ // ------------------ TComplexNegOpExpr ------------------ // ------------------ // DoEval // procedure TComplexNegOpExpr.DoEval(const args : TExprBaseListExec; var result : IDataContext); var v : IDataContext; begin v:=TDataExpr(args.ExprBase[0]).DataPtr[args.Exec]; result.AsFloat[0]:=-v.AsFloat[0]; result.AsFloat[1]:=-v.AsFloat[1]; end; // ------------------ // ------------------ TComplexConjugateOpExpr ------------------ // ------------------ // DoEval // procedure TComplexConjugateOpExpr.DoEval(const args : TExprBaseListExec; var result : IDataContext); var v : IDataContext; begin v := TDataExpr(args.ExprBase[0]).DataPtr[args.Exec]; result.AsFloat[0] := v.AsFloat[0]; result.AsFloat[1] := -v.AsFloat[1]; end; // ------------------ // ------------------ TComplexAddOpExpr ------------------ // ------------------ // DoEval // procedure TComplexAddOpExpr.DoEval(const args : TExprBaseListExec; var result : IDataContext); var leftData, rightData : IDataContext; begin leftData:=TDataExpr(args.ExprBase[0]).DataPtr[args.Exec]; rightData:=TDataExpr(args.ExprBase[1]).DataPtr[args.Exec]; result[0]:=leftData[0]+rightData[0]; result[1]:=leftData[1]+rightData[1]; end; // ------------------ // ------------------ TComplexSubOpExpr ------------------ // ------------------ // DoEval // procedure TComplexSubOpExpr.DoEval(const args : TExprBaseListExec; var result : IDataContext); var leftData, rightData : IDataContext; begin leftData:=TDataExpr(args.ExprBase[0]).DataPtr[args.Exec]; rightData:=TDataExpr(args.ExprBase[1]).DataPtr[args.Exec]; result[0]:=leftData[0]-rightData[0]; result[1]:=leftData[1]-rightData[1]; end; // ------------------ // ------------------ TComplexMultOpExpr ------------------ // ------------------ // DoEval // procedure TComplexMultOpExpr.DoEval(const args : TExprBaseListExec; var result : IDataContext); var leftData, rightData : IDataContext; begin leftData:=TDataExpr(args.ExprBase[0]).DataPtr[args.Exec]; rightData:=TDataExpr(args.ExprBase[1]).DataPtr[args.Exec]; result[0]:=leftData[0]*rightData[0]-leftData[1]*rightData[1]; result[1]:=leftData[1]*rightData[0]+leftData[0]*rightData[1]; end; // ------------------ // ------------------ TComplexDivOpExpr ------------------ // ------------------ // DoEval // procedure TComplexDivOpExpr.DoEval(const args : TExprBaseListExec; var result : IDataContext); var leftData, rightData : IDataContext; d : Double; begin leftData:=TDataExpr(args.ExprBase[0]).DataPtr[args.Exec]; rightData:=TDataExpr(args.ExprBase[1]).DataPtr[args.Exec]; d:=Sqr(rightData[0])+Sqr(rightData[1]); result[0]:=(leftData[0]*rightData[0]+leftData[1]*rightData[1])/d; result[1]:=(leftData[1]*rightData[0]-leftData[0]*rightData[1])/d; end; // ------------------ // ------------------ TComplexExpOpExpr ------------------ // ------------------ // DoEval // procedure TComplexExpOpExpr.DoEval(const args : TExprBaseListExec; var result : IDataContext); var v : IDataContext; theta, c, s : Double; buf : array [0..1] of Double; begin v := TDataExpr(args.ExprBase[0]).DataPtr[args.Exec]; buf[0] := Exp(v.AsFloat[0]); buf[1] := v.AsFloat[1]; theta := buf[0]; SinCos(buf[1], c, s); result.AsFloat[0] := theta * c; result.AsFloat[1] := theta * s; end; // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ initialization // ------------------------------------------------------------------ // ------------------------------------------------------------------ // ------------------------------------------------------------------ dwsInternalUnit.AddSymbolsRegistrationProc(RegisterComplexType); dwsInternalUnit.AddOperatorsRegistrationProc(RegisterComplexOperators); RegisterInternalFloatFunction(TComplexAbsExpr, 'Abs', ['v', SYS_COMPLEX], [iffOverloaded, iffStateLess]); RegisterInternalFunction(TComplexMakeExpr, 'Complex', ['real', SYS_FLOAT, 'imaginary', SYS_FLOAT], SYS_COMPLEX, [iffStateLess]); RegisterInternalStringFunction(TComplexToStrExpr, 'ComplexToStr', ['&c', SYS_COMPLEX], [iffStateLess], 'ToString'); RegisterInternalFloatFunction(TComplexToRealExpr, 'ComplexReal', ['&c', SYS_COMPLEX], [iffStateLess], 'Real'); RegisterInternalFloatFunction(TComplexToImagExpr, 'ComplexImag', ['&c', SYS_COMPLEX], [iffStateLess], 'Imag'); RegisterInternalFunction(TComplexNegOpExpr, 'ComplexNeg', ['&v', SYS_COMPLEX], SYS_COMPLEX, [ iffStateLess ], 'Negate'); RegisterInternalFunction(TComplexConjugateOpExpr, 'ComplexConjugate', ['&v', SYS_COMPLEX], SYS_COMPLEX, [iffStateLess], 'Conjugate'); RegisterInternalFunction(TComplexAddOpExpr, 'ComplexAdd', ['&left', SYS_COMPLEX, '&right', SYS_COMPLEX], SYS_COMPLEX, [iffStateLess], 'Add'); RegisterInternalFunction(TComplexSubOpExpr, 'ComplexSub', ['&left', SYS_COMPLEX, '&right', SYS_COMPLEX], SYS_COMPLEX, [iffStateLess], 'Sub'); RegisterInternalFunction(TComplexMultOpExpr, 'ComplexMult', ['&left', SYS_COMPLEX, '&right', SYS_COMPLEX], SYS_COMPLEX, [iffStateLess], 'Mult'); RegisterInternalFunction(TComplexDivOpExpr, 'ComplexDiv', ['&left', SYS_COMPLEX, '&right', SYS_COMPLEX], SYS_COMPLEX, [iffStateLess], 'Div'); RegisterInternalFunction(TComplexExpOpExpr, 'ComplexExp', ['&v', SYS_COMPLEX], SYS_COMPLEX, [iffStateLess], 'Exp'); end.
35.488889
147
0.592048
f1d11989473cf484dbe0901df53a43becc525b1d
2,841
pas
Pascal
paf-ecf/binario/fontes/VO/R06VO.pas
claudiobsi/T2Ti-ERP-1.0-Java
3a91981d0a11e5ff258d09df6fee73f5b6d1cb07
[ "MIT" ]
1
2020-08-03T03:28:37.000Z
2020-08-03T03:28:37.000Z
paf-ecf/binario/fontes/VO/R06VO.pas
claudiobsi/T2Ti-ERP-1.0-Java
3a91981d0a11e5ff258d09df6fee73f5b6d1cb07
[ "MIT" ]
null
null
null
paf-ecf/binario/fontes/VO/R06VO.pas
claudiobsi/T2Ti-ERP-1.0-Java
3a91981d0a11e5ff258d09df6fee73f5b6d1cb07
[ "MIT" ]
2
2020-07-15T17:57:30.000Z
2020-08-29T23:07:36.000Z
{******************************************************************************* Title: T2Ti ERP Description: VO da tabela do PAF: R06. 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 R06VO; interface type TR06VO = class private FID: Integer; FID_OPERADOR: Integer; FID_IMPRESSORA: Integer; FID_ECF_CAIXA: Integer; FSERIE_ECF: String; FCOO: Integer; FGNF: Integer; FGRG: Integer; FCDC: Integer; FDENOMINACAO: String; FDATA_EMISSAO: String; FHORA_EMISSAO: String; FSINCRONIZADO: String; FHASH_TRIPA: String; FHASH_INCREMENTO: Integer; published property Id: Integer read FID write FID; property IdOperador: Integer read FID_OPERADOR write FID_OPERADOR; property IdImpressora: Integer read FID_IMPRESSORA write FID_IMPRESSORA; property IdCaixa: Integer read FID_ECF_CAIXA write FID_ECF_CAIXA; property SerieEcf: String read FSERIE_ECF write FSERIE_ECF; property COO: Integer read FCOO write FCOO; property GNF: Integer read FGNF write FGNF; property GRG: Integer read FGRG write FGRG; property CDC: Integer read FCDC write FCDC; property Denominacao: String read FDENOMINACAO write FDENOMINACAO; property DataEmissao: String read FDATA_EMISSAO write FDATA_EMISSAO; property HoraEmissao: String read FHORA_EMISSAO write FHORA_EMISSAO; property Sincronizado: String read FSINCRONIZADO write FSINCRONIZADO; property HashTripa: String read FHASH_TRIPA write FHASH_TRIPA; property HashIncremento: Integer read FHASH_INCREMENTO write FHASH_INCREMENTO; end; implementation end.
34.646341
82
0.725801
fc1418db34eb1743dfcedf898a16742db5729e52
1,372
dfm
Pascal
Tools/PascalCommentReplace/PascalCommentRepFrm.dfm
PassByYou888/ZNet
8f5439ec275ee4eb5d68e00c33675e6117379fcf
[ "BSD-3-Clause" ]
24
2022-01-20T13:59:38.000Z
2022-03-25T01:11:43.000Z
Tools/PascalCommentReplace/PascalCommentRepFrm.dfm
lovong/ZNet
ad67382654ea1979c316c2dc9716fd6d8509f028
[ "BSD-3-Clause" ]
null
null
null
Tools/PascalCommentReplace/PascalCommentRepFrm.dfm
lovong/ZNet
ad67382654ea1979c316c2dc9716fd6d8509f028
[ "BSD-3-Clause" ]
5
2022-01-20T14:44:24.000Z
2022-02-13T10:07:38.000Z
object PascalCommentRepForm: TPascalCommentRepForm Left = 0 Top = 0 AutoSize = True BorderStyle = bsSingle BorderWidth = 20 Caption = 'Pascal source Comments Replace. create by.qq600585' ClientHeight = 585 ClientWidth = 1017 Color = clBtnFace Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -12 Font.Name = 'Consolas' Font.Style = [] OldCreateOrder = False Position = poDesktopCenter PixelsPerInch = 96 TextHeight = 14 object Memo: TMemo Left = 0 Top = 0 Width = 809 Height = 585 Lines.Strings = ( 'program helloworld;' 'begin' ' //' ' // print hello world' ' //' ' writeln('#39'hello world'#39');' ' //' 'end.') ScrollBars = ssBoth TabOrder = 0 WordWrap = False end object Rep1Button: TButton Left = 815 Top = 0 Width = 202 Height = 25 Caption = 'replace //xx as { xx }' TabOrder = 1 OnClick = Rep1ButtonClick end object removeEmptyButton: TButton Left = 815 Top = 63 Width = 202 Height = 25 Caption = 'remove empty comment' TabOrder = 3 OnClick = removeEmptyButtonClick end object Rep2Button: TButton Left = 815 Top = 31 Width = 202 Height = 25 Caption = 'replace //xx as (* xx *)' TabOrder = 2 OnClick = Rep2ButtonClick end end
20.787879
64
0.608601
fcb2666e103ecac887aaebf50fc51fcf676934b0
4,185
pas
Pascal
src/src/delphi/misc/test.pas
amindlost/wdosx
1e256d22c1547e7b1f1ccd23e400f5b81b8bd013
[ "Unlicense" ]
7
2022-01-20T08:27:54.000Z
2022-03-17T10:15:31.000Z
src/src/delphi/misc/test.pas
amindlost/wdosx
1e256d22c1547e7b1f1ccd23e400f5b81b8bd013
[ "Unlicense" ]
null
null
null
src/src/delphi/misc/test.pas
amindlost/wdosx
1e256d22c1547e7b1f1ccd23e400f5b81b8bd013
[ "Unlicense" ]
null
null
null
{ test program, mainly testing the CRT unit, not that anyone cares... } { compile: DCC32 TEST.PAS and say: STUBIT TEST.EXE } { Make sure the compiler can find the CRT unit! } { This is a 100% Turbo Pascal program, it compiles and runs the same way with } { Turbo Pascal 5.5! } program testall; uses crt; var c:char; b:byte; f:text; s:string; a:boolean; begin textmode(CO80); textcolor(white); textbackground(blue); window(5,5,75,20); clrscr; window(7,6,73,19); textbackground(black); clrscr; gotoxy(20,7); highvideo; writeln('Welcome to Turbo Pascal 10 !!'); gotoxy(1,14); for b:=0 to 5 do begin delay(50); sound((6-b)*220); writeln end; nosound; gotoxy(14,7); textcolor(lightgreen); writeln('Well, at least the loader did not crash :)'); gotoxy(20,8); textcolor(lightred); writeln('Press any key to continue...'); while keypressed do c:=readkey; repeat until keypressed; gotoxy(1,7); for b:=0 to 7 do begin delay(50); sound((b+1)*220); insline; end; nosound; gotoxy(19,14); textcolor(lightgreen); write('Now let',chr(39),'s have some more tests !'); gotoxy(19,7); for b:=0 to 6 do begin delay(50); sound((6-b)*220); delline; end; nosound; delay(1000); gotoxy(18,8); textcolor(lightred); writeln('Press any key to set textmode BW40'); {usually this is colored also...} while keypressed do c:=readkey; repeat until keypressed; textmode(BW40); writeln('Welcome to mode BW40'); lowvideo; writeln('Any key to test mode CO40...'); while keypressed do c:=readkey; repeat until keypressed; textmode(CO40); highvideo; writeln('Welcome to mode CO40'); lowvideo; writeln('Any key to test mode BW80...'); while keypressed do c:=readkey; repeat until keypressed; textmode(BW80); highvideo; writeln('Welcome to mode BW80'); lowvideo; writeln('Any key to test mode CO80...'); while keypressed do c:=readkey; repeat until keypressed; textmode(CO80); highvideo; writeln('Welcome to mode CO80'); lowvideo; writeln('Any key to test mode CO80 + Font8x8...'); while keypressed do c:=readkey; repeat until keypressed; textmode(CO80+Font8x8); highvideo; writeln('Are you actually able to read this???'); lowvideo; writeln('Any key to get out of here...'); while keypressed do c:=readkey; repeat until keypressed; textmode(CO80); textcolor(white); textbackground(blue); window(5,5,75,20); clrscr; window(7,6,73,19); textbackground(black); clrscr; gotoxy(20,7); highvideo; writeln('Welcome to Turbo Pascal 10 !!!'); gotoxy(1,14); for b:=0 to 5 do begin delay(50); sound((6-b)*220); writeln end; nosound; gotoxy(20,7); textcolor(lightgreen); writeln('Whowww, still not crashed ???'); gotoxy(16,8); textcolor(white); writeln('Press any key to have some file IO...'); while keypressed do c:=readkey; repeat until keypressed; gotoxy(1,7); for b:=0 to 7 do begin delay(50); sound((b+1)*220); insline; end; nosound; repeat while keypressed do c:=readkey; gotoxy(2,7); writeln('Enter a file we could write some garbage to ! [RETURN SKIPS] :'); gotoxy(14,8); a:=true; delline; readln(s); if s <> '' then begin assign(f,s); {$I-} reset(f); {$I+} if (ioresult<>0) then {$I-} rewrite(f) {$I+} else begin gotoxy(14,8); clreol; writeln('File already exists !'); delay (500); a:=false; close(f); end; end; until ( ((ioresult=0) or (s='')) and a); gotoxy(2,7); delline; if s<>'' then begin writeln(f,'Wuschel',chr(39),'s garbage file'); for b:=0 to 200 do writeln (f,b,' SPAM SPAM SPAM SPAM SPAM SPAM...'); close(f); clrscr; clreol; writeln('Garbage written to file "',s,'", any key to exit'); end else writeln('No garbage written to no file. Any key to exit...'); while keypressed do c:=readkey; repeat until keypressed; while keypressed do c:=readkey; end.
24.331395
79
0.612903
fc9fca573b71e3a42c47dff98fef91beee4f1c4b
46,071
pas
Pascal
Chapter 8/Abbrevia/source/AbDfStrm.pas
PacktPublishing/Delphi-High-Performance
bcb84190e8660a28cbc0caada2e1bed3b8adfe42
[ "MIT" ]
45
2018-04-08T07:01:13.000Z
2022-02-18T17:28:10.000Z
Chapter 8/Abbrevia/source/AbDfStrm.pas
anomous/Delphi-High-Performance
051a8f7d7460345b60cb8d2a10a974ea8179ea41
[ "MIT" ]
null
null
null
Chapter 8/Abbrevia/source/AbDfStrm.pas
anomous/Delphi-High-Performance
051a8f7d7460345b60cb8d2a10a974ea8179ea41
[ "MIT" ]
17
2018-03-21T11:22:15.000Z
2022-03-16T05:55:54.000Z
(* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TurboPower Abbrevia * * The Initial Developer of the Original Code is * TurboPower Software * * Portions created by the Initial Developer are Copyright (C) 1997-2002 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** *) {*********************************************************} {* ABBREVIA: AbDfStrm.pas *} {*********************************************************} {* Deflate streams unit for various streams *} {*********************************************************} unit AbDfStrm; {$I AbDefine.inc} interface uses Classes, AbDfBase, AbDfInW, AbDfHufD; type TAb32bit = Integer; { a 32-bit type} PAbDfLitBuckets = ^TAbDfLitBuckets; TAbDfLitBuckets = array [0..285] of integer; PAbDfDistBuckets = ^TAbDfDistBuckets; TAbDfDistBuckets = array [0..31] of integer; PAbDfCodeLenBuckets = ^TAbDfCodeLenBuckets; TAbDfCodeLenBuckets = array [0..18] of integer; const AbExtractMask : array [1..31] of TAb32bit = ($00000001, $00000003, $00000007, $0000000F, $0000001F, $0000003F, $0000007F, $000000FF, $000001FF, $000003FF, $000007FF, $00000FFF, $00001FFF, $00003FFF, $00007FFF, $0000FFFF, $0001FFFF, $0003FFFF, $0007FFFF, $000FFFFF, $001FFFFF, $003FFFFF, $007FFFFF, $00FFFFFF, $01FFFFFF, $03FFFFFF, $07FFFFFF, $0FFFFFFF, $1FFFFFFF, $3FFFFFFF, $7FFFFFFF); type TAbDfInBitStream = class { input bit stream} private FBitBuffer : TAb32bit; FBitsLeft : integer; FBufEnd : PByte; FBuffer : PByte; FBufPos : PByte; FByteCount : Integer; FFakeCount : integer; FOnProgress: TAbProgressStep; {$IFOPT C+} FPeekCount : integer; {$ENDIF} FStream : TStream; FStreamSize: Integer; protected function ibsFillBuffer : boolean; public constructor Create(aStream : TStream; aOnProgress : TAbProgressStep; aStreamSize : Integer); destructor Destroy; override; procedure AlignToByte; procedure DiscardBits(aCount : integer); procedure DiscardMoreBits(aCount : integer); function PeekBits(aCount : integer) : integer; function PeekMoreBits(aCount : integer) : integer; function ReadBit : boolean; function ReadBits(aCount : integer) : integer; procedure ReadBuffer(var aBuffer; aCount : integer); property BitBuffer : TAb32bit read FBitBuffer write FBitBuffer; property BitsLeft : integer read FBitsLeft write FBitsLeft; end; type TAbDfOutBitStream = class { output bit stream} private FBitBuffer : TAb32bit; FBitsUsed : integer; FBufEnd : PByte; FBuffer : PByte; FBufPos : PByte; FStream : TStream; protected procedure obsEmptyBuffer; public constructor Create(aStream : TStream); destructor Destroy; override; procedure AlignToByte; function Position : Integer; procedure WriteBit(aBit : boolean); procedure WriteBits(aBits : integer; aCount : integer); procedure WriteBuffer(var aBuffer; aCount : integer); procedure WriteMoreBits(aBits : integer; aCount : integer); property BitBuffer : TAb32bit read FBitBuffer write FBitBuffer; property BitsUsed : integer read FBitsUsed write FBitsUsed; end; type TAbDfLZStream = class { LZ77 token stream} private FCurPos : PByte; FDistBuckets : PAbDfDistBuckets; FDistCount : integer; FLitBuckets : PAbDfLitBuckets; FLitCount : integer; FLog : TAbLogger; FSlideWin : TAbDfInputWindow; FStartOfs : Int64; FStoredSize : UInt32; FStream : PByte; FStrmEnd : PByte; {$IFDEF UseLogging} FSWPos : Integer; {$ENDIF} FUseDeflate64: boolean; protected function lzsGetApproxSize : UInt32; function lzsGetStaticSize : integer; function lzsGetStoredSize : integer; function lzsIsFull : boolean; public constructor Create(aSlideWin : TAbDfInputWindow; aUseDeflate64 : boolean; aLog : TAbLogger); destructor Destroy; override; function AddLenDist(aLen : integer; aDist : integer) : boolean; { returns true if the stream is "full"} function AddLiteral(aCh : Byte) : boolean; { returns true if the stream is "full"} procedure Clear; procedure Encode(aBitStrm : TAbDfOutBitStream; aLitTree : TAbDfDecodeHuffmanTree; aDistTree : TAbDfDecodeHuffmanTree; aUseDeflate64 : boolean); procedure Rewind; procedure ReadStoredBuffer(var aBuffer; aCount : integer); property LenDistCount : integer read FDistCount; property LiteralCount : integer read FLitCount; property DistBuckets : PAbDfDistBuckets read FDistBuckets; property LitBuckets : PAbDfLitBuckets read FLitBuckets; property StaticSize : integer read lzsGetStaticSize;{ in bits} property StoredSize : integer read lzsGetStoredSize;{ in bytes} end; type TAbDfCodeLenStream = class { codelength token stream} private FBuckets : PAbDfCodeLenBuckets; FPosition : PByte; FStream : PByte; {array [0..285+32*2] of byte;} FStrmEnd : PByte; protected public constructor Create(aLog : TAbLogger); destructor Destroy; override; procedure Build(const aCodeLens : array of integer; aCount : integer); procedure Encode(aBitStrm : TAbDfOutBitStream; aTree : TAbDfDecodeHuffmanTree); property Buckets : PAbDfCodeLenBuckets read FBuckets; end; implementation uses SysUtils, AbDfXlat; type PAb32bit = ^TAb32bit; const BitStreamBufferSize = 16*1024; {===TAbDfInBitStream=================================================} constructor TAbDfInBitStream.Create(aStream : TStream; aOnProgress : TAbProgressStep; aStreamSize : Integer); begin {protect against dumb programming mistakes} Assert(aStream <> nil, 'TAbDfInBitStream.Create: Cannot create a bit stream wrapping a nil stream'); {create the ancestor} inherited Create; {save the stream instance, allocate the buffer} FStream := aStream; GetMem(FBuffer, BitStreamBufferSize); {save the on progress handler} if Assigned(aOnProgress) and (aStreamSize > 0) then begin FOnProgress := aOnProgress; FStreamSize := aStreamSize; end; end; {--------} destructor TAbDfInBitStream.Destroy; begin {if we did some work...} if (FBuffer <> nil) then begin {reposition the underlying stream to the point where we stopped; this position is equal to... the position of the underlying stream, PLUS the number of fake bytes we added, LESS the number of bytes in the buffer, PLUS the position in the buffer, PLUS the number of complete bytes in the bit buffer} FStream.Seek(FStream.Position + FFakeCount - (FBufEnd - FBuffer) + (FBufPos - FBuffer) - (FBitsLeft div 8), soBeginning); {free the buffer} FreeMem(FBuffer); end; {destroy the ancestor} inherited Destroy; end; {--------} procedure TAbDfInBitStream.AlignToByte; begin {get rid of the odd bits by shifting them out of the bit cache} FBitBuffer := FBitBuffer shr (FBitsLeft mod 8); dec(FBitsLeft, FBitsLeft mod 8); end; {--------} procedure TAbDfInBitStream.DiscardBits(aCount : integer); var BitsToGo : integer; begin {aCount comes from a (possibly corrupt) stream, so check that it is the correct range, 1..32} if (aCount <= 0) or (aCount > 32) then raise EAbInternalInflateError.Create( 'count of bits must be between 1 and 32 inclusive [TAbDfInBitStream.DiscardBits]'); {$IFOPT C+} {verify that the count of bits to discard is less than or equal to the recent count from PeekBits--a programming error} Assert((aCount <= FPeekCount), 'TAbDfInBitStream.DiscardBits: discarding more bits than peeked'); {since we're discarding bits already peeked, reset the peek count} FPeekCount := 0; {$ENDIF} {if we have more than enough bits in our bit buffer, update the bitbuffer and the number of bits left} if (aCount <= FBitsLeft) then begin FBitBuffer := FBitBuffer shr aCount; dec(FBitsLeft, aCount); end {otherwise we shall have to read another integer out of the buffer to satisfy the request} else begin {check that there is data in the buffer, if not it's indicates a corrupted stream: PeekBits should have filled it} if (FBufPos = FBufEnd) then raise EAbInternalInflateError.Create( 'no more compressed data in stream [TAbDfInBitStream.DiscardBits]'); {refill the bit buffer} BitsToGo := aCount - FBitsLeft; FBitBuffer := PAb32bit(FBufPos)^; inc(FBufPos, sizeof(TAb32bit)); FBitBuffer := FBitBuffer shr BitsToGo; FBitsLeft := 32 - BitsToGo; end; end; {--------} procedure TAbDfInBitStream.DiscardMoreBits(aCount : integer); var BitsToGo : integer; begin {aCount comes from a (possibly corrupt) stream, so check that it is the correct range, 1..32} if (aCount <= 0) or (aCount > 32) then raise EAbInternalInflateError.Create( 'count of bits must be between 1 and 32 inclusive [TAbDfInBitStream.DiscardMoreBits]'); {$IFOPT C+} {verify that the count of bits to discard is less than or equal to the recent count from PeekBits--a programming error} Assert((aCount <= FPeekCount), 'TAbDfInBitStream.DiscardBits: discarding more bits than peeked'); {since we're discarding bits already peeked, reset the peek count} FPeekCount := 0; {$ENDIF} {check that there is data in the buffer, if not it's indicates a corrupted stream: PeekBits/PeekMoreBits should have filled it} if (FBufPos = FBufEnd) then raise EAbInternalInflateError.Create( 'no more compressed data in stream [TAbDfInBitStream.DiscardBits]'); {refill the bit buffer} BitsToGo := aCount - FBitsLeft; FBitBuffer := PAb32bit(FBufPos)^; inc(FBufPos, sizeof(TAb32bit)); FBitBuffer := FBitBuffer shr BitsToGo; FBitsLeft := 32 - BitsToGo; end; {--------} function TAbDfInBitStream.ibsFillBuffer : boolean; var BytesRead : Integer; BytesToRead : Integer; i : integer; Percent : integer; Buffer : PByte; BufferCount : integer; begin {check for dumb programming mistakes: this routine should only be called if there are less than 4 bytes unused in the buffer} Assert((FBufEnd - FBufPos) < sizeof(Integer), 'TAbDfInBitStream.ibsFillBuffer: the buffer should be almost empty'); {if there are still 1, 2, or three bytes unused, move them to the front of the buffer} Buffer := FBuffer; while (FBufPos <> FBufEnd) do begin Buffer^ := FBufPos^; inc(FBufPos); inc(Buffer); end; {fill the buffer} BytesToRead := BitStreamBufferSize - (Buffer - FBuffer); BytesRead := FStream.Read(Buffer^, BytesToRead); {reset the internal pointers} FBufPos := FBuffer; FBufEnd := Buffer + BytesRead; BufferCount := FBufEnd - FBuffer; {if, as a result of the read, no data is in the buffer, return false; the caller will decide what to do about the problem} if (BufferCount = 0) then Result := false {otherwise there is data to be processed} else begin Result := true; {if we didn't read anything from the stream, we need to make sure that enough buffer is zeroed out so that reading Integer values don't produce (dreadfully) bogus values} if (BytesRead = 0) and ((BufferCount mod 4) <> 0) then begin FFakeCount := 4 - (BufferCount mod 4); for i := 0 to pred(FFakeCount) do begin FBufEnd^ := 0; inc(FBufEnd); end; end; {fire the progress event} if Assigned(FOnProgress) then begin inc(FByteCount, BytesRead); Percent := Round((100.0 * FByteCount) / FStreamSize); FOnProgress(Percent); end; end; end; {--------} function TAbDfInBitStream.PeekBits(aCount : integer) : integer; var BitsToGo : integer; TempBuffer : integer; begin {check that aCount is in the correct range 1..32} Assert((0 <= aCount) and (aCount <= 32), 'TAbDfInBitStream.PeekBits: count of bits must be between 1 and 32 inclusive'); {if we have more than enough bits in our bit buffer, return as many as needed} if (aCount <= FBitsLeft) then Result := FBitBuffer and AbExtractMask[aCount] {otherwise we shall have to read another integer out of the buffer to satisfy the request; note that this will fill the stream buffer if required} else begin BitsToGo := aCount - FBitsLeft; Result := FBitBuffer; if ((FBufEnd - FBufPos) < sizeof(TAb32bit)) then if not ibsFillBuffer then TempBuffer := 0 else TempBuffer := PAb32bit(FBufPos)^ else TempBuffer := PAb32bit(FBufPos)^; Result := Result + ((TempBuffer and AbExtractMask[BitsToGo]) shl FBitsLeft); end; {$IFOPT C+} {save the number of bits peeked for an assertion check later} FPeekCount := aCount; {$ENDIF} end; {--------} function TAbDfInBitStream.PeekMoreBits(aCount : integer) : integer; var BitsToGo : integer; TempBuffer : integer; begin BitsToGo := aCount - FBitsLeft; Result := FBitBuffer; if ((FBufEnd - FBufPos) < sizeof(TAb32bit)) then if not ibsFillBuffer then TempBuffer := 0 else TempBuffer := PAb32bit(FBufPos)^ else TempBuffer := PAb32bit(FBufPos)^; Result := Result + ((TempBuffer and AbExtractMask[BitsToGo]) shl FBitsLeft); end; {--------} function TAbDfInBitStream.ReadBit : boolean; begin if (FBitsLeft = 0) then begin if ((FBufEnd - FBufPos) < sizeof(TAb32bit)) then if not ibsFillBuffer then raise EAbInternalInflateError.Create( 'no more compressed data in stream [TAbDfInBitStream.ReadBit]'); FBitBuffer := PAb32bit(FBufPos)^; inc(FBufPos, sizeof(TAb32bit)); FBitsLeft := 32; end; Result := Odd(FBitBuffer); FBitBuffer := FBitBuffer shr 1; dec(FBitsLeft); end; {--------} function TAbDfInBitStream.ReadBits(aCount : integer) : integer; var BitsToGo : integer; begin {aCount comes from a (possibly corrupt) stream, so check that it is the correct range, 1..16} if (aCount <= 0) or (aCount > 16) then raise EAbInternalInflateError.Create( 'count of bits must be between 1 and 16 inclusive [TAbDfInBitStream.ReadBits]'); {if we have more than enough bits in our bit buffer, return as many as needed, and update the bitbuffer and the number of bits left} if (aCount <= FBitsLeft) then begin Result := FBitBuffer and AbExtractMask[aCount]; FBitBuffer := FBitBuffer shr aCount; dec(FBitsLeft, aCount); end {if we have exactly enough bits in our bit buffer, return them all, and update the bitbuffer and the number of bits left} else if (aCount = FBitsLeft) then begin Result := FBitBuffer; FBitBuffer := 0; FBitsLeft := 0; end {otherwise we shall have to read another integer out of the buffer to satisfy the request} else begin BitsToGo := aCount - FBitsLeft; Result := FBitBuffer; if ((FBufEnd - FBufPos) < sizeof(TAb32bit)) then if not ibsFillBuffer then raise EAbInternalInflateError.Create( 'no more compressed data in stream [TAbDfInBitStream.ReadBits]'); FBitBuffer := PAb32bit(FBufPos)^; inc(FBufPos, sizeof(TAb32bit)); Result := Result + ((FBitBuffer and AbExtractMask[BitsToGo]) shl FBitsLeft); FBitBuffer := FBitBuffer shr BitsToGo; FBitsLeft := 32 - BitsToGo; end; end; {--------} procedure TAbDfInBitStream.ReadBuffer(var aBuffer; aCount : integer); var i : integer; Buffer : PByte; BytesToRead : integer; BytesInBuffer : integer; begin {this method is designed to read a set of bytes and this can only be done if the stream has been byte aligned--if it isn't, it's a programming error} Assert((FBitsLeft mod 8) = 0, 'TAbDfInBitStream.ReadBuffer. cannot read a buffer unless the stream is byte-aligned'); {get the address of the user buffer as a PChar: easier arithmetic} Buffer := @aBuffer; {if we have some bits left in the bit buffer, we need to copy those first} if (FBitsLeft > 0) then begin BytesToRead := FBitsLeft div 8; for i := 0 to pred(BytesToRead) do begin Buffer^ := Byte(FBitBuffer and $FF); inc(Buffer); FBitBuffer := FBitBuffer shr 8; end; {calculate the count of bytes still to read} dec(aCount, BytesToRead); end; {calculate the number of bytes to copy} BytesInBuffer := FBufEnd - FBufPos; if (aCount <= BytesInBuffer) then BytesToRead := aCount else BytesToRead := BytesInBuffer; {copy the data from our buffer to the user buffer} Move(FBufPos^, Buffer^, BytesToRead); {update variables} dec(aCount, BytesToRead); inc(FBufPos, BytesToRead); {while there is still data to copy, keep on filling our internal buffer and copy it to the user buffer} while (aCount <> 0) do begin {increment the user buffer pointer past the data just copied} inc(Buffer, BytesToRead); {fill our buffer} if not ibsFillBuffer then raise EAbInternalInflateError.Create( 'no more compressed data in stream [TAbDfInBitStream.ReadBuffer]'); {calculate the number of bytes to copy} BytesInBuffer := FBufEnd - FBufPos; if (aCount <= BytesInBuffer) then BytesToRead := aCount else BytesToRead := BytesInBuffer; {copy the data from our buffer to the user buffer} Move(FBufPos^, Buffer^, BytesToRead); {update variables} dec(aCount, BytesToRead); inc(FBufPos, BytesToRead); end; {now we've copied everything over, reset the bit variables: they're empty and need refilling} FBitBuffer := 0; FBitsLeft := 0; end; {====================================================================} {===TAbDfOutBitStream================================================} constructor TAbDfOutBitStream.Create(aStream : TStream); begin {protect against dumb programming mistakes} Assert(aStream <> nil, 'TAbDfOutBitStream.Create: Cannot create a bit stream wrapping a nil stream'); {create the ancestor} inherited Create; {save the stream instance, allocate the buffer} FStream := aStream; GetMem(FBuffer, BitStreamBufferSize); FBufEnd := FBuffer + BitStreamBufferSize; FBufPos := FBuffer; end; {--------} destructor TAbDfOutBitStream.Destroy; var i : integer; begin {if the buffer was allocated...} if (FBuffer <> nil) then begin {if there are still some bits in the bit buffer...} if (FBitsUsed <> 0) then begin {pad the bit buffer to a byte boundary} AlignToByte; {empty the main buffer if there isn't enough room to copy over the 1 to 4 bytes in the bit buffer} if ((FBufEnd - FBufPos) < FBitsUsed div 8) then obsEmptyBuffer; {flush the bit buffer} for i := 1 to (FBitsUsed div 8) do begin FBufPos^ := Byte(FBitBuffer); FBitBuffer := FBitBuffer shr 8; inc(FBufPos); end; end; {if there is some data in the main buffer, empty it} if (FBufPos <> FBuffer) then obsEmptyBuffer; {free the buffer} FreeMem(FBuffer); end; {destroy the ancestor} inherited Destroy; end; {--------} procedure TAbDfOutBitStream.AlignToByte; begin {round up the number of bits used to the nearest 8} FBitsUsed := (FBitsUsed + 7) and $F8; {if the bit buffer is now full, flush it to the main buffer} if (FBitsUsed = 32) then begin if ((FBufEnd - FBufPos) < sizeof(TAb32bit)) then obsEmptyBuffer; PAb32bit(FBufPos)^ := FBitBuffer; inc(FBufPos, sizeof(TAb32bit)); FBitBuffer := 0; FBitsUsed := 0; end; end; {--------} procedure TAbDfOutBitStream.obsEmptyBuffer; var ByteCount : integer; BytesWritten : Integer; begin {empty the buffer} ByteCount := FBufPos - FBuffer; BytesWritten := FStream.Write(FBuffer^, ByteCount); {if we couldn't write the correct number of bytes, it's an error} if (BytesWritten <> ByteCount) then raise EAbInternalDeflateError.Create( 'could not write to the output stream [TAbDfInBitStream.obsEmptyBuffer]'); {reset the pointers} FBufPos := FBuffer; end; {--------} function TAbDfOutBitStream.Position : Integer; begin Assert(false, 'TAbDfOutBitStream.Position: not implemented yet!'); Result := -1; end; {--------} procedure TAbDfOutBitStream.WriteBit(aBit : boolean); begin {only set the corresponding bit in the bit buffer if the passed bit is set (the bit buffer is set to zero when emptied, so we don't actually have to record clear bits)} if aBit then FBitBuffer := FBitBuffer or (1 shl FBitsUsed); {we've now got one more bit} inc(FBitsUsed); {if the bit buffer is now full, flush it to the main buffer} if (FBitsUsed = 32) then begin if ((FBufEnd - FBufPos) < sizeof(TAb32bit)) then obsEmptyBuffer; PAb32bit(FBufPos)^ := FBitBuffer; inc(FBufPos, sizeof(TAb32bit)); FBitBuffer := 0; FBitsUsed := 0; end; end; {--------} procedure TAbDfOutBitStream.WriteBits(aBits : integer; aCount : integer); begin {protect against programming mistakes...} {..the count should be in the range 1 to 16 (BTW, the latter is only used once: Deflate64 with length symbol 258)} Assert((0 < aCount) and (aCount <= 16), 'TAbDfOutBitStream.WriteBits: aCount should be from 1 to 16'); {..there shouldn't be more than aCount bits} Assert((aBits shr aCount) = 0, 'TAbDfOutBitStream.WriteBits: aBits has more than aCount bits'); {copy as many bits as we can to the bit buffer} FBitBuffer := FBitBuffer or (aBits shl FBitsUsed); {increment the number of bits used} inc(FBitsUsed, aCount); {if we've overshot...} if (FBitsUsed >= 32) then begin {the bit buffer is now full, so flush it} if ((FBufEnd - FBufPos) < sizeof(TAb32bit)) then obsEmptyBuffer; PAb32bit(FBufPos)^ := FBitBuffer; inc(FBufPos, sizeof(TAb32bit)); {patch up the bit buffer and the number of bits used} dec(FBitsUsed, 32); FBitBuffer := aBits shr (aCount - FBitsUsed); end; end; {--------} procedure TAbDfOutBitStream.WriteBuffer(var aBuffer; aCount : integer); var Buffer : PByte; BytesToCopy : integer; begin {guard against dumb programming errors: we must be byte aligned} Assert((FBitsUsed and $7) = 0, 'TAbDfOutBitStream.WriteBuffer: must be byte aligned'); {use the user buffer as a PChar} Buffer := @aBuffer; {flush the bit buffer to the underlying stream} while (FBitsUsed <> 0) do begin if (FBufEnd = FBufPos) then obsEmptyBuffer; FBufPos^ := Byte(FBitBuffer and $FF); inc(FBufPos); FBitBuffer := FBitBuffer shr 8; dec(FBitsUsed, 8); end; {copy over the data to the underlying stream} BytesToCopy := FBufEnd - FBufPos; if (BytesToCopy > aCount) then BytesToCopy := aCount; Move(Buffer^, FBufPos^, BytesToCopy); inc(FBufPos, BytesToCopy); dec(aCount, BytesToCopy); while (aCount <> 0) do begin inc(Buffer, BytesToCopy); obsEmptyBuffer; BytesToCopy := FBufEnd - FBufPos; if (BytesToCopy > aCount) then BytesToCopy := aCount; Move(Buffer^, FBufPos^, BytesToCopy); inc(FBufPos, BytesToCopy); dec(aCount, BytesToCopy); end; {finish with a flushed buffer} obsEmptyBuffer; end; {--------} procedure TAbDfOutBitStream.WriteMoreBits(aBits : integer; aCount : integer); begin {the bit buffer is now full, so flush it} if ((FBufEnd - FBufPos) < sizeof(TAb32bit)) then obsEmptyBuffer; PAb32bit(FBufPos)^ := FBitBuffer; inc(FBufPos, sizeof(TAb32bit)); {patch up the bit buffer and the number of bits used} dec(FBitsUsed, 32); FBitBuffer := aBits shr (aCount - FBitsUsed); end; {====================================================================} {===TAbDfLZStream====================================================} const {Implementation note: this stream size has been chosen so that if the data must be stored, a block size of about 64K will result} StreamSize = 160 * 1024; type PWord = ^word; {--------} constructor TAbDfLZStream.Create(aSlideWin : TAbDfInputWindow; aUseDeflate64 : boolean; aLog : TAbLogger); begin {create the ancestor} inherited Create; {save the sliding window and the logger} FSlideWin := aSlideWin; FUseDeflate64 := aUseDeflate64; FLog := aLog; {create the buckets} New(FDistBuckets); New(FLitBuckets); {create the memory stream, allocate its buffer, position at start} GetMem(FStream, StreamSize); Clear; end; {--------} destructor TAbDfLZStream.Destroy; begin {free the buckets} if (FDistBuckets <> nil) then Dispose(FDistBuckets); if (FLitBuckets <> nil) then Dispose(FLitBuckets); {free the memory stream} if (FStream <> nil) then FreeMem(FStream); {destroy the ancestor} inherited Destroy; end; {--------} {$IFDEF UseLogging} procedure AddLenDistToLog(aLog : TAbLogger; aPosn : Integer; aLen : integer; aDist : integer; aOverLap : boolean); begin {NOTE the reason for this separate routine is to avoid string allocations and try..finally blocks in the main method: an optimization issue} if aOverLap then aLog.WriteLine(Format('%8x Len: %-3d, Dist: %-5d **overlap**', [aPosn, aLen, aDist])) else aLog.WriteLine(Format('%8x Len: %-3d, Dist: %-5d', [aPosn, aLen, aDist])); end; {$ENDIF} {--------} function TAbDfLZStream.AddLenDist(aLen : integer; aDist : integer) : boolean; var LenSymbol : integer; DistSymbol : integer; CurPos : PByte; begin {$IFDEF UseLogging} {log it} if (FLog <> nil) then begin if (aLen > aDist) then AddLenDistToLog(FLog, FSWPos, aLen, aDist, true) else AddLenDistToLog(FLog, FSWPos, aLen, aDist, false); inc(FSWPos, aLen); end; {$ENDIF} {write a length/distance record to the stream} CurPos := FCurPos; CurPos^ := Byte(false); inc(CurPos); PWord(CurPos)^ := word(aLen - 1); inc(CurPos, sizeof(word)); PWord(CurPos)^ := word(aDist - 1); inc(CurPos, sizeof(word)); FCurPos := CurPos; {increment the various counters} inc(FDistCount); inc(FStoredSize, aLen); {convert the length and distance to their symbols} {$IFOPT C+} {if Assertions are on} LenSymbol := AbSymbolTranslator.TranslateLength(aLen); DistSymbol := AbSymbolTranslator.TranslateDistance(aDist); {$ELSE} if (3 <= aLen) and (aLen <= 258) then LenSymbol := AbSymbolTranslator.LenSymbols[aLen-3] + 257 else LenSymbol := 285; if (aDist <= 256) then DistSymbol := AbSymbolTranslator.ShortDistSymbols[aDist - 1] else if (aDist <= 32768) then DistSymbol := AbSymbolTranslator.MediumDistSymbols[((aDist - 1) div 128) - 2] else DistSymbol := AbSymbolTranslator.LongDistSymbols[((aDist - 1) div 16384) - 2]; {$ENDIF} {increment the buckets} inc(FLitBuckets^[LenSymbol]); inc(FDistBuckets^[DistSymbol]); {return whether the stream is full and needs encoding} Result := lzsIsFull; end; {--------} {$IFDEF UseLogging} procedure AddLiteralToLog(aLog : TAbLogger; aPosn : Integer; aCh : AnsiChar); begin {NOTE the reason for this separate routine is to avoid string allocations and try..finally blocks in the main method: an optimization issue} if (' ' < aCh) and (aCh <= '~') then aLog.WriteLine(Format('%8x Char: %3d $%2x [%s]', [aPosn, ord(aCh), ord(aCh), aCh])) else aLog.WriteLine(Format('%8x Char: %3d $%2x', [aPosn, ord(aCh), ord(aCh)])); end; {$ENDIF} {--------} function TAbDfLZStream.AddLiteral(aCh : Byte) : boolean; var CurPos : PByte; begin {$IFDEF UseLogging} {log it} if (FLog <> nil) then begin AddLiteralToLog(FLog, FSWPos, aCh); inc(FSWPos); end; {$ENDIF} {write a literal to the internal stream} CurPos := FCurPos; CurPos^ := Byte(true); inc(CurPos); CurPos^ := aCh; inc(CurPos); FCurPos := CurPos; {increment the various counters} inc(FLitCount); inc(FLitBuckets^[byte(aCh)]); inc(FStoredSize); {return whether the stream is full and needs encoding} Result := lzsIsFull; end; {--------} procedure TAbDfLZStream.Clear; begin {position the stream at the start} Rewind; {reset all variables} FStrmEnd := nil; FLitCount := 0; FDistCount := 0; FStartOfs := FSlideWin.Position; FStoredSize := 0; {$IFDEF UseLogging} FSWPos := FStartOfs; {$ENDIF} {reset the buckets} FillChar(FLitBuckets^, sizeof(FLitBuckets^), 0); FLitBuckets^[256] := 1; { end-of-block marker: it's always there...} FillChar(FDistBuckets^, sizeof(FDistBuckets^), 0); end; {--------} procedure TAbDfLZStream.Encode(aBitStrm : TAbDfOutBitStream; aLitTree : TAbDfDecodeHuffmanTree; aDistTree : TAbDfDecodeHuffmanTree; aUseDeflate64 : boolean); var Len : integer; Dist : integer; Symbol : integer; CurPos : PByte; StrmEnd : PByte; Code : Integer; ExtraBits : Integer; begin {rewind the LZ77 stream} Rewind; {for speed use local variables} CurPos := FCurPos; StrmEnd := FStrmEnd; {while there are still items in the stream...} while (CurPos < StrmEnd) do begin {if the next item is a literal...} if boolean(CurPos^) then begin {encode the literal character as a symbol} inc(CurPos); {$IFOPT C+} {if Assertions are on} Code := aLitTree.Encode(byte(CurPos^)); {$ELSE} Code := aLitTree.Encodes^[byte(CurPos^)]; {$ENDIF} inc(CurPos); {write the code out to the bit stream} {$IFOPT C+} aBitStrm.WriteBits(Code and $FFFF, (Code shr 16) and $FF); {$ELSE} with aBitStrm do begin BitBuffer := BitBuffer or ((Code and $FFFF) shl BitsUsed); BitsUsed := BitsUsed + ((Code shr 16) and $FF); if (BitsUsed >= 32) then WriteMoreBits(Code and $FFFF, (Code shr 16) and $FF); end; {$ENDIF} end {otherwise it's a length/distance pair} else begin {DO THE LENGTH FIRST-------------------------------------------} {get the length from the stream} inc(CurPos); Len := integer(PWord(CurPos)^) + 1; inc(CurPos, sizeof(word)); {translate it to a symbol and convert that to a code using the literal/length huffman tree} {$IFOPT C+} {if Assertions are on} Symbol := AbSymbolTranslator.TranslateLength(Len); Code := aLitTree.Encode(Symbol); {$ELSE} if (3 <= Len) and (Len <= 258) then Symbol := AbSymbolTranslator.LenSymbols[Len-3] + 257 else Symbol := 285; Code := aLitTree.Encodes^[Symbol]; {$ENDIF} {output the length code} {$IFOPT C+} aBitStrm.WriteBits(Code and $FFFF, (Code shr 16) and $FF); {$ELSE} with aBitStrm do begin BitBuffer := BitBuffer or ((Code and $FFFF) shl BitsUsed); BitsUsed := BitsUsed + ((Code shr 16) and $FF); if (BitsUsed >= 32) then WriteMoreBits(Code and $FFFF, (Code shr 16) and $FF); end; {$ENDIF} {if the length symbol were 285, its definition changes from Deflate to Deflate64, so make it a special case: for Deflate there are no extra bits, for Deflate64 output the (length - 3) as 16 bits} if (Symbol = 285) then begin if aUseDeflate64 then begin {$IFOPT C+} aBitStrm.WriteBits(Len - 3, 16); {$ELSE} with aBitStrm do begin BitBuffer := BitBuffer or ((Len - 3) shl BitsUsed); BitsUsed := BitsUsed + 16; if (BitsUsed >= 32) then WriteMoreBits(Len - 3, 16); end; {$ENDIF} end; end {otherwise if there are extra bits to be output for this length, calculate them and output them} else begin ExtraBits := Code shr 24; if (ExtraBits <> 0) then begin {$IFOPT C+} aBitStrm.WriteBits((Len - dfc_LengthBase[Symbol - 257]), ExtraBits); {$ELSE} with aBitStrm do begin BitBuffer := BitBuffer or ((Len - dfc_LengthBase[Symbol - 257]) shl BitsUsed); BitsUsed := BitsUsed + ExtraBits; if (BitsUsed >= 32) then WriteMoreBits((Len - dfc_LengthBase[Symbol - 257]), ExtraBits); end; {$ENDIF} end; end; {DO THE DISTANCE NEXT------------------------------------------} {get the distance from the stream} Dist := integer(PWord(CurPos)^) + 1; inc(CurPos, sizeof(word)); {translate it to a symbol and convert that to a code using the distance huffman tree} {$IFOPT C+} {if Assertions are on} Symbol := AbSymbolTranslator.TranslateDistance(Dist); Assert(aUseDeflate64 or (Symbol < 30), 'TAbDfLZStream.Encode: a Deflate64 distance symbol has been generated for Deflate'); Code := aDistTree.Encode(Symbol); {$ELSE} if (Dist <= 256) then Symbol := AbSymbolTranslator.ShortDistSymbols[Dist - 1] else if (Dist <= 32768) then Symbol := AbSymbolTranslator.MediumDistSymbols[((Dist - 1) div 128) - 2] else Symbol := AbSymbolTranslator.LongDistSymbols[((Dist - 1) div 16384) - 2]; Code := aDistTree.Encodes^[Symbol]; {$ENDIF} {output the distance code} {$IFOPT C+} aBitStrm.WriteBits(Code and $FFFF, (Code shr 16) and $FF); {$ELSE} with aBitStrm do begin BitBuffer := BitBuffer or ((Code and $FFFF) shl BitsUsed); BitsUsed := BitsUsed + ((Code shr 16) and $FF); if (BitsUsed >= 32) then WriteMoreBits(Code and $FFFF, (Code shr 16) and $FF); end; {$ENDIF} {if there are extra bits to be output for this distance, calculate them and output them} ExtraBits := Code shr 24; if (ExtraBits <> 0) then begin {$IFOPT C+} aBitStrm.WriteBits((Dist - dfc_DistanceBase[Symbol]), ExtraBits); {$ELSE} with aBitStrm do begin BitBuffer := BitBuffer or ((Dist - dfc_DistanceBase[Symbol]) shl BitsUsed); BitsUsed := BitsUsed + ExtraBits; if (BitsUsed >= 32) then WriteMoreBits((Dist - dfc_DistanceBase[Symbol]), ExtraBits); end; {$ENDIF} end; end; end; {clear the stream; ready for some more items} { Clear;} end; {--------} function TAbDfLZStream.lzsGetApproxSize : UInt32; var i : integer; begin {note: calculates an approximate compressed size without taking too long about it. The average encoded bit length for literals and lengths is assumed to be 8. Distances are assumed to follow the static tree definition (ie, 5 bits per distance, plus any extra bits). There are FLitCount literals, FDistCount lengths, and FDistCount distances} Result := (13 * FDistCount) + (8 * FLitCount); for i := 4 to 31 do inc(Result, FDistBuckets^[i] * dfc_DistExtraBits[i]); Result := Result div 8; end; {--------} function TAbDfLZStream.lzsGetStaticSize : integer; var i : integer; begin Result := 0; for i := 0 to 143 do inc(Result, FLitBuckets^[i] * 8); for i := 144 to 255 do inc(Result, FLitBuckets^[i] * 9); inc(Result, FLitBuckets^[256] * 7); for i := 257 to 279 do inc(Result, FLitBuckets^[i] * (7 + dfc_LitExtraBits[i - dfc_LitExtraOffset])); for i := 280 to 284 do inc(Result, FLitBuckets^[i] * (8 + dfc_LitExtraBits[i - dfc_LitExtraOffset])); if FUseDeflate64 then inc(Result, FLitBuckets^[285] * (8 + 16)) else inc(Result, FLitBuckets^[285] * 8); for i := 0 to 31 do inc(Result, FDistBuckets^[i] * (5 + dfc_DistExtraBits[i])); end; {--------} function TAbDfLZStream.lzsGetStoredSize : integer; begin Result := FStoredSize; {Result := FSlideWin.Position - FStartOfs;} end; {--------} function TAbDfLZStream.lzsIsFull : boolean; begin {if the number of hits on the (eventual) literal tree is a multiple of 8192, the stream is full if the majority were straight literals and we're getting approx 50% compression} if (((FLitCount + FDistCount) and $1FFF) = 0) then begin Result := (FDistCount < FLitCount) and (lzsGetApproxSize < (FStoredSize div 2)); if Result then Exit; end; {otherwise the stream is full if the number of hits on the literal tree or on the distance tree is 32768} { Result := (FCurPos - FStream) > (StreamSIze - 100);} Result := (FDistCount >= 32768) or ((FLitCount + FDistCount) >= 32768); end; {--------} procedure TAbDfLZStream.ReadStoredBuffer(var aBuffer; aCount : integer); begin FSlideWin.ReadBuffer(aBuffer, aCount, FStartOfs); inc(FStartOfs, aCount); end; {--------} procedure TAbDfLZStream.Rewind; begin {position the stream at the beginning} FStrmEnd := FCurPos; FCurPos := FStream; end; {====================================================================} {===TAbDfCodeLenStream===============================================} constructor TAbDfCodeLenStream.Create(aLog : TAbLogger); begin {create the ancestor} inherited Create; {allocate the stream (to contain all literals and distances and possible extra data} GetMem(FStream, (285 + 32) * 2); FPosition := FStream; {allocate the buckets} FBuckets := AllocMem(sizeof(TAbDfCodeLenBuckets)); end; {--------} destructor TAbDfCodeLenStream.Destroy; begin {free the stream} if (FStream <> nil) then FreeMem(FStream); {free the buckets} if (FBuckets <> nil) then Dispose(FBuckets); {destroy the ancestor} inherited Destroy; end; {--------} procedure TAbDfCodeLenStream.Build(const aCodeLens : array of integer; aCount : integer); var i : integer; State : (ScanStart, ScanNormal, Got2nd, Got3rd); Count : integer; ThisCount : integer; CodeLen : integer; PrevCodeLen : integer; CurPos : PByte; Buckets : PAbDfCodeLenBuckets; begin {start the automaton} State := ScanStart; CurPos := FStream; Buckets := FBuckets; Count := 0; PrevCodeLen := 0; {for all the codelengths in the array (plus a fake one at the end to ensure all codeslengths are counted)...} for i := 0 to aCount do begin {get the current codelength} if (i = aCount) then CodeLen := -1 else CodeLen := aCodeLens[i]; {switch based on the state...} case State of ScanStart : begin PrevCodeLen := CodeLen; State := ScanNormal; end; ScanNormal : begin {if the current code is the same as the previous, move to the next state} if (CodeLen = PrevCodeLen) then State := Got2nd {otherwise output the previous code} else begin CurPos^ := Byte(PrevCodeLen); inc(CurPos); inc(Buckets^[PrevCodeLen]); PrevCodeLen := CodeLen; end; end; Got2nd : begin {if the current code is the same as the previous, move to the next state; we now have three similar codes in a row} if (CodeLen = PrevCodeLen) then begin State := Got3rd; Count := 3; end {otherwise output the previous two similar codes, move back to the initial state} else begin CurPos^ := Byte(PrevCodeLen); inc(CurPos); CurPos^ := Byte(PrevCodeLen); inc(CurPos); inc(Buckets^[PrevCodeLen], 2); PrevCodeLen := CodeLen; State := ScanNormal; end; end; Got3rd: begin {if the current code is the same as the previous, increment the count of similar codes} if (CodeLen = PrevCodeLen) then inc(Count) {otherwise we need to output the repeat values...} else begin {if the previous code were a zero code...} if (PrevCodeLen = 0) then begin {while there are zero codes to be output...} while (Count <> 0) do begin {if there are less than three zero codes, output them individually} if (Count < 3) then begin while (Count <> 0) do begin CurPos^ := 0; inc(CurPos); inc(Buckets^[0]); dec(Count); end; end {if there are less than 11 successive zero codes, output a 17 code and the count of zeros} else if (Count < 11) then begin CurPos^ := 17; inc(CurPos); inc(Buckets^[17]); CurPos^ := Byte(Count - 3); inc(CurPos); Count := 0; end {otherwise output an 18 code and the count of zeros} else begin ThisCount := Count; if (ThisCount > 138) then ThisCount := 138; CurPos^ := 18; inc(CurPos); inc(Buckets^[18]); CurPos^ := Byte(ThisCount - 11); inc(CurPos); dec(Count, ThisCount); end; end; end {otherwise the previous code was a non-zero code...} else begin {output the first code} CurPos^ := Byte(PrevCodeLen); inc(CurPos); inc(Buckets^[PrevCodeLen]); dec(Count); {while there are more codes to be output...} while (Count <> 0) do begin {if there are less than three codes, output them individually} if (Count < 3) then begin while (Count <> 0) do begin CurPos^ := Byte(PrevCodeLen); inc(CurPos); inc(Buckets^[PrevCodeLen]); dec(Count); end; end {otherwise output an 16 code and the count} else begin ThisCount := Count; if (ThisCount > 6) then ThisCount := 6; CurPos^ := 16; inc(CurPos); inc(Buckets^[16]); CurPos^ := Byte(ThisCount - 3); inc(CurPos); dec(Count, ThisCount); end; end; end; {move back to the initial state} PrevCodeLen := CodeLen; State := ScanNormal; end; end; end; end; {set the read position} FStrmEnd := CurPos; FPosition := FStream; end; {--------} procedure TAbDfCodeLenStream.Encode(aBitStrm : TAbDfOutBitStream; aTree : TAbDfDecodeHuffmanTree); var Symbol : integer; ExtraData : integer; Code : Integer; CurPos : PByte; StrmEnd : PByte; begin {prepare for the loop} CurPos := FPosition; StrmEnd := FStrmEnd; {while there are tokens in the stream...} while (CurPos <> StrmEnd) do begin {get the next symbol} Symbol := ord(CurPos^); inc(CurPos); {if the symbol is 0..15, get the code and output it} if (Symbol <= 15) then begin {$IFOPT C+} {if Assertions are on} Code := aTree.Encode(Symbol); {$ELSE} Code:= aTree.Encodes^[Symbol]; {$ENDIF} aBitStrm.WriteBits(Code and $FFFF, (Code shr 16) and $FF); end {otherwise the symbol is 16, 17, or 18} else begin {get the extra data} ExtraData := ord(CurPos^); inc(CurPos); {get the code and output it} {$IFOPT C+} {if Assertions are on} Code := aTree.Encode(Symbol); {$ELSE} Code:= aTree.Encodes^[Symbol]; {$ENDIF} aBitStrm.WriteBits(Code and $FFFF, (Code shr 16) and $FF); if (Symbol = 16) then aBitStrm.WriteBits(ExtraData, 2) else if (Symbol = 17) then aBitStrm.WriteBits(ExtraData, 3) else {Symbol = 18} aBitStrm.WriteBits(ExtraData, 7); end; end; end; {====================================================================} end.
30.309868
96
0.612511
fce27799404cd825dcad4304420ef583df2fd9b7
10
pas
Pascal
test_pascal/autofix/missingtoken/dot.pas
tranleduy2000/pascalnide
c7f3f79ecf4cf6a81b32c7d389aad7f4034c8f01
[ "Apache-2.0" ]
81
2017-05-07T13:26:56.000Z
2022-03-03T19:39:15.000Z
04_say_hello_and_goodbye/nada.txt
pricees/jison_tutorial
5a8c02c1f44875ccd05ccbf1b1deef97ae6b8848
[ "MIT" ]
52
2017-06-13T08:46:43.000Z
2021-06-09T09:50:07.000Z
test_pascal/autofix/missingtoken/dot.pas
tranleduy2000/pascalnide
c7f3f79ecf4cf6a81b32c7d389aad7f4034c8f01
[ "Apache-2.0" ]
28
2017-05-22T21:09:58.000Z
2021-09-07T13:05:27.000Z
begin end
3.333333
5
0.8
fcfdb49080d7842833a3b8a46e598054abbd9356
209
dpr
Pascal
sample/WizEdit/WizGBCEdit.dpr
bryful/Wiz
020e0b5eb180595d7ce879d8305ed3792c49455d
[ "MIT" ]
null
null
null
sample/WizEdit/WizGBCEdit.dpr
bryful/Wiz
020e0b5eb180595d7ce879d8305ed3792c49455d
[ "MIT" ]
1
2019-11-23T06:26:38.000Z
2019-11-23T06:26:38.000Z
sample/WizEdit/WizGBCEdit.dpr
bryful/Wiz
020e0b5eb180595d7ce879d8305ed3792c49455d
[ "MIT" ]
null
null
null
program WizGBCEdit; uses Forms, MainForm in 'MainForm.pas' {Form1}, WizGBC in 'WizGBC.pas'; {$R *.res} begin Application.Initialize; Application.CreateForm(TForm1, Form1); Application.Run; end.
13.933333
40
0.708134
c3678162347e11a0fda057e9d95ebbd8eec6d413
78,754
pas
Pascal
Source/vcl/WrapVclGraphics.pas
eugenekryukov/python4delphi
624d9b658dd97afacf4556ab86a40e2cba9ed3ea
[ "MIT" ]
null
null
null
Source/vcl/WrapVclGraphics.pas
eugenekryukov/python4delphi
624d9b658dd97afacf4556ab86a40e2cba9ed3ea
[ "MIT" ]
null
null
null
Source/vcl/WrapVclGraphics.pas
eugenekryukov/python4delphi
624d9b658dd97afacf4556ab86a40e2cba9ed3ea
[ "MIT" ]
null
null
null
{$I ..\Definition.Inc} unit WrapVclGraphics; interface uses Classes, Windows, SysUtils, PythonEngine, WrapDelphi, WrapDelphiClasses, Graphics; type TPyDelphiGraphic = class(TPyDelphiPersistent) private function GetDelphiObject: TGraphic; procedure SetDelphiObject(const Value: TGraphic); protected // Exposed Methods function LoadFromFile_Wrapper(args : PPyObject) : PPyObject; cdecl; function SaveToFile_Wrapper(args : PPyObject) : PPyObject; cdecl; function LoadFromStream_Wrapper(args : PPyObject) : PPyObject; cdecl; function SaveToStream_Wrapper(args : PPyObject) : PPyObject; cdecl; function LoadFromClipboardFormat_Wrapper(args : PPyObject) : PPyObject; cdecl; function SaveToClipboardFormat_Wrapper(args : PPyObject) : PPyObject; cdecl; // Property Getters function Get_Empty( AContext : Pointer) : PPyObject; cdecl; function Get_Height( AContext : Pointer) : PPyObject; cdecl; function Get_Modified( AContext : Pointer) : PPyObject; cdecl; function Get_Palette( AContext : Pointer) : PPyObject; cdecl; function Get_PaletteModified( AContext : Pointer) : PPyObject; cdecl; function Get_Transparent( AContext : Pointer) : PPyObject; cdecl; function Get_Width( AContext : Pointer) : PPyObject; cdecl; // Property Setters function Set_Height( AValue : PPyObject; AContext : Pointer) : integer; cdecl; function Set_Modified( AValue : PPyObject; AContext : Pointer) : integer; cdecl; function Set_Palette( AValue : PPyObject; AContext : Pointer) : integer; cdecl; function Set_PaletteModified( AValue : PPyObject; AContext : Pointer) : integer; cdecl; function Set_Transparent( AValue : PPyObject; AContext : Pointer) : integer; cdecl; function Set_Width( AValue : PPyObject; AContext : Pointer) : integer; cdecl; public class function DelphiObjectClass : TClass; override; class procedure RegisterGetSets( PythonType : TPythonType ); override; class procedure RegisterMethods( PythonType : TPythonType ); override; // Properties property DelphiObject: TGraphic read GetDelphiObject write SetDelphiObject; end; TPyDelphiBitmap = class(TPyDelphiGraphic) private function GetDelphiObject: TBitmap; procedure SetDelphiObject(const Value: TBitmap); protected // Exposed Methods {$IFNDEF FPC} function Dormant_Wrapper(args : PPyObject) : PPyObject; cdecl; {$ENDIF FPC} function FreeImage_Wrapper(args : PPyObject) : PPyObject; cdecl; function LoadFromResourceName_Wrapper(args : PPyObject) : PPyObject; cdecl; function LoadFromResourceID_Wrapper(args : PPyObject) : PPyObject; cdecl; function Mask_Wrapper(args : PPyObject) : PPyObject; cdecl; function ReleaseHandle_Wrapper(args : PPyObject) : PPyObject; cdecl; function ReleaseMaskHandle_Wrapper(args : PPyObject) : PPyObject; cdecl; function ReleasePalette_Wrapper(args : PPyObject) : PPyObject; cdecl; // Property Getters function Get_Canvas( AContext : Pointer) : PPyObject; cdecl; function Get_Handle( AContext : Pointer) : PPyObject; cdecl; function Get_HandleAllocated( AContext : Pointer) : PPyObject; cdecl; function Get_HandleType( AContext : Pointer) : PPyObject; cdecl; {$IFNDEF FPC} function Get_IgnorePalette( AContext : Pointer) : PPyObject; cdecl; {$ENDIF FPC} function Get_MaskHandle( AContext : Pointer) : PPyObject; cdecl; function Get_Monochrome( AContext : Pointer) : PPyObject; cdecl; function Get_PixelFormat( AContext : Pointer) : PPyObject; cdecl; function Get_TransparentColor( AContext : Pointer) : PPyObject; cdecl; function Get_TransparentMode( AContext : Pointer) : PPyObject; cdecl; // Property Setters function Set_Handle( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; function Set_HandleType( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; {$IFNDEF FPC} function Set_IgnorePalette( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; {$ENDIF FPC} function Set_MaskHandle( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; function Set_Monochrome( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; function Set_PixelFormat( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; function Set_TransparentColor( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; function Set_TransparentMode( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; public class function DelphiObjectClass : TClass; override; class procedure RegisterGetSets( PythonType : TPythonType ); override; class procedure RegisterMethods( PythonType : TPythonType ); override; // Properties property DelphiObject: TBitmap read GetDelphiObject write SetDelphiObject; end; {$IFNDEF FPC} TPyDelphiMetaFile = class(TPyDelphiGraphic) private function GetDelphiObject: TMetaFile; procedure SetDelphiObject(const Value: TMetaFile); protected // Exposed Methods function Clear_Wrapper(args : PPyObject) : PPyObject; cdecl; function ReleaseHandle_Wrapper(args : PPyObject) : PPyObject; cdecl; // Property Getters function Get_CreatedBy( AContext : Pointer) : PPyObject; cdecl; function Get_Description( AContext : Pointer) : PPyObject; cdecl; function Get_Enhanced( AContext : Pointer) : PPyObject; cdecl; function Get_Handle( AContext : Pointer) : PPyObject; cdecl; function Get_HandleAllocated( AContext : Pointer) : PPyObject; cdecl; function Get_MMWidth( AContext : Pointer) : PPyObject; cdecl; function Get_MMHeight( AContext : Pointer) : PPyObject; cdecl; function Get_Inch( AContext : Pointer) : PPyObject; cdecl; // Property Setters function Set_Enhanced( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; function Set_Handle( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; function Set_MMWidth( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; function Set_MMHeight( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; function Set_Inch( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; public class function DelphiObjectClass : TClass; override; class procedure RegisterGetSets( PythonType : TPythonType ); override; class procedure RegisterMethods( PythonType : TPythonType ); override; // Properties property DelphiObject: TMetaFile read GetDelphiObject write SetDelphiObject; end; {$ENDIF FPC} TPyDelphiIcon = class(TPyDelphiGraphic) private function GetDelphiObject: TIcon; procedure SetDelphiObject(const Value: TIcon); protected // Exposed Methods function ReleaseHandle_Wrapper(args : PPyObject) : PPyObject; cdecl; // Property Getters function Get_Handle( AContext : Pointer) : PPyObject; cdecl; function Get_HandleAllocated( AContext : Pointer) : PPyObject; cdecl; // Property Setters function Set_Handle( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; public class function DelphiObjectClass : TClass; override; class procedure RegisterGetSets( PythonType : TPythonType ); override; class procedure RegisterMethods( PythonType : TPythonType ); override; // Properties property DelphiObject: TIcon read GetDelphiObject write SetDelphiObject; end; TPyDelphiPicture = class(TPyDelphiPersistent) private function GetDelphiObject: TPicture; procedure SetDelphiObject(const Value: TPicture); protected // Exposed Methods function LoadFromFile_Wrapper(args : PPyObject) : PPyObject; cdecl; function SaveToFile_Wrapper(args : PPyObject) : PPyObject; cdecl; // Property Getters function Get_Bitmap( AContext : Pointer) : PPyObject; cdecl; function Get_Graphic( AContext : Pointer) : PPyObject; cdecl; function Get_Height( AContext : Pointer) : PPyObject; cdecl; function Get_Icon( AContext : Pointer) : PPyObject; cdecl; {$IFNDEF FPC} function Get_MetaFile( AContext : Pointer) : PPyObject; cdecl; {$ENDIF FPC} function Get_Width( AContext : Pointer) : PPyObject; cdecl; // Property Setters function Set_Bitmap( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; function Set_Graphic( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; function Set_Icon( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; {$IFNDEF FPC} function Set_MetaFile( AValue : PPyObject; AContext : Pointer) : Integer; cdecl; {$ENDIF FPC} public class function DelphiObjectClass : TClass; override; class procedure RegisterGetSets( PythonType : TPythonType ); override; class procedure RegisterMethods( PythonType : TPythonType ); override; // Properties property DelphiObject: TPicture read GetDelphiObject write SetDelphiObject; end; { PyObject wrapping TCanvas } TPyDelphiCanvas = class(TPyDelphiPersistent) private function GetDelphiObject: TCanvas; procedure SetDelphiObject(const Value: TCanvas); protected // Exposed Methods function Arc_Wrapper(args : PPyObject) : PPyObject; cdecl; {$IFNDEF FPC} function BrushCopy_Wrapper(args : PPyObject) : PPyObject; cdecl; {$ENDIF FPC} function Chord_Wrapper(args : PPyObject) : PPyObject; cdecl; function CopyRect_Wrapper(args : PPyObject) : PPyObject; cdecl; function Draw_Wrapper(args : PPyObject) : PPyObject; cdecl; function DrawFocusRect_Wrapper(args : PPyObject) : PPyObject; cdecl; function Ellipse_Wrapper(args : PPyObject) : PPyObject; cdecl; function FillRect_Wrapper(args : PPyObject) : PPyObject; cdecl; function FloodFill_Wrapper(args : PPyObject) : PPyObject; cdecl; function FrameRect_Wrapper(args : PPyObject) : PPyObject; cdecl; function LineTo_Wrapper(args : PPyObject) : PPyObject; cdecl; function Lock_Wrapper(args : PPyObject) : PPyObject; cdecl; function MoveTo_Wrapper(args : PPyObject) : PPyObject; cdecl; function Pie_Wrapper(args : PPyObject) : PPyObject; cdecl; function Polygon_Wrapper(args : PPyObject) : PPyObject; cdecl; function Polyline_Wrapper(args : PPyObject) : PPyObject; cdecl; function PolyBezier_Wrapper(args : PPyObject) : PPyObject; cdecl; {$IFNDEF FPC} function PolyBezierTo_Wrapper(args : PPyObject) : PPyObject; cdecl; {$ENDIF FPC} function Rectangle_Wrapper(args : PPyObject) : PPyObject; cdecl; function Refresh_Wrapper(args : PPyObject) : PPyObject; cdecl; function RoundRect_Wrapper(args : PPyObject) : PPyObject; cdecl; function StretchDraw_Wrapper(args : PPyObject) : PPyObject; cdecl; function TextExtent_Wrapper(args : PPyObject) : PPyObject; cdecl; function TextHeight_Wrapper(args : PPyObject) : PPyObject; cdecl; function TextOut_Wrapper(args : PPyObject) : PPyObject; cdecl; function TextRect_Wrapper(args : PPyObject) : PPyObject; cdecl; function TextWidth_Wrapper(args : PPyObject) : PPyObject; cdecl; function TryLock_Wrapper(args : PPyObject) : PPyObject; cdecl; function Unlock_Wrapper(args : PPyObject) : PPyObject; cdecl; // Pixels[x,y] : TColor wrapper -> GetPixel / SetPixel function GetPixel(args : PPyObject) : PPyObject; cdecl; function SetPixel(args : PPyObject) : PPyObject; cdecl; // Property Getters function Get_HandleAllocated( AContext : Pointer) : PPyObject; cdecl; function Get_ClipRect( AContext : Pointer) : PPyObject; cdecl; function Get_Handle( AContext : Pointer) : PPyObject; cdecl; function Get_LockCount( AContext : Pointer) : PPyObject; cdecl; {$IFNDEF FPC} function Get_CanvasOrientation( AContext : Pointer) : PPyObject; cdecl; function Get_TextFlags( AContext : Pointer) : PPyObject; cdecl; {$ENDIF FPC} function Get_PenPos( AContext : Pointer) : PPyObject; cdecl; function Get_OnChange( AContext : Pointer) : PPyObject; cdecl; function Get_OnChanging( AContext : Pointer) : PPyObject; cdecl; // Property Setters function Set_Handle( AValue : PPyObject; AContext : Pointer) : integer; cdecl; {$IFNDEF FPC} function Set_TextFlags( AValue : PPyObject; AContext : Pointer) : integer; cdecl; {$ENDIF FPC} function Set_OnChange( AValue : PPyObject; AContext : Pointer) : integer; cdecl; function Set_OnChanging( AValue : PPyObject; AContext : Pointer) : integer; cdecl; public class function DelphiObjectClass : TClass; override; class procedure RegisterGetSets( PythonType : TPythonType ); override; class procedure RegisterMethods( PythonType : TPythonType ); override; // Properties property DelphiObject: TCanvas read GetDelphiObject write SetDelphiObject; end; implementation uses Types, {$IFDEF FPC} GraphType, {$ENDIF FPC} WrapDelphiTypes; { Register the wrappers, the globals and the constants } type TGraphicsRegistration = class(TRegisteredUnit) public function Name : string; override; procedure RegisterWrappers(APyDelphiWrapper : TPyDelphiWrapper); override; procedure DefineVars(APyDelphiWrapper : TPyDelphiWrapper); override; end; { TGraphicsRegistration } procedure TGraphicsRegistration.DefineVars(APyDelphiWrapper: TPyDelphiWrapper); begin inherited; APyDelphiWrapper.DefineVar('clScrollBar', clScrollBar); APyDelphiWrapper.DefineVar('clBackground', clBackground); APyDelphiWrapper.DefineVar('clActiveCaption', clActiveCaption); APyDelphiWrapper.DefineVar('clInactiveCaption', clInactiveCaption); APyDelphiWrapper.DefineVar('clMenu', clMenu); APyDelphiWrapper.DefineVar('clWindow', clWindow); APyDelphiWrapper.DefineVar('clWindowFrame', clWindowFrame); APyDelphiWrapper.DefineVar('clMenuText', clMenuText); APyDelphiWrapper.DefineVar('clWindowText', clWindowText); APyDelphiWrapper.DefineVar('clCaptionText', clCaptionText); APyDelphiWrapper.DefineVar('clActiveBorder', clActiveBorder); APyDelphiWrapper.DefineVar('clInactiveBorder', clInactiveBorder); APyDelphiWrapper.DefineVar('clAppWorkSpace', clAppWorkSpace); APyDelphiWrapper.DefineVar('clHighlight', clHighlight); APyDelphiWrapper.DefineVar('clHighlightText', clHighlightText); APyDelphiWrapper.DefineVar('clBtnFace', clBtnFace); APyDelphiWrapper.DefineVar('clBtnShadow', clBtnShadow); APyDelphiWrapper.DefineVar('clGrayText', clGrayText); APyDelphiWrapper.DefineVar('clBtnText', clBtnText); APyDelphiWrapper.DefineVar('clInactiveCaptionText', clInactiveCaptionText); APyDelphiWrapper.DefineVar('clBtnHighlight', clBtnHighlight); APyDelphiWrapper.DefineVar('cl3DDkShadow', cl3DDkShadow); APyDelphiWrapper.DefineVar('cl3DLight', cl3DLight); APyDelphiWrapper.DefineVar('clInfoText', clInfoText); APyDelphiWrapper.DefineVar('clInfoBk', clInfoBk); APyDelphiWrapper.DefineVar('clHotLight', clHotLight); APyDelphiWrapper.DefineVar('clGradientActiveCaption', clGradientActiveCaption); APyDelphiWrapper.DefineVar('clGradientInactiveCaption', clGradientInactiveCaption); APyDelphiWrapper.DefineVar('clMenuHighlight', clMenuHighlight); APyDelphiWrapper.DefineVar('clMenuBar', clMenuBar); APyDelphiWrapper.DefineVar('clBlack', clBlack); APyDelphiWrapper.DefineVar('clMaroon', clMaroon); APyDelphiWrapper.DefineVar('clGreen', clGreen); APyDelphiWrapper.DefineVar('clOlive', clOlive); APyDelphiWrapper.DefineVar('clNavy', clNavy); APyDelphiWrapper.DefineVar('clPurple', clPurple); APyDelphiWrapper.DefineVar('clTeal', clTeal); APyDelphiWrapper.DefineVar('clGray', clGray); APyDelphiWrapper.DefineVar('clSilver', clSilver); APyDelphiWrapper.DefineVar('clRed', clRed); APyDelphiWrapper.DefineVar('clLime', clLime); APyDelphiWrapper.DefineVar('clYellow', clYellow); APyDelphiWrapper.DefineVar('clBlue', clBlue); APyDelphiWrapper.DefineVar('clFuchsia', clFuchsia); APyDelphiWrapper.DefineVar('clAqua', clAqua); APyDelphiWrapper.DefineVar('clLtGray', clLtGray); APyDelphiWrapper.DefineVar('clDkGray', clDkGray); APyDelphiWrapper.DefineVar('clWhite', clWhite); APyDelphiWrapper.DefineVar('clMoneyGreen', clMoneyGreen); APyDelphiWrapper.DefineVar('clSkyBlue', clSkyBlue); APyDelphiWrapper.DefineVar('clCream', clCream); APyDelphiWrapper.DefineVar('clMedGray', clMedGray); APyDelphiWrapper.DefineVar('clNone', clNone); APyDelphiWrapper.DefineVar('clDefault', clDefault); APyDelphiWrapper.DefineVar('fsSurface', 'fsSurface'); APyDelphiWrapper.DefineVar('fsBorder', 'fsBorder'); end; function TGraphicsRegistration.Name: string; begin Result := 'Graphics'; end; procedure TGraphicsRegistration.RegisterWrappers(APyDelphiWrapper: TPyDelphiWrapper); begin inherited; APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiGraphic); APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiBitmap); {$IFNDEF FPC} APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiMetaFile); {$ENDIF FPC} APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiIcon); APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiPicture); APyDelphiWrapper.RegisterDelphiWrapper(TPyDelphiCanvas); end; { TPyDelphiGraphic } class function TPyDelphiGraphic.DelphiObjectClass: TClass; begin Result := TGraphic; end; function TPyDelphiGraphic.GetDelphiObject: TGraphic; begin Result := TGraphic(inherited DelphiObject); end; function TPyDelphiGraphic.Get_Empty(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.VariantAsPyObject(DelphiObject.Empty); end; function TPyDelphiGraphic.Get_Height(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.Height); end; function TPyDelphiGraphic.Get_Modified(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.VariantAsPyObject(DelphiObject.Modified); end; function TPyDelphiGraphic.Get_Palette(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.Palette); end; function TPyDelphiGraphic.Get_PaletteModified( AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.VariantAsPyObject(DelphiObject.PaletteModified); end; function TPyDelphiGraphic.Get_Transparent(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.VariantAsPyObject(DelphiObject.Transparent); end; function TPyDelphiGraphic.Get_Width(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.Width); end; function TPyDelphiGraphic.LoadFromClipboardFormat_Wrapper( args: PPyObject): PPyObject; var _format : Integer; {$IFNDEF FPC} _data : Integer; _palette : Integer; {$ENDIF FPC} begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin {$IFDEF FPC} if PyArg_ParseTuple( args, 'i:LoadFromClipboardFormat',@_format ) <> 0 then begin DelphiObject.LoadFromClipboardFormat(_format); {$ELSE FPC} if PyArg_ParseTuple( args, 'iii:LoadFromClipboardFormat',@_format, @_data, @_palette ) <> 0 then begin DelphiObject.LoadFromClipboardFormat(_format, _data, _palette); {$ENDIF FPC} Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiGraphic.LoadFromFile_Wrapper(args: PPyObject): PPyObject; var _pFileName : PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'O:LoadFromFile',@_pFileName ) <> 0 then begin DelphiObject.LoadFromFile(PyObjectAsString(_pFileName)); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiGraphic.LoadFromStream_Wrapper( args: PPyObject): PPyObject; var _obj : TObject; _oStream : PPyObject; _stream : TStream; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin _oStream := nil; if (PyArg_ParseTuple( args, 'O:LoadFromStrea',@_oStream ) <> 0) and CheckObjAttribute(_oStream, 'Stream', TStream, _obj) then begin _stream := TStream(_obj); DelphiObject.LoadFromStream(_stream); Result := ReturnNone; end else Result := nil; end; end; class procedure TPyDelphiGraphic.RegisterGetSets(PythonType: TPythonType); begin inherited; with PythonType do begin AddGetSet('Empty', @TPyDelphiGraphic.Get_Empty, nil, '', nil); AddGetSet('Height', @TPyDelphiGraphic.Get_Height, @TPyDelphiGraphic.Set_Height, '', nil); AddGetSet('Modified', @TPyDelphiGraphic.Get_Modified, @TPyDelphiGraphic.Set_Modified, '', nil); AddGetSet('Palette', @TPyDelphiGraphic.Get_Palette, @TPyDelphiGraphic.Set_Palette, '', nil); AddGetSet('PaletteModified', @TPyDelphiGraphic.Get_PaletteModified, @TPyDelphiGraphic.Set_PaletteModified, '', nil); AddGetSet('Transparent', @TPyDelphiGraphic.Get_Transparent, @TPyDelphiGraphic.Set_Transparent, '', nil); AddGetSet('Width', @TPyDelphiGraphic.Get_Width, @TPyDelphiGraphic.Set_Width, '', nil); end; end; class procedure TPyDelphiGraphic.RegisterMethods(PythonType: TPythonType); begin inherited; PythonType.AddMethod('LoadFromFile', @TPyDelphiGraphic.LoadFromFile_Wrapper, 'TGraphic.LoadFromFile()'#10 + ''); PythonType.AddMethod('SaveToFile', @TPyDelphiGraphic.SaveToFile_Wrapper, 'TGraphic.SaveToFile()'#10 + ''); PythonType.AddMethod('LoadFromStream', @TPyDelphiGraphic.LoadFromStream_Wrapper, 'TGraphic.LoadFromStream()'#10 + ''); PythonType.AddMethod('SaveToStream', @TPyDelphiGraphic.SaveToStream_Wrapper, 'TGraphic.SaveToStream()'#10 + ''); PythonType.AddMethod('LoadFromClipboardFormat', @TPyDelphiGraphic.LoadFromClipboardFormat_Wrapper, 'TGraphic.LoadFromClipboardFormat()'#10 + ''); PythonType.AddMethod('SaveToClipboardFormat', @TPyDelphiGraphic.SaveToClipboardFormat_Wrapper, 'TGraphic.SaveToClipboardFormat()'#10 + ''); end; function TPyDelphiGraphic.SaveToClipboardFormat_Wrapper( args: PPyObject): PPyObject; var _format : Word; {$IFNDEF FPC} _data : THandle; _palette : HPALETTE; {$ENDIF FPC} begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin {$IFDEF FPC} if PyArg_ParseTuple( args, ':SaveToClipboardFormat') <> 0 then begin DelphiObject.SaveToClipboardFormat(_format); {$ELSE FPC} if PyArg_ParseTuple( args, ':SaveToClipboardFormat') <> 0 then begin DelphiObject.SaveToClipboardFormat(_format, _data, _palette); {$ENDIF FPC} Result := PyTuple_New(3); PyTuple_SetItem(Result, 0, PyLong_FromLong(_format)); {$IFNDEF FPC} PyTuple_SetItem(Result, 1, PyLong_FromLong(_data)); PyTuple_SetItem(Result, 2, PyLong_FromLong(_palette)); {$ENDIF FPC} end else Result := nil; end; end; function TPyDelphiGraphic.SaveToFile_Wrapper(args: PPyObject): PPyObject; var _pFileName : PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'O:SaveToFile',@_pFileName ) <> 0 then begin DelphiObject.SaveToFile(PyObjectAsString(_pFileName)); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiGraphic.SaveToStream_Wrapper(args: PPyObject): PPyObject; var _obj : TObject; _oStream : PPyObject; _stream : TStream; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin _oStream := nil; if (PyArg_ParseTuple( args, 'O:SaveToStream',@_oStream ) <> 0) and CheckObjAttribute(_oStream, 'Stream', TStream, _obj) then begin _stream := TStream(_obj); DelphiObject.SaveToStream(_stream); Result := ReturnNone; end else Result := nil; end; end; procedure TPyDelphiGraphic.SetDelphiObject(const Value: TGraphic); begin inherited DelphiObject := Value; end; function TPyDelphiGraphic.Set_Height(AValue: PPyObject; AContext: Pointer): integer; var _value : Integer; begin Adjust(@Self); if CheckIntAttribute(AValue, 'Height', _value) then begin DelphiObject.Height := _value; Result := 0; end else Result := -1; end; function TPyDelphiGraphic.Set_Modified(AValue: PPyObject; AContext: Pointer): integer; var _value : Boolean; begin Adjust(@Self); if CheckBoolAttribute(AValue, 'Modified', _value) then begin DelphiObject.Modified := _value; Result := 0; end else Result := -1; end; function TPyDelphiGraphic.Set_Palette(AValue: PPyObject; AContext: Pointer): integer; var _value : Integer; begin Adjust(@Self); if CheckIntAttribute(AValue, 'Palette', _value) then begin DelphiObject.Palette := _value; Result := 0; end else Result := -1; end; function TPyDelphiGraphic.Set_PaletteModified(AValue: PPyObject; AContext: Pointer): integer; var _value : Boolean; begin Adjust(@Self); if CheckBoolAttribute(AValue, 'PaletteModified', _value) then begin DelphiObject.PaletteModified := _value; Result := 0; end else Result := -1; end; function TPyDelphiGraphic.Set_Transparent(AValue: PPyObject; AContext: Pointer): integer; var _value : Boolean; begin Adjust(@Self); if CheckBoolAttribute(AValue, 'Transparent', _value) then begin DelphiObject.Transparent := _value; Result := 0; end else Result := -1; end; function TPyDelphiGraphic.Set_Width(AValue: PPyObject; AContext: Pointer): integer; var _value : Integer; begin Adjust(@Self); if CheckIntAttribute(AValue, 'Width', _value) then begin DelphiObject.Width := _value; Result := 0; end else Result := -1; end; { TPyDelphiBitmap } class function TPyDelphiBitmap.DelphiObjectClass: TClass; begin Result := TBitmap; end; {$IFNDEF FPC} function TPyDelphiBitmap.Dormant_Wrapper(args: PPyObject): PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, ':Dormant') <> 0 then begin DelphiObject.Dormant; Result := ReturnNone; end else Result := nil; end; end; {$ENDIF FPC} function TPyDelphiBitmap.FreeImage_Wrapper(args: PPyObject): PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, ':FreeImage') <> 0 then begin DelphiObject.FreeImage; Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiBitmap.GetDelphiObject: TBitmap; begin Result := TBitmap(inherited DelphiObject); end; function TPyDelphiBitmap.Get_Canvas(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := Wrap(DelphiObject.Canvas); end; function TPyDelphiBitmap.Get_Handle(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.Handle); end; function TPyDelphiBitmap.Get_HandleAllocated(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.VariantAsPyObject(DelphiObject.HandleAllocated); end; function TPyDelphiBitmap.Get_HandleType(AContext: Pointer): PPyObject; begin Adjust(@Self); with GetPythonEngine do begin case DelphiObject.HandleType of bmDIB: Result := PyUnicodeFromString('bmDIB'); bmDDB: Result := PyUnicodeFromString('bmDDB'); else Result := ReturnNone; end; end; end; {$IFNDEF FPC} function TPyDelphiBitmap.Get_IgnorePalette(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.VariantAsPyObject(DelphiObject.IgnorePalette); end; {$ENDIF FPC} function TPyDelphiBitmap.Get_MaskHandle(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.MaskHandle); end; function TPyDelphiBitmap.Get_Monochrome(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.VariantAsPyObject(DelphiObject.Monochrome); end; function TPyDelphiBitmap.Get_PixelFormat(AContext: Pointer): PPyObject; begin Adjust(@Self); with GetPythonEngine do begin case DelphiObject.PixelFormat of pfDevice: Result := PyUnicodeFromString('pfDevice'); pf1bit: Result := PyUnicodeFromString('pf1bit'); pf4bit: Result := PyUnicodeFromString('pf4bit'); pf8bit: Result := PyUnicodeFromString('pf8bit'); pf15bit: Result := PyUnicodeFromString('pf15bit'); pf16bit: Result := PyUnicodeFromString('pf16bit'); pf24bit: Result := PyUnicodeFromString('pf24bit'); pf32bit: Result := PyUnicodeFromString('pf32bit'); pfCustom: Result := PyUnicodeFromString('pfCustom'); else Result := ReturnNone; end; end; end; function TPyDelphiBitmap.Get_TransparentColor( AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.TransparentColor); end; function TPyDelphiBitmap.Get_TransparentMode(AContext: Pointer): PPyObject; begin Adjust(@Self); with GetPythonEngine do begin case DelphiObject.TransparentMode of tmAuto: Result := PyUnicodeFromString('tmAuto'); tmFixed: Result := PyUnicodeFromString('tmFixed'); else Result := ReturnNone; end; end; end; function TPyDelphiBitmap.LoadFromResourceID_Wrapper( args: PPyObject): PPyObject; var _instance : Integer; _resID : Integer; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'ii:LoadFromResourceID',@_instance, @_resID ) <> 0 then begin {$IFNDEF CROSSVCL} DelphiObject.LoadFromResourceID(_instance, _resID); {$ENDIF} Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiBitmap.LoadFromResourceName_Wrapper( args: PPyObject): PPyObject; var _instance : Integer; _resName : PAnsiChar; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin _resName := nil; if PyArg_ParseTuple( args, 'is:LoadFromResourceName',@_instance, @_resName ) <> 0 then begin if _resName <> nil then DelphiObject.LoadFromResourceName(_instance, string(_resName)); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiBitmap.Mask_Wrapper(args: PPyObject): PPyObject; var _transpColor : Integer; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'i:Mask',@_transpColor ) <> 0 then begin DelphiObject.Mask(_transpColor); Result := ReturnNone; end else Result := nil; end; end; class procedure TPyDelphiBitmap.RegisterGetSets(PythonType: TPythonType); begin inherited; with PythonType do begin AddGetSet('Canvas', @TPyDelphiBitmap.Get_Canvas, nil, '', nil); AddGetSet('Handle', @TPyDelphiBitmap.Get_Handle, @TPyDelphiBitmap.Set_Handle, '', nil); AddGetSet('HandleAllocated', @TPyDelphiBitmap.Get_HandleAllocated, nil, '', nil); AddGetSet('HandleType', @TPyDelphiBitmap.Get_HandleType, @TPyDelphiBitmap.Set_HandleType, '', nil); {$IFNDEF FPC} AddGetSet('IgnorePalette', @TPyDelphiBitmap.Get_IgnorePalette, @TPyDelphiBitmap.Set_IgnorePalette, '', nil); {$ENDIF FPC} AddGetSet('MaskHandle', @TPyDelphiBitmap.Get_MaskHandle, @TPyDelphiBitmap.Set_MaskHandle, '', nil); AddGetSet('Monochrome', @TPyDelphiBitmap.Get_Monochrome, @TPyDelphiBitmap.Set_Monochrome, '', nil); AddGetSet('PixelFormat', @TPyDelphiBitmap.Get_PixelFormat, @TPyDelphiBitmap.Set_PixelFormat, '', nil); AddGetSet('TransparentColor', @TPyDelphiBitmap.Get_TransparentColor, @TPyDelphiBitmap.Set_TransparentColor, '', nil); AddGetSet('TransparentMode', @TPyDelphiBitmap.Get_TransparentMode, @TPyDelphiBitmap.Set_TransparentMode, '', nil); end; end; class procedure TPyDelphiBitmap.RegisterMethods(PythonType: TPythonType); begin inherited; {$IFNDEF FPC} PythonType.AddMethod('Dormant', @TPyDelphiBitmap.Dormant_Wrapper, 'TBitmap.Dormant()'#10 + ''); {$ENDIF FPC} PythonType.AddMethod('FreeImage', @TPyDelphiBitmap.FreeImage_Wrapper, 'TBitmap.FreeImage()'#10 + ''); PythonType.AddMethod('LoadFromResourceName', @TPyDelphiBitmap.LoadFromResourceName_Wrapper, 'TBitmap.LoadFromResourceName()'#10 + ''); PythonType.AddMethod('LoadFromResourceID', @TPyDelphiBitmap.LoadFromResourceID_Wrapper, 'TBitmap.LoadFromResourceID()'#10 + ''); PythonType.AddMethod('Mask', @TPyDelphiBitmap.Mask_Wrapper, 'TBitmap.Mask()'#10 + ''); PythonType.AddMethod('ReleaseHandle', @TPyDelphiBitmap.ReleaseHandle_Wrapper, 'TBitmap.ReleaseHandle()'#10 + ''); PythonType.AddMethod('ReleaseMaskHandle', @TPyDelphiBitmap.ReleaseMaskHandle_Wrapper, 'TBitmap.ReleaseMaskHandle()'#10 + ''); PythonType.AddMethod('ReleasePalette', @TPyDelphiBitmap.ReleasePalette_Wrapper, 'TBitmap.ReleasePalette()'#10 + ''); end; function TPyDelphiBitmap.ReleaseHandle_Wrapper(args: PPyObject): PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, ':ReleaseHandle') <> 0 then begin Result := PyLong_FromLong(DelphiObject.ReleaseHandle); end else Result := nil; end; end; function TPyDelphiBitmap.ReleaseMaskHandle_Wrapper( args: PPyObject): PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, ':ReleaseMaskHandle') <> 0 then begin Result := PyLong_FromLong(DelphiObject.ReleaseMaskHandle); end else Result := nil; end; end; function TPyDelphiBitmap.ReleasePalette_Wrapper( args: PPyObject): PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, ':ReleasePalette') <> 0 then begin Result := PyLong_FromLong(DelphiObject.ReleasePalette); end else Result := nil; end; end; procedure TPyDelphiBitmap.SetDelphiObject(const Value: TBitmap); begin inherited DelphiObject := Value; end; function TPyDelphiBitmap.Set_Handle(AValue: PPyObject; AContext: Pointer): Integer; var _value : Integer; begin Adjust(@Self); if CheckIntAttribute(AValue, 'Handle', _value) then begin DelphiObject.Handle := _value; Result := 0; end else Result := -1; end; function TPyDelphiBitmap.Set_HandleType(AValue: PPyObject; AContext: Pointer): Integer; var _value : string; begin Adjust(@Self); if CheckStrAttribute(AValue, 'HandleType', _value) then begin if SameText(_value, 'bmDIB') then DelphiObject.HandleType := bmDIB else if SameText(_value, 'bmDDB') then DelphiObject.HandleType := bmDDB else begin with GetPythonEngine do PyErr_SetString (PyExc_AttributeError^, PAnsiChar(AnsiString(Format('Unknown THandleType value "%s"', [_value])))); Result := -1; Exit; end; Result := 0; end else Result := -1; end; {$IFNDEF FPC} function TPyDelphiBitmap.Set_IgnorePalette(AValue: PPyObject; AContext: Pointer): Integer; var _value : Boolean; begin Adjust(@Self); if CheckBoolAttribute(AValue, 'IgnorePalette', _value) then begin DelphiObject.IgnorePalette := _value; Result := 0; end else Result := -1; end; {$ENDIF FPC} function TPyDelphiBitmap.Set_MaskHandle(AValue: PPyObject; AContext: Pointer): Integer; var _value : Integer; begin Adjust(@Self); if CheckIntAttribute(AValue, 'MaskHandle', _value) then begin DelphiObject.MaskHandle := _value; Result := 0; end else Result := -1; end; function TPyDelphiBitmap.Set_Monochrome(AValue: PPyObject; AContext: Pointer): Integer; var _value : Boolean; begin Adjust(@Self); if CheckBoolAttribute(AValue, 'Monochrome', _value) then begin DelphiObject.Monochrome := _value; Result := 0; end else Result := -1; end; function TPyDelphiBitmap.Set_PixelFormat(AValue: PPyObject; AContext: Pointer): Integer; var _value : string; begin with GetPythonEngine do begin Adjust(@Self); if CheckStrAttribute(AValue, 'PixelFormat', _value) then begin if SameText(_value, 'pfDevice') then DelphiObject.PixelFormat := pfDevice else if SameText(_value, 'pf1bit') then DelphiObject.PixelFormat := pf1bit else if SameText(_value, 'pf4bit') then DelphiObject.PixelFormat := pf4bit else if SameText(_value, 'pf8bit') then DelphiObject.PixelFormat := pf8bit else if SameText(_value, 'pf15bit') then DelphiObject.PixelFormat := pf15bit else if SameText(_value, 'pf16bit') then DelphiObject.PixelFormat := pf16bit else if SameText(_value, 'pf24bit') then DelphiObject.PixelFormat := pf24bit else if SameText(_value, 'pf32bit') then DelphiObject.PixelFormat := pf32bit else if SameText(_value, 'pfCustom') then DelphiObject.PixelFormat := pfCustom else begin PyErr_SetString (PyExc_AttributeError^, PAnsiChar(AnsiString(Format('Unknown TPixelFormat value "%s"', [_value])))); Result := -1; Exit; end; Result := 0; end else Result := -1; end; end; function TPyDelphiBitmap.Set_TransparentColor(AValue: PPyObject; AContext: Pointer): Integer; var _value : Integer; begin Adjust(@Self); if CheckIntAttribute(AValue, 'TransparentColor', _value) then begin DelphiObject.TransparentColor := _value; Result := 0; end else Result := -1; end; function TPyDelphiBitmap.Set_TransparentMode(AValue: PPyObject; AContext: Pointer): Integer; var _value : string; begin Adjust(@Self); if CheckStrAttribute(AValue, 'TransparentMode', _value) then begin if SameText(_value, 'tmAuto') then DelphiObject.TransparentMode := tmAuto else if SameText(_value, 'tmFixed') then DelphiObject.TransparentMode := tmFixed else begin with GetPythonEngine do PyErr_SetString (PyExc_AttributeError^, PAnsiChar(AnsiString(Format('Unknown TTransparentMode value "%s"', [_value])))); Result := -1; Exit; end; Result := 0; end else Result := -1; end; { TPyDelphiCanvas } function TPyDelphiCanvas.Arc_Wrapper(args: PPyObject): PPyObject; var x1, y1, x2, y2, x3, y3, x4, y4: Integer; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'iiiiiiii:Arc',@x1, @y1, @x2, @y2, @x3, @y3, @x4, @y4 ) <> 0 then begin DelphiObject.Arc(x1, y1, x2, y2, x3, y3, x4, y4); Result := ReturnNone; end else Result := nil; end; end; {$IFNDEF FPC} function TPyDelphiCanvas.BrushCopy_Wrapper(args: PPyObject): PPyObject; var _obj : TObject; _oBitmap: PPyObject; _bitmap : TBitmap; _color : Integer; _dest : TRect; _source : TRect; _oDest : PPyObject; _oSource : PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin _oBitmap := nil; _oSource := nil; _oDest := nil; if (PyArg_ParseTuple( args, 'OOOi:BrushCopy',@_oDest, @_oBitmap, @_oSource, @_color ) <> 0) and CheckRectAttribute(_oDest, 'Dest', _dest) and CheckRectAttribute(_oSource , 'Source', _source) and CheckObjAttribute(_oBitmap, 'Bitmap', TBitmap, _obj) then begin _bitmap := TBitmap(_obj); DelphiObject.BrushCopy(_dest, _bitmap, _source, _color); Result := ReturnNone; end else Result := nil; end; end; {$ENDIF FPC} function TPyDelphiCanvas.Chord_Wrapper(args: PPyObject): PPyObject; var x1, y1, x2, y2, x3, y3, x4, y4: Integer; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'iiiiiiii:Chord',@x1, @y1, @x2, @y2, @x3, @y3, @x4, @y4 ) <> 0 then begin DelphiObject.Chord(x1, y1, x2, y2, x3, y3, x4, y4); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.CopyRect_Wrapper(args: PPyObject): PPyObject; var _obj : TObject; _oCanvas : PPyObject; _canvas : TCanvas; _oDest : PPyObject; _dest : TRect; _oSource : PPyObject; _source : TRect; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin _oCanvas := nil; _oSource := nil; _oDest := nil; if (PyArg_ParseTuple( args, 'OOO:CopyRect',@_oDest, @_oCanvas, @_oSource ) <> 0) and CheckRectAttribute(_oDest, 'Dest', _dest) and CheckRectAttribute(_oSource, 'Source', _source) and CheckObjAttribute(_oCanvas, 'Canvas', TCanvas, _obj) then begin _canvas := TCanvas(_obj); DelphiObject.CopyRect(_dest, _canvas, _source); Result := ReturnNone; end else Result := nil; end; end; class function TPyDelphiCanvas.DelphiObjectClass: TClass; begin Result := TCanvas; end; function TPyDelphiCanvas.Draw_Wrapper(args: PPyObject): PPyObject; var x, y : Integer; _obj : TObject; _oGraphic : PPyObject; _graphic : TGraphic; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin x := 0; y := 0; _oGraphic := nil; if (PyArg_ParseTuple( args, 'iiO:Draw',@x, @y, @_oGraphic ) <> 0) and CheckObjAttribute(_oGraphic, 'Graphic', TGraphic, _obj) then begin _graphic := TGraphic(_obj); DelphiObject.Draw(x, y, _graphic); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.DrawFocusRect_Wrapper(args: PPyObject): PPyObject; var _rectO : PPyObject; _rect : TRect; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if (PyArg_ParseTuple( args, 'O:DrawFocusRect',@_rectO ) <> 0) and CheckRectAttribute(_rectO, 'Rect', _rect) then begin DelphiObject.DrawFocusRect(_rect); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.Ellipse_Wrapper(args: PPyObject): PPyObject; var x1, y1, x2, y2: Integer; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'iiii:Ellipse',@x1, @y1, @x2, @y2 ) <> 0 then begin DelphiObject.Ellipse(x1, y1, x2, y2); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.FillRect_Wrapper(args: PPyObject): PPyObject; var _rectO : PPyObject; _rect : TRect; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if (PyArg_ParseTuple( args, 'O:FillRect',@_rectO ) <> 0) and CheckRectAttribute(_rectO, 'Rect', _rect) then begin DelphiObject.FillRect(_rect); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.FloodFill_Wrapper(args: PPyObject): PPyObject; var x, y, _color: Integer; _pFillStyle : PPyObject; _FillStyle : TFillStyle; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'iiiO:FloodFill',@x, @y, @_color, @_pFillStyle ) <> 0 then begin if SameText(PyObjectAsString(_pFillStyle), 'fsBorder') then _FillStyle := fsBorder else _FillStyle := fsSurface; DelphiObject.FloodFill(x, y, _color, _fillStyle); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.FrameRect_Wrapper(args: PPyObject): PPyObject; var _rectO : PPyObject; _rect : TRect; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if (PyArg_ParseTuple( args, 'O:FrameRect',@_rectO ) <> 0) and CheckRectAttribute(_rectO, 'Rect', _rect) then begin DelphiObject.FrameRect(_rect); Result := ReturnNone; end else Result := nil; end; end; {$IFNDEF FPC} function TPyDelphiCanvas.Get_CanvasOrientation( AContext: Pointer): PPyObject; begin Adjust(@Self); with GetPythonEngine do begin if DelphiObject.CanvasOrientation = coRightToLeft then Result := PyUnicodeFromString('coRightToLeft') else Result := PyUnicodeFromString('coLeftToRight'); end; end; {$ENDIF FPC} function TPyDelphiCanvas.Get_ClipRect(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := WrapRect(PyDelphiWrapper, DelphiObject.ClipRect); end; function TPyDelphiCanvas.Get_Handle(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.Handle); end; function TPyDelphiCanvas.Get_HandleAllocated(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.VariantAsPyObject(DelphiObject.HandleAllocated); end; function TPyDelphiCanvas.Get_LockCount(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.LockCount); end; function TPyDelphiCanvas.Get_OnChange(AContext: Pointer): PPyObject; begin //todo Result := GetPythonEngine.ReturnNone; end; function TPyDelphiCanvas.Get_OnChanging(AContext: Pointer): PPyObject; begin //todo Result := GetPythonEngine.ReturnNone; end; function TPyDelphiCanvas.Get_PenPos(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := WrapPoint(PyDelphiWrapper, DelphiObject.PenPos); end; {$IFNDEF FPC} function TPyDelphiCanvas.Get_TextFlags(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.TextFlags); end; {$ENDIF FPC} function TPyDelphiCanvas.GetDelphiObject: TCanvas; begin Result := TCanvas(inherited DelphiObject); end; function TPyDelphiCanvas.GetPixel(args: PPyObject): PPyObject; var x, y : Integer; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin x := 0; y := 0; if PyArg_ParseTuple( args, 'ii:GetPixel',@x, @y ) <> 0 then begin Result := PyLong_FromLong(DelphiObject.Pixels[x, y]); end else Result := nil; end; end; function TPyDelphiCanvas.LineTo_Wrapper(args: PPyObject): PPyObject; var x, y : Integer; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin x := 0; y := 0; if PyArg_ParseTuple( args, 'ii:LineTo',@x, @y ) <> 0 then begin DelphiObject.LineTo(x, y); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.Lock_Wrapper(args: PPyObject): PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, ':Lock') <> 0 then begin DelphiObject.Lock; Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.MoveTo_Wrapper(args: PPyObject): PPyObject; var x, y : Integer; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin x := 0; y := 0; if PyArg_ParseTuple( args, 'ii:MoveTo',@x, @y ) <> 0 then begin DelphiObject.MoveTo(x, y); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.Pie_Wrapper(args: PPyObject): PPyObject; var x1, y1, x2, y2, x3, y3, x4, y4: Integer; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'iiiiiiii:Pie',@x1, @y1, @x2, @y2, @x3, @y3, @x4, @y4 ) <> 0 then begin DelphiObject.Pie(x1, y1, x2, y2, x3, y3, x4, y4); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.PolyBezier_Wrapper(args: PPyObject): PPyObject; var i : Integer; p : TPoint; _points : array of TPoint; _oPoints : PPyObject; _oPoint : PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin _oPoints := nil; if PyArg_ParseTuple( args, 'O:PolyBezier',@_oPoints ) <> 0 then begin if PySequence_Check(_oPoints) <> 0 then begin SetLength(_points, PySequence_Length(_oPoints)); for i := 0 to Length(_points)-1 do begin _oPoint := PySequence_GetItem(_oPoints, i); try if CheckPointAttribute(_oPoint, Format('Item #%d of Point sequence', [i]), p) then _points[i] := p else begin Result := nil; Exit; end; finally Py_XDecRef(_oPoint); end; end; DelphiObject.PolyBezier(_points); Result := GetPythonEngine.ReturnNone; end else begin Result := nil; PyErr_SetString (PyExc_AttributeError^, 'PolyBezier accepts only a sequence of points as single parameter'); end; end else Result := nil; end; end; {$IFNDEF FPC} function TPyDelphiCanvas.PolyBezierTo_Wrapper(args: PPyObject): PPyObject; var i : Integer; p : TPoint; _points : array of TPoint; _oPoints : PPyObject; _oPoint : PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin _oPoints := nil; if PyArg_ParseTuple( args, 'O:PolyBezierTo',@_oPoints ) <> 0 then begin if PySequence_Check(_oPoints) <> 0 then begin SetLength(_points, PySequence_Length(_oPoints)); for i := 0 to Length(_points)-1 do begin _oPoint := PySequence_GetItem(_oPoints, i); try if CheckPointAttribute(_oPoint, Format('Item #%d of Point sequence', [i]), p) then _points[i] := p else begin Result := nil; Exit; end; finally Py_XDecRef(_oPoint); end; end; DelphiObject.PolyBezierTo(_points); Result := GetPythonEngine.ReturnNone; end else begin Result := nil; PyErr_SetString (PyExc_AttributeError^, 'PolyBezierTo accepts only a sequence of points as single parameter'); end; end else Result := nil; end; end; {$ENDIF FPC} function TPyDelphiCanvas.Polygon_Wrapper(args: PPyObject): PPyObject; var i : Integer; p : TPoint; _points : array of TPoint; _oPoints : PPyObject; _oPoint : PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin _oPoints := nil; if PyArg_ParseTuple( args, 'O:Polygon',@_oPoints ) <> 0 then begin if PySequence_Check(_oPoints) <> 0 then begin SetLength(_points, PySequence_Length(_oPoints)); for i := 0 to Length(_points)-1 do begin _oPoint := PySequence_GetItem(_oPoints, i); try if CheckPointAttribute(_oPoint, Format('Item #%d of Point sequence', [i]), p) then _points[i] := p else begin Result := nil; Exit; end; finally Py_XDecRef(_oPoint); end; end; DelphiObject.Polygon(_points); Result := GetPythonEngine.ReturnNone; end else begin Result := nil; PyErr_SetString (PyExc_AttributeError^, 'Polygon accepts only a sequence of points as single parameter'); end; end else Result := nil; end; end; function TPyDelphiCanvas.Polyline_Wrapper(args: PPyObject): PPyObject; var i : Integer; p : TPoint; _points : array of TPoint; _oPoints : PPyObject; _oPoint : PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin _oPoints := nil; if PyArg_ParseTuple( args, 'O:Polyline',@_oPoints ) <> 0 then begin if PySequence_Check(_oPoints) <> 0 then begin SetLength(_points, PySequence_Length(_oPoints)); for i := 0 to Length(_points)-1 do begin _oPoint := PySequence_GetItem(_oPoints, i); try if CheckPointAttribute(_oPoint, Format('Item #%d of Point sequence', [i]), p) then _points[i] := p else begin Result := nil; Exit; end; finally Py_XDecRef(_oPoint); end; end; DelphiObject.Polyline(_points); Result := GetPythonEngine.ReturnNone; end else begin Result := nil; PyErr_SetString (PyExc_AttributeError^, 'Polyline accepts only a sequence of points as single parameter'); end; end else Result := nil; end; end; function TPyDelphiCanvas.Rectangle_Wrapper(args: PPyObject): PPyObject; var x1, y1, x2, y2: Integer; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'iiii:Rectangle',@x1, @y1, @x2, @y2 ) <> 0 then begin DelphiObject.Rectangle(x1, y1, x2, y2); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.Refresh_Wrapper(args: PPyObject): PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, ':Refresh') <> 0 then begin DelphiObject.Refresh; Result := ReturnNone; end else Result := nil; end; end; class procedure TPyDelphiCanvas.RegisterGetSets(PythonType: TPythonType); begin inherited; with PythonType do begin AddGetSet('HandleAllocated', @TPyDelphiCanvas.Get_HandleAllocated, nil, '', nil); AddGetSet('ClipRect', @TPyDelphiCanvas.Get_ClipRect, nil, 'Specifies the boundaries of the clipping rectangle.', nil); AddGetSet('Handle', @TPyDelphiCanvas.Get_Handle, @TPyDelphiCanvas.Set_Handle, 'Specifies the handle for this canvas.', nil); AddGetSet('LockCount', @TPyDelphiCanvas.Get_LockCount,nil, 'Indicates the number of times the canvas has been locked to prevent interference from other threads.', nil); {$IFNDEF FPC} AddGetSet('CanvasOrientation', @TPyDelphiCanvas.Get_CanvasOrientation, nil, 'Determines the orientation of the canvas as left-to-right or right-to-left.', nil); {$ENDIF FPC} AddGetSet('PenPos', @TPyDelphiCanvas.Get_PenPos, nil, 'Specifies the current drawing position of the Pen. ', nil); {$IFNDEF FPC} AddGetSet('TextFlags', @TPyDelphiCanvas.Get_TextFlags, @TPyDelphiCanvas.Set_TextFlags, 'Specifies how text is written to the canvas.', nil); {$ENDIF FPC} AddGetSet('OnChange', @TPyDelphiCanvas.Get_OnChange, @TPyDelphiCanvas.Set_OnChange, 'Occurs when the image has just changed.', nil); AddGetSet('OnChanging', @TPyDelphiCanvas.Get_OnChanging, @TPyDelphiCanvas.Set_OnChanging, 'Occurs just before a change is made to the image.', nil); end; end; class procedure TPyDelphiCanvas.RegisterMethods(PythonType: TPythonType); begin inherited; PythonType.AddMethod('Arc', @TPyDelphiCanvas.Arc_Wrapper, 'TCanvas.Arc()'#10 + ''); {$IFNDEF FPC} PythonType.AddMethod('BrushCopy', @TPyDelphiCanvas.BrushCopy_Wrapper, 'TCanvas.BrushCopy()'#10 + ''); {$ENDIF FPC} PythonType.AddMethod('Chord', @TPyDelphiCanvas.Chord_Wrapper, 'TCanvas.Chord()'#10 + ''); PythonType.AddMethod('CopyRect', @TPyDelphiCanvas.CopyRect_Wrapper, 'TCanvas.CopyRect()'#10 + ''); PythonType.AddMethod('Draw', @TPyDelphiCanvas.Draw_Wrapper, 'TCanvas.Draw()'#10 + ''); PythonType.AddMethod('DrawFocusRect', @TPyDelphiCanvas.DrawFocusRect_Wrapper, 'TCanvas.DrawFocusRect()'#10 + ''); PythonType.AddMethod('Ellipse', @TPyDelphiCanvas.Ellipse_Wrapper, 'TCanvas.Ellipse()'#10 + ''); PythonType.AddMethod('FillRect', @TPyDelphiCanvas.FillRect_Wrapper, 'TCanvas.FillRect()'#10 + ''); PythonType.AddMethod('FloodFill', @TPyDelphiCanvas.FloodFill_Wrapper, 'TCanvas.FloodFill()'#10 + ''); PythonType.AddMethod('FrameRect', @TPyDelphiCanvas.FrameRect_Wrapper, 'TCanvas.FrameRect()'#10 + ''); PythonType.AddMethod('LineTo', @TPyDelphiCanvas.LineTo_Wrapper, 'TCanvas.LineTo()'#10 + ''); PythonType.AddMethod('Lock', @TPyDelphiCanvas.Lock_Wrapper, 'TCanvas.Lock()'#10 + ''); PythonType.AddMethod('MoveTo', @TPyDelphiCanvas.MoveTo_Wrapper, 'TCanvas.MoveTo()'#10 + ''); PythonType.AddMethod('Pie', @TPyDelphiCanvas.Pie_Wrapper, 'TCanvas.Pie()'#10 + ''); PythonType.AddMethod('Polygon', @TPyDelphiCanvas.Polygon_Wrapper, 'TCanvas.Polygon()'#10 + ''); PythonType.AddMethod('Polyline', @TPyDelphiCanvas.Polyline_Wrapper, 'TCanvas.Polyline()'#10 + ''); PythonType.AddMethod('PolyBezier', @TPyDelphiCanvas.PolyBezier_Wrapper, 'TCanvas.PolyBezier()'#10 + ''); {$IFNDEF FPC} PythonType.AddMethod('PolyBezierTo', @TPyDelphiCanvas.PolyBezierTo_Wrapper, 'TCanvas.PolyBezierTo()'#10 + ''); {$ENDIF FPC} PythonType.AddMethod('Rectangle', @TPyDelphiCanvas.Rectangle_Wrapper, 'TCanvas.Rectangle()'#10 + ''); PythonType.AddMethod('Refresh', @TPyDelphiCanvas.Refresh_Wrapper, 'TCanvas.Refresh()'#10 + ''); PythonType.AddMethod('RoundRect', @TPyDelphiCanvas.RoundRect_Wrapper, 'TCanvas.RoundRect()'#10 + ''); PythonType.AddMethod('StretchDraw', @TPyDelphiCanvas.StretchDraw_Wrapper, 'TCanvas.StretchDraw()'#10 + ''); PythonType.AddMethod('TextExtent', @TPyDelphiCanvas.TextExtent_Wrapper, 'TCanvas.TextExtent()'#10 + ''); PythonType.AddMethod('TextHeight', @TPyDelphiCanvas.TextHeight_Wrapper, 'TCanvas.TextHeight()'#10 + ''); PythonType.AddMethod('TextOut', @TPyDelphiCanvas.TextOut_Wrapper, 'TCanvas.TextOut()'#10 + ''); PythonType.AddMethod('TextRect', @TPyDelphiCanvas.TextRect_Wrapper, 'TCanvas.TextRect()'#10 + ''); PythonType.AddMethod('TextWidth', @TPyDelphiCanvas.TextWidth_Wrapper, 'TCanvas.TextWidth()'#10 + ''); PythonType.AddMethod('TryLock', @TPyDelphiCanvas.TryLock_Wrapper, 'TCanvas.TryLock()'#10 + ''); PythonType.AddMethod('Unlock', @TPyDelphiCanvas.Unlock_Wrapper, 'TCanvas.Unlock()'#10 + ''); PythonType.AddMethod('GetPixel', @TPyDelphiCanvas.GetPixel, 'TCanvas.GetPixel(x, y) -> TColor'#10 + 'This is the same as TCanvas.Pixels[x, y].'#13+ 'Returns the color of the pixels within the current ClipRect.'); PythonType.AddMethod('SetPixel', @TPyDelphiCanvas.SetPixel, 'TCanvas.SetPixel(x, y, color)'#10 + 'This is the same as TCanvas.Pixels[x, y] := color'#13+ 'Specifies the color of the pixels within the current ClipRect.'); end; function TPyDelphiCanvas.RoundRect_Wrapper(args: PPyObject): PPyObject; var x1, y1, x2, y2, x3, y3: Integer; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'iiiiii:RoundRect',@x1, @y1, @x2, @y2, @x3, @y3 ) <> 0 then begin DelphiObject.RoundRect(x1, y1, x2, y2, x3, y3); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.Set_Handle(AValue: PPyObject; AContext: Pointer): integer; var _value : Integer; begin Adjust(@Self); if CheckIntAttribute(AValue, 'Handle', _value) then begin DelphiObject.Handle := _value; Result := 0; end else Result := -1; end; function TPyDelphiCanvas.Set_OnChange(AValue: PPyObject; AContext: Pointer): integer; begin //todo Result := 0; end; function TPyDelphiCanvas.Set_OnChanging(AValue: PPyObject; AContext: Pointer): integer; begin //todo Result := 0; end; {$IFNDEF FPC} function TPyDelphiCanvas.Set_TextFlags(AValue: PPyObject; AContext: Pointer): integer; var _value : Integer; begin Adjust(@Self); if CheckIntAttribute(AValue, 'TextFlags', _value) then begin DelphiObject.TextFlags := _value; Result := 0; end else Result := -1; end; {$ENDIF FPC} procedure TPyDelphiCanvas.SetDelphiObject(const Value: TCanvas); begin inherited DelphiObject := Value; end; function TPyDelphiCanvas.SetPixel(args: PPyObject): PPyObject; var x, y : Integer; _color : TColor; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin x := 0; y := 0; if PyArg_ParseTuple( args, 'iii:SetPixel',@x, @y, @_color ) <> 0 then begin DelphiObject.Pixels[x, y] := _color; Result := GetPythonEngine.ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.StretchDraw_Wrapper(args: PPyObject): PPyObject; var _obj : TObject; _oGraphic : PPyObject; _graphic : TGraphic; _oRect : PPyObject; _rect : TRect; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin _oGraphic := nil; _oRect := nil; if (PyArg_ParseTuple( args, 'iiO:StretchDraw',@_oRect, @_oGraphic ) <> 0) and CheckRectAttribute(_oRect, 'Rect', _rect) and CheckObjAttribute(_oGraphic, 'Graphic', TGraphic, _obj) then begin _graphic := TGraphic(_obj); DelphiObject.StretchDraw(_rect, _graphic); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.TextExtent_Wrapper(args: PPyObject): PPyObject; var _pText : PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'O:TextExtent',@_pText ) <> 0 then begin Result := WrapSize(PyDelphiWrapper, DelphiObject.TextExtent(PyObjectAsString(_pText))); end else Result := nil; end; end; function TPyDelphiCanvas.TextHeight_Wrapper(args: PPyObject): PPyObject; var _pText : PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'O:TextHeight',@_pText ) <> 0 then begin Result := PyLong_FromLong(DelphiObject.TextHeight(PyObjectAsString(_pText))); end else Result := nil; end; end; function TPyDelphiCanvas.TextOut_Wrapper(args: PPyObject): PPyObject; var x, y : Integer; _text : PAnsiChar; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin x := 0; y := 0; if PyArg_ParseTuple( args, 'iis:TextRect',@x, @y, @_text ) <> 0 then begin if _text <> nil then DelphiObject.TextOut(x, y, string(_text)); Result := GetPythonEngine.ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.TextRect_Wrapper(args: PPyObject): PPyObject; var x, y : Integer; _rectO : PPyObject; _rect : TRect; _text : PAnsiChar; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin x := 0; y := 0; _rectO := nil; _text := nil; if (PyArg_ParseTuple( args, 'Oiis:TextRect',@_rectO, @x, @y, @_text ) <> 0) and CheckRectAttribute(_rectO, 'Rect', _rect) then begin if _text <> nil then DelphiObject.TextRect(_rect, x, y, string(_text)); Result := GetPythonEngine.ReturnNone; end else Result := nil; end; end; function TPyDelphiCanvas.TextWidth_Wrapper(args: PPyObject): PPyObject; var _pText : PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'O:TextWidth',@_pText ) <> 0 then begin Result := PyLong_FromLong(DelphiObject.TextWidth(PyObjectAsString(_pText))); end else Result := nil; end; end; function TPyDelphiCanvas.TryLock_Wrapper(args: PPyObject): PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, ':Unlock') <> 0 then begin Result := VariantAsPyObject( DelphiObject.TryLock ); end else Result := nil; end; end; function TPyDelphiCanvas.Unlock_Wrapper(args: PPyObject): PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, ':Unlock') <> 0 then begin DelphiObject.Unlock; Result := ReturnNone; end else Result := nil; end; end; {$IFNDEF FPC} { TPyDelphiMetaFile } function TPyDelphiMetaFile.Clear_Wrapper(args: PPyObject): PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, ':Clear') <> 0 then begin DelphiObject.Clear; Result := ReturnNone; end else Result := nil; end; end; class function TPyDelphiMetaFile.DelphiObjectClass: TClass; begin Result := TMetaFile; end; function TPyDelphiMetaFile.GetDelphiObject: TMetaFile; begin Result := TMetaFile(inherited DelphiObject); end; function TPyDelphiMetaFile.Get_CreatedBy(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyUnicodeFromString(DelphiObject.CreatedBy); end; function TPyDelphiMetaFile.Get_Description(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyUnicodeFromString(DelphiObject.Description); end; function TPyDelphiMetaFile.Get_Enhanced(AContext: Pointer): PPyObject; begin with GetPythonEngine do begin Adjust(@Self); Result := VariantAsPyObject(DelphiObject.Enhanced); end; end; function TPyDelphiMetaFile.Get_Handle(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.Handle); end; function TPyDelphiMetaFile.Get_HandleAllocated( AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.VariantAsPyObject(DelphiObject.HandleAllocated); end; function TPyDelphiMetaFile.Get_Inch(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.Inch); end; function TPyDelphiMetaFile.Get_MMHeight(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.MMHeight); end; function TPyDelphiMetaFile.Get_MMWidth(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.MMWidth); end; class procedure TPyDelphiMetaFile.RegisterGetSets(PythonType: TPythonType); begin inherited; with PythonType do begin AddGetSet('CreatedBy', @TPyDelphiMetaFile.Get_CreatedBy, nil, '', nil); AddGetSet('Description', @TPyDelphiMetaFile.Get_Description, nil, '', nil); AddGetSet('Enhanced', @TPyDelphiMetaFile.Get_Enhanced, @TPyDelphiMetaFile.Set_Enhanced, '', nil); AddGetSet('Handle', @TPyDelphiMetaFile.Get_Handle, @TPyDelphiMetaFile.Set_Handle, '', nil); AddGetSet('HandleAllocated', @TPyDelphiMetaFile.Get_HandleAllocated, nil, '', nil); AddGetSet('MMWidth', @TPyDelphiMetaFile.Get_MMWidth, @TPyDelphiMetaFile.Set_MMWidth, '', nil); AddGetSet('MMHeight', @TPyDelphiMetaFile.Get_MMHeight, @TPyDelphiMetaFile.Set_MMHeight, '', nil); AddGetSet('Inch', @TPyDelphiMetaFile.Get_Inch, @TPyDelphiMetaFile.Set_Inch, '', nil); end; end; class procedure TPyDelphiMetaFile.RegisterMethods(PythonType: TPythonType); begin inherited; PythonType.AddMethod('Clear', @TPyDelphiMetaFile.Clear_Wrapper, 'TMetaFile.Clear()'#10 + ''); PythonType.AddMethod('ReleaseHandle', @TPyDelphiMetaFile.ReleaseHandle_Wrapper, 'TMetaFile.ReleaseHandle()'#10 + ''); end; function TPyDelphiMetaFile.ReleaseHandle_Wrapper( args: PPyObject): PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, ':ReleaseHandle') <> 0 then begin Result := PyLong_FromLong(DelphiObject.ReleaseHandle); end else Result := nil; end; end; procedure TPyDelphiMetaFile.SetDelphiObject(const Value: TMetaFile); begin inherited DelphiObject := Value; end; function TPyDelphiMetaFile.Set_Enhanced(AValue: PPyObject; AContext: Pointer): Integer; var _value : Boolean; begin Adjust(@Self); if CheckBoolAttribute(AValue, 'Enhanced', _value) then begin DelphiObject.Enhanced := _value; Result := 0; end else Result := -1; end; function TPyDelphiMetaFile.Set_Handle(AValue: PPyObject; AContext: Pointer): Integer; var _value : Integer; begin Adjust(@Self); if CheckIntAttribute(AValue, 'Handle', _value) then begin DelphiObject.Handle := _value; Result := 0; end else Result := -1; end; function TPyDelphiMetaFile.Set_Inch(AValue: PPyObject; AContext: Pointer): Integer; var _value : Integer; begin Adjust(@Self); if CheckIntAttribute(AValue, 'Inch', _value) then begin DelphiObject.Inch := _value; Result := 0; end else Result := -1; end; function TPyDelphiMetaFile.Set_MMHeight(AValue: PPyObject; AContext: Pointer): Integer; var _value : Integer; begin Adjust(@Self); if CheckIntAttribute(AValue, 'MMHeight', _value) then begin DelphiObject.MMHeight := _value; Result := 0; end else Result := -1; end; function TPyDelphiMetaFile.Set_MMWidth(AValue: PPyObject; AContext: Pointer): Integer; var _value : Integer; begin Adjust(@Self); if CheckIntAttribute(AValue, 'MMWidth', _value) then begin DelphiObject.MMWidth := _value; Result := 0; end else Result := -1; end; {$ENDIF FPC} { TPyDelphiIcon } class function TPyDelphiIcon.DelphiObjectClass: TClass; begin Result := TIcon; end; function TPyDelphiIcon.GetDelphiObject: TIcon; begin Result := TIcon(inherited DelphiObject); end; function TPyDelphiIcon.Get_Handle(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.Handle); end; function TPyDelphiIcon.Get_HandleAllocated(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.VariantAsPyObject(DelphiObject.HandleAllocated); end; class procedure TPyDelphiIcon.RegisterGetSets(PythonType: TPythonType); begin inherited; with PythonType do begin AddGetSet('Handle', @TPyDelphiIcon.Get_Handle, @TPyDelphiIcon.Set_Handle, '', nil); AddGetSet('HandleAllocated', @TPyDelphiIcon.Get_HandleAllocated, nil, '', nil); end; end; class procedure TPyDelphiIcon.RegisterMethods(PythonType: TPythonType); begin inherited; PythonType.AddMethod('ReleaseHandle', @TPyDelphiIcon.ReleaseHandle_Wrapper, 'TIcon.ReleaseHandle()'#10 + ''); end; function TPyDelphiIcon.ReleaseHandle_Wrapper(args: PPyObject): PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, ':ReleaseHandle') <> 0 then begin Result := PyLong_FromLong(DelphiObject.ReleaseHandle); end else Result := nil; end; end; procedure TPyDelphiIcon.SetDelphiObject(const Value: TIcon); begin inherited DelphiObject := Value; end; function TPyDelphiIcon.Set_Handle(AValue: PPyObject; AContext: Pointer): Integer; var _value : Integer; begin Adjust(@Self); if CheckIntAttribute(AValue, 'Handle', _value) then begin DelphiObject.Handle := _value; Result := 0; end else Result := -1; end; { TPyDelphiPicture } class function TPyDelphiPicture.DelphiObjectClass: TClass; begin Result := TPicture; end; function TPyDelphiPicture.Get_Bitmap(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := Wrap(DelphiObject.Bitmap); end; function TPyDelphiPicture.Get_Graphic(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := Wrap(DelphiObject.Graphic); end; function TPyDelphiPicture.Get_Height(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.Height); end; function TPyDelphiPicture.Get_Icon(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := Wrap(DelphiObject.Icon); end; {$IFNDEF FPC} function TPyDelphiPicture.Get_MetaFile(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := Wrap(DelphiObject.MetaFile); end; {$ENDIF FPC} function TPyDelphiPicture.Get_Width(AContext: Pointer): PPyObject; begin Adjust(@Self); Result := GetPythonEngine.PyLong_FromLong(DelphiObject.Width); end; function TPyDelphiPicture.GetDelphiObject: TPicture; begin Result := TPicture(inherited DelphiObject); end; function TPyDelphiPicture.LoadFromFile_Wrapper(args: PPyObject): PPyObject; var _pFileName : PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'O:LoadFromFile',@_pFileName ) <> 0 then begin DelphiObject.LoadFromFile(PyObjectAsString(_pFileName)); Result := ReturnNone; end else Result := nil; end; end; class procedure TPyDelphiPicture.RegisterGetSets(PythonType: TPythonType); begin inherited; with PythonType do begin AddGetSet('Bitmap', @TPyDelphiPicture.Get_Bitmap, @TPyDelphiPicture.Set_Bitmap, '', nil); AddGetSet('Graphic', @TPyDelphiPicture.Get_Graphic, @TPyDelphiPicture.Set_Graphic, '', nil); AddGetSet('Height', @TPyDelphiPicture.Get_Height, nil, '', nil); AddGetSet('Icon', @TPyDelphiPicture.Get_Icon, @TPyDelphiPicture.Set_Icon, '', nil); {$IFNDEF FPC} AddGetSet('Metafile', @TPyDelphiPicture.Get_Metafile, @TPyDelphiPicture.Set_Metafile, '', nil); {$ENDIF FPC} AddGetSet('Width', @TPyDelphiPicture.Get_Width, nil, '', nil); end; end; class procedure TPyDelphiPicture.RegisterMethods(PythonType: TPythonType); begin inherited; PythonType.AddMethod('LoadFromFile', @TPyDelphiPicture.LoadFromFile_Wrapper, 'TPicture.LoadFromFile()'#10 + ''); PythonType.AddMethod('SaveToFile', @TPyDelphiPicture.SaveToFile_Wrapper, 'TPicture.SaveToFile()'#10 + ''); end; function TPyDelphiPicture.SaveToFile_Wrapper(args: PPyObject): PPyObject; var _pFileName : PPyObject; begin // We adjust the transmitted self argument Adjust(@Self); with GetPythonEngine do begin if PyArg_ParseTuple( args, 'O:SaveToFile',@_pFileName ) <> 0 then begin DelphiObject.SaveToFile(PyObjectAsString(_pFileName)); Result := ReturnNone; end else Result := nil; end; end; function TPyDelphiPicture.Set_Bitmap(AValue: PPyObject; AContext: Pointer): Integer; var _object : TObject; begin Adjust(@Self); if CheckObjAttribute(AValue, 'Bitmap', TBitmap, _object) then begin Self.DelphiObject.Bitmap := TBitmap(_object); Result := 0; end else Result := -1; end; function TPyDelphiPicture.Set_Graphic(AValue: PPyObject; AContext: Pointer): Integer; var _object : TObject; begin Adjust(@Self); if CheckObjAttribute(AValue, 'Graphic', TGraphic, _object) then begin Self.DelphiObject.Graphic := TGraphic(_object); Result := 0; end else Result := -1; end; function TPyDelphiPicture.Set_Icon(AValue: PPyObject; AContext: Pointer): Integer; var _object : TObject; begin Adjust(@Self); if CheckObjAttribute(AValue, 'Icon', TIcon, _object) then begin Self.DelphiObject.Icon := TIcon(_object); Result := 0; end else Result := -1; end; {$IFNDEF FPC} function TPyDelphiPicture.Set_MetaFile(AValue: PPyObject; AContext: Pointer): Integer; var _object : TObject; begin Adjust(@Self); if CheckObjAttribute(AValue, 'MetaFile', TMetaFile, _object) then begin Self.DelphiObject.MetaFile := TMetaFile(_object); Result := 0; end else Result := -1; end; {$ENDIF FPC} procedure TPyDelphiPicture.SetDelphiObject(const Value: TPicture); begin inherited DelphiObject := Value; end; initialization RegisteredUnits.Add(TGraphicsRegistration.Create); end.
30.093237
129
0.68361
c38fc37c314e53db362ce78a68ccf385c47f3d7f
7,025
pas
Pascal
automata_theory/Lab1/formcolor.pas
danilbushkov/university
9f2e22c4691a2c8156748f4feaab57cd53fa4c67
[ "MIT" ]
1
2021-03-28T08:54:13.000Z
2021-03-28T08:54:13.000Z
automata_theory/Lab1/formcolor.pas
danilbushkov/university
9f2e22c4691a2c8156748f4feaab57cd53fa4c67
[ "MIT" ]
null
null
null
automata_theory/Lab1/formcolor.pas
danilbushkov/university
9f2e22c4691a2c8156748f4feaab57cd53fa4c67
[ "MIT" ]
null
null
null
unit FormColor; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ColorBox; type { TFColor } TFColor = class(TForm) Button1: TButton; Button2: TButton; ColorBox1: TColorBox; ColorBox2: TColorBox; ColorBox3: TColorBox; ColorBox4: TColorBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; RadioButton1: TRadioButton; RadioButton2: TRadioButton; RadioButton3: TRadioButton; RadioButton4: TRadioButton; Shape1: TShape; Shape2: TShape; Shape3: TShape; Shape4: TShape; Shape5: TShape; Shape6: TShape; Shape7: TShape; Shape8: TShape; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure ColorBox1Change(Sender: TObject); procedure ColorBox1Click(Sender: TObject); procedure ColorBox2Click(Sender: TObject); procedure ColorBox3Click(Sender: TObject); procedure ColorBox4Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure SetColor(c1,c2:Tcolor); procedure Shape1ChangeBounds(Sender: TObject); procedure Shape1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Shape2MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Shape3MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Shape4MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Shape5MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Shape6MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Shape7ChangeBounds(Sender: TObject); procedure Shape7MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure Shape8MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); private public end; var FColor: TFColor; sColor: array[0..1] of Tcolor; pl:integer=1; implementation {$R *.lfm} { TFColor } uses main,checkerunit; procedure TFColor.FormCreate(Sender: TObject); begin ColorBox1.Selected:=cllime; ColorBox2.Selected:=clwhite; ColorBox3.Selected:=clYellow; ColorBox4.Selected:=claqua; ColorBox1.AddItem('Зеленый',TObject(cllime)); ColorBox1.AddItem('Красный',TObject(clred)); ColorBox2.AddItem('Белый',TObject(clwhite)); ColorBox2.AddItem('Коричневый',TObject(clMaroon)); ColorBox3.AddItem('Желтый',TObject(clYellow)); ColorBox3.AddItem('Синий',TObject(clblue)); ColorBox4.AddItem('Голубой',TObject(claqua)); ColorBox4.AddItem('Фиолетовый',TObject(clFuchsia)); end; procedure TFColor.Button1Click(Sender: TObject); begin if RadioButton1.Checked then begin sColor[0]:=ColorBox1.Selected; if ColorBox1.Selected=ColorBox1.Colors[0] then begin pl:=1; sColor[1]:=ColorBox1.Colors[1]; end else begin pl:=2; sColor[1]:=ColorBox1.Colors[0]; end; end; if RadioButton2.Checked then begin sColor[0]:=ColorBox2.Selected; if ColorBox2.Selected=ColorBox2.Colors[0] then begin pl:=1; sColor[1]:=ColorBox2.Colors[1]; end else begin pl:=2; sColor[1]:=ColorBox2.Colors[0]; end; end; if RadioButton3.Checked then begin sColor[0]:=ColorBox3.Selected; if ColorBox3.Selected=ColorBox3.Colors[0] then begin pl:=1; sColor[1]:=ColorBox3.Colors[1]; end else begin pl:=2; sColor[1]:=ColorBox3.Colors[0]; end; end; if RadioButton4.Checked then begin sColor[0]:=ColorBox4.Selected; if ColorBox4.Selected=ColorBox4.Colors[0] then begin pl:=1; sColor[1]:=ColorBox4.Colors[1]; end else begin pl:=2; sColor[1]:=ColorBox4.Colors[0]; end; end; SetColor(sColor[0],sColor[1]); Close(); end; procedure TFColor.Button2Click(Sender: TObject); begin Close(); end; procedure TFColor.ColorBox1Change(Sender: TObject); begin end; procedure TFColor.ColorBox1Click(Sender: TObject); begin RadioButton1.Checked:=true; end; procedure TFColor.ColorBox2Click(Sender: TObject); begin RadioButton2.Checked:=true; end; procedure TFColor.ColorBox3Click(Sender: TObject); begin RadioButton3.Checked:=true; end; procedure TFColor.ColorBox4Click(Sender: TObject); begin RadioButton4.Checked:=true; end; procedure TFColor.SetColor(c1,c2:Tcolor); var i:integer; begin //игрок for i:=0 to 11 do begin checkers[i].brush.Color:=c1; checkers[i].pen.Color:=clblack; end; //бот for i:=12 to 23 do begin checkers[i].brush.Color:=c2; checkers[i].pen.Color:=clblack; end; end; procedure TFColor.Shape1ChangeBounds(Sender: TObject); begin end; procedure TFColor.Shape1MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin RadioButton1.Checked:=true; ColorBox1.Selected:=Shape1.Brush.color; end; procedure TFColor.Shape2MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin RadioButton1.Checked:=true; ColorBox1.Selected:=Shape2.Brush.color; end; procedure TFColor.Shape3MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin RadioButton2.Checked:=true; ColorBox2.Selected:=Shape3.Brush.color; end; procedure TFColor.Shape4MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin RadioButton2.Checked:=true; ColorBox2.Selected:=Shape4.Brush.color; end; procedure TFColor.Shape5MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin RadioButton3.Checked:=true; ColorBox3.Selected:=Shape5.Brush.color; end; procedure TFColor.Shape6MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin RadioButton3.Checked:=true; ColorBox3.Selected:=Shape6.Brush.color; end; procedure TFColor.Shape7ChangeBounds(Sender: TObject); begin end; procedure TFColor.Shape7MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin RadioButton4.Checked:=true; ColorBox4.Selected:=Shape7.Brush.color; end; procedure TFColor.Shape8MouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin RadioButton4.Checked:=true; ColorBox4.Selected:=Shape8.Brush.color; end; end.
23.573826
76
0.665338
470ede486df394f4cf6241779ad2f52bde0d0530
228
pas
Pascal
AuthenticatorDesign.pas
WJeanSmith/GoogleOAuth2Authenticator
85d2eb9a85be5f0954607205b9c458996f5469c8
[ "MIT" ]
1
2021-03-02T01:11:55.000Z
2021-03-02T01:11:55.000Z
AuthenticatorDesign.pas
WJeanSmith/GoogleOAuth2Authenticator
85d2eb9a85be5f0954607205b9c458996f5469c8
[ "MIT" ]
null
null
null
AuthenticatorDesign.pas
WJeanSmith/GoogleOAuth2Authenticator
85d2eb9a85be5f0954607205b9c458996f5469c8
[ "MIT" ]
null
null
null
unit AuthenticatorDesign; interface procedure Register; implementation uses OAuth2AuthenticatorGoogle, System.Classes; procedure Register; begin RegisterComponents('REST Client', [TOAuth2AuthenticatorGoogle]); end; end.
13.411765
66
0.820175
47d57246eedec9d6b798bc9d3a1d49f2cc170bbf
617
pas
Pascal
windows/src/ext/jedi/jvcl/tests/archive/jvcl/Convert/fAboutMe.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jvcl/tests/archive/jvcl/Convert/fAboutMe.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jvcl/tests/archive/jvcl/Convert/fAboutMe.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
unit fAboutMe; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, jpeg, ExtCtrls, JvLabel, JvComponent, JvxCtrls; type TfrmAboutMe = class(TForm) Panel1: TPanel; Label1: TLabel; Image1: TImage; Label2: TLabel; Memo1: TMemo; OKButton: TButton; JvHotLink2: TJvLabel; Label3: TLabel; JvHotLink1: TJvLabel; Version: TLabel; Comments: TLabel; private { Private declarations } public { Public declarations } end; var frmAboutMe: TfrmAboutMe; implementation {$R *.dfm} { TfrmAboutMe } end.
15.425
76
0.679092
c34247ec07dce3c6ec6e5717fc6da640ee30a93c
107,952
pas
Pascal
contrib/mORMot/SQLite3/mORMotDDD.pas
Razor12911/bms2xtool
0493cf895a9dbbd9f2316a3256202bcc41d9079c
[ "MIT" ]
4
2020-04-24T07:43:43.000Z
2021-08-29T08:36:08.000Z
mORMot/SQLite3/mORMotDDD.pas
LongDirtyAnimAlf/AsphyrePXL
9151ff88eca1fa01dce083b09e7ea20076f6d334
[ "Apache-2.0" ]
1
2022-02-17T07:17:16.000Z
2022-02-17T07:17:16.000Z
contrib/mORMot/SQLite3/mORMotDDD.pas
Razor12911/bms2xtool
0493cf895a9dbbd9f2316a3256202bcc41d9079c
[ "MIT" ]
2
2020-08-18T09:42:33.000Z
2021-04-22T08:15:27.000Z
/// Domain-Driven-Design toolbox for mORMot // - this unit is a part of the freeware Synopse mORMot framework, // licensed under a MPL/GPL/LGPL tri-license; version 1.18 unit mORMotDDD; { This file is part of Synopse mORMot framework. Synopse mORMot framework. Copyright (C) 2020 Arnaud Bouchez Synopse Informatique - https://synopse.info *** BEGIN LICENSE BLOCK ***** Version: MPL 1.1/GPL 2.0/LGPL 2.1 The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is Synopse mORMot framework. The Initial Developer of the Original Code is Arnaud Bouchez. Portions created by the Initial Developer are Copyright (C) 2020 the Initial Developer. All Rights Reserved. Contributor(s): Alternatively, the contents of this file may be used under the terms of either the GNU General Public License Version 2 or later (the "GPL"), or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms of the MPL, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the MPL, the GPL or the LGPL. ***** END LICENSE BLOCK ***** } {$I Synopse.inc} // define HASINLINE CPU32 CPU64 OWNNORMTOUPPER interface uses {$ifdef MSWINDOWS} Windows, {$else} {$ifdef FPC} SynFPCLinux, {$endif FPC} {$endif MSWINDOWS} SysUtils, Classes, Contnrs, Variants, SyncObjs, SynCrtSock, SynCommons, SynLog, SynCrypto, SynTable, // for TSynFilter and TSynValidate mORMot; { some mORMot conventions about DDD implementation: * most services methods should return an enumerate: - Exceptions should be raised only in case of a real failure (e.g. unexpected execution context, service shutdown...) but most of the time an enumerate will be used to manage errors - no textual error message should be sent by the application layer: it is up to the end-user application to react to a given unexpected result - within the DDD services, CQRS methods will use a TCQRSResult enumerate and advanced error process, with an optional error text for debugging - first value should mean success, so that TInterfaceStub would let the test pass by returning the default 0 ordinal * persistence ignorance is mostly implemented via CQRS repository services: - we implement the "Command Query Responsibility Segregation" pattern to potentially increase scaling ability of reading, and allow distributed transactions via a service-based two-phase commit, implementing the Unit Of Work pattern - no ID should be transmitted most of the time, but write commands have to follow a read query which would specify the corresponding item so that the ID would be stored during the process - I*Query interfaces should have some SelectBy*() methods to change the current selected aggregate, which could later on be retrieved by a Get(out aAggregate: T....) method - I*Command instances would be our way of implementing the Unit Of Work - I*Command interfaces should have standard Add/Update/Delete methods, expecting a previous SelectBy*() call for Update/Delete: those methods should prepare the corresponding data change - I*Command interfaces should have Commit to perform all the pending changes (which may be implemented by transactions or via TSQLRestBatch) - I*Command interfaces should abort the process if the instance is released without any prior call to Commit (e.g. rollback the transaction or free any pending TSQLRestBatch instance) } { *********** Some Domain-Driven-Design Common Definitions } type /// abstract ancestor for all Domain-Driven Design related Exceptions EDDDException = class(ESynException); /// Exception type linked to CQRS repository service methods ECQRSException = class(EDDDException); /// abstract ancestor for any Domain-Driven Design infrastructure Exceptions EDDDInfraException = class(EDDDException); { ----- Persistence / Repository Interfaces } type /// result enumerate for I*Query/I*Command CQRS repository service methods // - cqrsSuccess will map the default TInterfaceStub returned value // - cqrsSuccessWithMoreData would be used e.g. for versioned publish/ // subscribe to notify the caller that there are still data available, and // the call should be reiterated until cqrsSuccess is returned // - cqrsBadRequest would indicate that the method was not called in the // expected workflow sequence // - cqrsNotFound appear after a I*Query SelectBy*() method with no match // - cqrsNoMoreData indicates a GetNext*() method has no more matching data // - cqrsDataLayerError indicates a low-level error at database level // - cqrsInvalidCallback is returned if a callback is required for this method // - cqrsInternalError for an unexpected issue, like an Exception raised // - cqrsDDDValidationFailed will be trigerred when // - cqrsInvalidContent for any I*Command method with invalid aggregate input // value (e.g. a missing field) // - cqrsAlreadyExists for a I*Command.Add method with a primay key conflict // - cqrsNoPriorQuery for a I*Command.Update/Delete method with no prior // call to SelectBy*() // - cqrsNoPriorCommand for a I*Command.Commit with no prior Add/Update/Delete // - cqrsNoMatch will notify that a command did not have any match // - cqrsNotImplemented may be returned when there is no code yet for a method // - cqrsBusy is returned if the command could not be executed, since it is // currently processing a request // - cqrsTimeout indicates that the method didn't succeed in the expected time // - otherwise, cqrsUnspecifiedError will be used for any other kind of error TCQRSResult = (cqrsSuccess, cqrsSuccessWithMoreData, cqrsUnspecifiedError, cqrsBadRequest, cqrsNotFound, cqrsNoMoreData, cqrsDataLayerError, cqrsInvalidCallback, cqrsInternalError, cqrsDDDValidationFailed, cqrsInvalidContent, cqrsAlreadyExists, cqrsNoPriorQuery, cqrsNoPriorCommand, cqrsNoMatch, cqrsNotImplemented, cqrsBusy, cqrsTimeout); /// generic interface, to be used for CQRS I*Query and I*Command types definition // - TCQRSService class will allow to easily implement LastError* members // - all CQRS services, which may be executed remotely, would favor a function // result as TCQRSResult enumeration for error handling, rather than a local // Exception, which is not likely to be transferred easily on consummer side ICQRSService = interface(IInvokable) /// should return the last error as an enumerate // - when stubed or mocked via TInterfaceStub, any method interface would // return 0, i.e. cqrsSuccess by default, to let the test pass function GetLastError: TCQRSResult; /// should return addition information for the last error // - may be a plain string, or a JSON document stored as TDocVariant function GetLastErrorInfo: variant; end; /// returns the text equivalency of a CQRS result enumeration function ToText(res: TCQRSResult): PShortString; overload; const /// successfull result enumerates for I*Query/I*Command CQRS // - those items would generate no log entry // - i.e. any command not included in CQRSRESULT_SUCCESS nor CQRSRESULT_WARNING // would trigger a sllDDDError log entry CQRSRESULT_SUCCESS = [ cqrsSuccess, cqrsSuccessWithMoreData, cqrsNoMoreData, cqrsNotFound]; /// dubious result enumerates for I*Query/I*Command CQRS // - those items would generate a sllDDDInfo log entry // - i.e. any command not included in CQRSRESULT_SUCCESS nor CQRSRESULT_WARNING // would trigger a sllDDDError log entry CQRSRESULT_WARNING = [ cqrsNotFound, cqrsNoMatch]; { ----- Services / Daemon Interfaces } type /// generic interface, to be used so that you may retrieve a running state IMonitored = interface(IInvokable) ['{7F5E1569-E06B-48A0-954C-95784EC23363}'] /// retrieve the current status of the instance // - the status is returned as a schema-less value (typically a TDocVariant // document), which may contain statistics about the current processing // numbers, timing and throughput function RetrieveState(out Status: variant): TCQRSResult; end; /// generic interface, to be used so that you may manage a service/daemon instance IMonitoredDaemon = interface(IMonitored) ['{F5717AFC-5D0E-4E13-BD5B-25C08CB177A7}'] /// launch the service/daemon // - should first stop any previous running instance (so may be used to // restart a service on demand) function Start: TCQRSResult; /// abort the service/daemon, returning statistics about the whole execution function Stop(out Information: variant): TCQRSResult; end; /// generic interface, to manage a service/daemon instance from an executable // - in addition to Start/Stop methods, Halt would force the whole executable // to abort its execution, SubscribeLog allows log monitoring, and // DatabaseList/DatabaseExecute remote SQL/SOA execution on one or several // logicial REST servers // - those methods would allow a single administration daemon (installed e.g. // as a Windows Service) to be able to launch and monitor child processes as // individual executables, or via a custom DDD's ToolsAdmin tool // - since SubscribeLog() uses a callback, this REST server should be // published via supported transmission protocol, e.g. WebSockets IAdministratedDaemon = interface(IMonitoredDaemon) ['{BD02919E-56ED-4559-967A-EFBC0E85C031}'] /// will Stop the service/daemon process, then quit the executable // - the returned Information and TCQRSResult are passed directly from // the Stop() method function Halt(out Information: variant): TCQRSResult; /// returns a list of internal database names, exposed by this daemon // - in practice, each database name should identify a TSQLRest instance // - the database name should be supplied to DatabaseExecute() as target function DatabaseList: TRawUTF8DynArray; /// returns a list of tables, stored in the internal database names // - the database name should match one existing in the DatabaseList // - in practice, returns all TSQLRecord table of the TSQLRest instance function DatabaseTables(const DatabaseName: RawUTF8): TRawUTF8DynArray; /// execute a SQL query on an internal database // - the database name should match one existing in the DatabaseList // - the supplied SQL parameter may be #cmd internal commands: in this case, // the database name may not be mandatory // - will return JSON most of the time, but may return binary if needed function DatabaseExecute(const DatabaseName,SQL: RawUTF8): TServiceCustomAnswer; /// used to subscribe for real-time remote log monitoring // - allows to track the specified log events, with a callback // - you can specify a number of KB of existing log content to send to the // monitoring tool, before the actual real-time process: Callback.Log() // would be called first with Level=sllNone and all the existing text procedure SubscribeLog(const Level: TSynLogInfos; const Callback: ISynLogCallback; ReceiveExistingKB: cardinal); /// will be called when a callback is released on the client side // - this method matches IServiceWithCallbackReleased signature // - will be used to unsubscribe any previous ISynLogCallback notification procedure CallbackReleased(const callback: IInvokable; const interfaceName: RawUTF8); end; /// any service/daemon implementing this interface would be able to redirect // all the administration process to another service/daemon // - i.e. would work as a safe proxy service, over several networks IAdministratedDaemonAsProxy = interface(IAdministratedDaemon) ['{5B7A9086-3D96-48F2-8E27-C6624B2EB45A}'] /// allows to connect to another service/daemon IAdministratedDaemon // - detailed connection definition would be supplied as a TDocVariantData // object, serialized from dddInfraApp.pas TDDDRestClientSettings function StartProxy(const aDDDRestClientSettings: variant): TCQRSResult; end; /// allow persistence of any TObject settings storage IDDDSettingsStorable = interface ['{713A9C16-4BBD-4FB6-A7A6-566162767622}'] /// persist the settings if needed // - will call the virtual InternalPersist method procedure StoreIfUpdated; end; { *********** Cross-Cutting Layer Implementation} { ----- Persistence / Repository CQRS Implementation } type /// which kind of process is about to take place after an CqrsBeginMethod() TCQRSQueryAction = ( qaNone, qaSelect, qaGet, qaCommandDirect, qaCommandOnSelect, qaCommit); /// define one or several process to take place after an CqrsBeginMethod() TCQRSQueryActions = set of TCQRSQueryAction; /// the current step of a TCQRSQuery state machine // - basic state diagram is defined by the methods execution: // - qsNone refers to the default state, with no currently selected values, // nor any pending write request // - qsQuery corresponds to a successful I*Query.Select*(), expecting // either a I*Query.Get*(), or a I*Command.Add/Update/Delete // - qsCommand corresponds to a successful I*Command.Add/Update/Delete, // expected a I*Command.Commit TCQRSQueryState = (qsNone, qsQuery, qsCommand); /// to be inherited to implement CQRS I*Query or I*Command services extended // error process // - you should never assign directly a cqrs* value to a method result, but // rather use the CqrsBeginMethod/CqrsSetResult/CqrsSetResultMsg methods provided by this class: // ! function TMyService.MyMethod: TCQRSResult; // ! begin // ! CqrsBeginMethod(qsNone,result); // reset the error information to cqrsUnspecifiedError // ! ... // do some work // ! if error then // ! CqrsSetResultMsg(cqrsUnspecifiedError,'Oups! For "%"',[name],result) else // ! CqrsSetResult(cqrsSuccess,result); // instead of result := cqrsSuccess // ! end; // - the methods are implemented as a simple state machine, following // the TCQRSQueryAction and TCQRSQueryState definitions // - warning: by definition, fLastError* access is NOT thread-safe so the // CqrsBeginMethod/CqrsSetResult feature should be used in a single context TCQRSService = class(TInjectableObject, ICQRSService) protected fLastError: TCQRSResult; fLastErrorContext: variant; fAction: TCQRSQueryAction; fState: TCQRSQueryState; {$ifdef WITHLOG} fLog: TSynLogFamily; {$endif} fSafe: TSynLocker; // method to be called at first for LastError process function CqrsBeginMethod(aAction: TCQRSQueryAction; var aResult: TCQRSResult; aError: TCQRSResult=cqrsUnspecifiedError): boolean; virtual; function CqrsSetResultError(aError: TCQRSResult): TCQRSResult; virtual; // methods to be used to set the process end status procedure CqrsSetResult(Error: TCQRSResult; var Result: TCQRSResult); overload; procedure CqrsSetResult(E: Exception; var Result: TCQRSResult); overload; procedure CqrsSetResultSuccessIf(SuccessCondition: boolean; var Result: TCQRSResult; ErrorIfFalse: TCQRSResult=cqrsDataLayerError); procedure CqrsSetResultMsg(Error: TCQRSResult; const ErrorMessage: RawUTF8; var Result: TCQRSResult); overload; procedure CqrsSetResultMsg(Error: TCQRSResult; const ErrorMsgFmt: RawUTF8; const ErrorMsgArgs: array of const; var Result: TCQRSResult); overload; procedure CqrsSetResultString(Error: TCQRSResult; const ErrorMessage: string; var Result: TCQRSResult); procedure CqrsSetResultDoc(Error: TCQRSResult; const ErrorInfo: variant; var Result: TCQRSResult); procedure CqrsSetResultJSON(Error: TCQRSResult; const JSONFmt: RawUTF8; const Args,Params: array of const; var Result: TCQRSResult); function GetLastError: TCQRSResult; function GetLastErrorInfo: variant; virtual; procedure InternalCqrsSetResult(Error: TCQRSResult; var Result: TCQRSResult); virtual; procedure AfterInternalCqrsSetResult; virtual; public /// initialize the instance constructor Create; override; /// finalize the instance destructor Destroy; override; {$ifdef WITHLOG} /// where logging should take place property Log: TSynLogFamily read fLog write fLog; {$endif} published /// the last error, as an enumerate property LastError: TCQRSResult read GetLastError; /// the last error extended information, as a string or TDocVariant property LastErrorInfo: variant read GetLastErrorInfo; /// the action currently processing property Action: TCQRSQueryAction read fAction; /// current step of the TCQRSService state machine property State: TCQRSQueryState read fState; end; /// a CQRS Service, which maintains an internal list of "Subscribers" // - allow to notify in cascade when a callback is released TCQRSServiceSubscribe = class(TCQRSService) protected fSubscriber: array of IServiceWithCallbackReleased; // will call all fSubscriber[].CallbackReleased() methods procedure CallbackReleased(const callback: IInvokable; const interfaceName: RawUTF8); end; /// a CQRS Service, ready to implement a set of synchronous (blocking) commands // over an asynchronous (non-blocking) service // - you may use this class e.g. at API level, over a blocking REST server, // and communicate with the Domain event-driven services via asynchronous calls // - this class won't inherit from TCQRSService, since it would be called // from multiple threads at once, so all CQRSSetResult() methods would fail TCQRSServiceSynch = class(TInterfacedObject) protected fSharedCallbackRef: IUnknown; public constructor Create(const sharedcallback: IUnknown); reintroduce; end; /// used to acknowledge asynchronous CQRS Service calls // - e.g. to implement TCQRSServiceSynch TCQRSServiceAsynchAck = class(TInterfacedObject) protected fLog: TSynLogClass; fCalls: TBlockingProcessPool; public destructor Destroy; override; end; /// class-reference type (metaclass) of TCQRSService TCQRSServiceClass = class of TCQRSService; /// returns the text equivalency of a CQRS state enumeration function ToText(res: TCQRSQueryState): PShortString; overload; { ----- Persistence / Repository Implementation using mORMot's ORM } type TDDDRepositoryRestFactory = class; TDDDRepositoryRestQuery = class; /// class-reference type (metaclass) to implement I*Query or I*Command // interface definitions using our RESTful ORM TDDDRepositoryRestClass = class of TDDDRepositoryRestQuery; /// abstract ancestor for all persistence/repository related Exceptions EDDDRepository = class(ESynException) public /// constructor like FormatUTF8() which will also serialize the caller info constructor CreateUTF8(Caller: TDDDRepositoryRestFactory; const Format: RawUTF8; const Args: array of const); end; /// store reference of several factories, each with one mapping definition TDDDRepositoryRestFactoryObjArray = array of TDDDRepositoryRestFactory; /// home repository of several DDD Entity factories using REST storage // - this shared class will be can to manage a service-wide repositories, // e.g. manage actual I*Query/I*Command implementation classes accross a // set of TSQLRest instances // - is designed to optimize BATCH or transactional process TDDDRepositoryRestManager = class protected fFactory: TDDDRepositoryRestFactoryObjArray; public /// finalize all factories destructor Destroy; override; /// register one DDD Entity repository over an ORM's TSQLRecord // - will raise an exception if the aggregate has already been defined function AddFactory( const aInterface: TGUID; aImplementation: TDDDRepositoryRestClass; aAggregate: TClass; aRest: TSQLRest; aTable: TSQLRecordClass; const TableAggregatePairs: array of RawUTF8): TDDDRepositoryRestFactory; /// retrieve the registered definition of a given DDD Entity in Factory[] // - returns -1 if the TPersistence class is unknown function GetFactoryIndex(const aInterface: TGUID): integer; /// retrieve the registered Factory definition of a given DDD Entity // - raise an EDDDRepository exception if the TPersistence class is unknown function GetFactory(const aInterface: TGUID): TDDDRepositoryRestFactory; /// read-only access to all defined DDD Entity factories property Factory: TDDDRepositoryRestFactoryObjArray read fFactory; end; /// implement a DDD Entity factory over one ORM's TSQLRecord // - it will centralize some helper classes and optimized class mapping // - the Entity class may be defined as any TPersistent or TSynPersistent, with // an obvious preference for TSynPersistent and TSynAutoCreateFields classes TDDDRepositoryRestFactory = class(TInterfaceResolverForSingleInterface) protected fOwner: TDDDRepositoryRestManager; fInterface: TInterfaceFactory; fRest: TSQLRest; fTable: TSQLRecordClass; fAggregate: TClassInstance; fAggregateRTTI: TSQLPropInfoList; // stored in fGarbageCollector, following fAggregateProp[] fGarbageCollector: TObjectDynArray; fFilter: array of array of TSynFilter; fValidate: array of array of TSynValidate; // TSQLPropInfoList correspondance, as filled by ComputeMapping: fAggregateToTable: TSQLPropInfoObjArray; fAggregateProp: TSQLPropInfoRTTIObjArray; fAggregateID: TSQLPropInfoRTTI; // store custom field mapping between TSQLRecord and Aggregate fPropsMapping: TSQLRecordPropertiesMapping; fPropsMappingVersion: cardinal; procedure ComputeMapping; function GetAggregateName: string; function GetTableName: string; // override those methods to customize the data marshalling procedure AggregatePropToTable( aAggregate: TObject; aAggregateProp: TSQLPropInfo; aRecord: TSQLRecord; aRecordProp: TSQLPropInfo); virtual; procedure TablePropToAggregate( aRecord: TSQLRecord; aRecordProp: TSQLPropInfo; aAggregate: TObject; aAggregateProp: TSQLPropInfo); virtual; function GetAggregateRTTIOptions: TSQLPropInfoListOptions; virtual; // main IoC/DI method, returning a TDDDRepositoryRest instance function CreateInstance: TInterfacedObject; override; public /// will compute the ORM TSQLRecord* source code type definitions // corresponding to DDD aggregate objects into a a supplied file name // - will generate one TSQLRecord* per aggregate class level, following the // inheritance hierarchy // - dedicated DDD types will be translated into native ORM types (e.g. RawUTF8) // - if no file name is supplied, it will generate a dddsqlrecord.inc file // in the executable folder // - could be used as such: // ! TDDDRepositoryRestFactory.ComputeSQLRecord([TPersonContactable,TAuthInfo]); // - once created, you may refine the ORM definition, by adding // ! ... read f.... write f... stored AS_UNIQUE; // for fields which should be unique, and/or // ! ... read f... write f... index #; // to specify an optional textual field width (VARCHAR n) for SQL storage // - most advanced ORM-level filters/validators, or low-level implementation // details (like the Sqlite3 collation) may be added by overriding this method: // !protected // ! class procedure InternalDefineModel(Props: TSQLRecordProperties); override; // ! ... // !class procedure TSQLRecordMyAggregate.InternalDefineModel( // ! Props: TSQLRecordProperties); // !begin // ! AddFilterNotVoidText(['HashedPassword']); // ! Props.SetCustomCollation('Field','BINARY'); // ! Props.AddFilterOrValidate('Email',TSynValidateEmail.Create); // !end; class procedure ComputeSQLRecord(const aAggregate: array of TClass; DestinationSourceCodeFile: TFileName=''); /// initialize the DDD Aggregate factory using a mORMot ORM class // - by default, field names should match on both sides - but you can // specify a custom field mapping as TSQLRecord,Aggregate pairs // - any missing or unexpected field on any side will just be ignored constructor Create( const aInterface: TGUID; aImplementation: TDDDRepositoryRestClass; aAggregate: TClass; aRest: TSQLRest; aTable: TSQLRecordClass; const TableAggregatePairs: array of RawUTF8; aOwner: TDDDRepositoryRestManager=nil); reintroduce; overload; /// initialize the DDD Aggregate factory using a mORMot ORM class // - this overloaded constructor does not expect any custom fields // - any missing or unexpected field on any side will just be ignored constructor Create( const aInterface: TGUID; aImplementation: TDDDRepositoryRestClass; aAggregate: TClass; aRest: TSQLRest; aTable: TSQLRecordClass; aOwner: TDDDRepositoryRestManager=nil); reintroduce; overload; /// finalize the factory destructor Destroy; override; /// register a custom filter or validator to some Aggregate's fields // - once added, the TSynFilterOrValidate instance will be owned to // this factory, until it is released // - the field names should be named from their full path (e.g. 'Email' or // 'Address.Country.Iso') unless aFieldNameFlattened is TRUE, which will // expect ORM-like naming (e.g. 'Address_Country') // - if '*' is specified as field name, it will be applied to all text // fields, so the following will ensure that all text fields will be // trimmed for spaces: // ! AddFilterOrValidate(['*'],TSynFilterTrim.Create); // - filters and validators will be applied to a specified aggregate using // AggregateFilterAndValidate() method // - the same filtering classes as with the ORM can be applied to DDD's // aggregates, e.g. TSynFilterUpperCase, TSynFilterLowerCase or // TSynFilterTrim // - the same validation classes as with the ORM can be applied to DDD's // aggregates, e.g. TSynValidateText.Create for a void field, // TSynValidateText.Create('{MinLength:5}') for a more complex test // (including custom password strength validation if TSynValidatePassWord // is not enough), TSynValidateIPAddress.Create or TSynValidateEmail.Create // for some network settings, or TSynValidatePattern.Create() // - you should not define TSynValidateUniqueField here, which could't be // checked at DDD level, but rather set a "stored AS_UNIQUE" attribute // in the corresponding property of the TSQLRecord type definition procedure AddFilterOrValidate(const aFieldNames: array of RawUTF8; aFilterOrValidate: TSynFilterOrValidate; aFieldNameFlattened: boolean=false); virtual; /// clear all properties of a given DDD Aggregate procedure AggregateClear(aAggregate: TObject); /// create a new DDD Aggregate instance function AggregateCreate: TObject; {$ifdef HASINLINE}inline;{$endif} /// perform filtering and validation on a supplied DDD Aggregate // - all logic defined by AddFilterOrValidate() will be processed function AggregateFilterAndValidate(aAggregate: TObject; aInvalidFieldIndex: PInteger=nil; aValidator: PSynValidate=nil): RawUTF8; virtual; /// serialize a DDD Aggregate as JSON // - you can optionaly force the generated JSON to match the mapped // TSQLRecord fields, so that it would be compatible with ORM's JSON procedure AggregateToJSON(aAggregate: TObject; W: TJSONSerializer; ORMMappedFields: boolean; aID: TID); overload; /// serialize a DDD Aggregate as JSON RawUTF8 function AggregateToJSON(aAggregate: TObject; ORMMappedFields: boolean; aID: TID): RawUTF8; overload; /// convert a DDD Aggregate into an ORM TSQLRecord instance procedure AggregateToTable(aAggregate: TObject; aID: TID; aDest: TSQLRecord); /// convert a ORM TSQLRecord instance into a DDD Aggregate procedure AggregateFromTable(aSource: TSQLRecord; aAggregate: TObject); /// convert ORM TSQLRecord.FillPrepare instances into a DDD Aggregate ObjArray procedure AggregatesFromTableFill(aSource: TSQLRecord; var aAggregateObjArray); /// the home repository owning this factory property Owner: TDDDRepositoryRestManager read fOwner; /// the DDD's Entity class handled by this factory // - may be any TPersistent, but very likely a TSynAutoCreateFields class property Aggregate: TClass read fAggregate.ItemClass; /// the ORM's TSQLRecord used for actual storage property Table: TSQLRecordClass read fTable; /// the mapped DDD's Entity class published properties RTTI property Props: TSQLPropInfoList read fAggregateRTTI; /// access to the Aggregate / ORM field mapping property FieldMapping: TSQLRecordPropertiesMapping read fPropsMapping; published /// the associated I*Query / I*Command repository interface property Repository: TInterfaceFactory read fInterface; /// the associated TSQLRest instance property Rest: TSQLRest read fRest; /// the DDD's Entity class name handled by this factory property AggregateClass: string read GetAggregateName; /// the ORM's TSQLRecord class name used for actual storage property TableClass: string read GetTableName; end; /// abstract repository class to implement I*Query interface using RESTful ORM // - actual repository implementation will just call the ORM*() protected // method from the published Aggregate-oriented CQRS service interface TDDDRepositoryRestQuery = class(TCQRSService) protected fFactory: TDDDRepositoryRestFactory; fCurrentORMInstance: TSQLRecord; function CqrsBeginMethod(aAction: TCQRSQueryAction; var aResult: TCQRSResult; aError: TCQRSResult=cqrsUnspecifiedError): boolean; override; // one-by-one retrieval in local ORM: TSQLRecord function ORMSelectOne(const ORMWhereClauseFmt: RawUTF8; const Bounds: array of const; ForcedBadRequest: boolean=false): TCQRSResult; function ORMSelectID(const ID: TID; RetrieveRecord: boolean=true; ForcedBadRequest: boolean=false): TCQRSResult; overload; function ORMSelectID(const ID: RawUTF8; RetrieveRecord: boolean=true; ForcedBadRequest: boolean=false): TCQRSResult; overload; function ORMGetAggregate(aAggregate: TObject): TCQRSResult; // list retrieval - using cursor-like access via ORM.FillOne function ORMSelectAll(const ORMWhereClauseFmt: RawUTF8; const Bounds: array of const; ForcedBadRequest: boolean=false): TCQRSResult; function ORMGetNextAggregate(aAggregate: TObject; aRewind: boolean=false): TCQRSResult; function ORMGetAllAggregates(var aAggregateObjArray): TCQRSResult; function ORMSelectCount(const ORMWhereClauseFmt: RawUTF8; const Args,Bounds: array of const; out aResultCount: integer; ForcedBadRequest: boolean=false): TCQRSResult; public /// you should not have to use this constructor, since the instances would // be injected by TDDDRepositoryRestFactory.TryResolve() constructor Create(aFactory: TDDDRepositoryRestFactory); reintroduce; virtual; /// finalize the used memory destructor Destroy; override; /// return the number all currently selected aggregates // - returns 0 if no select was available, 1 if it was a ORMGetSelectOne(), // or the number of items after a ORMGetSelectAll() // - this is a generic operation which would work for any class // - if you do not need this method, just do not declare it in I*Command function GetCount: integer; virtual; /// returns the associated TSQLRest instance used in the associated factory // - this method is able to extract it from a I*Query/I*Command instance, // if it is implemented by a TDDDRepositoryRestQuery class // - returns nil if the supplied Service is not recognized class function GetRest(const Service: ICQRSService): TSQLRest; published /// access to the associated factory property Factory: TDDDRepositoryRestFactory read fFactory; /// access to the current state of the underlying mapped TSQLRecord // - is nil if no query was run yet // - contains the queried object after a successful Select*() method // - is either a single object, or a list of objects, via its internal // CurrentORMInstance.FillTable cursor property CurrentORMInstance: TSQLRecord read fCurrentORMInstance; end; /// abstract class to implement I*Command interface using ORM's TSQLRecord // - it will use an internal TSQLRestBatch for dual-phase commit, therefore // implementing a generic Unit Of Work / Transaction pattern TDDDRepositoryRestCommand = class(TDDDRepositoryRestQuery) protected fBatch: TSQLRestBatch; fBatchAutomaticTransactionPerRow: cardinal; fBatchOptions: TSQLRestBatchOptions; fBatchResults: TIDDynArray; procedure ORMEnsureBatchExists; virtual; // this default implementation will check the status vs command, // call DDD's + ORM's FilterAndValidate, then add to the internal BATCH // - you should override it, if you need a specific behavior // - if aAggregate is nil, fCurrentORMInstance field values would be used // - if aAggregate is set, its fields would be set to fCurrentORMInstance procedure ORMPrepareForCommit(aCommand: TSQLOccasion; aAggregate: TObject; var Result: TCQRSResult; aAllFields: boolean=false); virtual; /// minimal implementation using AggregateToTable() conversion function ORMAdd(aAggregate: TObject; aAllFields: boolean=false): TCQRSResult; virtual; function ORMUpdate(aAggregate: TObject; aAllFields: boolean=false): TCQRSResult; virtual; /// this default implementation will send the internal BATCH // - you should override it, if you need a specific behavior procedure InternalCommit(var Result: TCQRSResult); virtual; /// on rollback, delete the internal BATCH - called by Destroy procedure InternalRollback; virtual; public /// this constructor will set default fBatch options constructor Create(aFactory: TDDDRepositoryRestFactory); override; /// finalize the Unit Of Work context // - any uncommited change will be lost destructor Destroy; override; /// perform a deletion on the currently selected aggregate // - this is a generic operation which would work for any class // - if you do not need this method, just do not declare it in I*Command function Delete: TCQRSResult; virtual; /// perform a deletion on all currently selected aggregates // - this is a generic operation which would work for any class // - if you do not need this method, just do not declare it in I*Command function DeleteAll: TCQRSResult; virtual; /// write all pending changes prepared by Add/Update/Delete methods // - this is the only mandatory method, to be declared in your I*Command // - in practice, will send the current internal BATCH to the REST instance function Commit: TCQRSResult; virtual; /// flush any pending changes prepared by Add/Update/Delete methods // - if you do not need this method, just do not publish it in I*Command // - the easiest to perform a roll-back would be to release the I*Command // instance - but you may explictly reset the pending changes by calling // this method // - in practice, will release the internal BATCH instance function Rollback: TCQRSResult; virtual; /// access to the low-level BATCH instance, used for dual-phase commit // - you should not need to access it directly, but rely on Commit and // Rollback methods to property Batch: TSQLRestBatch read fBatch; end; /// abstract CQRS class tied to a TSQLRest instance for low-level persistence // - not used directly by the DDD repositories (since they will rely on // a TDDDRepositoryRestFactory for the actual ORM process), but may be the // root class for any Rest-based infrastructure cross-cutting features TCQRSQueryObjectRest = class(TCQRSService) protected fRest: TSQLRest; public /// this constructor would identify a TServiceContainer SOA resolver // and set the Rest property // - when called e.g. by TServiceFactoryServer.CreateInstance() constructor CreateWithResolver(aResolver: TInterfaceResolver; aRaiseEServiceExceptionIfNotFound: boolean); overload; override; /// reintroduced constructor, allowing to specify the associated REST instance constructor Create(aRest: TSQLRest); reintroduce; virtual; /// reintroduced constructor, associating a REST instance with the supplied // IoC resolvers constructor CreateWithResolver(aRest: TSQLRest; aResolver: TInterfaceResolver; aRaiseEServiceExceptionIfNotFound: boolean=true); reintroduce; overload; /// reintroduced constructor, associating a REST instance with the supplied // IoC resolvers (may be stubs/mocks, resolver classes or single instances) constructor CreateInjected(aRest: TSQLRest; const aStubsByGUID: array of TGUID; const aOtherResolvers: array of TInterfaceResolver; const aDependencies: array of TInterfacedObject); reintroduce; /// access to the associated REST instance property Rest: TSQLRest read FRest; end; { ----- Services / Daemon Implementation } type TDDDMonitoredDaemon = class; /// the current state of a process thread TDDDMonitoredDaemonProcessState = ( dpsPending, dpsProcessing, dpsProcessed, dpsFailed); /// abstract process thread class with monitoring abilities TDDDMonitoredDaemonProcess = class(TThread) protected fDaemon: TDDDMonitoredDaemon; fIndex: integer; fProcessIdleDelay: cardinal; fMonitoring: TSynMonitorWithSize; /// the main thread loop, which will call the protected Execute* methods procedure Execute; override; protected /// check for any pending task, and mark it as started // - will be executed within fDaemon.fProcessLock so that it would be // atomic among all fDaemon.fProcess[] threads - overriden implementation // should therefore ensure that this method executes as fast as possible // to minimize contention // - returns FALSE if there is no pending task // - returns TRUE if there is a pending task, and ExecuteProcessAndSetResult // should be called by Execute outside the fDaemon.fProcessLock function ExecuteRetrievePendingAndSetProcessing: boolean; virtual; abstract; /// execute the task, and set its resulting state // - resulting state may be e.g. "processed" or "failed" // - should return the number of bytes processed, for fMonitoring update // - will be executed outside fDaemon.fProcessLock so that overriden // implementation may take as much time as necessary for its process function ExecuteProcessAndSetResult: QWord; virtual; abstract; /// finalize the pending task // - will always be called, even if ExecuteRetrievePendingAndSetProcessing // returned FALSE procedure ExecuteProcessFinalize; virtual; abstract; /// is called when there is no more pending task // - may be used e.g. to release a connection or some resource (e.g. an // ORM TSQLRestBatch instance) procedure ExecuteIdle; virtual; abstract; /// will be called on any exception in Execute // - this default implementation will call fMonitoring.ProcessError() procedure ExecuteOnException(E: Exception); virtual; public /// initialize the process thread for a given Service/Daemon instance constructor Create(aDaemon: TDDDMonitoredDaemon; aIndexInDaemon: integer); virtual; /// finalize the process thread destructor Destroy; override; /// milliseconds delay defined before getting the next pending tasks // - equals TDDDMonitoredDaemon.ProcessIdleDelay, unless a fatal exception // occurred during TDDDMonitoredDaemonProcess.ExecuteIdle method: in this // case, the delay would been increased to 500 ms property IdleDelay: cardinal read fProcessIdleDelay; end; /// abstract process thread class with monitoring abilities, using the ORM // for pending tasks persistence // - a protected TSQLRecord instance will be maintained to store the // processing task and its current state TDDDMonitoredDaemonProcessRest = class(TDDDMonitoredDaemonProcess) protected /// the internal ORM instance used to maintain the current task // - it should contain the data to be processed, the processing state // (e.g. at least "processing", "processed" and "failed"), and optionally // the resulting content (if any) // - overriden ExecuteRetrievePendingAndSetProcessing method should create // fPendingTask then save fPendingTask.State to "processing" // - overriden ExecuteProcessAndSetResult method should perform the task, // then save fPendingTask.State to "processed" or "failed" fPendingTask: TSQLRecord; /// finalize the pending task: will free fPendingTask and set it to nil procedure ExecuteProcessFinalize; override; end; /// class-reference type (metaclass) to determine which actual thread class // will implement the monitored process TDDDMonitoredDaemonProcessClass = class of TDDDMonitoredDaemonProcess; /// abstract class using several process threads and with monitoring abilities // - able to implement any DDD Daemon/Service, with proper statistics gathering // - each TDDDMonitoredDaemon will own its TDDDMonitoredDaemonProcess TDDDMonitoredDaemon = class(TCQRSQueryObjectRest,IMonitoredDaemon) protected fProcess: array of TDDDMonitoredDaemonProcess; fProcessClass: TDDDMonitoredDaemonProcessClass; fProcessMonitoringClass: TSynMonitorClass; fProcessLock: IAutoLocker; fProcessTimer: TPrecisionTimer; fProcessThreadCount: integer; fProcessIdleDelay: integer; fMonitoringClass: TSynMonitorClass; function GetStatus: variant; virtual; public /// abstract constructor, which should not be called by itself constructor Create(aRest: TSQLRest); overload; override; /// you should override this constructor to set the actual process // - i.e. define the fProcessClass protected property constructor Create(aRest: TSQLRest; aProcessThreadCount: integer); reintroduce; overload; /// finalize the Daemon destructor Destroy; override; /// monitor the Daemon/Service by returning some information as a TDocVariant // - its Status.stats sub object will contain global processing statistics, // and Status.threadstats similar information, detailled by running thread function RetrieveState(out Status: variant): TCQRSResult; /// launch all processing threads // - any previous running threads are first stopped function Start: TCQRSResult; virtual; /// finalize all processing threads // - and returns updated statistics as a TDocVariant function Stop(out Information: variant): TCQRSResult; virtual; published /// how many process threads should be created by this Daemon/Service property ProcessThreadCount: integer read fProcessThreadCount; /// how many milliseconds each process thread should wait before checking // for pending tasks // - default value is 50 ms, which seems good enough in practice property ProcessIdleDelay: integer read fProcessIdleDelay write fProcessIdleDelay; end; /// current status of an administrable service/daemon TDDDAdministratedDaemonStatus = ( dsUnknown, dsCreated, dsStarted, dsStopped, dsHalted); /// abstract class to implement an administrable service/daemon // - a single administration daemon (running e.g. as a Windows Service) would // be able to launch and administrate such process, via a remote REST link // - inherited class should override the Internal* virtual abstract protected // methods to supply the actual process (e.g. set a background thread) TDDDAdministratedDaemon = class(TCQRSService, IAdministratedDaemon) protected {$ifdef WITHLOG} fLog: TSynLogFamily; {$endif} fStatus: TDDDAdministratedDaemonStatus; fFinished: TEvent; fRemoteLog: TSynLogCallbacks; fInternalDatabases: TSQLRestDynArray; fInternalSettings: TObject; fInternalSettingsFolder: TFileName; fAdministrationServer: TSQLRestServer; fAdministrationServerOwned: boolean; fAdministrationHTTPServer: TObject; // return TRUE e.g. if TDDDAdministratedThreadDaemon.fThread<>nil function InternalIsRunning: boolean; virtual; abstract; // should start the daemon: e.g. set TDDDAdministratedThreadDaemon.fThread procedure InternalStart; virtual; abstract; // return TRUE and set Status (e.g. from monitoring info) on success // - this default implement returns the system memory info as current state function InternalRetrieveState(var Status: variant): boolean; virtual; // should end the daemon: e.g. TDDDAdministratedThreadDaemon.fThread := nil procedure InternalStop; virtual; // set the list of published TSQLRestInstances - InternalStop would release it procedure PublishORMTables(const Rest: array of TSQLRest); virtual; function PublishedORM(const DatabaseName: RawUTF8): TSQLRest; procedure SetInternalSettings(Settings: TObject); virtual; public /// initialize the administrable service/daemon // - aAdministrationServer.ServiceDefine(IAdministratedDaemon) will be // called to publish the needed methods over it, to allow remote // administration from a single administration daemon (installed e.g. as a // Windows Service) // - this constructor won't start the associated process, which would be // idle until the Start method is called constructor Create(aAdministrationServer: TSQLRestServer); reintroduce; overload; virtual; /// initialize the administrable service/daemon with its own TSQLRestServer // - will initialize and own its dedicated TSQLRestServerFullMemory // - if aUserName is specified, authentication will be enabled, and a // single TSQLAuthUser will be created, with the supplied credentials // (the password matching TSQLAuthUser.PasswordHashHexa expectations) // - under Windows, you can export the administration server as named pipe, // if the optional aServerNamedPipe parameter is set constructor Create(const aUserName,aHashedPassword: RawUTF8; const aRoot: RawUTF8='admin'; const aServerNamedPipe: TFileName=''); reintroduce; overload; /// finalize the service/daemon // - will call Halt() if the associated process is still running destructor Destroy; override; /// monitor the Daemon/Service by returning some information as a TDocVariant function RetrieveState(out Status: variant): TCQRSResult; virtual; /// IAdministratedDaemon command to launch the associated process // - if the process was already running, returns cqrsAlreadyExists function Start: TCQRSResult; virtual; /// IAdministratedDaemon command to finalize the associated process // - and returns updated statistics as a TDocVariant function Stop(out Information: variant): TCQRSResult; virtual; /// IAdministratedDaemon command to Stop the associated process, then // quit the executable // - returning the same output information than Stop() function Halt(out Information: variant): TCQRSResult; virtual; /// IAdministratedDaemon command to retrieve all internal databases names // - will return fInternalDatabases[].Model.Root values function DatabaseList: TRawUTF8DynArray; virtual; /// IAdministratedDaemon command to return the table names of an internal database function DatabaseTables(const DatabaseName: RawUTF8): TRawUTF8DynArray; virtual; /// IAdministratedDaemon command to execute a SQL query on an internal database // - you may override this method to implement addition "pseudo-SQL" commands function DatabaseExecute(const DatabaseName,SQL: RawUTF8): TServiceCustomAnswer; virtual; /// IAdministratedDaemon command to subscribe to a set of events for // real-time remote monitoring of the specified log events procedure SubscribeLog(const Levels: TSynLogInfos; const Callback: ISynLogCallback; ReceiveExistingKB: cardinal); virtual; /// IAdministratedDaemon command called when a callback is released on the client side procedure CallbackReleased(const callback: IInvokable; const interfaceName: RawUTF8); /// run the daemon, until it is halted // - if RemotelyAdministrated is FALSE, it will Start the process, then // wait until the [Enter] key is pressed (to be used in pure console mode) // - if RemotelyAdministrated is TRUE, it will follow remote activation // from its administration server // - both modes will log some minimal message on the console (if any) procedure Execute(RemotelyAdministrated: boolean); /// this method will wait until Halt() is executed // - i.e. protected fFinished TEvent is notified procedure WaitUntilHalted; virtual; /// returns the daemon name // - e.g. TMyOwnDaemon would return 'MyOwn' text function DaemonName: RawUTF8; virtual; {$ifdef WITHLOG} /// access to the associated loging class property Log: TSynLogFamily read fLog; {$endif} /// access to the associated internal settings // - is defined as an opaque TObject instance, to avoid unneeded dependencies property InternalSettings: TObject read fInternalSettings write SetInternalSettings; /// access to the associated internal settings storage folder property InternalSettingsFolder: TFileName read fInternalSettingsFolder write fInternalSettingsFolder; /// reference to the WebSockets/HTTP server publishing AdministrationServer // - is defined as an opaque TObject instance, to avoid unneeded dependencies property AdministrationHTTPServer: TObject read fAdministrationHTTPServer write fAdministrationHTTPServer; published /// the current status of the service/daemon property Status: TDDDAdministratedDaemonStatus read fStatus; /// reference to the REST server publishing IAdministratedDaemon service // - e.g. from named pipe local communication on Windows property AdministrationServer: TSQLRestServer read fAdministrationServer; end; /// type used to define a class kind of TDDDAdministratedDaemon TDDDAdministratedDaemonClass = class of TDDDAdministratedDaemon; /// abstract class to implement an TThread-based administrable service/daemon // - inherited class should override InternalStart and InternalRetrieveState // abstract methods, and set the protected fThread with the processing thread TDDDAdministratedThreadDaemon = class(TDDDAdministratedDaemon) protected fThread: TThread; // return TRUE if fThread<>nil (i.e. has been set by InternalStart) function InternalIsRunning: boolean; override; // end the daemon, i.e fThread := nil procedure InternalStop; override; end; /// abstract class to implement a TSQLRest-based administrable service/daemon // - inherited class should override InternalStart and InternalRetrieveState // abstract methods, and set the protected fRest with the processing TSQLRest TDDDAdministratedRestDaemon = class(TDDDAdministratedDaemon) protected fRest: TSQLRestServer; // return TRUE if fRest<>nil (i.e. has been set by InternalStart) function InternalIsRunning: boolean; override; // end the daemon, i.e. FreeAndNil(fRest) procedure InternalStop; override; public /// read-only access to the associated REST instance // - is assigned only between daemon Start/Stop property Rest: TSQLRestServer read fRest; end; /// abstract class to monitor an administrable service/daemon // - including Input/Output statistics and connected Clients count // - including OS Memory information TDDDAdministratedDaemonMonitor = class(TSynAutoCreateFields) protected fServer: TSynMonitorServer; function GetMemory: variant; public procedure ProcessException(E: Exception); virtual; published /// information about the REST server process property Server: TSynMonitorServer read fServer; /// information about the main System memory, as returned by the OS property SystemMemory: variant read GetMemory; end; { *********** Application Layer Implementation } type /// abstract class for implementing an Application Layer service // - is defined as an TInjectableAutoCreateFields, so that any published // properties defined as interfaces would be resolved at creation, and // published properties defined as TPersistent/TSynPersistent will be // managed by this instance, i.e. created and released with it TDDDApplication = class(TInjectableAutoCreateFields) protected public end; implementation { *********** Persistence / Repository Interfaces } var TCQRSResultText: array[TCQRSResult] of PShortString; function ToText(res: TCQRSResult): PShortString; begin result := TCQRSResultText[res]; end; function ToText(res: TCQRSQueryState): PShortString; overload; begin result := GetEnumName(TypeInfo(TCQRSQueryState),ord(res)); end; { TCQRSService } constructor TCQRSService.Create; begin inherited Create; fSafe.Init; {$ifdef WITHLOG} fLog := SQLite3Log.Family; // may be overriden {$endif} end; function TCQRSService.GetLastError: TCQRSResult; begin result := fLastError; end; function TCQRSService.GetLastErrorInfo: Variant; begin result := fLastErrorContext; end; const NEEDS_QUERY = [qaGet, qaCommandOnSelect]; NEEDS_COMMAND = [qaCommit]; ACTION_TO_STATE: array[TCQRSQueryAction] of TCQRSQueryState = ( // qsNone = no state change after this action qsNone, qsQuery, qsNone, qsCommand, qsCommand, qsNone); function TCQRSService.CqrsBeginMethod(aAction: TCQRSQueryAction; var aResult: TCQRSResult; aError: TCQRSResult): boolean; begin aResult := aError; VarClear(fLastErrorContext); if (aAction in NEEDS_QUERY) and (fState<qsQuery) then begin CqrsSetResult(cqrsNoPriorQuery, aResult); result := false; exit; end; if (aAction in NEEDS_COMMAND) and (fState<qsCommand) then begin CqrsSetResult(cqrsNoPriorCommand, aResult); result := false; exit; end; fAction := aAction; result := true; end; function TCQRSService.CqrsSetResultError(aError: TCQRSResult): TCQRSResult; begin CqrsBeginMethod(qaNone,result); CqrsSetResult(aError,result); end; procedure TCQRSService.CqrsSetResult(Error: TCQRSResult; var Result: TCQRSResult); begin InternalCqrsSetResult(Error,Result); AfterInternalCqrsSetResult; end; procedure TCQRSService.CqrsSetResult(E: Exception; var Result: TCQRSResult); begin InternalCqrsSetResult(cqrsInternalError,Result); _ObjAddProps(['Exception',ObjectToVariantDebug(E)],fLastErrorContext); AfterInternalCqrsSetResult; end; procedure TCQRSService.InternalCqrsSetResult(Error: TCQRSResult; var Result: TCQRSResult); begin Result := Error; fLastError := Error; if Error<>cqrsSuccess then fLastErrorContext := ObjectToVariantDebug(self,'%',[NowToString]) else if ACTION_TO_STATE[fAction]<>qsNone then fState := ACTION_TO_STATE[fAction]; fAction := qaNone; end; procedure TCQRSService.AfterInternalCqrsSetResult; {$ifdef WITHLOG} var level: TSynLogInfo; {$endif} begin {$ifdef WITHLOG} if fLastError in CQRSRESULT_SUCCESS then exit; if fLastError in CQRSRESULT_WARNING then level := sllDDDInfo else level := sllDDDError; if level in fLog.Level then fLog.SynLog.Log(level, 'CqrsSetResult(%) state=% %', [ToText(fLastError)^, ToText(fState)^, fLastErrorContext], self); {$endif} end; procedure TCQRSService.CqrsSetResultSuccessIf(SuccessCondition: boolean; var Result: TCQRSResult; ErrorIfFalse: TCQRSResult); begin if SuccessCondition then CqrsSetResult(cqrsSuccess,Result) else CqrsSetResult(ErrorIfFalse,Result); end; procedure TCQRSService.CqrsSetResultDoc(Error: TCQRSResult; const ErrorInfo: variant; var Result: TCQRSResult); begin InternalCqrsSetResult(Error,Result); _ObjAddProps(['ErrorInfo',ErrorInfo],fLastErrorContext); AfterInternalCqrsSetResult; end; procedure TCQRSService.CqrsSetResultJSON(Error: TCQRSResult; const JSONFmt: RawUTF8; const Args,Params: array of const; var Result: TCQRSResult); begin CqrsSetResultDoc(Error,_JsonFastFmt(JSONFmt,Args,Params),Result); end; procedure TCQRSService.CqrsSetResultMsg(Error: TCQRSResult; const ErrorMessage: RawUTF8; var Result: TCQRSResult); begin InternalCqrsSetResult(Error,Result); _ObjAddProps(['Msg',ErrorMessage],fLastErrorContext); AfterInternalCqrsSetResult; end; procedure TCQRSService.CqrsSetResultString(Error: TCQRSResult; const ErrorMessage: string; var Result: TCQRSResult); begin InternalCqrsSetResult(Error,Result); _ObjAddProps(['Msg',ErrorMessage],fLastErrorContext); AfterInternalCqrsSetResult; end; procedure TCQRSService.CqrsSetResultMsg(Error: TCQRSResult; const ErrorMsgFmt: RawUTF8; const ErrorMsgArgs: array of const; var Result: TCQRSResult); begin CqrsSetResultMsg(Error,FormatUTF8(ErrorMsgFmt,ErrorMsgArgs),Result); end; destructor TCQRSService.Destroy; begin inherited Destroy; fSafe.Done; end; { TCQRSServiceSubscribe } procedure TCQRSServiceSubscribe.CallbackReleased(const callback: IInvokable; const interfaceName: RawUTF8); var i: integer; begin fSafe.Lock; try {$ifdef WITHLOG} fLog.SynLog.Log(sllTrace,'CallbackReleased(%,"%") callback=%', [callback,interfaceName,ObjectFromInterface(callback)],Self); {$endif} for i := 0 to high(fSubscriber) do // try to release on ALL subscribers fSubscriber[i].CallbackReleased(callback, interfaceName); finally fSafe.UnLock; end; end; { TCQRSServiceSynch } constructor TCQRSServiceSynch.Create(const sharedcallback: IInterface); begin inherited Create; if sharedcallback = nil then raise EDDDException.CreateUTF8('%.Create(nil)', [self]); fSharedCallbackRef := sharedcallback; end; { TCQRSServiceAsynchAck } destructor TCQRSServiceAsynchAck.Destroy; begin fCalls.Free; // would force evTimeOut if some WaitFor are still pending inherited Destroy; end; { ----- Persistence / Repository Implementation using mORMot's ORM } { EDDDRepository } constructor EDDDRepository.CreateUTF8(Caller: TDDDRepositoryRestFactory; const Format: RawUTF8; const Args: array of const); begin if Caller=nil then inherited CreateUTF8(Format,Args) else inherited CreateUTF8('% - %',[FormatUTF8(Format,Args),ObjectToJSONDebug(Caller)]); end; { TDDDRepositoryRestFactory } constructor TDDDRepositoryRestFactory.Create( const aInterface: TGUID; aImplementation: TDDDRepositoryRestClass; aAggregate: TClass; aRest: TSQLRest; aTable: TSQLRecordClass; const TableAggregatePairs: array of RawUTF8; aOwner: TDDDRepositoryRestManager); begin fInterface := TInterfaceFactory.Get(aInterface); if fInterface=nil then raise EDDDRepository.CreateUTF8(self, '%.Create(%): Interface not registered - you could use TInterfaceFactory.'+ 'RegisterInterfaces()',[self,GUIDToShort(aInterface)]); inherited Create(fInterface.InterfaceTypeInfo,aImplementation); fOwner := aOwner; fRest := aRest; fTable := aTable; if (aAggregate=nil) or (fRest=nil) or (fTable=nil) then raise EDDDRepository.CreateUTF8(self,'Invalid %.Create(nil)',[self]); fAggregate.Init(aAggregate); fPropsMapping.Init(aTable,RawUTF8(aAggregate.ClassName),aRest,false,[]); fPropsMapping.MapFields(['ID','####']); // no ID/RowID for our aggregates fPropsMapping.MapFields(TableAggregatePairs); fAggregateRTTI := TSQLPropInfoList.Create(aAggregate, GetAggregateRTTIOptions); SetLength(fAggregateToTable,fAggregateRTTI.Count); SetLength(fAggregateProp,fAggregateRTTI.Count); ComputeMapping; {$ifdef WITHLOG} Rest.LogClass.Add.Log(sllDDDInfo,'Started % implementing % for % over %', [self,fInterface.InterfaceName,aAggregate,fTable],self); {$endif} end; constructor TDDDRepositoryRestFactory.Create(const aInterface: TGUID; aImplementation: TDDDRepositoryRestClass; aAggregate: TClass; aRest: TSQLRest; aTable: TSQLRecordClass; aOwner: TDDDRepositoryRestManager); begin Create(aInterface,aImplementation,aAggregate,aRest,aTable,[],aOwner); end; function TDDDRepositoryRestFactory.GetAggregateRTTIOptions: TSQLPropInfoListOptions; begin Result := [pilAllowIDFields,pilSubClassesFlattening,pilIgnoreIfGetter]; end; destructor TDDDRepositoryRestFactory.Destroy; begin {$ifdef WITHLOG} Rest.LogClass.Add.Log(sllDDDInfo,'Destroying %',[self],self); {$endif} fAggregateRTTI.Free; ObjArrayClear(fGarbageCollector); inherited; end; class procedure TDDDRepositoryRestFactory.ComputeSQLRecord( const aAggregate: array of TClass; DestinationSourceCodeFile: TFileName); const RAW_TYPE: array[TSQLFieldType] of RawUTF8 = ( // values left to '' will use the RTTI type '', // sftUnknown 'RawUTF8', // sftAnsiText 'RawUTF8', // sftUTF8Text '', // sftEnumerate '', // sftSet '', // sftInteger '', // sftID = TSQLRecord(aID) 'TRecordReference',// sftRecord = TRecordReference 'boolean', // sftBoolean 'double', // sftFloat 'TDateTime', // sftDateTime 'TTimeLog', // sftTimeLog 'currency', // sftCurrency '', // sftObject 'variant', // sftVariant '', // sftNullable 'TSQLRawBlob', // sftBlob 'variant', // sftBlobDynArray T*ObjArray=JSON=variant (RawUTF8?) '', // sftBlobCustom 'variant', // sftUTF8Custom '', // sftMany 'TModTime', // sftModTime 'TCreateTime', // sftCreateTime '', // sftTID 'TRecordVersion', // sftRecordVersion = TRecordVersion 'TSessionUserID', // sftSessionUserID '', // sftDateTimeMS '', // sftUnixTime ''); // sftUnixMSTime var hier: TClassDynArray; a,i,f: integer; code,aggname,recname,parentrecname,typ: RawUTF8; map: TSQLPropInfoList; rectypes: TRawUTF8DynArray; begin {$ifdef KYLIX3} hier := nil; {$endif to make compiler happy} if DestinationSourceCodeFile='' then DestinationSourceCodeFile := ExeVersion.ProgramFilePath+'ddsqlrecord.inc'; for a := 0 to high(aAggregate) do begin hier := ClassHierarchyWithField(aAggregate[a]); code := code+#13#10'type'; parentrecname := 'TSQLRecord'; for i := 0 to high(hier) do begin aggname := RawUTF8(hier[i].ClassName); recname := 'TSQLRecord'+copy(aggname,2,100); map := TSQLPropInfoList.Create(hier[i], [pilSingleHierarchyLevel,pilAllowIDFields, pilSubClassesFlattening,pilIgnoreIfGetter]); try code := FormatUTF8('%'#13#10+ ' /// ORM class corresponding to % DDD aggregate'#13#10+ ' % = class(%)'#13#10' protected'#13#10, [code,aggname,recname,parentrecname]); SetLength(rectypes,map.count); for f := 0 to map.Count-1 do with map.List[f] do begin rectypes[f] := RAW_TYPE[SQLFieldType]; if rectypes[f]='' then if SQLFieldType=sftInteger then begin rectypes[f] := 'Int64'; if InheritsFrom(TSQLPropInfo) then with TSQLPropInfoRTTI(map.List[f]).PropType^ do if (Kind=tkInteger) and (OrdType<>otULong) then rectypes[f] := 'integer'; // cardinal -> Int64 end else rectypes[f] := SQLFieldRTTITypeName; code := FormatUTF8('% f%: %; // %'#13#10, [code,Name,rectypes[f],SQLFieldRTTITypeName]); end; code := code+' published'#13#10; for f := 0 to map.Count-1 do with map.List[f] do begin typ := SQLFieldRTTITypeName; if IdemPropNameU(typ, rectypes[f]) then typ := '' else typ := ' ('+typ+')'; code := FormatUTF8('% /// maps %.%%'#13#10+ ' property %: % read f% write f%;'#13#10, [code,aggname, NameUnflattened,typ,Name,rectypes[f],Name,Name]); end; code := code+' end;'#13#10; finally map.Free; end; parentrecname := recname; end; end; FileFromString(code,DestinationSourceCodeFile); end; procedure TDDDRepositoryRestFactory.ComputeMapping; procedure EnsureCompatible(agg,rec: TSQLPropInfo); { note about dynamic arrays (e.g. TRawUTF8DynArray or T*ObjArray) published fields: TOrder = class(TSynAutoCreateFields) published property Lines: TOrderLineObjArray In all cases, T*ObjArray should be accessible directly, using ObjArray*() wrapper functions, and other dynamic arrays too. Storage at TSQLRecord level would use JSON format, i.e. a variant in the current implementation - you may use a plain RawUTF8 field if the on-the-fly conversion to/from TDocVariant appears to be a bottleneck. } begin if agg.SQLDBFieldType=rec.SQLDBFieldType then exit; // very same type at DB level -> OK if (agg.SQLFieldType=sftBlobDynArray) and (rec.SQLFieldType in [sftVariant,sftUTF8Text]) then exit; // allow array <-> JSON/TEXT <-> variant/RawUTF8 marshalling raise EDDDRepository.CreateUTF8(self, '% types do not match at DB level: %.%:%=% and %.%:%=%',[self, Aggregate,agg.Name,agg.SQLFieldRTTITypeName,agg.SQLDBFieldTypeName^, fTable,rec.Name,rec.SQLFieldRTTITypeName,rec.SQLDBFieldTypeName^]); end; var i,ndx: integer; ORMProps: TSQLPropInfoObjArray; agg: TSQLPropInfoRTTI; begin fAggregateID := nil; ORMProps := fTable.RecordProps.Fields.List; for i := 0 to fAggregateRTTI.Count-1 do begin agg := fAggregateRTTI.List[i] as TSQLPropInfoRTTI; fAggregateProp[i] := agg; ndx := fPropsMapping.ExternalToInternalIndex(agg.Name); if ndx=-1 then // ID/RowID mapped with an existing String/Hexa field if agg.SQLDBFieldType in [ftInt64,ftUTF8] then begin fAggregateID := agg; fAggregateToTable[i] := nil; end else raise EDDDRepository.CreateUTF8(self,'% types error: %.%:%=% and %.RowID', [self,Aggregate,agg.Name,agg.SQLFieldRTTITypeName,agg.SQLDBFieldTypeName^,fTable]) else if ndx<0 then // e.g. TSynPersistent property flattened in TSQLRecord fAggregateToTable[i] := nil else begin fAggregateToTable[i] := ORMProps[ndx]; EnsureCompatible(agg,fAggregateToTable[i]); end; end; fPropsMappingVersion := fPropsMapping.MappingVersion; end; procedure TDDDRepositoryRestFactory.AggregatePropToTable( aAggregate: TObject; aAggregateProp: TSQLPropInfo; aRecord: TSQLRecord; aRecordProp: TSQLPropInfo); procedure ProcessID; var v: RawUTF8; id: TID; begin fAggregateID.GetValueVar(aAggregate,false,v,nil); case fAggregateID.SQLDBFieldType of ftInt64: SetID(pointer(v),id); ftUTF8: if not HexDisplayToBin(pointer(v),@id,sizeof(id)) then id := 0; end; aRecord.IDValue := id; end; begin if fAggregateID=aAggregateProp then ProcessID else if aRecordProp<>nil then aAggregateProp.CopyProp(aAggregate,aRecordProp,aRecord); end; procedure TDDDRepositoryRestFactory.TablePropToAggregate( aRecord: TSQLRecord; aRecordProp: TSQLPropInfo; aAggregate: TObject; aAggregateProp: TSQLPropInfo); procedure ProcessID; var v: RawUTF8; begin case fAggregateID.SQLDBFieldType of ftInt64: begin Int64ToUtf8(aRecord.IDValue,v); fAggregateID.SetValue(aAggregate,pointer(v),false); end; ftUTF8: begin Int64ToHex(aRecord.IDValue,v); fAggregateID.SetValue(aAggregate,pointer(v),true); end; end; end; begin if fAggregateID=aAggregateProp then ProcessID else if aRecordProp=nil then aAggregateProp.SetValue(aAggregate,nil,false) else aRecordProp.CopyProp(aRecord,aAggregateProp,aAggregate); end; function TDDDRepositoryRestFactory.CreateInstance: TInterfacedObject; begin result := TDDDRepositoryRestClass(fImplementation.ItemClass).Create(self); end; procedure TDDDRepositoryRestFactory.AggregateClear(aAggregate: TObject); var i: integer; begin if aAggregate<>nil then for i := 0 to high(fAggregateProp) do with fAggregateProp[i] do SetValue(Flattened(aAggregate),nil,false); end; function TDDDRepositoryRestFactory.AggregateCreate: TObject; begin result := fAggregate.CreateNew; end; procedure TDDDRepositoryRestFactory.AggregateToJSON(aAggregate: TObject; W: TJSONSerializer; ORMMappedFields: boolean; aID: TID); var i: integer; begin if fPropsMapping.MappingVersion<>fPropsMappingVersion then ComputeMapping; if aAggregate=nil then begin W.AddShort('null'); exit; end; W.Add('{'); if aID<>0 then begin W.AddShort('"RowID":'); W.Add(aID); W.Add(','); end; for i := 0 to high(fAggregateProp) do begin if ORMMappedFields then if fAggregateToTable[i]=nil then continue else W.AddFieldName(fAggregateToTable[i].Name) else W.AddFieldName(fAggregateProp[i].Name); with fAggregateProp[i] do GetJSONValues(Flattened(aAggregate),W); W.Add(','); end; W.CancelLastComma; W.Add('}'); end; function TDDDRepositoryRestFactory.AggregateToJSON( aAggregate: TObject; ORMMappedFields: boolean; aID: TID): RawUTF8; var W: TJSONSerializer; begin if aAggregate=nil then begin result := 'null'; exit; end; W := TJSONSerializer.CreateOwnedStream; try AggregateToJSON(aAggregate,W,ORMMappedFields,aID); W.SetText(result); finally W.Free; end; end; procedure TDDDRepositoryRestFactory.AggregateToTable( aAggregate: TObject; aID: TID; aDest: TSQLRecord); var i: integer; begin if fPropsMapping.MappingVersion<>fPropsMappingVersion then ComputeMapping; if aDest=nil then raise EDDDRepository.CreateUTF8(self,'%.AggregateToTable(%,%,%=nil)', [self,aAggregate,aID,fTable]); aDest.ClearProperties; aDest.IDValue := aID; if aAggregate<>nil then for i := 0 to length(fAggregateProp)-1 do AggregatePropToTable(aAggregate,fAggregateProp[i],aDest,fAggregateToTable[i]); end; procedure TDDDRepositoryRestFactory.AggregateFromTable( aSource: TSQLRecord; aAggregate: TObject); var i: integer; begin if fPropsMapping.MappingVersion<>fPropsMappingVersion then ComputeMapping; if aAggregate=nil then raise EDDDRepository.CreateUTF8(self,'%.AggregateFromTable(%=nil)',[self,Aggregate]); if aSource=nil then AggregateClear(aAggregate) else for i := 0 to length(fAggregateProp)-1 do TablePropToAggregate(aSource,fAggregateToTable[i],aAggregate,fAggregateProp[i]); end; procedure TDDDRepositoryRestFactory.AggregatesFromTableFill( aSource: TSQLRecord; var aAggregateObjArray); var res: TObjectDynArray absolute aAggregateObjArray; i: integer; begin SetLength(res, aSource.FillTable.RowCount); i := 0; if aSource.FillRewind then while aSource.FillOne do begin res[i] := fAggregate.CreateNew; AggregateFromTable(aSource,res[i]); inc(i); end; if i <> length(res) then ObjArrayClear(res); end; function TDDDRepositoryRestFactory.GetAggregateName: string; begin if (self=nil) or (Aggregate=nil) then result := '' else result := string(Aggregate.ClassName); end; function TDDDRepositoryRestFactory.GetTableName: string; begin if (self=nil) or (fTable=nil) then result := '' else result := fTable.ClassName; end; procedure TDDDRepositoryRestFactory.AddFilterOrValidate( const aFieldNames: array of RawUTF8; aFilterOrValidate: TSynFilterOrValidate; aFieldNameFlattened: boolean); var f,ndx: integer; arr: ^TPointerDynArray; begin if aFilterOrValidate=nil then exit; ObjArrayAdd(fGarbageCollector,aFilterOrValidate); for f := 0 to high(aFieldNames) do begin if aFilterOrValidate.InheritsFrom(TSynValidate) then arr := @fValidate else arr := @fFilter; if arr^=nil then SetLength(arr^,fAggregateRTTI.Count); if aFieldNames[f]='*' then begin // apply to all text fields for ndx := 0 to high(fAggregateProp) do if fAggregateProp[ndx].SQLFieldType in RAWTEXT_FIELDS then aFilterOrValidate.AddOnce(TSynFilterOrValidateObjArray(arr^[ndx]),false); end else begin if aFieldNameFlattened then ndx := fAggregateRTTI.IndexByNameUnflattenedOrExcept(aFieldNames[f]) else ndx := fAggregateRTTI.IndexByNameOrExcept(aFieldNames[f]); aFilterOrValidate.AddOnce(TSynFilterOrValidateObjArray(arr^[ndx]),false); end; end; end; function TDDDRepositoryRestFactory.AggregateFilterAndValidate( aAggregate: TObject; aInvalidFieldIndex: PInteger; aValidator: PSynValidate): RawUTF8; var f,i: integer; Value: TRawUTF8DynArray; // avoid twice retrieval Old: RawUTF8; msg: string; str: boolean; begin if (aAggregate=nil) or not aAggregate.ClassType.InheritsFrom(Aggregate) then raise EDDDRepository.CreateUTF8(self,'%.AggregateFilterAndValidate(%) '+ 'expects a % instance',[self,aAggregate,Aggregate]); // first process all filters SetLength(Value,fAggregateRTTI.Count); for f := 0 to high(fFilter) do if fFilter[f]<>nil then begin with fAggregateProp[f] do GetValueVar(Flattened(aAggregate),false,Value[f],@str); Old := Value[f]; for i := 0 to high(fFilter[f]) do fFilter[f,i].Process(f,Value[f]); if Old<>Value[f] then with fAggregateProp[f] do SetValueVar(Flattened(aAggregate),Value[f],str); end; // then validate the content for f := 0 to high(fValidate) do if fValidate[f]<>nil then begin if Value[f]='' then // if not already retrieved with fAggregateProp[f] do GetValueVar(Flattened(aAggregate),false,Value[f],nil); for i := 0 to high(fValidate[f]) do if not fValidate[f,i].Process(f,Value[f],msg) then begin if aInvalidFieldIndex<>nil then aInvalidFieldIndex^ := f; if aValidator<>nil then aValidator^ := fValidate[f,i]; if msg='' then // no custom message -> show a default message msg := format(sValidationFailed,[GetCaptionFromClass(fValidate[f,i].ClassType)]); result := FormatUTF8('%.%: %',[Aggregate,fAggregateProp[f].NameUnflattened,msg]); exit; end; end; result := ''; // if we reached here, there was no error end; { TDDDRepositoryRestManager } function TDDDRepositoryRestManager.AddFactory( const aInterface: TGUID; aImplementation: TDDDRepositoryRestClass; aAggregate: TClass; aRest: TSQLRest; aTable: TSQLRecordClass; const TableAggregatePairs: array of RawUTF8): TDDDRepositoryRestFactory; begin if GetFactoryIndex(aInterface)>=0 then raise EDDDRepository.CreateUTF8(nil,'Duplicated GUID for %.AddFactory(%,%,%)', [self,GUIDToShort(aInterface),aImplementation,aAggregate]); result := TDDDRepositoryRestFactory.Create( aInterface,aImplementation,aAggregate,aRest,aTable,TableAggregatePairs,self); ObjArrayAdd(fFactory,result); {$ifdef WITHLOG} aRest.LogClass.Add.Log(sllDDDInfo,'Added factory % to %',[result,self],self); {$endif} end; destructor TDDDRepositoryRestManager.Destroy; begin ObjArrayClear(fFactory); inherited; end; function TDDDRepositoryRestManager.GetFactory( const aInterface: TGUID): TDDDRepositoryRestFactory; var i: integer; begin i := GetFactoryIndex(aInterface); if i<0 then raise EDDDRepository.CreateUTF8(nil,'%.GetFactory(%)=nil', [self,GUIDToShort(aInterface)]); result := fFactory[i]; end; function TDDDRepositoryRestManager.GetFactoryIndex( const aInterface: TGUID): integer; begin for result := 0 to length(fFactory)-1 do if IsEqualGUID(@fFactory[result].fInterface.InterfaceIID,@aInterface) then exit; result := -1; end; { TDDDRepositoryRestQuery } constructor TDDDRepositoryRestQuery.Create( aFactory: TDDDRepositoryRestFactory); begin fFactory := aFactory; fCurrentORMInstance := fFactory.Table.Create; {$ifdef WITHLOG} fLog := fFactory.Rest.LogFamily; {$endif} end; destructor TDDDRepositoryRestQuery.Destroy; begin fCurrentORMInstance.Free; inherited; end; class function TDDDRepositoryRestQuery.GetRest(const Service: ICQRSService): TSQLRest; var instance: TObject; begin instance := ObjectFromInterface(Service); if (instance=nil) or not instance.InheritsFrom(TDDDRepositoryRestQuery) then result := nil else result := TDDDRepositoryRestQuery(instance).fFactory.fRest; end; function TDDDRepositoryRestQuery.CqrsBeginMethod(aAction: TCQRSQueryAction; var aResult: TCQRSResult; aError: TCQRSResult): boolean; begin result := inherited CqrsBeginMethod(aAction,aResult,aError); if aAction=qaSelect then fCurrentORMInstance.ClearProperties; // reset internal instance end; function TDDDRepositoryRestQuery.ORMSelectOne(const ORMWhereClauseFmt: RawUTF8; const Bounds: array of const; ForcedBadRequest: boolean): TCQRSResult; begin CqrsBeginMethod(qaSelect,result); if ForcedBadRequest then CqrsSetResult(cqrsBadRequest,result) else CqrsSetResultSuccessIf(Factory.Rest.Retrieve(ORMWhereClauseFmt,[],Bounds, fCurrentORMInstance),result,cqrsNotFound); end; function TDDDRepositoryRestQuery.ORMSelectID(const ID: TID; RetrieveRecord, ForcedBadRequest: boolean): TCQRSResult; begin CqrsBeginMethod(qaSelect,result); if ForcedBadRequest or (ID=0) then CqrsSetResult(cqrsBadRequest,result) else if RetrieveRecord then CqrsSetResultSuccessIf(Factory.Rest.Retrieve(ID,fCurrentORMInstance),result,cqrsNotFound) else begin fCurrentORMInstance.IDValue := ID; CqrsSetResult(cqrsSuccess,result); end end; function TDDDRepositoryRestQuery.ORMSelectID(const ID: RawUTF8; RetrieveRecord, ForcedBadRequest: boolean): TCQRSResult; begin result := ORMSelectID(HexDisplayToInt64(ID),RetrieveRecord,ForcedBadRequest); end; function TDDDRepositoryRestQuery.ORMSelectAll( const ORMWhereClauseFmt: RawUTF8; const Bounds: array of const; ForcedBadRequest: boolean): TCQRSResult; begin CqrsBeginMethod(qaSelect,result); if ForcedBadRequest then CqrsSetResult(cqrsBadRequest,result) else CqrsSetResultSuccessIf(fCurrentORMInstance.FillPrepare( Factory.Rest,ORMWhereClauseFmt,[],Bounds),result,cqrsNotFound); end; function TDDDRepositoryRestQuery.ORMSelectCount( const ORMWhereClauseFmt: RawUTF8; const Args,Bounds: array of const; out aResultCount: integer; ForcedBadRequest: boolean): TCQRSResult; var tmp: Int64; begin CqrsBeginMethod(qaNone,result); // qaNone and not qaSelect which would fill ORM if ForcedBadRequest then CqrsSetResult(cqrsBadRequest,result) else if Factory.Rest.OneFieldValue( Factory.Table,'count(*)',ORMWhereClauseFmt,Args,Bounds,tmp) then begin aResultCount := tmp; CqrsSetResult(cqrsSuccess,result) end else CqrsSetResult(cqrsNotFound,result); end; function TDDDRepositoryRestQuery.GetCount: integer; var dummy: TCQRSResult; begin if not CqrsBeginMethod(qaGet,dummy) then result := 0 else if fCurrentORMInstance.FillTable<>nil then result := fCurrentORMInstance.FillTable.RowCount else if fCurrentORMInstance.IDValue=0 then result := 0 else result := 1; end; function TDDDRepositoryRestQuery.ORMGetAggregate( aAggregate: TObject): TCQRSResult; begin if CqrsBeginMethod(qaGet,result) then begin Factory.AggregateFromTable(fCurrentORMInstance,aAggregate); CqrsSetResult(cqrsSuccess,result); end; end; function TDDDRepositoryRestQuery.ORMGetNextAggregate( aAggregate: TObject; aRewind: boolean): TCQRSResult; begin if CqrsBeginMethod(qaGet,result) then if (aRewind and fCurrentORMInstance.FillRewind) or (not aRewind and fCurrentORMInstance.FillOne) then begin Factory.AggregateFromTable(fCurrentORMInstance,aAggregate); CqrsSetResult(cqrsSuccess,result); end else CqrsSetResult(cqrsNoMoreData,result); end; function TDDDRepositoryRestQuery.ORMGetAllAggregates( var aAggregateObjArray): TCQRSResult; begin if CqrsBeginMethod(qaGet,result) then if (fCurrentORMInstance.FillTable=nil) or (fCurrentORMInstance.FillTable.RowCount=0) then CqrsSetResult(cqrsSuccess,result) else begin Factory.AggregatesFromTableFill(fCurrentORMInstance,aAggregateObjArray); if Pointer(aAggregateObjArray)=nil then CqrsSetResult(cqrsNoMoreData,result) else CqrsSetResult(cqrsSuccess,result); end; end; { TDDDRepositoryRestCommand } constructor TDDDRepositoryRestCommand.Create( aFactory: TDDDRepositoryRestFactory); begin inherited Create(aFactory); fBatchAutomaticTransactionPerRow := 1000; // for better performance fBatchOptions := [boExtendedJSON]; end; destructor TDDDRepositoryRestCommand.Destroy; begin InternalRollback; inherited Destroy; end; function TDDDRepositoryRestCommand.Delete: TCQRSResult; begin if CqrsBeginMethod(qaCommandOnSelect,result) then ORMPrepareForCommit(soDelete,nil,result); end; function TDDDRepositoryRestCommand.DeleteAll: TCQRSResult; var i: integer; begin if CqrsBeginMethod(qaCommandOnSelect,result) then if fCurrentORMInstance.FillTable=nil then ORMPrepareForCommit(soDelete,nil,result) else if fState<qsQuery then CqrsSetResult(cqrsNoPriorQuery,result) else begin ORMEnsureBatchExists; for i := 1 to fCurrentORMInstance.FillTable.RowCount do if fBatch.Delete(fCurrentORMInstance.FillTable.IDColumnHiddenValue(i))<0 then begin CqrsSetResult(cqrsDataLayerError,result); exit; end; CqrsSetResult(cqrsSuccess,result); end; end; function TDDDRepositoryRestCommand.ORMAdd(aAggregate: TObject; aAllFields: boolean): TCQRSResult; begin if CqrsBeginMethod(qaCommandDirect,result) then ORMPrepareForCommit(soInsert,aAggregate,result,aAllFields); end; function TDDDRepositoryRestCommand.ORMUpdate(aAggregate: TObject; aAllFields: boolean): TCQRSResult; begin if CqrsBeginMethod(qaCommandOnSelect,result) then ORMPrepareForCommit(soUpdate,aAggregate,result,aAllFields); end; procedure TDDDRepositoryRestCommand.ORMEnsureBatchExists; begin if fBatch=nil then fBatch := TSQLRestBatch.Create(Factory.Rest,Factory.Table, fBatchAutomaticTransactionPerRow,fBatchOptions); end; procedure TDDDRepositoryRestCommand.ORMPrepareForCommit( aCommand: TSQLOccasion; aAggregate: TObject; var Result: TCQRSResult; aAllFields: boolean); var msg: RawUTF8; validator: TSynValidate; ndx: integer; fields: TSQLFieldBits; procedure SetValidationError(default: TCQRSResult); begin if (validator<>nil) and (validator.ClassType=TSynValidateUniqueField) then CqrsSetResultMsg(cqrsAlreadyExists,msg,Result) else CqrsSetResultMsg(default,msg,Result); end; begin case aCommand of soSelect: begin CqrsSetResult(cqrsBadRequest,Result); exit; end; soUpdate,soDelete: if (fState<qsQuery) or (fCurrentORMInstance.IDValue=0) then begin CqrsSetResult(cqrsNoPriorQuery,Result); exit; end; end; if aCommand in [soUpdate,soInsert] then begin if aAggregate<>nil then begin msg := Factory.AggregateFilterAndValidate(aAggregate,nil,@validator); if msg<>'' then begin SetValidationError(cqrsDDDValidationFailed); exit; end; Factory.AggregateToTable(aAggregate,fCurrentORMInstance.IDValue,fCurrentORMInstance); end; msg := fCurrentORMInstance.FilterAndValidate( Factory.Rest,[0..MAX_SQLFIELDS-1],@validator); if msg<>'' then begin SetValidationError(cqrsDataLayerError); exit; end; end; ORMEnsureBatchExists; ndx := -1; if aAllFields then fields := ALL_FIELDS else fields := []; case aCommand of soInsert: ndx := fBatch.Add(fCurrentORMInstance,true,fFactory.fAggregateID<>nil,fields); soUpdate: ndx := fBatch.Update(fCurrentORMInstance,fields); soDelete: ndx := fBatch.Delete(fCurrentORMInstance.IDValue); end; CqrsSetResultSuccessIf(ndx>=0,Result); end; procedure TDDDRepositoryRestCommand.InternalCommit(var Result: TCQRSResult); begin if fBatch.Count=0 then CqrsSetResult(cqrsBadRequest,Result) else begin CqrsSetResultSuccessIf(Factory.Rest.BatchSend(fBatch,fBatchResults)=HTTP_SUCCESS,Result); FreeAndNil(fBatch); end; end; procedure TDDDRepositoryRestCommand.InternalRollback; begin FreeAndNil(fBatch); fBatchResults := nil; end; function TDDDRepositoryRestCommand.Commit: TCQRSResult; begin if CqrsBeginMethod(qaCommit,result) then InternalCommit(result); end; function TDDDRepositoryRestCommand.Rollback: TCQRSResult; begin CqrsBeginMethod(qaNone,result,cqrsSuccess); if fBatch.Count=0 then CqrsSetResult(cqrsNoPriorCommand,result) else InternalRollback; end; { TCQRSQueryObjectRest } constructor TCQRSQueryObjectRest.Create(aRest: TSQLRest); begin fRest := aRest; if (fResolver<>nil) or (aRest=nil) or (aRest.Services=nil) then inherited Create else inherited CreateWithResolver(aRest.Services); end; constructor TCQRSQueryObjectRest.CreateInjected(aRest: TSQLRest; const aStubsByGUID: array of TGUID; const aOtherResolvers: array of TInterfaceResolver; const aDependencies: array of TInterfacedObject); begin if not Assigned(aRest) then raise ECQRSException.CreateUTF8('%.CreateInjected(Rest=nil)',[self]); Create(aRest); inherited CreateInjected(aStubsByGUID,aOtherResolvers, aDependencies,true); end; constructor TCQRSQueryObjectRest.CreateWithResolver(aRest: TSQLRest; aResolver: TInterfaceResolver; aRaiseEServiceExceptionIfNotFound: boolean); begin if not Assigned(aRest) then raise ECQRSException.CreateUTF8('%.CreateWithResolver(Rest=nil)',[self]); fRest := aRest; inherited CreateWithResolver(aResolver,aRaiseEServiceExceptionIfNotFound); end; constructor TCQRSQueryObjectRest.CreateWithResolver( aResolver: TInterfaceResolver; aRaiseEServiceExceptionIfNotFound: boolean); begin if (aResolver<>nil) and aResolver.InheritsFrom(TServiceContainer) then fRest := TServiceContainer(aResolver).Rest; inherited CreateWithResolver(aResolver,aRaiseEServiceExceptionIfNotFound); end; { TDDDMonitoredDaemonProcess } constructor TDDDMonitoredDaemonProcess.Create(aDaemon: TDDDMonitoredDaemon; aIndexInDaemon: integer); begin fDaemon := aDaemon; if fDaemon.fProcessMonitoringClass=nil then fMonitoring := TSynMonitorWithSize.Create(aDaemon.Rest.Model.Root) else fMonitoring := fDaemon.fProcessMonitoringClass.Create(aDaemon.Rest.Model.Root) as TSynMonitorWithSize; fProcessIdleDelay := fDaemon.ProcessIdleDelay; fIndex := aIndexInDaemon; inherited Create(False); end; destructor TDDDMonitoredDaemonProcess.Destroy; begin fMonitoring.Free; inherited; end; procedure TDDDMonitoredDaemonProcess.Execute; begin fDaemon.Rest.BeginCurrentThread(self); try repeat SleepHiRes(fProcessIdleDelay); try try repeat if Terminated then exit; try try fDaemon.fProcessLock.Enter; // atomic unqueue via pending.Status try fMonitoring.ProcessStart; if not ExecuteRetrievePendingAndSetProcessing then break; // no more pending tasks fMonitoring.ProcessDoTask; finally fDaemon.fProcessLock.Leave; end; // always set, even if Terminated fMonitoring.AddSize(ExecuteProcessAndSetResult); finally fMonitoring.ProcessEnd; ExecuteProcessFinalize; end; except on E: Exception do begin ExecuteOnException(E); break; // will call ExecuteIdle then go to idle state end; end; until false; finally ExecuteIdle; end; except on E: Exception do begin ExecuteOnException(E); // exception during ExecuteIdle should not happen if fProcessIdleDelay<500 then fProcessIdleDelay := 500; // avoid CPU+resource burning end; end; until false; finally fDaemon.Rest.EndCurrentThread(self); end; end; procedure TDDDMonitoredDaemonProcess.ExecuteOnException(E: Exception); begin fMonitoring.ProcessError(ObjectToVariantDebug( E,'{threadindex:?,daemon:?}',[fIndex,fDaemon.GetStatus])); end; { TDDDMonitoredDaemonProcessRest } procedure TDDDMonitoredDaemonProcessRest.ExecuteProcessFinalize; begin FreeAndNil(fPendingTask); end; { TDDDMonitoredDaemon } constructor TDDDMonitoredDaemon.Create(aRest: TSQLRest); begin fProcessIdleDelay := 50; fProcessLock := TAutoLocker.Create; if fProcessThreadCount<1 then fProcessThreadCount := 1 else if fProcessThreadCount>20 then fProcessThreadCount := 20; inherited Create(aRest); end; constructor TDDDMonitoredDaemon.Create(aRest: TSQLRest; aProcessThreadCount: integer); begin fProcessThreadCount := aProcessThreadCount; Create(aRest); end; destructor TDDDMonitoredDaemon.Destroy; var dummy: variant; begin Stop(dummy); inherited Destroy; end; function TDDDMonitoredDaemon.GetStatus: variant; var i,working: integer; stats: TSynMonitor; pool: TDocVariantData; begin {$ifdef WITHLOG} Rest.LogClass.Enter('GetStatus',[],self); {$endif} VarClear(result); fProcessLock.Enter; try try working := 0; if fMonitoringClass=nil then if fProcessMonitoringClass=nil then stats := TSynMonitorWithSize.Create else stats := fProcessMonitoringClass.Create else stats := fMonitoringClass.Create; try pool.InitArray([],JSON_OPTIONS[true]); for i := 0 to High(fProcess) do with fProcess[i] do begin if fMonitoring.Processing then inc(working); pool.AddItem(fMonitoring.ComputeDetails); stats.Sum(fMonitoring); end; result := ObjectToVariantDebug(self); _ObjAddProps(['working',working, 'stats',stats.ComputeDetails, 'threadstats',variant(pool)],result); finally stats.Free; end; except on E: Exception do result := ObjectToVariantDebug(E); end; finally fProcessLock.Leave; end; end; function TDDDMonitoredDaemon.RetrieveState( out Status: variant): TCQRSResult; begin CqrsBeginMethod(qaNone,result,cqrsSuccess); Status := GetStatus; end; function TDDDMonitoredDaemon.Start: TCQRSResult; var i: integer; {$ifdef WITHLOG} Log: ISynLog; {$endif} dummy: variant; begin {$ifdef WITHLOG} Log := Rest.LogClass.Enter('Start %',[fProcessClass],self); {$endif} if fProcessClass=nil then raise EDDDException.CreateUTF8('%.Start with no fProcessClass',[self]); Stop(dummy); // ignore any error when stopping fProcessTimer.Resume; {$ifdef WITHLOG} if Log<>nil then Log.Log(sllTrace,'Start %',[self],self); {$endif} CqrsBeginMethod(qaNone,result,cqrsSuccess); SetLength(fProcess,fProcessThreadCount); for i := 0 to fProcessThreadCount-1 do fProcess[i] := fProcessClass.Create(self,i); SleepHiRes(1); // some time to actually start the threads end; function TDDDMonitoredDaemon.Stop(out Information: variant): TCQRSResult; var i: integer; allfinished: boolean; begin CqrsBeginMethod(qaNone,result); try if fProcess<>nil then begin fProcessTimer.Pause; Information := GetStatus; {$ifdef WITHLOG} Rest.LogClass.Enter('Stop % process %',[fProcessClass,Information],self); {$endif} fProcessLock.Enter; try for i := 0 to high(fProcess) do fProcess[i].Terminate; finally fProcessLock.Leave; end; repeat SleepHiRes(5); allfinished := true; fProcessLock.Enter; try for i := 0 to high(fProcess) do if fProcess[i].fMonitoring.Processing then begin allfinished := false; break; end; finally fProcessLock.Leave; end; until allfinished; fProcessLock.Enter; try ObjArrayClear(fProcess); finally fProcessLock.Leave; end; end; CqrsSetResult(cqrsSuccess,result); except on E: Exception do CqrsSetResult(E,result); end; end; { TDDDAdministratedDaemon } constructor TDDDAdministratedDaemon.Create( aAdministrationServer: TSQLRestServer); begin if aAdministrationServer=nil then raise ECQRSException.CreateUTF8('%.Create(aAdministrationServer=nil)',[self]); fAdministrationServer := aAdministrationServer; {$ifdef WITHLOG} fLog := fAdministrationServer.LogFamily; {$endif} CreateWithResolver(fAdministrationServer.ServiceContainer); fAdministrationServer.ServiceDefine(self,[IAdministratedDaemon]); fFinished := TEvent.Create(nil,false,false,''); fStatus := dsCreated; end; constructor TDDDAdministratedDaemon.Create( const aUserName, aHashedPassword, aRoot: RawUTF8; const aServerNamedPipe: TFileName); var server: TSQLRestServer; begin server := TSQLRestServerFullMemory.CreateWithOwnedAuthenticatedModel([], aUserName,aHashedPassword,aRoot); server.Options := server.Options+[rsoSecureConnectionRequired]; Create(server); if FRefCount=2 then dec(FRefCount); // circumvent a Delphi compiler bug fAdministrationServerOwned := true; if aServerNamedPipe<>'' then {$ifdef MSWINDOWS} fAdministrationServer.ExportServerNamedPipe(aServerNamedPipe); {$else} {$ifdef WITHLOG} fLog.SynLog.Log(sllTrace,'Ignored AuthNamedPipeName=% under Linux', [aServerNamedPipe],self); {$endif} {$endif} end; destructor TDDDAdministratedDaemon.Destroy; var dummy: variant; {$ifdef WITHLOG} log: ISynLog; begin log := fLog.SynLog.Enter(self, 'Destroy'); {$else} begin {$endif} if InternalIsRunning then Halt(dummy); try FreeAndNil(fAdministrationHTTPServer); inherited Destroy; fFinished.Free; FreeAndNil(fRemoteLog); finally if fAdministrationServerOwned then FreeAndNil(fAdministrationServer); end; end; function TDDDAdministratedDaemon.Start: TCQRSResult; {$ifdef WITHLOG} var log: ISynLog; begin log := fLog.SynLog.Enter(self, 'Start'); {$else} begin {$endif} CqrsBeginMethod(qaNone,result); if not (fStatus in [dsCreated,dsStopped]) then CqrsSetResultError(cqrsBadRequest) else if InternalIsRunning then CqrsSetResult(cqrsAlreadyExists,result) else try {$ifdef WITHLOG} if log<>nil then log.Log(sllDDDInfo,'Starting',self); {$endif} InternalStart; fStatus := dsStarted; CqrsSetResult(cqrsSuccess,result); except on E: Exception do try CqrsSetResult(E,result); InternalStop; // automatically release resources on starting error except end; end; end; function TDDDAdministratedDaemon.RetrieveState(out Status: variant): TCQRSResult; begin CqrsBeginMethod(qaNone,result); try if not InternalIsRunning then CqrsSetResult(cqrsBadRequest,result) else if InternalRetrieveState(Status) then CqrsSetResult(cqrsSuccess,result) else CqrsSetResult(cqrsInternalError,result); except on E: Exception do CqrsSetResult(E,result); end; end; function TDDDAdministratedDaemon.Stop(out Information: variant): TCQRSResult; {$ifdef WITHLOG} var log: ISynLog; begin log := fLog.SynLog.Enter(self, 'Stop'); {$else} begin {$endif} CqrsBeginMethod(qaNone,result); if fStatus<>dsStarted then CqrsSetResultError(cqrsBadRequest) else begin if InternalRetrieveState(Information) then try {$ifdef WITHLOG} if log<>nil then log.Log(sllDDDInfo,'Stopping %',[Information],self); {$endif} InternalStop; // always stop fStatus := dsStopped; {$ifdef WITHLOG} if log<>nil then log.Log(sllDDDInfo,'Stopped: %',[Information],self); {$endif} CqrsSetResult(cqrsSuccess,result); except on E: Exception do CqrsSetResult(E,result); end else CqrsSetResult(cqrsInternalError,result); end; end; function TDDDAdministratedDaemon.Halt(out Information: variant): TCQRSResult; {$ifdef WITHLOG} var log: ISynLog; begin log := fLog.SynLog.Enter(self, 'Halt'); {$else} begin {$endif} CqrsBeginMethod(qaNone,result); if InternalIsRunning then try {$ifdef WITHLOG} if log<>nil then log.Log(sllDDDInfo,'Halting',self); {$endif} CqrsSetResult(Stop(Information),result); except on E: Exception do CqrsSetResult(E,result); end else CqrsSetResult(cqrsSuccess,result); fStatus := dsHalted; fFinished.SetEvent; end; procedure TDDDAdministratedDaemon.WaitUntilHalted; begin if fStatus in [dsUnknown] then exit; {$ifdef WITHLOG} with fLog.SynLog.Enter(self, 'WaitUntilHalted') do {$endif} FixedWaitForever(fFinished); end; procedure TDDDAdministratedDaemon.Execute(RemotelyAdministrated: boolean); var name: string; msg: RawUTF8; {$ifdef WITHLOG} log: ISynLog; begin log := fLog.SynLog.Enter(self, 'Execute'); {$else} begin {$endif} name := ClassName; {$I-} if RemotelyAdministrated then begin writeln(name,' expecting commands'); WaitUntilHalted; end else begin if Start=cqrsSuccess then writeln(name,' is running') else begin writeln(#10,name,' failed to Start'); if _Safe(LastErrorInfo)^.GetAsRawUTF8('Exception',msg) then begin TextColor(ccLightMagenta); writeln(msg); TextColor(ccLightGray); end; end; writeln('Press [Enter] to quit'); ioresult; readln; {$ifdef LINUX} if ioresult<>0 then // e.g. when redirected from "nohup daemon &" command WaitUntilHalted; {$endif} end; writeln('Shutting down server'); ioresult; {$I+} end; procedure TDDDAdministratedDaemon.CallbackReleased( const callback: IInvokable; const interfaceName: RawUTF8); begin if IdemPropNameU(interfaceName,'ISynLogCallback') and (fRemoteLog<>nil) then fRemoteLog.Unsubscribe(ISynLogCallback(callback)); end; procedure TDDDAdministratedDaemon.SubscribeLog(const Levels: TSynLogInfos; const Callback: ISynLogCallback; ReceiveExistingKB: cardinal); {$ifdef WITHLOG} var previousContentSize: integer; begin if fRemoteLog=nil then fRemoteLog := TSynLogCallbacks.Create(fLog); previousContentSize := fRemoteLog.Subscribe(Levels,Callback,ReceiveExistingKB); fLog.SynLog.Log(sllTrace,'SubscribeLog sent % bytes as previous content', [previousContentSize],self); {$else} begin {$endif} end; function TDDDAdministratedDaemon.PublishedORM(const DatabaseName: RawUTF8): TSQLRest; var i: integer; begin for i := 0 to high(fInternalDatabases) do begin result := fInternalDatabases[i]; if IdemPropNameU(result.Model.Root,DatabaseName) then exit; end; result := nil; end; function TDDDAdministratedDaemon.DatabaseExecute(const DatabaseName,SQL: RawUTF8): TServiceCustomAnswer; var rest: TSQLRest; name,value: RawUTF8; doc: TDocVariantData; valid: Boolean; status: variant; res: TCQRSResult; cmd: integer; store: IDDDSettingsStorable; begin result.Header := JSON_CONTENT_TYPE_HEADER_VAR; result.Status := HTTP_SUCCESS; if SQL='' then exit; if SQL[1]='#' then begin cmd := IdemPCharArray(@SQL[2],['STATE','SETTINGS','VERSION','COMPUTER','LOG', 'CHAT','STARTDAEMON','STOPDAEMON','RESTARTDAEMON','HELP','INFO']); case cmd of 0: begin if InternalRetrieveState(status) then result.Content := VariantSaveJSON(status) else result.Content := '"Daemon seems stopped"'; exit; end; 1: if fInternalSettings<>nil then begin if SQL[10]=' ' then begin name := copy(SQL,11,maxInt); if PosExChar('=',name)>0 then begin Split(name,'=',name,value); if (name<>'') and (value<>'') then begin VariantLoadJSON(status,pointer(value)); doc.InitObjectFromPath(name,status); JsonToObject(fInternalSettings,pointer(doc.ToJSON),valid); end; end else if IdemPropNameU(name,'save') then begin if fInternalSettings.GetInterface(IDDDSettingsStorable,store) then begin store.StoreIfUpdated; result.Content := FormatUTF8('"% saved"',[fInternalSettings.ClassType]); end else result.Content := FormatUTF8('"% does not implement IDDDSettingsStorable"', [fInternalSettings.ClassType]); exit; end else if fInternalSettingsFolder<>'' then begin AdministrationExecuteGetFiles(fInternalSettingsFolder, '*.config;*.settings',name,result); exit; end; end; result.Content := ObjectToJSON(fInternalSettings,[woEnumSetsAsText]); exit; end; 2: result.Content := JSONEncode(['daemon',DaemonName, 'exe',ExeVersion.ProgramFileName,'version',ExeVersion.Version.Detailed, 'buildTime',DateTimeToIso8601(ExeVersion.Version.BuildDateTime,true), 'framework',SYNOPSE_FRAMEWORK_FULLVERSION,'compiler',GetDelphiCompilerVersion]); // no exit: #version handled e.g. in TSQLRestServerDB.AdministrationExecute 3: begin {$ifdef MSWINDOWS_INCLUDESENV} P := pointer(GetEnvironmentStringsA); while P^<>#0 do begin L := StrLen(P); if (L>0) and (P^<>'=') then begin if value<>'' then value := value+#10; SetString(name,PAnsiChar(P),L); value := value+name; end; inc(P,table+1); end; {$endif} result.Content := SystemInfoJson; {$ifdef MSWINDOWS} result.Content[length(result.Content)] := ','; result.Content := result.Content+'"ip":"'+GetIPAddressesText+'"}'; {$endif} exit; end; {$ifdef WITHLOG} 4: begin split(SQL,' ',name,value); if value='' then result.Content := ObjectToJSON(fLog.SynLog,[woEnumSetsAsText]) else AdministrationExecuteGetFiles(fLog.DestinationPath,'*.log;*.synlz',value,result); exit; end; 5: begin fLog.SynLog.Log(sllMonitoring,'[CHAT] % %', [ServiceContext.Request.InHeader['remoteip'],copy(SQL,7,maxInt)]); exit; end; {$endif} 6,7,8: begin // 6=start/7=stop/8=restart if cmd=6 then res := cqrsSuccess else res := Stop(status); if res=cqrsSuccess then begin if cmd=8 then SleepHiRes(200); // leave some time between stop and start if cmd<>7 then res := Start; if res=cqrsSuccess then result.Content := VariantSaveJSON(status) else result.Content := JSONEncode(['errorStart',ToText(res)^, 'stopStatus',status]); end else result.Content := JSONEncode(['errorStop',ToText(res)^]); exit; end; 9: result.Content := '"Enter either a SQL request, or one of the following commands:|'+ '|#state|#settings [full.path=value/*/save/filename]|#version|#computer|#log [*/filename]|'+ '#startdaemon|#stopdaemon|#restartdaemon|#help"'; 10: begin result.Content := JSONEncode(['daemon',DaemonName]); if (DatabaseName='') and (fInternalDatabases<>nil) then begin fInternalDatabases[0].AdministrationExecute('',SQL,result); exit; end; end; end; end; rest := PublishedORM(DatabaseName); if rest<>nil then rest.AdministrationExecute(DatabaseName,SQL,result); end; function TDDDAdministratedDaemon.DatabaseList: TRawUTF8DynArray; var i,n: integer; begin n := length(fInternalDatabases); SetLength(result,n); for i := 0 to n-1 do result[i] := fInternalDatabases[i].Model.Root; end; function TDDDAdministratedDaemon.DatabaseTables(const DatabaseName: RawUTF8): TRawUTF8DynArray; var rest: TSQLRest; i: integer; begin rest := PublishedORM(DatabaseName); if rest=nil then result := nil else with rest.Model do begin SetLength(result,TablesMax+1); for i := 0 to TablesMax do result[i] := TableProps[i].Props.SQLTableName; end; end; procedure TDDDAdministratedDaemon.PublishORMTables(const Rest: array of TSQLRest); var i,n: integer; begin SetLength(fInternalDatabases,length(Rest)); n := 0; for i := 0 to high(Rest) do if Rest[i]<>nil then begin fInternalDatabases[n] := Rest[i]; inc(n); end; SetLength(fInternalDatabases,n); end; procedure TDDDAdministratedDaemon.InternalStop; begin fInternalDatabases := nil; end; function TDDDAdministratedDaemon.InternalRetrieveState( var Status: variant): boolean; begin Status := _ObjFast(['SystemMemory',TSynMonitorMemory.ToVariant]); result := true; end; procedure TDDDAdministratedDaemon.SetInternalSettings(Settings: TObject); begin fInternalSettings := Settings; end; function TDDDAdministratedDaemon.DaemonName: RawUTF8; var L: integer; begin result := RawUTF8(ClassName); if result[1]='T' then delete(result,1,1); L := length(result); if copy(result,L-5,6)='Daemon' then SetLength(result,L-6); end; { TDDDAdministratedThreadDaemon } function TDDDAdministratedThreadDaemon.InternalIsRunning: boolean; begin result := fThread<>nil; end; procedure TDDDAdministratedThreadDaemon.InternalStop; begin inherited InternalStop; // fInternalDatabases := [] FreeAndNil(fThread); // should terminate and wait for the thread to finish end; { TDDDAdministratedRestDaemon } function TDDDAdministratedRestDaemon.InternalIsRunning: boolean; begin result := fRest<>nil; end; procedure TDDDAdministratedRestDaemon.InternalStop; begin inherited InternalStop; // fInternalDatabases := [] FreeAndNil(fRest); end; { TDDDAdministratedDaemonMonitor } function TDDDAdministratedDaemonMonitor.GetMemory: variant; begin result := TSynMonitorMemory.ToVariant; end; procedure TDDDAdministratedDaemonMonitor.ProcessException(E: Exception); begin Server.ProcessError(ObjectToVariantDebug(E)); end; initialization {$ifndef ISDELPHI2010} {$ifndef HASINTERFACERTTI} // circumvent a old FPC bug TTextWriter.RegisterCustomJSONSerializerFromTextSimpleType([ TypeInfo(TCQRSResult), TypeInfo(TCQRSQueryAction), TypeInfo(TCQRSQueryState), TypeInfo(TDDDAdministratedDaemonStatus)]); {$endif} {$endif} GetEnumNames(TypeInfo(TCQRSResult), @TCQRSResultText); TInterfaceFactory.RegisterInterfaces([ TypeInfo(IMonitored),TypeInfo(IMonitoredDaemon), TypeInfo(IAdministratedDaemon),TypeInfo(IAdministratedDaemonAsProxy)]); end.
38.091743
104
0.731112
f1c22ff9e865d5ba8e51ba72b4c37d2a1a021edb
6,570
pas
Pascal
windows/src/ext/jedi/jvcl/tests/Jans/run/JvPainterEffectsForm.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jvcl/tests/Jans/run/JvPainterEffectsForm.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jvcl/tests/Jans/run/JvPainterEffectsForm.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
{----------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvPainterEffectsU.PAS, released on 2002-06-15. The Initial Developer of the Original Code is Jan Verhoeven [jan1.verhoeven@wxs.nl] Portions created by Jan Verhoeven are Copyright (C) 2002 Jan Verhoeven. All Rights Reserved. Contributor(s): Robert Love [rlove@slcdug.org]. Last Modified: 2000-06-15 You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.sourceforge.net Known Issues: -----------------------------------------------------------------------------} {$I JEDI.INC} unit JvPainterEffectsForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, JvDrawImage; type TPainterEffectsF = class(TForm) effectspanel: TPanel; EBar: TScrollBar; extrabar: TScrollBar; ETree: TTreeView; cxbar: TScrollBar; cybar: TScrollBar; Label1: TLabel; Label2: TLabel; Label3: TLabel; procedure EListClick(Sender: TObject); procedure EBarChange(Sender: TObject); private PainterF: TJvDrawImage; procedure bar(max, min, pos: integer); { Private declarations } public { Public declarations } procedure setDrawImage(aDrawImage: TJvdrawImage); end; var PainterEffectsF: TPainterEffectsF; implementation {$R *.DFM} procedure TPainterEffectsF.bar(max, min, pos: integer); begin Ebar.Max := max; Ebar.Min := min; Ebar.Position := pos; end; procedure TPainterEffectsF.EListClick(Sender: TObject); var index: integer; begin if ETree.Selected = nil then exit; index := ETree.Selected.ImageIndex; if index < 0 then exit; case index of 0: bar(100, 0, 0); //contrast 1: bar(255, 0, 0); //saturation 2: bar(100, 0, 0); //brightness 3: bar(20, 0, 0); //gaussian blur 4: bar(30, 0, 0); //split blur 5: bar(200, 0, 0); //color noise 6: bar(200, 0, 0); //mono noise 7: bar(20, 0, 0); //smooth 8: bar(15, 3, 5); //seamless 9: bar(30, 2, 15); //mosaic 10: bar(50, 1, 10); //twist 11: bar(100, 55, 60); //fisheye 12: bar(200, 1, 15); //wave 13: bar(200, 1, 15); //wave extra 14: bar(10, 1, 1); //wave inference 15: bar(360, 0, 0); //smooth rotate 16: bar(10, 1, 1); //split light 17: bar(400, 1, 1); //wings 18: bar(400, 1, 1); //wings down 19: bar(400, 1, 1); //wings up 20: bar(400, 1, 1); //wings fold 21: bar(400, 1, 1); //wings touche 22: bar(400, 1, 1); //wings flyer 23: bar(400, 1, 1); //wings flipover 24: bar(400, 1, 1); //wings wavy 25: bar(100, 0, 0); //emboss 26: bar(255, 0, 128); //filter red 27: bar(255, 0, 128); //filter green 28: bar(255, 0, 128); //filter blue 29: bar(255, 0, 128); //filter Xred 30: bar(255, 0, 128); //filter Xgreen 31: bar(255, 0, 128); //filter xblue 32: bar(255, 0, 0); //squeezehor 33: bar(255, 0, 0); //squeezetop 34: bar(255, 0, 0); //squeezebottom 35: bar(255, 0, 0); //squeezediamond 36: bar(255, 0, 0); //squeezewaste 37: bar(255, 0, 0); //squeezeround 38: bar(255, 0, 0); //squeezeround2 39: bar(255, 0, 0); //splitround 40: bar(255, 0, 0); //splitwaste 41: bar(100, 0, 0); //shear 42: bar(100, 1, 1); //plasma 43: bar(100, 0, 0); //mandelbrot 44: bar(100, 0, 0); //julia 45: bar(127, 5, 19); //triangles 46: bar(100, 3, 3); //ripple tooth 47: bar(100, 3, 3); //ripple triangle 48: bar(100, 3, 3); //ripple random 49: bar(100, 3, 3); //texturize tile 50: bar(100, 3, 3); //texturize overlap 51: bar(100, 1, 1); //map 52: bar(100, 0, 0); //blend; 53: bar(255, 0, 1); //solarize 54: bar(255, 1, 1); //posterize end; end; procedure TPainterEffectsF.EBarChange(Sender: TObject); var index: integer; begin if ETree.selected = nil then exit; index := ETree.selected.ImageIndex; if index < 0 then exit; case index of 0: PainterF.contrastbarChange(sender); 1: PainterF.saturationbarChange(sender); 2: PainterF.lightnessbarChange(sender); 3: PainterF.blurbarChange(sender); 4: PainterF.splitblurbarChange(sender); 5: PainterF.colornoisebarChange(sender); 6: PainterF.mononoisebarChange(sender); 7: PainterF.smoothbarChange(sender); 8: PainterF.seambarChange; 9: PainterF.MosaicbarChange; 10: PainterF.TwistbarChange; 11: PainterF.FisheyebarChange; 12: PainterF.wavebarChange; 13: PainterF.waveextraChange; 14: PainterF.waveinfChange; 15: PainterF.rotatebar; 16: PainterF.xformAbarchange; 17: PainterF.marblebarchange; 18: PainterF.marble2barchange; 19: PainterF.marble3barchange; 20: PainterF.marble4barchange; 21: PainterF.marble5barchange; 22: PainterF.marble6barchange; 23: PainterF.marble7barchange; 24: PainterF.marble8barchange; 25: PainterF.embossbarchange; 26: PainterF.filterredbarchange; 27: PainterF.filtergreenbarchange; 28: PainterF.filterbluebarchange; 29: PainterF.filterxredbarchange; 30: PainterF.filterxgreenbarchange; 31: PainterF.filterxbluebarchange; 32: PainterF.squeezehorbarchange; 33: PainterF.squeezetopbarchange; 34: PainterF.squeezebotbarchange; 35: PainterF.squeezediamondbarchange; 36: PainterF.squeezewastebarchange; 37: PainterF.squeezeroundbarchange; 38: PainterF.squeezeround2barchange; 39: PainterF.splitroundbarchange; 40: PainterF.splitwastebarchange; 41: PainterF.shearbarchange; 42: PainterF.plasmabarchange; 43: PainterF.DrawMandelJulia(true); 44: PainterF.DrawMandelJulia(false); 45: PainterF.drawTriangles; 46: PainterF.rippleTooth; 47: painterF.rippleTriangle; 48: painterF.rippleRandom; 49: PainterF.texturizeTile; 50: painterF.texturizeOverlap; 51: PainterF.drawmap; 52: PainterF.drawblend; 53: PainterF.drawsolarize; 54: painterF.posterize; end; end; procedure TPainterEffectsF.setDrawImage(aDrawImage: TJvDrawImage); begin PainterF := aDrawImage; end; end.
31.435407
86
0.658447
fc7a8aff0fc6535cdfd58471bc2caf4981be5a7d
3,332
pas
Pascal
egavga/0162.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
11
2015-12-12T05:13:15.000Z
2020-10-14T13:32:08.000Z
egavga/0162.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
null
null
null
egavga/0162.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
8
2017-05-05T05:24:01.000Z
2021-07-03T20:30:09.000Z
{ With this program you can view monocrome pcx files, smaller than 60KB. It will only work on VGA cards. A Program to view monocrome PCX files A MacSoft production in 1994 by Andreas Oestlund } Type TPCX_Header = Record Manufacturer : Byte; {always A0h } Version : Byte; {version } Encoding : Byte; {always 1} Bits_Per_Pixel : Byte; {color bits} XMin,YMin : Word; {image origin} XMax,YMax : Word; {dimensions} HRes : Word; {resolution val} VRes : Word; {} Palette : Array[1..48] Of Byte;{palette} Reserved : Byte; {} Color_Planes : Byte; {color planes} Bytes_Per_Line : Word; {line buffer size} Palette_Type : Word; {gray or color pal} Filler : Array[1..58] Of Byte;{} End; TPCXData = Array[1..60000] Of Byte; Procedure SetMode (m : Byte); Assembler; Asm Mov AH, 0 Mov AL, m Int 10h End; Var Header : TPCX_Header; F : File; B,C : Byte; Line_Table : Array[0..479] Of Word; PcxData : ^TPcxData; Width, Height, Bytes_Per_Line : Word; NuRead : Word; Procedure Decode_PCX_Line (l : Word); Var i,j : Word; Const Data_NDX : Word = 0; Begin i := 0; While i < Bytes_Per_Line Do Begin Inc (Data_NDX); B := PcxData^[Data_NDX]; If (B And $C0) = $C0 Then Begin B := B And $3F; Inc (Data_NDX); C := PcxData^[Data_NDX]; For j := 1 To B Do Begin Mem[$A000:Line_Table[l]+i] := C; Inc (i); End; End Else Begin Mem[$A000:Line_Table[l]+i] := B; Inc (i); End; End; End; Var i : Word; Mem2Get : Word; Begin If Paramcount = 0 then HALT; Assign (F,ParamStr(1)); Reset (F,1); BlockRead (F,Header,SizeOf(TPCX_Header)); Width := (Header.XMax - Header.XMax)+1; Height := (Header.YMax - Header.YMin)+1; Bytes_Per_Line := Header.Bytes_Per_Line; For i := 0 To 479 Do Line_Table[i] := i*80; Mem2Get := FileSize(F) - FilePos(F); GetMem (PcxData,Mem2Get); BlockRead (F,PcxData^,60000,NuRead); SetMode ($12); For i := 0 To (Height-1) Do Decode_PCX_Line (i); Readln; FreeMem (PcxData,Mem2Get); SetMode (3); Close (F); End. 
29.75
79
0.391957
fc20f26b9fdc406b394eeadf4ad02c3fe9a6f520
7,928
pas
Pascal
echo.pas
alexanderlarin/underworld
6510fe921e0d013f190419746404d5b05d3b3646
[ "WTFPL" ]
4
2016-07-18T12:26:32.000Z
2022-01-06T21:45:10.000Z
echo.pas
alexanderlarin/underworld
6510fe921e0d013f190419746404d5b05d3b3646
[ "WTFPL" ]
9
2016-06-02T10:53:16.000Z
2016-12-18T22:55:56.000Z
echo.pas
alexanderlarin/underworld
6510fe921e0d013f190419746404d5b05d3b3646
[ "WTFPL" ]
23
2016-04-05T11:28:27.000Z
2019-11-12T09:58:25.000Z
unit Echo; interface uses canvas, outputcolor, types; procedure PrintEvent(event: TEvent; line: Integer; fullLine: Boolean); procedure PrintEvent(event: TEvent; var line: Integer); procedure PrintConditionText(condition: TCondition; var line: Integer); procedure PrintCommand(command: TCommand; var line: Integer); procedure PrintCommands(commands: TCommands); procedure PrintStatsHero(hero: THero); procedure PrintCurrentStatsHero(hero: THero); procedure PrintLocation(locationName: TColorString); procedure PrintStatsChangingHero(var hero: THero); procedure PrintTransition(transition: TTransition; var line: Integer); procedure PrintTransLocation(transition: TTransition; lineTransition: Integer); implementation procedure PrintCommand(command: TCommand; var line: Integer); var I: Integer; begin GotoXY(0, line); if command.isMultiLine then begin for I := 0 to Length(command.texts) - 1 do begin line := line + ColorWrite(command.texts[I].text, command.texts[I].color, 1); end; end else begin if command.text.text <> '' then begin line := line + ColorWrite(command.text.text, command.text.color, 1); end; end; end; procedure PrintConditionText(condition: TCondition; var line: Integer); var I: Integer; begin if condition.isMultiLine then for I := 0 to Length(condition.texts) - 1 do begin ColorWrite(condition.texts[I].text, condition.texts[I].color); GotoXY(0, line + 1); line := line + 1; end else begin ColorWrite(condition.text.text, condition.text.color); GotoXY(0, line + 1); line := line + 1; end; end; procedure PrintStatsHero(hero: THero); // Procedure is depricated. begin ColorWrite('=======ХАРАКТЕРИСТИКИ ПЕРСОНАЖА=======',ColorDefault,1); ColorWrite('Здоровье: ', ColorAttribute); ColorWrite(hero.health.value, ColorNumber); ColorWrite('0%', ColorNumber, 1); ColorWrite('Бодрость: ', ColorAttribute); ColorWrite(hero.energy.value, ColorNumber); ColorWrite('0%', ColorNumber, 1); ColorWrite('Содержание алкоголя: ', ColorAttribute); ColorWrite(hero.alchohol.value, ColorNumber); ColorWrite('0%', ColorNumber, 1); ColorWrite('Накуренность: ', ColorAttribute); ColorWrite(hero.vape.value, ColorNumber); ColorWrite('0%', ColorNumber, 1); ColorWrite('Сила: ',ColorAttribute); ColorWrite(hero.strength.value, ColorNumber); ColorWrite('0%', ColorNumber, 1); ColorWrite('Интеллект: ',ColorAttribute); ColorWrite(hero.intelligence.value, ColorNumber); ColorWrite('0%', ColorNumber, 1); ColorWrite('Удача: ',ColorAttribute); ColorWrite(hero.fortune.value, ColorNumber); ColorWrite('0%', ColorNumber, 1); ColorWrite('Счастье: ',ColorAttribute); ColorWrite(hero.happy.value, ColorNumber); ColorWrite('0%', ColorNumber, 1); ColorWrite('Репутация в группе: ',ColorAttribute); ColorWrite(hero.reputationInGroup.value, ColorNumber); ColorWrite('0%', ColorNumber, 1); ColorWrite('Репутация в универе: ',ColorAttribute); ColorWrite(hero.reputationInUnderworld.value, ColorNumber); ColorWrite('0%', ColorNumber, 1); ColorWrite('======================================', ColorDefault, 1); end; procedure PrintStat(value: Integer; number: Integer); begin GotoXY(PosStatX - 1, number); ColorWrite('.', ColorAttribute); if value = 10 then GotoXY(PosStatX - 1, number) else GotoXY(PosStatX, number); ColorWrite(value, ColorNumber); ColorWrite('0%', ColorNumber); end; procedure PrintStatChanging(var stat: TStat; number: Integer); begin if (stat.changed = 0) then Exit(); PrintStat(stat.value, number); GotoXY(PosStatX + 3, number); if stat.changed > 0 then begin ColorWrite('+', ColorPositiveChanging); ColorWrite(stat.changed, ColorPositiveChanging); ColorWrite('0%', ColorPositiveChanging); end else begin ColorWrite(stat.changed, ColorNegativeChanging); ColorWrite('0%', ColorNegativeChanging); end; stat.changed := 0; end; procedure PrintCurrentStatsHero(hero: THero); begin PrintStat(hero.health.value, 1); PrintStat(hero.energy.value, 2); PrintStat(hero.alchohol.value, 3); PrintStat(hero.vape.value, 4); PrintStat(hero.strength.value, 5); PrintStat(hero.intelligence.value, 6); PrintStat(hero.fortune.value, 7); PrintStat(hero.happy.value, 8); PrintStat(hero.reputationInGroup.value, 9); PrintStat(hero.reputationInUnderworld.value, 10); CanvasResetPos(); end; procedure PrintStatsChangingHero(var hero: THero); begin PrintStatChanging(hero.health, 1); PrintStatChanging(hero.energy, 2); PrintStatChanging(hero.alchohol, 3); PrintStatChanging(hero.vape, 4); PrintStatChanging(hero.strength, 5); PrintStatChanging(hero.intelligence, 6); PrintStatChanging(hero.fortune, 7); PrintStatChanging(hero.happy, 8); PrintStatChanging(hero.reputationInGroup, 9); PrintStatChanging(hero.reputationInUnderworld, 10); CanvasResetPos(); end; procedure PrintLocation(locationName: TColorString); begin GotoXY(62, 21); LineChar(52, 21, 25, ' '); if (locationName.color = '') then locationName.color := ColorLocation; GotoXY(PosStatsX + ((ConsoleWidth - PosStatsX) div 2) - (Length(UTF8Decode(locationName.text)) div 2), 21); ColorWrite(locationName.text, locationName.color); GotoXY(0, 0); end; procedure PrintEvent(event: TEvent; line: Integer; fullLine: Boolean); var I: Integer; begin GotoXY(0, line); if event.isMultiLine then begin for I := 0 to Length(event.texts) - 1 do begin if fullLine then begin ColorWrite(event.texts[I].text, event.texts[I].color); ColorWrite('', ColorDefault, 1); end else begin ColorWrite(event.texts[I].text, event.texts[I].color, 1); end; end; end else begin if fullLine then ColorWrite(event.text.text, event.text.color) else ColorWrite(event.text.text, event.text.color, 1); end; end; procedure PrintEvent(event: TEvent; var line: Integer); var I: Integer; begin GotoXY(0, line); if event.isMultiLine then begin for I := 0 to Length(event.texts) - 1 do begin line := line + ColorWrite(event.texts[I].text, event.texts[I].color, 1); end; end else begin line := line + ColorWrite(event.text.text, event.text.color, 1); end; end; procedure PrintCommands(commands: TCommands); var I: Integer; begin GotoXY(0, PosCommandsBeginY); for I := 0 to Length(commands) - 1 do begin ColorWrite(commands[I].cmd, ColorNumber); ColorWrite(': ', ColorDefault); ColorWrite(commands[I].name.text, commands[I].name.color, 1, 46); end; end; procedure PrintTransition(transition: TTransition; var line: Integer); var I: Integer; begin GotoXY(0, line); if transition.isMultiLine then begin for I := 0 to Length(transition.texts) - 1 do begin line := line + ColorWrite(transition.texts[I].text, transition.texts[I].color, 1); end; end else begin if transition.text.text <> '' then begin line := line + ColorWrite(transition.text.text, transition.text.color, 1); end end; end; procedure PrintTransLocation(transition: TTransition; lineTransition: Integer); begin GotoXY(0, PosTransitionBeginY + lineTransition); ColorWrite(' --> ', ColorLocationChanging); ColorWrite('Переход на локацию "', ColorTransLocation); ColorWrite(transition.toLocation, ColorLocation); ColorWrite('" ', ColorTransLocation); ColorWrite('к событию "', ColorTransLocation); ColorWrite(transition.toEvent, ColorEventName); ColorWrite('" ', ColorTransLocation, 1); lineTransition := lineTransition + 1; end; end.
30.030303
110
0.681635
fce4722d9a1f5199c299fec96cb34fe68ed5fcff
4,566
dfm
Pascal
u_new_muzaki.dfm
AndanTeknomedia/bazda-delphi-xe8
3cb9589e41bf7a7492323348a429a6ef7f357817
[ "MIT" ]
null
null
null
u_new_muzaki.dfm
AndanTeknomedia/bazda-delphi-xe8
3cb9589e41bf7a7492323348a429a6ef7f357817
[ "MIT" ]
null
null
null
u_new_muzaki.dfm
AndanTeknomedia/bazda-delphi-xe8
3cb9589e41bf7a7492323348a429a6ef7f357817
[ "MIT" ]
null
null
null
object FNewMuzaki: TFNewMuzaki Left = 0 Top = 0 BorderStyle = bsDialog Caption = 'Muzaki Baru' ClientHeight = 304 ClientWidth = 535 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False Position = poDesktopCenter PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 28 Top = 19 Width = 85 Height = 13 Caption = 'Nama Muzaki/UPZ' end object Label2: TLabel Left = 28 Top = 41 Width = 59 Height = 13 Caption = 'Jenis Muzaki' end object Label3: TLabel Left = 28 Top = 64 Width = 105 Height = 13 Caption = 'Kelurahan/Kecamatan' end object Label4: TLabel Left = 20 Top = 90 Width = 90 Height = 13 Caption = 'Data Tambahan' Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [fsBold] ParentFont = False end object Label5: TLabel Left = 28 Top = 113 Width = 17 Height = 13 Caption = 'NIK' end object Label6: TLabel Left = 28 Top = 135 Width = 29 Height = 13 Caption = 'NPWP' end object Label7: TLabel Left = 28 Top = 158 Width = 32 Height = 13 Caption = 'No. KK' end object Label8: TLabel Left = 28 Top = 182 Width = 24 Height = 13 Caption = 'Telp.' end object Label9: TLabel Left = 28 Top = 204 Width = 76 Height = 13 Caption = 'Alamat Lengkap' end object eNama: TEdit Left = 140 Top = 16 Width = 349 Height = 21 TabOrder = 0 Text = 'eNama' end object eTipe: TDBLookupComboBox Left = 140 Top = 39 Width = 349 Height = 21 KeyField = 'kode' ListField = 'kode;uraian' ListFieldIndex = 1 ListSource = dsTipe TabOrder = 1 end object eNik: TEdit Left = 140 Top = 110 Width = 349 Height = 21 TabOrder = 3 Text = 'eNama' end object eNPWP: TEdit Left = 140 Top = 133 Width = 349 Height = 21 TabOrder = 4 Text = 'eNama' end object eKelurahan: TDBLookupComboBox Left = 140 Top = 62 Width = 349 Height = 21 KeyField = 'kode' ListField = 'kode;nama' ListFieldIndex = 1 ListSource = dsKel2 TabOrder = 2 end object eAlamat: TMemo Left = 140 Top = 202 Width = 349 Height = 45 Lines.Strings = ( 'eAlamat') ScrollBars = ssVertical TabOrder = 7 end object eNoKK: TEdit Left = 140 Top = 156 Width = 349 Height = 21 TabOrder = 5 Text = 'eNoKK' end object eTelp: TEdit Left = 140 Top = 179 Width = 349 Height = 21 TabOrder = 6 Text = 'eNoKK' end object Panel1: TPanel Left = 0 Top = 263 Width = 535 Height = 41 Align = alBottom BevelOuter = bvNone Caption = 'Panel1' ShowCaption = False TabOrder = 8 object Bevel1: TBevel Left = 0 Top = 0 Width = 535 Height = 8 Align = alTop Shape = bsTopLine end object Button1: TButton Left = 280 Top = 8 Width = 75 Height = 25 Cancel = True Caption = 'Cancel' TabOrder = 0 OnClick = Button1Click end object Button2: TButton Left = 414 Top = 8 Width = 75 Height = 25 Caption = 'Save' Default = True TabOrder = 1 OnClick = Button2Click end end object qKel2: TUniQuery Connection = FMain.Koneksi SQL.Strings = ( 'select kode, (nama||'#39', '#39'||kecamatan)::varchar(100) nama from v_k' + 'elurahan order by kode asc') Left = 407 Top = 46 object qKel2kode: TStringField FieldName = 'kode' Size = 10 end object qKel2nama: TStringField FieldName = 'nama' ReadOnly = True Size = 100 end end object dsKel2: TDataSource DataSet = qKel2 Left = 432 Top = 48 end object qTipe: TUniQuery Connection = FMain.Koneksi SQL.Strings = ( 'select kode, uraian from baz_jenis_muzakki order by kode asc') Left = 303 Top = 46 object qTipekode: TStringField FieldName = 'kode' Required = True FixedChar = True Size = 2 end object qTipeuraian: TStringField FieldName = 'uraian' Required = True Size = 100 end end object dsTipe: TDataSource DataSet = qTipe Left = 328 Top = 48 end end
18.636735
84
0.574463
c3a916444fb846d0b6e2835a1389fc409a4c01e3
16,695
pas
Pascal
windows/src/ext/jedi/jcl/jcl/source/common/JclPreProcessorTreesTemplates.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jcl/jcl/source/common/JclPreProcessorTreesTemplates.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jcl/jcl/source/common/JclPreProcessorTreesTemplates.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
{**************************************************************************************************} { } { Project JEDI Code Library (JCL) } { } { The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); } { you may not use this file except in compliance with the License. You may obtain a copy of the } { License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF } { ANY KIND, either express or implied. See the License for the specific language governing rights } { and limitations under the License. } { } { The Original Code is JclTreesTemplates.pas. } { } { The Initial Developer of the Original Code is Florent Ouchet } { <outchy att users dott sourceforge dott net> } { Portions created by Florent Ouchet are Copyright (C) of Florent Ouchet. All rights reserved. } { } { Contributors: } { } {**************************************************************************************************} { } { Last modified: $Date:: $ } { Revision: $Rev:: $ } { Author: $Author:: $ } { } {**************************************************************************************************} unit JclPreProcessorTreesTemplates; interface {$I jcl.inc} uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} JclPreProcessorContainerTypes, JclPreProcessorContainerTemplates, JclPreProcessorContainer1DTemplates; type (* JCLTREETYPESINT(NODETYPENAME, EQUALITYCOMPARERINTERFACENAME, CONSTKEYWORD, PARAMETERNAME, TYPENAME) *) TJclTreeTypeIntParams = class(TJclContainerInterfaceParams) public function AliasAttributeIDs: TAllTypeAttributeIDs; override; published property NodeTypeName: string index taTreeNodeClassName read GetTypeAttribute write SetTypeAttribute stored IsTypeAttributeStored; property EqualityComparerInterfaceName: string index taEqualityComparerInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property ConstKeyword: string index taConstKeyword read GetTypeAttribute write SetTypeAttribute stored False; property ParameterName: string index taParameterName read GetTypeAttribute write SetTypeAttribute stored False; property TypeName: string index taTypeName read GetTypeAttribute write SetTypeAttribute stored False; end; (* JCLTREEINT(NODETYPENAME, SELFCLASSNAME, ANCESTORCLASSNAME, BASECONTAINERINTERFACENAME, FLATCONTAINERINTERFACENAME, EQUALITYCOMPARERINTERFACENAME, COLLECTIONINTERFACENAME, TREEINTERFACENAME, STDITRINTERFACENAME, TREEITRINTERFACENAME, INTERFACEADDITIONAL, SECTIONADDITIONAL, COLLECTIONFLAGS, OWNERSHIPDECLARATION, CONSTKEYWORD, PARAMETERNAME, TYPENAME, DEFAULTVALUE) *) TJclTreeIntParams = class(TJclCollectionInterfaceParams) protected // function CodeUnit: string; override; function GetOwnershipDeclaration: string; override; public function AliasAttributeIDs: TAllTypeAttributeIDs; override; published property NodeTypeName: string index taTreeNodeClassName read GetTypeAttribute write SetTypeAttribute stored False; property SelfClassName: string index taTreeClassName read GetTypeAttribute write SetTypeAttribute stored IsTypeAttributeStored; property AncestorClassName; property BaseContainerInterfaceName: string index taContainerInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property FlatContainerInterfaceName: string index taFlatContainerInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property EqualityComparerInterfaceName: string index taEqualityComparerInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property CollectionInterfaceName: string index taCollectionInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property TreeInterfaceName: string index taTreeInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property StdItrInterfaceName: string index taIteratorInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property TreeItrInterfaceName: string index taTreeIteratorInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property InterfaceAdditional; property SectionAdditional; property OwnershipDeclaration; property CollectionFlags; property ConstKeyword: string index taConstKeyword read GetTypeAttribute write SetTypeAttribute stored False; property ParameterName: string index taParameterName read GetTypeAttribute write SetTypeAttribute stored False; property TypeName: string index taTypeName read GetTypeAttribute write SetTypeAttribute stored False; property DefaultValue: string index taDefaultValue read GetTypeAttribute write SetTypeAttribute stored False; end; (* JCLTREEITRINT(BASEITRCLASSNAME, PREORDERITRCLASSNAME, POSTORDERITRCLASSNAME, NODETYPENAME, TREECLASSNAME, STDITRINTERFACENAME, TREEITRINTERFACENAME, EQUALITYCOMPARERINTERFACENAME, CONSTKEYWORD, PARAMETERNAME, TYPENAME, DEFAULTVALUE, GETTERFUNCTIONNAME, SETTERPROCEDURENAME) *) TJclTreeItrIntParams = class(TJclContainerInterfaceParams) protected // function CodeUnit: string; override; public function AliasAttributeIDs: TAllTypeAttributeIDs; override; published property BaseItrClassName: string index taTreeBaseIteratorClassName read GetTypeAttribute write SetTypeAttribute stored IsTypeAttributeStored; property PreOrderItrClassName: string index taTreePreOrderIteratorClassName read GetTypeAttribute write SetTypeAttribute stored IsTypeAttributeStored; property PostOrderItrClassName: string index taTreePostOrderIteratorClassName read GetTypeAttribute write SetTypeAttribute stored IsTypeAttributeStored; property NodeTypeName: string index taTreeNodeClassName read GetTypeAttribute write SetTypeAttribute stored False; property TreeClassName: string index taTreeClassName read GetTypeAttribute write SetTypeAttribute stored False; property StdItrInterfaceName: string index taIteratorInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property TreeItrInterfaceName: string index taTreeIteratorInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property EqualityComparerInterfaceName: string index taEqualityComparerInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property ConstKeyword: string index taConstKeyword read GetTypeAttribute write SetTypeAttribute stored False; property ParameterName: string index taParameterName read GetTypeAttribute write SetTypeAttribute stored False; property TypeName: string index taTypeName read GetTypeAttribute write SetTypeAttribute stored False; property DefaultValue: string index taDefaultValue read GetTypeAttribute write SetTypeAttribute stored False; property GetterFunctionName: string index taGetterFunctionName read GetTypeAttribute write SetTypeAttribute stored False; property SetterProcedureName: string index taSetterProcedureName read GetTypeAttribute write SetTypeAttribute stored False; end; (* JCLTREETYPESIMP(NODETYPENAME, EQUALITYCOMPARERINTERFACENAME, CONSTKEYWORD, PARAMETERNAME, TYPENAME) *) TJclTreeTypeImpParams = class(TJclContainerImplementationParams) published property NodeTypeName: string index taTreeNodeClassName read GetTypeAttribute write SetTypeAttribute stored False; property EqualityComparerInterfaceName: string index taEqualityComparerInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property ConstKeyword: string index taConstKeyword read GetTypeAttribute write SetTypeAttribute stored False; property ParameterName: string index taParameterName read GetTypeAttribute write SetTypeAttribute stored False; property TypeName: string index taTypeName read GetTypeAttribute write SetTypeAttribute stored False; end; (* JCLTREEIMP(NODETYPENAME, SELFCLASSNAME, PREORDERITRCLASSNAME, POSTORDERITRCLASSNAME, COLLECTIONINTERFACENAME, STDITRINTERFACENAME, TREEITRINTERFACENAME, EQUALITYCOMPARERINTERFACENAME, OWNERSHIPDECLARATION, OWNERSHIPPARAMETERNAME, CONSTKEYWORD, PARAMETERNAME, TYPENAME, DEFAULTVALUE, RELEASERFUNCTIONNAME) *) TJclTreeImpParams = class(TJclCollectionImplementationParams) protected // function CodeUnit: string; override; function GetConstructorParameters: string; override; function GetSelfClassName: string; override; function GetOwnershipDeclaration: string; override; published property SelfClassName: string index taTreeClassName read GetTypeAttribute write SetTypeAttribute stored False; property NodeTypeName: string index taTreeNodeClassName read GetTypeAttribute write SetTypeAttribute stored False; property PreOrderItrClassName: string index taTreePreOrderIteratorClassName read GetTypeAttribute write SetTypeAttribute stored False; property PostOrderItrClassName: string index taTreePostOrderIteratorClassName read GetTypeAttribute write SetTypeAttribute stored False; property CollectionInterfaceName: string index taCollectionInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property StdItrInterfaceName: string index taIteratorInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property TreeItrInterfaceName: string index taTreeIteratorInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property EqualityComparerInterfaceName: string index taEqualityComparerInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property OwnershipDeclaration; property OwnershipParameterName: string index taOwnershipParameterName read GetTypeAttribute write SetTypeAttribute stored False; property ConstKeyword: string index taConstKeyword read GetTypeAttribute write SetTypeAttribute stored False; property ParameterName: string index taParameterName read GetTypeAttribute write SetTypeAttribute stored False; property TypeName: string index taTypeName read GetTypeAttribute write SetTypeAttribute stored False; property DefaultValue: string index taDefaultValue read GetTypeAttribute write SetTypeAttribute stored False; property ReleaserFunctionName: string index taReleaserFunctionName read GetTypeAttribute write SetTypeAttribute stored False; property MacroFooter; end; (* JCLTREEITRIMP(BASEITRCLASSNAME, PREORDERITRCLASSNAME, POSTORDERITRCLASSNAME, NODETYPENAME, TREECLASSNAME, STDITRINTERFACENAME, TREEITRINTERFACENAME, EQUALITYCOMPARERINTERFACENAME, CONSTKEYWORD, PARAMETERNAME, TYPENAME, DEFAULTVALUE, GETTERFUNCTIONNAME, SETTERPROCEDURENAME, RELEASERFUNCTIONNAME) *) TJclTreeItrImpParams = class(TJclContainerImplementationParams) protected // function CodeUnit: string; override; published property BaseItrClassName: string index taTreeBaseIteratorClassName read GetTypeAttribute write SetTypeAttribute stored False; property PreOrderItrClassName: string index taTreePreOrderIteratorClassName read GetTypeAttribute write SetTypeAttribute stored False; property PostOrderItrClassName: string index taTreePostOrderIteratorClassName read GetTypeAttribute write SetTypeAttribute stored False; property NodeTypeName: string index taTreeNodeClassName read GetTypeAttribute write SetTypeAttribute stored False; property TreeClassName: string index taTreeClassName read GetTypeAttribute write SetTypeAttribute stored False; property StdItrInterfaceName: string index taIteratorInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property TreeItrInterfaceName: string index taTreeIteratorInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property EqualityComparerInterfaceName: string index taEqualityComparerInterfaceName read GetTypeAttribute write SetTypeAttribute stored False; property ConstKeyword: string index taConstKeyword read GetTypeAttribute write SetTypeAttribute stored False; property ParameterName: string index taParameterName read GetTypeAttribute write SetTypeAttribute stored False; property TypeName: string index taTypeName read GetTypeAttribute write SetTypeAttribute stored False; property DefaultValue: string index taDefaultValue read GetTypeAttribute write SetTypeAttribute stored False; property GetterFunctionName: string index taGetterFunctionName read GetTypeAttribute write SetTypeAttribute stored False; property SetterProcedureName: string index taSetterProcedureName read GetTypeAttribute write SetTypeAttribute stored False; property ReleaserFunctionName: string index taReleaserFunctionName read GetTypeAttribute write SetTypeAttribute stored False; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL$'; Revision: '$Revision$'; Date: '$Date$'; LogPath: 'JCL\source\common'; Extra: ''; Data: nil ); {$ENDIF UNITVERSIONING} implementation uses {$IFDEF HAS_UNITSCOPE} System.SysUtils, {$ELSE ~HAS_UNITSCOPE} SysUtils, {$ENDIF ~HAS_UNITSCOPE} JclStrings; procedure RegisterJclContainers; begin RegisterContainerParams('JCLTREETYPESINT', TJclTreeTypeIntParams); RegisterContainerParams('JCLTREETYPESIMP', TJclTreeTypeImpParams, TJclTreeTypeIntParams); RegisterContainerParams('JCLTREEINT', TJclTreeIntParams); RegisterContainerParams('JCLTREEITRINT', TJclTreeItrIntParams); RegisterContainerParams('JCLTREEIMP', TJclTreeImpParams, TJclTreeIntParams); RegisterContainerParams('JCLTREEITRIMP', TJclTreeItrImpParams, TJclTreeItrIntParams); end; //=== { TJclTreeTypeIntParams } ============================================== function TJclTreeTypeIntParams.AliasAttributeIDs: TAllTypeAttributeIDs; begin Result := [taTreeNodeClassName]; end; //=== { TJclTreeIntParams } ================================================== function TJclTreeIntParams.AliasAttributeIDs: TAllTypeAttributeIDs; begin Result := [taTreeClassName]; end; function TJclTreeIntParams.GetOwnershipDeclaration: string; begin Result := TypeInfo.OwnershipDeclaration; end; //=== { TJclTreeItrIntParams } =============================================== function TJclTreeItrIntParams.AliasAttributeIDs: TAllTypeAttributeIDs; begin Result := [taTreeBaseIteratorClassName, taTreePreOrderIteratorClassName, taTreePostOrderIteratorClassName]; end; //=== { TJclTreeImpParams } ================================================== function TJclTreeImpParams.GetConstructorParameters: string; begin Result := ''; end; function TJclTreeImpParams.GetOwnershipDeclaration: string; begin Result := TypeInfo.OwnershipDeclaration; end; function TJclTreeImpParams.GetSelfClassName: string; begin Result := SelfClassName; end; initialization RegisterJclContainers; {$IFDEF UNITVERSIONING} RegisterUnitVersion(HInstance, UnitVersioning); {$ENDIF UNITVERSIONING} finalization {$IFDEF UNITVERSIONING} UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
63
156
0.724468
c33616f4e6497916e3ad01e543aaf0adeefd518e
199
pas
Pascal
rutinasDeEntradaODeSalida/saludo.pas
DeveloperLuisF3/Pascal_A_lenguajeDeProgramacion
40f671fab830cd7fa2eb77dabccbe807434e2e73
[ "MIT" ]
null
null
null
rutinasDeEntradaODeSalida/saludo.pas
DeveloperLuisF3/Pascal_A_lenguajeDeProgramacion
40f671fab830cd7fa2eb77dabccbe807434e2e73
[ "MIT" ]
null
null
null
rutinasDeEntradaODeSalida/saludo.pas
DeveloperLuisF3/Pascal_A_lenguajeDeProgramacion
40f671fab830cd7fa2eb77dabccbe807434e2e73
[ "MIT" ]
null
null
null
Program Saludo; uses crt; Var Nombre : String; Begin clrscr; WriteLn ('Escriba su nombre: '); ReadLn (Nombre); WriteLn ('Hola ', Nombre); readkey; End.
18.090909
40
0.537688
fced90dd7bbd36d3127d55cacd288f198f32c5ba
6,824
pas
Pascal
UCalcVec.pas
duzun/Figuri3D.pas
12e7901c2f6bf858313893cd94f3bdd93ea35fdb
[ "MIT" ]
null
null
null
UCalcVec.pas
duzun/Figuri3D.pas
12e7901c2f6bf858313893cd94f3bdd93ea35fdb
[ "MIT" ]
null
null
null
UCalcVec.pas
duzun/Figuri3D.pas
12e7901c2f6bf858313893cd94f3bdd93ea35fdb
[ "MIT" ]
null
null
null
unit UCalcVec; {---------------------------------------------------------------} interface {$N+} {---------------------------------------------------------------} type TCoord = Extended; TVector = packed array[1..3] of TCoord; PVector = ^TVector; TVec2Real = TVector; TPlan = packed record n: TVector; C: TCoord; end; {n - vectorul normal, C - coeficientul liber al ecuatiei} PPlan = ^TPlan; TVecList = array[0..100] of PVector; PVecList = ^TVecList; TVec2Int = packed array[1..2] of Integer; {---------------------------------------------------------------} const VecZero: TVector = (0, 0, 0); VecI: TVector = (1, 0, 0); {Vectorii unitari} VecJ: TVector = (0, 1, 0); VecK: TVector = (0, 0, 1); xOy: TPlan = (n: (0, 0, 1); C: 0); yOz: TPlan = (n: (1, 0, 0); C: 0); zOx: TPlan = (n: (0, 1, 0); C: 0); Pi_c = 3.1415926535897932384626433832795; Radiani = 180 / Pi_c; { x * Radiani = y Grade} Grade = Pi_c / 180; { x * Grade = y Radiani} Ax_X = 1; Ax_Y = 2; Ax_Z = 3; {---------------------------------------------------------------} function IsNul(v: TVector): boolean; { v = 0 } function Modul(v: TVector): Extended; { |v| } function ProdScal(v1, v2: TVector): Extended; { v1*v2 } procedure ProdVec (var r: TVector; v1, v2: TVector); { r := [v1,v2] } procedure AddVec (var r: TVector; v1, v2: TVector); { r := v1 + v2 } procedure SubVec (var r: TVector; v1, v2: TVector); { r := v1 - v2 } procedure MulScal (var r: TVector; v: TVector; scal: TCoord); { r := v * scal } procedure AddScal (var r: TVector; v: TVector; scal: TCoord); { r := v + scal } function VecParal(var u: TVector; v: TVector; scal: TCoord): TCoord; { u // v, |u| = scal } function EcPlan(var n: TVector; var A, B, C: TVector): TCoord; {n - vectorul normal, return C} function CosVec(v1, v2: PVector): Real; {---------------------------------------------------------------} procedure MulScal2D(var r: TVec2Real; v: TVec2Real; scal: TCoord); { r := v * scal } procedure AddVec2D (var r: TVec2Real; v1, v2: TVec2Real); { r := v1 + v2 } procedure SubVec2D (var r: TVec2Real; v1, v2: TVec2Real); { r := v1 - v2 } {---------------------------------------------------------------} procedure RotAx(var v: TVector; rad: Real; ax: byte); {roteste v cu rad in jurul ax} procedure RotVec(v1, v2: TVector; rad: Real; var x, y: TVector); function r(g:Real):Real; {grade -> radiani} function g(r:Real):Real; {radiani -> grade } {---------------------------------------------------------------} implementation {---------------------------------------------------------------} function EcPlan(var n: TVector; var A, B, C: TVector): TCoord; begin n[1] := (B[2]-A[2])*(C[3]-A[3]) - (B[3]-A[3])*(C[2]-A[2]) ; n[2] := (B[3]-A[3])*(C[1]-A[1]) - (B[1]-A[1])*(C[3]-A[3]) ; n[3] := (B[1]-A[1])*(C[2]-A[2]) - (B[2]-A[2])*(C[1]-A[1]) ; EcPlan := -A[1]*n[1] -A[2]*n[2] -A[3]*n[3] ; end; {---------------------------------------------------------------} function CosVec(v1, v2: PVector): Real; var m: Extended; begin m := (Modul(v1^)*Modul(v2^)); if m = 0 then CosVec := 1 else CosVec := ProdScal(v1^, v2^) / m; end; {---------------------------------------------------------------} procedure MulScal2D(var r: TVec2Real; v: TVec2Real; scal: TCoord); begin { r := v * scal } r[1] := v[1] * scal; r[2] := v[2] * scal; end; {---------------------------------------------------------------} procedure AddVec2D (var r: TVec2Real; v1, v2: TVec2Real); begin { r := v1 + v2 } r[1] := v1[1] + v2[1]; r[2] := v1[2] + v2[2]; end; {---------------------------------------------------------------} procedure SubVec2D (var r: TVec2Real; v1, v2: TVec2Real); begin { r := v1 - v2 } r[1] := v1[1] - v2[1]; r[2] := v1[2] - v2[2]; end; {---------------------------------------------------------------} procedure RotAx(var v: TVector; rad: Real; ax: byte); var sn, cs: Real; x, y: TCoord; i, j: byte; begin { case ax of 1: Ox; 2: Oy; 3: Oz; } sn := sin(rad); i := ax mod 3 + 1; inc(ax); x := v[i]; cs := cos(rad); j := ax mod 3 + 1; y := v[j]; v[i] := x*cs - y*sn; v[j] := x*sn + y*cs; end; {---------------------------------------------------------------} procedure RotVec(v1, v2: TVector; rad: Real; var x, y: TVector); var sn, cs: Real; begin {Roteste v1 spre v2} sn := sin(rad); cs := cos(rad); MulScal(x, v1, cs); MulScal(y, v2, cs); MulScal(v1, v1, sn); MulScal(v2, v2, sn); SubVec(x, x, v2); AddVec(y, y, v1); end; {---------------------------------------------------------------} function VecParal(var u: TVector; v: TVector; scal: TCoord): TCoord; var M: TCoord; begin { u // v, |u| = scal } M := Modul(v); if M <> 0 then MulScal(u, v, scal/M) else u := v; VecParal := M; end; {---------------------------------------------------------------} procedure MulScal(var r: TVector; v: TVector; scal: TCoord); begin { r := v * scal } r[1] := v[1] * scal; r[2] := v[2] * scal; r[3] := v[3] * scal; end; {---------------------------------------------------------------} procedure AddScal(var r: TVector; v: TVector; scal: TCoord); begin { r := v + scal } r[1] := v[1] + scal; r[2] := v[2] + scal; r[3] := v[3] + scal; end; {---------------------------------------------------------------} procedure AddVec(var r: TVector; v1, v2: TVector); begin { r := v1 + v2 } r[1] := v1[1] + v2[1]; r[2] := v1[2] + v2[2]; r[3] := v1[3] + v2[3]; end; {---------------------------------------------------------------} procedure SubVec(var r: TVector; v1, v2: TVector); begin { r := v1 - v2 } r[1] := v1[1] - v2[1]; r[2] := v1[2] - v2[2]; r[3] := v1[3] - v2[3]; end; {---------------------------------------------------------------} procedure ProdVec(var r: TVector; v1, v2: TVector); begin { r := [v1,v2] } r[1] := v1[2]*v2[3] - v1[3]*v2[2]; r[2] := v1[3]*v2[1] - v1[1]*v2[3]; r[3] := v1[1]*v2[2] - v1[2]*v2[1]; end; {---------------------------------------------------------------} function ProdScal(v1, v2: TVector): Extended; { v1*v2 } begin ProdScal := v1[1]*v2[1] + v1[2]*v2[2] + v1[3]*v2[3] end; {---------------------------------------------------------------} function Modul(v: TVector): Extended; { |v| } begin Modul := sqrt(sqr(v[1])+sqr(v[2])+sqr(v[3])) end; {---------------------------------------------------------------} function IsNul(v: TVector): boolean; { v = 0 } begin IsNul := (v[1] = 0) and (v[2] = 0) and (v[3] = 0) end; {---------------------------------------------------------------} function r(g:Real):Real; begin r:=g*Grade; end; function g(r:Real):Real; begin g:=r*Radiani; end; {---------------------------------------------------------------} end.
38.772727
116
0.41779
47f4f36c3bd7410f6ae5ba2a11cc45c6682b3e38
343,700
pas
Pascal
src/html/htmlparser.pas
kleopatra999/wattsi
7c72a58d948a463d1ab96504f4dd2e64585897e1
[ "MIT" ]
1
2021-06-25T15:00:01.000Z
2021-06-25T15:00:01.000Z
src/html/htmlparser.pas
kleopatra999/wattsi
7c72a58d948a463d1ab96504f4dd2e64585897e1
[ "MIT" ]
null
null
null
src/html/htmlparser.pas
kleopatra999/wattsi
7c72a58d948a463d1ab96504f4dd2e64585897e1
[ "MIT" ]
null
null
null
{$MODE OBJFPC} { -*- delphi -*- } {$INCLUDE settings.inc} unit htmlparser; interface uses unicode, plasticarrays, utf8, dom, webdom, canonicalstrings, {$IFDEF USEROPES} ropes {$ELSE} stringutils {$ENDIF}, wires, genericutils; // This parser intentionally differs from the standard in the following ways: // - it assumes UTF-8 // - it doesn't support scripting, document.write(), the insertion point // - it doesn't support streaming input; all data must be provided up-front // - it assumes that documents are not iframe srcdoc documents // - because it assumes no script is mutating the document as it goes, // certain features are simplified. For example, the "reconstruct the // active formatting elements" algorithm just clones the original, it // doesn't bother to store the original's token. // don't forget to also set DebugNow appropriately // {$DEFINE VERBOSETABLE} // {$DEFINE VERBOSETOKENISER} // {$DEFINE VERBOSEENUMERATOR} // {$DEFINE VERBOSEAAA} // {$DEFINE VERBOSETEXT} // if you want line/col information, enable this (it's always enabled when assertions are enabled) // {$DEFINE LINES} {$IFOPT C+} {$DEFINE LINES} {$ENDIF} // if you want parse error information, enable this (it's always enabled in debug mode) // {$DEFINE PARSEERROR} {$IFDEF DEBUG} {$DEFINE PARSEERROR} {$ENDIF} // When optimising for a specific data set //{$DEFINE INSTRUMENTING} type {$IFDEF USEROPES} TParserString = Rope; TCutParserString = CutRope; TParserStringPointer = TRopePointer; TParserStringEnumerator = RopeEnumerator; {$ELSE} {$WARNING Ropes not enabled -- compile with USEROPES defined for optimal performance} TParserString = UTF8String; TCutParserString = CutUTF8String; TParserStringPointer = TUTF8StringPointer; TParserStringEnumerator = UTF8StringEnumerator; {$ENDIF} {$IFDEF PARSEERROR} TParseErrorHandler = procedure(const Message: UTF8String) of object; {$ENDIF} THTMLParser = class protected type TInputStream = class strict private type TInputStreamFlag = (isAteCR, isManipulated, isPreConsumed {$IFDEF PARSEERROR}, isBadAlreadyNoted {$ENDIF} {$IFOPT C+}, isStarted, isSeenEOF {$ENDIF}); var FData: TParserString; FEnumerator: TParserStringEnumerator; FInputStreamFlags: set of TInputStreamFlag; {$IFDEF LINES} FLine, FColumn: Cardinal; {$ENDIF} FLastInputCharacter: TUnicodeCodepoint; {$IFNDEF USEROPES} function GetCurrentCharacterLength(): TUTF8SequenceLength; inline; {$ENDIF} function GetFlag(const Flag: TInputStreamFlag): Boolean; public type TBookmark = record private FPosition: TParserStringPointer; FLastInputCharacter: TUnicodeCodepoint; FInputStreamFlags: set of TInputStreamFlag; function GetFlag(const Flag: TInputStreamFlag): Boolean; public function GetPointer(): TParserStringPointer; property WasManipulated: Boolean index isManipulated read GetFlag; end; constructor Create(); destructor Destroy(); override; {$IFNDEF USEROPES} procedure PushData(const NewData: UTF8String); inline; {$ENDIF} procedure PushData(const NewData: Pointer; const NewLength: QWord); inline; procedure Freeze(); // do not use enumerator before this procedure Advance(); function GetBookmark(): TBookmark; procedure ReturnToBookmark(constref NewPosition: TBookmark); procedure Unconsume(); function Extract(constref NewStart, NewEnd: TParserStringPointer): TCutParserString; function GetPointer(): TParserStringPointer; inline; {$IFOPT C+} function GetDebugData(): UTF8String; {$ENDIF} {$IFNDEF USEROPES} function GetRawPointer(): Pointer; inline; {$ENDIF} {$IFDEF PARSEERROR} procedure NotedThatInputIsBad(); inline; {$ENDIF} property CurrentCharacter: TUnicodeCodepoint read FLastInputCharacter; {$IFNDEF USEROPES} property CurrentCharacterLength: TUTF8SequenceLength read GetCurrentCharacterLength; {$ENDIF} property WasManipulated: Boolean index isManipulated read GetFlag; {$IFDEF PARSEERROR} property WasNotedBad: Boolean index isBadAlreadyNoted read GetFlag; {$ENDIF} {$IFOPT C+} property WasStarted: Boolean index isStarted read GetFlag; {$ENDIF} property Data: TParserString read FData; {$IFDEF LINES} property Line: Cardinal read FLine; property Column: Cardinal read FColumn; {$ENDIF} end; TTokeniserState = (tsInitialState, tsDataState, tsRcdataState, tsRawtextState, tsScriptDataState, tsPlaintextState, tsTagOpenState, tsEndTagOpenState, tsTagNameState, tsRcdataLessThanSignState, tsRcdataEndTagOpenState, tsRcdataEndTagNameState, tsRawtextLessThanSignState, tsRawtextEndTagOpenState, tsRawtextEndTagNameState, tsScriptDataLessThanSignState, tsScriptDataEndTagOpenState, tsScriptDataEndTagNameState, tsScriptDataEscapeStartState, tsScriptDataEscapeStartDashState, tsScriptDataEscapedState, tsScriptDataEscapedDashState, tsScriptDataEscapedDashDashState, tsScriptDataEscapedLessThanSignState, tsScriptDataEscapedEndTagOpenState, tsScriptDataEscapedEndTagNameState, tsScriptDataDoubleEscapeStartState, tsScriptDataDoubleEscapedState, tsScriptDataDoubleEscapedDashState, tsScriptDataDoubleEscapedDashDashState, tsScriptDataDoubleEscapedLessThanSignState, tsScriptDataDoubleEscapeEndState, tsBeforeAttributeNameState, tsAttributeNameState, tsAfterAttributeNameState, tsBeforeAttributeValueState, tsAttributeValueDoubleQuotedState, tsAttributeValueSingleQuotedState, tsAttributeValueUnquotedState, {tsCharacterReferenceInAttributeValueState,} tsAfterAttributeValueQuotedState, tsSelfClosingStartTagState, tsBogusCommentState, tsMarkupDeclarationOpenState, tsCommentStartState, tsCommentStartDashState, tsCommentState, tsCommentEndDashState, tsCommentEndState, tsCommentEndBangState, tsDoctypeState, tsBeforeDoctypeNameState, tsDoctypeNameState, tsAfterDoctypeNameState, tsAfterDoctypePublicKeywordState, tsBeforeDoctypePublicIdentifierState, tsDoctypePublicIdentifierDoubleQuotedState, tsDoctypePublicIdentifierSingleQuotedState, tsAfterDoctypePublicIdentifierState, tsBetweenDoctypePublicAndSystemIdentifiersState, tsAfterDoctypeSystemKeywordState, tsBeforeDoctypeSystemIdentifierState, tsDoctypeSystemIdentifierDoubleQuotedState, tsDoctypeSystemIdentifierSingleQuotedState, tsAfterDoctypeSystemIdentifierState, tsBogusDoctypeState, tsCdataSectionState); TTokenKind = (tkNone, tkDOCTYPE, tkStartTag, tkEndTag, tkSourceCharacters, tkExtraCharacters, tkExtraSpaceCharacter, tkNullCharacter, tkComment, tkEOF); TToken = record // this is an expensive type, as it is basically all token types at once, so don't create many {$IFDEF PARSEERROR} strict private type TTokenParseErrorCallback = procedure (Message: UTF8String; const Count: Cardinal = 1) of object; var FOnParseError: TTokenParseErrorCallback; {$ENDIF} public Kind: TTokenKind; Ready: Boolean; {$IFDEF PARSEERROR} procedure Init(NewOnParseError: TTokenParseErrorCallback); {$ENDIF} procedure Reset(); procedure Destroy(); procedure Emit(); public // tkDOCTYPE DOCTYPEName, PublicID, SystemID: TParserString; DOCTYPENamePresent, PublicIDPresent, SystemIDPresent, ForceQuirksFlag: Boolean; procedure PrepareDOCTYPE(); public // tkStartTag, tkEndTag DraftTagName: TWire; // only for writing TagName: TCanonicalString; // only for reading SelfClosingFlag: Boolean; {$IFDEF PARSEERROR} SelfClosingAcknowledged: Boolean; {$ENDIF} CurrentAttributeName: TWire; CurrentAttributeValue: TParserString; strict private FAttributes: TElement.TAttributeHashTable; procedure PrepareTag(const NewKind: TTokenKind); procedure SaveAttribute(); inline; procedure ReplaceAttribute(const OldName, NewName: UTF8String); inline; public procedure PrepareStartTag(); inline; procedure PrepareEndTag(); inline; procedure RetractTag(); inline; procedure PrepareAttribute(); inline; {$IFDEF PARSEERROR} procedure AcknowledgeSelfClosingFlag(); inline; {$ENDIF} function TakeAttributes(): TElement.TAttributeHashTable; inline; function GetAttribute(const AttributeName: UTF8String): UTF8String; function HasAttributes(const AttributeNames: array of UTF8String): Boolean; procedure AdjustMathMLAttributes(); procedure AdjustSVGAttributes(); procedure AdjustForeignAttributes(); public // Source Characters type TSpaceState = (ssHaveLeadingSpace, ssHaveNonSpace, ssMightHaveNonLeadingSpace); var HavePendingCharacters: Boolean; SpaceState: set of TSpaceState; // if you append source characters with a gap between subsequent pointers, the characters between the pointers // will be added; they will be assumed to be non-space if you call AppendSourceNonSpaceCharacter(), and // space if you call AppendSourceSpaceCharacter(); but only do this from AppendFromBookmarkedCharacterToInputCharacter()! {$IFOPT C-} strict private {$ENDIF} FCharStart, FCharEnd: TParserStringPointer; public procedure AppendSourceNonSpaceCharacter(constref NewPointer: TParserStringPointer); inline; procedure AppendSourceSpaceCharacter(constref NewPointer: TParserStringPointer); inline; procedure AppendSourceNonSpaceBetweenBookmarks(constref StartPointer, EndPointer: TParserStringPointer); procedure EmitSourceCharacters(); // flushes the token if HavePendingCharacters procedure SkipLeadingSpaces(constref Data: TParserString); function SkipLeadingNonSpaces(constref Data: TParserString): Cardinal; function SkipOneLeadingNewline(constref Data: TParserString): Boolean; inline; // returns true if there's still more characters to deal with function ExtractLeadingSpaces(constref Data: TParserString): TCutParserString; // mutates self function ExtractSourceCharacters(constref Data: TParserString): TCutParserString; inline; // doesn't mutate self function GetCharacterCount(constref Data: TParserString): Cardinal; inline; // expensive public // Extra Characters ExtraChars: TUnicodeCodepointArray; procedure EmitExtraSpaceCharacter(const Character: TUnicodeCodepoint); inline; procedure EmitExtraNonSpaceCharacter(const Character: TUnicodeCodepoint); inline; procedure EmitExtraAmbiguousCharacters(const Characters: TUnicodeCodepointArray); inline; procedure EmitNullCharacter(); inline; public // Comment CommentValue: TParserString; procedure PrepareComment(); inline; public // tkEOF procedure EmitEOF(); end; TInsertionModeHandler = procedure (var Token: TToken) of object; TInsertionModeHandlerUtils = specialize DefaultUnorderedUtils <TInsertionModeHandler>; const Marker = nil; var FProprietaryVoids: specialize PlasticArray <TCanonicalString, TCanonicalString>; FInputStream: TInputStream; {$IFDEF PARSEERROR} FOnParseError: TParseErrorHandler; {$ENDIF} FTokeniserState: TTokeniserState; FCurrentToken: TToken; // only access this from tokeniser code; tree construction code should pass the Token in arguments FInsertionMode, FOriginalInsertionMode: TInsertionModeHandler; FDocument: TDocument; FStackOfTemplateInsertionModes: specialize PlasticArray<TInsertionModeHandler, TInsertionModeHandlerUtils>; FContextElement, FHeadElementPointer, FFormElementPointer: TElement; FLastStartTag: UTF8String; FTemporaryBuffer: TWire; FPendingTableCharacterTokensList: TParserString; FStackOfOpenElements: specialize PlasticArray<TElement, TObjectUtils>; FListOfActiveFormattingElements: specialize PlasticArray<TElement, TObjectUtils>; FFosterParenting: Boolean; // only true while processing the "anything else" clause of TheInTableInsertionMode FFramesetOkFlag: Boolean; FFragmentParsingMode, FScriptingFlag: Boolean; FPendingTableCharacterTokensListHasNonSpaces: Boolean; // only useful in TheInTableTextInsertionMode {$IFDEF PARSEERROR} procedure ParseError(Message: UTF8String; const Count: Cardinal = 1); {$ENDIF} procedure TreeConstructionDispatcher(var Token: TToken); inline; function StackOfOpenElementsHas(constref Namespace, LocalName: TCanonicalString): Boolean; function StackOfOpenElementsHasElementOtherThan(const TargetProperty: TElementProperties): Boolean; function StackOfOpenElementsHasInSpecificScope(constref Target: TCanonicalString; const ParticularScope: TElementProperties): Boolean; // nsHTML is assumed for Target function StackOfOpenElementsHasInSpecificScope(const Target: TElementProperties; const ParticularScope: TElementProperties): Boolean; function StackOfOpenElementsHasInSpecificScope(const Target: TElement; const ParticularScope: TElementProperties): Boolean; function StackOfOpenElementsHasInScope(constref Target: TCanonicalString): Boolean; inline; function StackOfOpenElementsHasInScope(const Target: TElementProperties): Boolean; inline; function StackOfOpenElementsHasInScope(const Target: TElement): Boolean; inline; function StackOfOpenElementsHasInListItemScope(constref Target: TCanonicalString): Boolean; inline; function StackOfOpenElementsHasInButtonScope(constref Target: TCanonicalString): Boolean; inline; function StackOfOpenElementsHasInTableScope(constref Target: TCanonicalString): Boolean; inline; function StackOfOpenElementsHasInTableScope(const Target: TElementProperties): Boolean; inline; function StackOfOpenElementsHasInSelectScope(constref Target: TCanonicalString): Boolean; inline; procedure InsertMarkerAtEndOfListOfActiveFormattingElements(); inline; procedure PushOntoTheListOfActiveFormattingElements(const Target: TElement); procedure ReconstructTheActiveFormattingElements(); procedure ClearTheListOfActiveFormattingElementsUpToTheLastMarker(); inline; procedure Tokenise(); function GetCurrentNode(): TElement; inline; // don't call directly, use CurrentNode function GetAdjustedCurrentNode(): TElement; inline; // don't call directly, use AdjustedCurrentNode procedure InsertNodeAtAppropriatePlaceForInsertingANode(const Node: TNode; Target: TElement = nil); function CreateAnElementFor(constref Token: TToken; constref Namespace: TCanonicalString): TElement; function InsertAForeignElementFor(constref Token: TToken; constref Namespace: TCanonicalString): TElement; function InsertAForeignElement(const Element: TElement): TElement; function InsertAnHTMLElementFor(constref Token: TToken): TElement; inline; function InsertAnHTMLElement(const Element: TElement): TElement; inline; procedure InsertCharacters(var Data: TCutParserString); {$IFDEF USEROPES} procedure InsertCharacters(var Data: TParserString); {$ENDIF} procedure InsertCharacters(const Data: UTF8String); procedure InsertCharacters(const Data: TUnicodeCodepointArray); inline; procedure InsertCharactersFor(constref Token: TToken); inline; procedure InsertLeadingSpacesFor(var Token: TToken); inline; function CreateACommentFor(var Token: TToken): TComment; inline; procedure InsertAComment(var Token: TToken); inline; procedure ResetTheInsertionModeAppropriately(); procedure GenericRCDataElementParsingAlgorithm(constref Token: TToken); procedure GenericRawTextElementParsingAlgorithm(constref Token: TToken); procedure GenerateImpliedEndTags(); inline; procedure GenerateAllImpliedEndTagsThoroughly(); inline; procedure GenerateImpliedEndTagsExceptFor(constref Exception: TCanonicalString); inline; procedure TheInitialInsertionMode(var Token: TToken); procedure TheBeforeHTMLInsertionMode(var Token: TToken); procedure TheBeforeHeadInsertionMode(var Token: TToken); procedure TheInHeadInsertionMode(var Token: TToken); procedure TheInHeadNoScriptInsertionMode(var Token: TToken); procedure TheAfterHeadInsertionMode(var Token: TToken); procedure TheInBodyInsertionMode(var Token: TToken); procedure TheTextInsertionMode(var Token: TToken); procedure TheInTableInsertionMode(var Token: TToken); procedure TheInTableTextInsertionMode(var Token: TToken); procedure TheInCaptionInsertionMode(var Token: TToken); procedure TheInColumnGroupInsertionMode(var Token: TToken); procedure TheInTableBodyInsertionMode(var Token: TToken); procedure TheInRowInsertionMode(var Token: TToken); procedure TheInCellInsertionMode(var Token: TToken); procedure TheInSelectInsertionMode(var Token: TToken); procedure TheInSelectInTableInsertionMode(var Token: TToken); procedure TheInTemplateInsertionMode(var Token: TToken); procedure TheAfterBodyInsertionMode(var Token: TToken); procedure TheInFramesetInsertionMode(var Token: TToken); procedure TheAfterFramesetInsertionMode(var Token: TToken); procedure TheAfterAfterBodyInsertionMode(var Token: TToken); procedure TheAfterAfterFramesetInsertionMode(var Token: TToken); procedure TheSkipNewLineInsertionMode(var Token: TToken); procedure TheSkipNewLineThenTextInsertionMode(var Token: TToken); procedure TheRulesForParsingTokensInForeignContent(var Token: TToken); property CurrentNode: TElement read GetCurrentNode; // only check this if there is one property AdjustedCurrentNode: TElement read GetAdjustedCurrentNode; // only check this if there is one public constructor Create(); destructor Destroy(); override; {$IFNDEF USEROPES} procedure SpoonFeed(const Data: UTF8String); // call this any number of times until all characters have been provided {$ENDIF} procedure SpoonFeed(const Data: Pointer; const Length: QWord); // call this any number of times until all characters have been provided procedure RegisterProperietaryVoidElements(const TagNames: array of TCanonicalString); function Parse(): TDocument; // then call this // XXX need a fragment parsing mode (if we support fragment parsing, set FFragmentParsingMode to true) {$IFDEF PARSEERROR} property OnParseError: TParseErrorHandler read FOnParseError write FOnParseError; {$ENDIF} property ScriptingEnabled: Boolean read FScriptingFlag write FScriptingFlag; end; {$IF DEFINED(VERBOSETABLE) OR DEFINED(VERBOSETOKENISER) OR DEFINED(VERBOSEENUMERATOR) OR DEFINED(VERBOSEAAA) OR DEFINED(VERBOSETEXT)} var DebugNow: Boolean = False; {$ENDIF} implementation uses exceptions, entities, sysutils, specutils; const forever = False; function PrefixMatch(const Value, Candidate: UTF8String): Boolean; type TBlob = Pointer; PBlobArray = ^TBlobArray; TBlobArray = array[0..0] of TBlob; var Steps, EndOfBlobs: Cardinal; Index: Cardinal; Blob1, Blob2: PBlobArray; begin Assert(Length(Candidate) > 0); if (Length(Candidate) > Length(Value)) then begin Result := False; exit; end; Assert(Length(Value) >= Length(Candidate)); Assert(Length(Candidate) > 0); Assert(SizeOf(TBlob) > 0); Steps := Length(Candidate) div SizeOf(TBlob); // $R- if (Steps > 0) then begin Blob1 := PBlobArray(@Value[1]); Blob2 := PBlobArray(@Candidate[1]); for Index := 0 to Steps-1 do // $R- if (Blob1^[Index] <> Blob2^[Index]) then begin Result := False; exit; end; Assert(High(EndOfBlobs) > Length(Candidate)); EndOfBlobs := Steps * SizeOf(TBlob); // $R- end else begin EndOfBlobs := 0; end; if (EndOfBlobs < Length(Candidate)) then for Index := EndOfBlobs+1 to Length(Candidate) do // $R- if (Value[Index] <> Candidate[Index]) then begin Result := False; exit; end; Result := True; end; function IsSpaceCharacter(const Candidate: TUnicodeCodepoint): Boolean; begin Assert(Candidate <> $0000); case (Candidate.Value) of $0009, $000A, $000C, $000D, $0020: Result := True; else Result := False; end; end; {$IFOPT C+} function IsSpaceCharacter(const Candidate: Byte): Boolean; begin Assert(Candidate <> $00); case (Candidate) of $09, $0A, $0C, $0D, $20: Result := True; else Result := False; end; end; {$ENDIF} function THTMLParser.TInputStream.TBookmark.GetFlag(const Flag: TInputStreamFlag): Boolean; begin Result := Flag in FInputStreamFlags; end; function THTMLParser.TInputStream.TBookmark.GetPointer(): TParserStringPointer; begin Result := FPosition; end; constructor THTMLParser.TInputStream.Create(); begin inherited; {$IFDEF LINES} FLine := 1; FColumn := 1; {$ENDIF} end; destructor THTMLParser.TInputStream.Destroy(); begin FEnumerator.Free(); inherited; end; {$IFNDEF USEROPES} function THTMLParser.TInputStream.GetCurrentCharacterLength(): TUTF8SequenceLength; inline; begin Assert(Assigned(FEnumerator)); Result := FEnumerator.CurrentLength; end; procedure THTMLParser.TInputStream.PushData(const NewData: UTF8String); begin {$IFOPT C+} Assert(not (isStarted in FInputStreamFlags)); {$ENDIF} Assert(not Assigned(FEnumerator)); FData.Append(@NewData); end; {$ENDIF} procedure THTMLParser.TInputStream.PushData(const NewData: Pointer; const NewLength: QWord); begin {$IFOPT C+} Assert(not (isStarted in FInputStreamFlags)); {$ENDIF} Assert(not Assigned(FEnumerator)); FData.Append(NewData, NewLength); end; procedure THTMLParser.TInputStream.Freeze(); begin {$IFOPT C+} Assert(not (isStarted in FInputStreamFlags)); {$ENDIF} Assert(not Assigned(FEnumerator)); FEnumerator := TParserStringEnumerator.Create(@FData); end; procedure THTMLParser.TInputStream.Advance(); begin Assert(Assigned(FEnumerator)); {$IFOPT C+} Include(FInputStreamFlags, isStarted); {$ENDIF} if (isPreConsumed in FInputStreamFlags) then begin Exclude(FInputStreamFlags, isPreConsumed); {$IFDEF VERBOSEENUMERATOR} if (DebugNow) then Writeln('Advance(): preconsumed - exiting with ', FLastInputCharacter.GetDebugDescription()); {$ENDIF} exit; end; {$IFOPT C+} Assert(not (isSeenEOF in FInputStreamFlags)); {$ENDIF} Exclude(FInputStreamFlags, isManipulated); repeat {$IFDEF VERBOSEENUMERATOR} if (DebugNow) then Writeln('Advance(): calling MoveNext() at ', FLine, ':', FColumn); {$ENDIF} if (not FEnumerator.MoveNext()) then begin {$IFDEF VERBOSEENUMERATOR} if (DebugNow) then Writeln('Advance(): MoveNext() returned false'); {$ENDIF} FLastInputCharacter := kEOF; Include(FInputStreamFlags, isManipulated); {$IFOPT C+} Include(FInputStreamFlags, isSeenEOF); {$ENDIF} end else begin FLastInputCharacter := FEnumerator.Current; {$IFDEF VERBOSEENUMERATOR} if (DebugNow) then Writeln('Advance(): Current is ', FLastInputCharacter.GetDebugDescription()); {$ENDIF} // CRLF handling if (FLastInputCharacter = $000D) then begin // turn CR into LF {$IFDEF VERBOSEENUMERATOR} if (DebugNow) then Writeln('Advance(): turning CR into LF'); {$ENDIF} FLastInputCharacter := $000A; Include(FInputStreamFlags, isManipulated); Include(FInputStreamFlags, isAteCR); end else if (isAteCR in FInputStreamFlags) then begin {$IFDEF VERBOSEENUMERATOR} if (DebugNow) then Writeln('Advance(): checking if this is an LF, since last we saw a CR'); {$ENDIF} // skip LF if following CR Exclude(FInputStreamFlags, isAteCR); if (FLastInputCharacter = $000A) then begin {$IFDEF VERBOSEENUMERATOR} if (DebugNow) then Writeln('Advance(): yup, this is an LF; looping over to MoveNext() again'); {$ENDIF} continue; end; end; {$IFDEF LINES} // count lines if (FLastInputCharacter = $000A) then begin {$IFDEF VERBOSEENUMERATOR} if (DebugNow) then Writeln('Advance(): incrementing line...'); {$ENDIF} Inc(FLine); FColumn := 1; end else Inc(FColumn); {$ENDIF} end; exit; until forever; {$IFDEF VERBOSEENUMERATOR} if (DebugNow) then Writeln('Advance(): exiting with ', FLastInputCharacter.GetDebugDescription()); {$ENDIF} end; function THTMLParser.TInputStream.GetFlag(const Flag: TInputStreamFlag): Boolean; begin Result := Flag in FInputStreamFlags; end; {$IFDEF PARSEERROR} procedure THTMLParser.TInputStream.NotedThatInputIsBad(); begin Include(FInputStreamFlags, isBadAlreadyNoted); end; {$ENDIF} function THTMLParser.TInputStream.GetBookmark(): TBookmark; begin {$IFDEF VERBOSEENUMERATOR} if (DebugNow) then Writeln('GetBookmark() - GetPointer()'); {$ENDIF} Assert(Assigned(FEnumerator)); Result.FPosition := FEnumerator.GetPointer(); Result.FLastInputCharacter := FLastInputCharacter; Result.FInputStreamFlags := FInputStreamFlags; {$IFOPT C+} Result.FPosition.AssertIdentity(@FData); {$ENDIF} end; {$IFOPT C+} function THTMLParser.TInputStream.GetDebugData(): UTF8String; function GetPos(): UTF8String; begin Result := 'L' + IntToStr(FLine) + ' C' + IntToStr(FColumn); end; begin if (FLastInputCharacter = kEOF) then Result := '[EOF ' + GetPos() + ']' else Result := CodepointToUTF8(FLastInputCharacter) + ' (' + GetPos() + ')'; end; {$ENDIF} procedure THTMLParser.TInputStream.ReturnToBookmark(constref NewPosition: TBookmark); begin {$IFDEF VERBOSEENUMERATOR} if (DebugNow) then Writeln('ReturnToBookmark() - ReturnToPointer()'); {$ENDIF} Assert(Assigned(FEnumerator)); FEnumerator.ReturnToPointer(NewPosition.FPosition); FLastInputCharacter := NewPosition.FLastInputCharacter; FInputStreamFlags := NewPosition.FInputStreamFlags; end; procedure THTMLParser.TInputStream.Unconsume(); begin Assert(not (isPreConsumed in FInputStreamFlags)); Include(FInputStreamFlags, isPreConsumed); end; function THTMLParser.TInputStream.Extract(constref NewStart, NewEnd: TParserStringPointer): TCutParserString; begin Result := FData.Extract(NewStart, NewEnd); end; function THTMLParser.TInputStream.GetPointer(): TParserStringPointer; inline; begin {$IFDEF VERBOSEENUMERATOR} if (DebugNow) then Writeln('GetPointer() - GetPointer()'); {$ENDIF} Assert(Assigned(FEnumerator)); Result := FEnumerator.GetPointer(); end; {$IFNDEF USEROPES} function THTMLParser.TInputStream.GetRawPointer(): Pointer; inline; begin {$IFDEF VERBOSEENUMERATOR} if (DebugNow) then Writeln('GetRawPointer() - GetRawPointer'); {$ENDIF} Assert(Assigned(FEnumerator)); Result := FEnumerator.GetRawPointer(); end; {$ENDIF} {$IFDEF PARSEERROR} procedure THTMLParser.TToken.Init(NewOnParseError: TTokenParseErrorCallback); begin FOnParseError := NewOnParseError; Assert(Assigned(FOnParseError)); end; {$ENDIF} procedure THTMLParser.TToken.Reset(); begin {$IFDEF PARSEERROR} Assert(Assigned(FOnParseError)); {$ENDIF} Assert(Kind <> tkNone); if (Kind in [tkStartTag, tkEndTag]) then begin if (Assigned(FAttributes)) then FAttributes.Empty(); end; Kind := tkNone; HavePendingCharacters := False; SpaceState := []; Ready := False; end; procedure THTMLParser.TToken.Destroy(); begin {$IFDEF PARSEERROR} Assert(Assigned(FOnParseError)); {$ENDIF} FAttributes.Free(); end; procedure THTMLParser.TToken.Emit(); begin {$IFDEF PARSEERROR} Assert(Assigned(FOnParseError)); {$ENDIF} Assert(Kind in [tkDOCTYPE, tkStartTag, tkEndTag, tkComment]); if (Kind in [tkStartTag, tkEndTag]) then begin TagName := Intern(DraftTagName.AsString); if (not CurrentAttributeName.IsEmpty) then SaveAttribute(); {$IFDEF PARSEERROR} if (Kind = tkEndTag) then begin if (Assigned(FAttributes) and (FAttributes.Count > 0)) then FOnParseError('End tag had attributes'); if (SelfClosingFlag) then FOnParseError('End tag had trailing slash'); end; {$ENDIF} end; Assert(Kind in [tkDOCTYPE, tkStartTag, tkEndTag, tkComment]); Ready := True; end; procedure THTMLParser.TToken.PrepareDOCTYPE(); begin Assert(Kind = tkNone); Kind := tkDOCTYPE; DOCTYPENamePresent := False; DOCTYPEName := Default(TParserString); PublicIDPresent := False; PublicID := Default(TParserString); SystemIDPresent := False; SystemID := Default(TParserString); ForceQuirksFlag := False; end; procedure THTMLParser.TToken.PrepareTag(const NewKind: TTokenKind); begin Assert(Kind = tkNone); Kind := NewKind; DraftTagName.Init(); SelfClosingFlag := False; {$IFDEF PARSEERROR} SelfClosingAcknowledged := False; {$ENDIF} CurrentAttributeName.Init(); end; procedure THTMLParser.TToken.SaveAttribute(); var CachedAttributeName: UTF8String; begin {$IFDEF PARSEERROR} Assert(Assigned(FOnParseError)); {$ENDIF} Assert(not CurrentAttributeName.IsEmpty); CachedAttributeName := CurrentAttributeName.AsString; if (not Assigned(FAttributes)) then FAttributes := TElement.TAttributeHashTable.Create() else if (FAttributes.Has(CachedAttributeName)) then begin {$IFDEF PARSEERROR} FOnParseError('duplicate attribute ("' + CachedAttributeName + '")'); {$ENDIF} exit; end; FAttributes.Add(CachedAttributeName, CurrentAttributeValue); CurrentAttributeName.Init(); CurrentAttributeValue := Default(TParserString); end; procedure THTMLParser.TToken.PrepareStartTag(); begin PrepareTag(tkStartTag); end; procedure THTMLParser.TToken.PrepareEndTag(); begin PrepareTag(tkEndTag); end; procedure THTMLParser.TToken.RetractTag(); begin Assert(Kind in [tkStartTag, tkEndTag]); {$IFOPT C+} Kind := tkNone; {$ENDIF} Assert(not Ready); end; procedure THTMLParser.TToken.PrepareAttribute(); begin if (not CurrentAttributeName.IsEmpty) then begin SaveAttribute(); CurrentAttributeName.Init(); CurrentAttributeValue := Default(TParserString); end; Assert(CurrentAttributeValue.IsEmpty); end; {$IFDEF PARSEERROR} procedure THTMLParser.TToken.AcknowledgeSelfClosingFlag(); begin Assert(Kind = tkStartTag); SelfClosingAcknowledged := True; end; {$ENDIF} function THTMLParser.TToken.TakeAttributes(): TElement.TAttributeHashTable; begin if (Assigned(FAttributes) and (FAttributes.Count > 0)) then begin Result := FAttributes; FAttributes := nil; end else begin Result := nil; end; end; function THTMLParser.TToken.GetAttribute(const AttributeName: UTF8String): UTF8String; begin if (Assigned(FAttributes)) then Result := FAttributes[AttributeName].AsString else Result := ''; end; function THTMLParser.TToken.HasAttributes(const AttributeNames: array of UTF8String): Boolean; var Name: UTF8String; begin if (Assigned(FAttributes)) then for Name in AttributeNames do // http://bugs.freepascal.org/view.php?id=25703 if (FAttributes.Has(Name)) then begin Result := True; exit; end; Result := False; end; procedure THTMLParser.TToken.ReplaceAttribute(const OldName, NewName: UTF8String); begin if (FAttributes.Has(OldName)) then begin FAttributes[NewName] := FAttributes[OldName]; FAttributes.Remove(OldName); end; end; procedure THTMLParser.TToken.AdjustMathMLAttributes(); begin if (not Assigned(FAttributes)) then exit; ReplaceAttribute('definitionurl', 'definitionURL'); end; procedure THTMLParser.TToken.AdjustSVGAttributes(); begin if (not Assigned(FAttributes)) then exit; ReplaceAttribute('attributename', 'attributeName'); ReplaceAttribute('attributetype', 'attributeType'); ReplaceAttribute('basefrequency', 'baseFrequency'); ReplaceAttribute('baseprofile', 'baseProfile'); ReplaceAttribute('calcmode', 'calcMode'); ReplaceAttribute('clippathunits', 'clipPathUnits'); ReplaceAttribute('diffuseconstant', 'diffuseConstant'); ReplaceAttribute('edgemode', 'edgeMode'); ReplaceAttribute('filterunits', 'filterUnits'); ReplaceAttribute('glyphref', 'glyphRef'); ReplaceAttribute('gradienttransform', 'gradientTransform'); ReplaceAttribute('gradientunits', 'gradientUnits'); ReplaceAttribute('kernelmatrix', 'kernelMatrix'); ReplaceAttribute('kernelunitlength', 'kernelUnitLength'); ReplaceAttribute('keypoints', 'keyPoints'); ReplaceAttribute('keysplines', 'keySplines'); ReplaceAttribute('keytimes', 'keyTimes'); ReplaceAttribute('lengthadjust', 'lengthAdjust'); ReplaceAttribute('limitingconeangle', 'limitingConeAngle'); ReplaceAttribute('markerheight', 'markerHeight'); ReplaceAttribute('markerunits', 'markerUnits'); ReplaceAttribute('markerwidth', 'markerWidth'); ReplaceAttribute('maskcontentunits', 'maskContentUnits'); ReplaceAttribute('maskunits', 'maskUnits'); ReplaceAttribute('numoctaves', 'numOctaves'); ReplaceAttribute('pathlength', 'pathLength'); ReplaceAttribute('patterncontentunits', 'patternContentUnits'); ReplaceAttribute('patterntransform', 'patternTransform'); ReplaceAttribute('patternunits', 'patternUnits'); ReplaceAttribute('pointsatx', 'pointsAtX'); ReplaceAttribute('pointsaty', 'pointsAtY'); ReplaceAttribute('pointsatz', 'pointsAtZ'); ReplaceAttribute('preservealpha', 'preserveAlpha'); ReplaceAttribute('preserveaspectratio', 'preserveAspectRatio'); ReplaceAttribute('primitiveunits', 'primitiveUnits'); ReplaceAttribute('refx', 'refX'); ReplaceAttribute('refy', 'refY'); ReplaceAttribute('repeatcount', 'repeatCount'); ReplaceAttribute('repeatdur', 'repeatDur'); ReplaceAttribute('requiredextensions', 'requiredExtensions'); ReplaceAttribute('requiredfeatures', 'requiredFeatures'); ReplaceAttribute('specularconstant', 'specularConstant'); ReplaceAttribute('specularexponent', 'specularExponent'); ReplaceAttribute('spreadmethod', 'spreadMethod'); ReplaceAttribute('startoffset', 'startOffset'); ReplaceAttribute('stddeviation', 'stdDeviation'); ReplaceAttribute('stitchtiles', 'stitchTiles'); ReplaceAttribute('surfacescale', 'surfaceScale'); ReplaceAttribute('systemlanguage', 'systemLanguage'); ReplaceAttribute('tablevalues', 'tableValues'); ReplaceAttribute('targetx', 'targetX'); ReplaceAttribute('targety', 'targetY'); ReplaceAttribute('textlength', 'textLength'); ReplaceAttribute('viewbox', 'viewBox'); ReplaceAttribute('viewtarget', 'viewTarget'); ReplaceAttribute('xchannelselector', 'xChannelSelector'); ReplaceAttribute('ychannelselector', 'yChannelSelector'); ReplaceAttribute('zoomandpan', 'zoomAndPan'); end; procedure THTMLParser.TToken.AdjustForeignAttributes(); begin if (not Assigned(FAttributes)) then exit; // since we don't support attribute namespaces natively, instead we use // the form '<namespaceid> <attributelocalname>' and don't use prefixes ReplaceAttribute('xlink:actuate', 'xlink actuate'); ReplaceAttribute('xlink:arcrole', 'xlink arcrole'); ReplaceAttribute('xlink:href', 'xlink href'); ReplaceAttribute('xlink:role', 'xlink role'); ReplaceAttribute('xlink:show', 'xlink show'); ReplaceAttribute('xlink:title', 'xlink title'); ReplaceAttribute('xlink:type', 'xlink type'); ReplaceAttribute('xml:base', 'xml base'); ReplaceAttribute('xml:lang', 'xml lang'); ReplaceAttribute('xml:space', 'xml space'); ReplaceAttribute('xmlns', 'xmlns xmlns'); ReplaceAttribute('xmlns:xlink', 'xmlns xlink'); end; procedure THTMLParser.TToken.AppendSourceNonSpaceCharacter(constref NewPointer: TParserStringPointer); begin Assert(Kind = tkNone); {$IFOPT C+} Assert((not NewPointer.IsZeroWidth()) or (NewPointer.IsEOF())); {$ENDIF} {$IFNDEF USEROPES} {$IFOPT C+} Assert(NewPointer.IsEOF() or not IsSpaceCharacter(NewPointer.GetByte())); {$ENDIF} {$ENDIF} if (not HavePendingCharacters) then begin {$IFOPT C+} Assert(not NewPointer.IsEOF()); {$ENDIF} Assert(SpaceState = []); HavePendingCharacters := True; FCharStart := NewPointer; end; Include(SpaceState, ssHaveNonSpace); FCharEnd := NewPointer; end; procedure THTMLParser.TToken.AppendSourceSpaceCharacter(constref NewPointer: TParserStringPointer); begin Assert(Kind = tkNone); {$IFOPT C+} Assert((not NewPointer.IsZeroWidth()) or (NewPointer.IsEOF())); {$ENDIF} {$IFNDEF USEROPES} {$IFOPT C+} Assert(NewPointer.IsEOF() or IsSpaceCharacter(NewPointer.GetByte())); {$ENDIF} {$ENDIF} if (not HavePendingCharacters) then begin {$IFOPT C+} Assert(not NewPointer.IsEOF()); {$ENDIF} Assert(SpaceState = []); HavePendingCharacters := True; Include(SpaceState, ssHaveLeadingSpace); FCharStart := NewPointer; end else begin Assert(SpaceState * [ssHaveLeadingSpace, ssHaveNonSpace] <> []); Include(SpaceState, ssMightHaveNonLeadingSpace); end; FCharEnd := NewPointer; end; procedure THTMLParser.TToken.AppendSourceNonSpaceBetweenBookmarks(constref StartPointer, EndPointer: TParserStringPointer); begin if (not HavePendingCharacters) then begin Assert(SpaceState = []); FCharStart := StartPointer; HavePendingCharacters := True; end; {$IFOPT C+} // XXX should assert no spaces in this string, using IsSpaceCharacter(StartPointer.GetByte()) and an enumerator walking it {$ENDIF} Include(SpaceState, ssHaveNonSpace); FCharEnd := EndPointer; end; procedure THTMLParser.TToken.EmitSourceCharacters(); begin Assert(Kind = tkNone); if (HavePendingCharacters) then begin Assert(SpaceState * [ssHaveLeadingSpace, ssHaveNonSpace] <> []); Kind := tkSourceCharacters; Ready := True; end else Assert(SpaceState = []); end; procedure THTMLParser.TToken.SkipLeadingSpaces(constref Data: TParserString); begin Assert(HavePendingCharacters); Assert(ssHaveLeadingSpace in SpaceState); Assert(ssHaveNonSpace in SpaceState); {$IFDEF USEROPES} repeat FCharStart.AdvanceToNext(); until not IsSpaceCharacter(FCharStart.CurrentCharacter); {$ELSE} while (IsSpaceCharacter(FCharStart.AdvanceToNext(Data))) do ; {$ENDIF} Assert(FCharStart <= FCharEnd); Exclude(SpaceState, ssHaveLeadingSpace); end; function THTMLParser.TToken.SkipLeadingNonSpaces(constref Data: TParserString): Cardinal; begin Assert(HavePendingCharacters); Assert(not (ssHaveLeadingSpace in SpaceState)); Assert(ssHaveNonSpace in SpaceState); Assert(FCharStart <= FCharEnd); {$IFOPT C+} Assert((not FCharStart.IsZeroWidth()) or (FCharStart.IsEOF())); {$ENDIF} {$IFOPT C+} Assert((not FCharEnd.IsZeroWidth()) or (FCharEnd.IsEOF())); {$ENDIF} Result := 1; while (FCharStart < FCharEnd) do begin {$IFDEF USEROPES} FCharStart.AdvanceToNext(); if (IsSpaceCharacter(FCharStart.CurrentCharacter)) then {$ELSE} if (IsSpaceCharacter(FCharStart.AdvanceToNext(Data))) then {$ENDIF} begin Include(SpaceState, ssHaveLeadingSpace); exit; end; Inc(Result); end; Assert(FCharStart = FCharEnd); // which would mean we're holding one character, a non-space, which we're now skipping HavePendingCharacters := False; end; function THTMLParser.TToken.SkipOneLeadingNewline(constref Data: TParserString): Boolean; begin Assert(HavePendingCharacters); {$IFOPT C+} Assert((not FCharStart.IsZeroWidth()) or (FCharStart.IsEOF())); {$ENDIF} {$IFOPT C+} Assert((not FCharEnd.IsZeroWidth()) or (FCharEnd.IsEOF())); {$ENDIF} if (ssHaveLeadingSpace in SpaceState) then begin {$IFOPT C+} Assert(not FCharStart.IsEOF()); {$ENDIF} {$IFOPT C+} Assert(FCharStart <= FCharEnd); {$ENDIF} {$IFDEF USERPOPES} FCharStart.ReadCurrent(); if (FCharStart.CurrentCharacter = $000A) then {$ELSE} if (Data.Extract(FCharStart, FCharStart).AsString = Chr($0A)) then {$ENDIF} begin {$IFDEF USEROPES} FCharStart.AdvanceToNext(); if (not IsSpaceCharacter(FCharStart.CurrentCharacter)) then {$ELSE} if (not IsSpaceCharacter(FCharStart.AdvanceToNext(Data))) then {$ENDIF} Exclude(SpaceState, ssHaveLeadingSpace); HavePendingCharacters := FCharStart <= FCharEnd; end; end; Result := HavePendingCharacters; end; function THTMLParser.TToken.ExtractLeadingSpaces(constref Data: TParserString): TCutParserString; var OriginalFCharStart, LeadingSpacesEnd: TParserStringPointer; begin Assert(HavePendingCharacters); Assert(ssHaveLeadingSpace in SpaceState); Assert(ssHaveNonSpace in SpaceState); OriginalFCharStart := FCharStart; {$IFDEF USEROPES} repeat FCharStart.AdvanceToNext(); until not IsSpaceCharacter(FCharStart.CurrentCharacter); {$ELSE} while (IsSpaceCharacter(FCharStart.AdvanceToNext(Data))) do ; {$ENDIF} Assert(FCharStart <= FCharEnd); Assert(OriginalFCharStart < FCharStart); LeadingSpacesEnd := FCharStart; LeadingSpacesEnd.SetToZeroWidth(); Result := Data.Extract(OriginalFCharStart, LeadingSpacesEnd); Exclude(SpaceState, ssHaveLeadingSpace); end; function THTMLParser.TToken.ExtractSourceCharacters(constref Data: TParserString): TCutParserString; begin Assert(HavePendingCharacters); Assert(FCharStart <= FCharEnd); Result := Data.Extract(FCharStart, FCharEnd); end; function THTMLParser.TToken.GetCharacterCount(constref Data: TParserString): Cardinal; begin Assert(HavePendingCharacters); Assert(FCharStart <= FCharEnd); Result := Data.CountCharacters(FCharStart, FCharEnd); end; procedure THTMLParser.TToken.EmitExtraSpaceCharacter(const Character: TUnicodeCodepoint); begin Assert(Kind = tkNone); {$IFOPT C+} Assert(IsSpaceCharacter(Character)); {$ENDIF} Kind := tkExtraSpaceCharacter; SetLength(ExtraChars, 1); ExtraChars[0] := Character; Assert(Kind <> tkNone); Ready := True; end; procedure THTMLParser.TToken.EmitExtraNonSpaceCharacter(const Character: TUnicodeCodepoint); begin Assert(Kind = tkNone); {$IFOPT C+} Assert(not IsSpaceCharacter(Character)); {$ENDIF} Kind := tkExtraCharacters; SetLength(ExtraChars, 1); ExtraChars[0] := Character; Assert(Kind <> tkNone); Ready := True; end; procedure THTMLParser.TToken.EmitExtraAmbiguousCharacters(const Characters: TUnicodeCodepointArray); begin Assert(Kind = tkNone); ExtraChars := Characters; if (Length(Characters) = 1) then begin case (Characters[0].Value) of $0009, $000A, $000C, $000D, $0020: Kind := tkExtraSpaceCharacter; else Kind := tkExtraCharacters; end; end else begin Assert(Length(Characters) = 2); {$IFOPT C+} Assert(not IsSpaceCharacter(Characters[0])); Assert(not IsSpaceCharacter(Characters[1])); {$ENDIF} Kind := tkExtraCharacters; end; Assert(Kind <> tkNone); Ready := True; end; procedure THTMLParser.TToken.EmitNullCharacter(); begin Assert(Kind = tkNone); Kind := tkNullCharacter; Ready := True; end; procedure THTMLParser.TToken.PrepareComment(); begin Assert(Kind = tkNone); Kind := tkComment; CommentValue := Default(TParserString); end; procedure THTMLParser.TToken.EmitEOF(); var S: UTF8String; begin Str(Kind, S); Assert(Kind = tkNone, S); Kind := tkEOF; Assert(Kind <> tkNone); Ready := True; end; constructor THTMLParser.Create(); begin inherited; FInsertionMode := @TheInitialInsertionMode; FInputStream := TInputStream.Create(); {$IFDEF PARSEERROR} FCurrentToken.Init(@ParseError); {$ENDIF} FFramesetOkFlag := True; end; destructor THTMLParser.Destroy(); begin //{$IFOPT C+} Assert(FInputStream.WasStarted); {$ENDIF} FInputStream.Free(); FCurrentToken.Destroy(); FDocument.Free(); // in case the parser failed to return somehow inherited; end; {$IFNDEF USEROPES} procedure THTMLParser.SpoonFeed(const Data: UTF8String); begin Assert(Assigned(FInputStream)); {$IFOPT C+} Assert(not FInputStream.WasStarted); {$ENDIF} FInputStream.PushData(Data); end; {$ENDIF} procedure THTMLParser.SpoonFeed(const Data: Pointer; const Length: QWord); begin Assert(Assigned(FInputStream)); {$IFOPT C+} Assert(not FInputStream.WasStarted); {$ENDIF} FInputStream.PushData(Data, Length); end; procedure THTMLParser.RegisterProperietaryVoidElements(const TagNames: array of TCanonicalString); var Name: TCanonicalString; begin {$IFOPT C+} Assert(not FInputStream.WasStarted); {$ENDIF} for Name in TagNames do FProprietaryVoids.Push(Name); end; function THTMLParser.Parse(): TDocument; var OldKind: TTokenKind; begin {$IFOPT C+} Assert(not FInputStream.WasStarted); {$ENDIF} FInputStream.Freeze(); Assert(FInsertionMode = @TheInitialInsertionMode); FDocument := TDocument.Create(); repeat Tokenise(); // updates FCurrentToken Assert(FCurrentToken.Kind <> tkNone); Assert(Assigned(FInsertionMode)); if (FCurrentToken.HavePendingCharacters) then begin OldKind := FCurrentToken.Kind; FCurrentToken.Kind := tkSourceCharacters; TreeConstructionDispatcher(FCurrentToken); FCurrentToken.Kind := OldKind; end else Assert(FCurrentToken.Kind <> tkSourceCharacters); Assert(FCurrentToken.Kind <> tkNone); if (FCurrentToken.Kind <> tkSourceCharacters) then begin Assert(Assigned(FInsertionMode)); TreeConstructionDispatcher(FCurrentToken); if (FCurrentToken.Kind = tkStartTag) then begin FLastStartTag := FCurrentToken.TagName.AsString; {$IFDEF PARSEERROR} if (FCurrentToken.SelfClosingFlag and not FCurrentToken.SelfClosingAcknowledged) then ParseError('Self-closing tag syntax used inappropriately'); {$ENDIF} end; if (FCurrentToken.Kind = tkEOF) then break; end; FCurrentToken.Reset(); until forever; {$IFOPT C+} Assert(FInputStream.WasStarted); {$ENDIF} Result := FDocument; FDocument := nil; end; {$IFDEF PARSEERROR} procedure THTMLParser.ParseError(Message: UTF8String; const Count: Cardinal = 1); var Index: Cardinal; begin Assert(Count >= 1); {$IFDEF LINES} Message := '(' + IntToStr(FInputStream.Line) + ',' + IntToStr(FInputStream.Column) + ') ' + Message; {$ENDIF} if (Assigned(FOnParseError)) then begin if (Count > 1) then begin for Index := 1 to Count do FOnParseError(Message + ' (' + IntToStr(Index) + ' of ' + IntToStr(Count) + ')'); end else begin FOnParseError(Message); end; end else raise ESyntaxError.Create(Message); end; {$ENDIF} procedure THTMLParser.TreeConstructionDispatcher(var Token: TToken); var CachedAdjustedCurrentNode: TElement; begin if (FStackOfOpenElements.Length = 0) then begin FInsertionMode(Token); // http://bugs.freepascal.org/view.php?id=26403 end else begin CachedAdjustedCurrentNode := AdjustedCurrentNode; Assert(Assigned(CachedAdjustedCurrentNode)); if ((CachedAdjustedCurrentNode.NamespaceURL = nsHTML) or (CachedAdjustedCurrentNode.HasProperties(propMathMLTextIntegrationPoint) and (((Token.Kind = tkStartTag) and (Token.TagName <> eMGlyph) and (Token.TagName <> eMAlignMark)) or (Token.Kind in [tkSourceCharacters, tkExtraCharacters, tkExtraSpaceCharacter, tkNullCharacter]))) or (CachedAdjustedCurrentNode.IsIdentity(nsMathML, eAnnotationXML) and (Token.Kind = tkStartTag) and (Token.TagName = eSVG)) or (CachedAdjustedCurrentNode.HasProperties(propHTMLIntegrationPoint) and (Token.Kind in [tkStartTag, tkSourceCharacters, tkExtraCharacters, tkExtraSpaceCharacter, tkNullCharacter])) or (Token.Kind = tkEOF)) then FInsertionMode(Token) else TheRulesForParsingTokensInForeignContent(Token); end; end; function THTMLParser.StackOfOpenElementsHas(constref Namespace, LocalName: TCanonicalString): Boolean; var StackIndex: Cardinal; begin StackIndex := FStackOfOpenElements.Length; while (StackIndex > 0) do begin Dec(StackIndex); // $R- if (FStackOfOpenElements[StackIndex].IsIdentity(Namespace, LocalName)) then begin Result := True; exit; end; end; Result := False; end; function THTMLParser.StackOfOpenElementsHasElementOtherThan(const TargetProperty: TElementProperties): Boolean; var StackIndex: Cardinal; begin Assert(TargetProperty <> 0); StackIndex := FStackOfOpenElements.Length; while (StackIndex > 0) do begin Dec(StackIndex); // $R- if (not FStackOfOpenElements[StackIndex].HasProperties(TargetProperty)) then begin Result := True; exit; end; end; Result := False; end; function THTMLParser.StackOfOpenElementsHasInSpecificScope(constref Target: TCanonicalString; const ParticularScope: TElementProperties): Boolean; // nsHTML assumed for the Target node var Node: TElement; Index: Cardinal; begin Assert(FStackOfOpenElements.Length > 0); Index := FStackOfOpenElements.Length-1; // $R- Node := FStackOfOpenElements[Index]; Assert(Assigned(Node)); while (not Node.IsIdentity(nsHTML, Target)) do begin if (Node.HasProperties(ParticularScope)) then begin Result := False; exit; end; Assert(Node.ParentNode is TElement); Dec(Index); Node := FStackOfOpenElements[Index]; Assert(Assigned(Node)); // if this fails, check that eHTML has ParticularScope set (and maybe figure out how to assert it) end; Result := True; end; function THTMLParser.StackOfOpenElementsHasInSpecificScope(const Target: TElementProperties; const ParticularScope: TElementProperties): Boolean; var Node: TElement; Index: Cardinal; begin Assert(FStackOfOpenElements.Length > 0); Index := FStackOfOpenElements.Length-1; // $R- Node := FStackOfOpenElements[Index]; Assert(Assigned(Node)); while (not Node.HasProperties(Target)) do begin if (Node.HasProperties(ParticularScope)) then begin Result := False; exit; end; Assert(Node.ParentNode is TElement); Dec(Index); Node := FStackOfOpenElements[Index]; Assert(Assigned(Node)); // if this fails, check that eHTML has ParticularScope set (and maybe figure out how to assert it) end; Result := True; end; function THTMLParser.StackOfOpenElementsHasInSpecificScope(const Target: TElement; const ParticularScope: TElementProperties): Boolean; var Node: TElement; Index: Cardinal; begin Assert(Assigned(Target)); Assert(FStackOfOpenElements.Length > 0); Index := FStackOfOpenElements.Length-1; // $R- Node := FStackOfOpenElements[Index]; Assert(Assigned(Node)); while (Node <> Target) do begin if (Node.HasProperties(ParticularScope)) then begin Result := False; exit; end; Assert(Node.ParentNode is TElement); Dec(Index); Node := FStackOfOpenElements[Index]; Assert(Assigned(Node)); // if this fails, check that eHTML has ParticularScope set (and maybe figure out how to assert it) end; Result := True; end; function THTMLParser.StackOfOpenElementsHasInScope(constref Target: TCanonicalString): Boolean; begin Result := StackOfOpenElementsHasInSpecificScope(Target, propGenericScope); end; function THTMLParser.StackOfOpenElementsHasInScope(const Target: TElementProperties): Boolean; begin Result := StackOfOpenElementsHasInSpecificScope(Target, propGenericScope); end; function THTMLParser.StackOfOpenElementsHasInScope(const Target: TElement): Boolean; begin Result := StackOfOpenElementsHasInSpecificScope(Target, propGenericScope); end; function THTMLParser.StackOfOpenElementsHasInListItemScope(constref Target: TCanonicalString): Boolean; begin Result := StackOfOpenElementsHasInSpecificScope(Target, propListItemScope); end; function THTMLParser.StackOfOpenElementsHasInButtonScope(constref Target: TCanonicalString): Boolean; begin Result := StackOfOpenElementsHasInSpecificScope(Target, propButtonScope); end; function THTMLParser.StackOfOpenElementsHasInTableScope(constref Target: TCanonicalString): Boolean; begin Result := StackOfOpenElementsHasInSpecificScope(Target, propTableScope); end; function THTMLParser.StackOfOpenElementsHasInTableScope(const Target: TElementProperties): Boolean; begin Result := StackOfOpenElementsHasInSpecificScope(Target, propTableScope); end; function THTMLParser.StackOfOpenElementsHasInSelectScope(constref Target: TCanonicalString): Boolean; var Node: TElement; begin Node := CurrentNode; Assert(Assigned(Node)); while (not Node.IsIdentity(nsHTML, Target)) do begin if (not Node.HasProperties(propSelectScope)) then begin Result := False; exit; end; Assert(Node.ParentNode is TElement); Node := Node.ParentNode as TElement; end; Result := True; end; procedure THTMLParser.InsertMarkerAtEndOfListOfActiveFormattingElements(); begin FListOfActiveFormattingElements.Push(Marker); Assert(FListOfActiveFormattingElements.Length > 0); end; procedure THTMLParser.PushOntoTheListOfActiveFormattingElements(const Target: TElement); function AttributesMatch(const A, B: TElement.TAttributeHashTable): Boolean; var Name: UTF8String; begin if (Assigned(A) and Assigned(B) and (A.Count = B.Count)) then begin for Name in A do if ((not B.Has(Name)) or (B[Name] <> A[Name])) then begin Result := False; exit; end; Result := True; end else Result := ((not Assigned(A)) and (not Assigned(B))); end; var StartIndex, Index: Cardinal; FirstMatchIndex, Count: Cardinal; begin StartIndex := FListOfActiveFormattingElements.Length; if (StartIndex > 0) then begin // Noah's Ark Clause // find last marker or start of list repeat Dec(StartIndex); if (FListOfActiveFormattingElements[StartIndex] = Marker) then begin Inc(StartIndex); break; end; until StartIndex = 0; // now walk from that marker to the end of the list, checking for matches Count := 0; Index := StartIndex; while ((Index < FListOfActiveFormattingElements.Length) and (Count < 3)) do begin if ((FListOfActiveFormattingElements[Index].LocalName = Target.LocalName) and (FListOfActiveFormattingElements[Index].NamespaceURL = Target.NamespaceURL) and (AttributesMatch(FListOfActiveFormattingElements[Index].Attributes, Target.Attributes))) then begin if (Count = 0) then FirstMatchIndex := Index; Inc(Count); end; Inc(Index); end; if (Count >= 3) then FListOfActiveFormattingElements.RemoveAt(FirstMatchIndex); // $DFA- for FirstMatchIndex end; FListOfActiveFormattingElements.Push(Target); end; procedure THTMLParser.ReconstructTheActiveFormattingElements(); var Index: Cardinal; begin if (FListOfActiveFormattingElements.Length = 0) then exit; if ((FListOfActiveFormattingElements.Last = Marker) or (FStackOfOpenElements.Contains(FListOfActiveFormattingElements.Last))) then exit; Index := FListOfActiveFormattingElements.Length-1; // $R- while (Index > 0) do begin Dec(Index); if ((FListOfActiveFormattingElements[Index] = Marker) or (FStackOfOpenElements.Contains(FListOfActiveFormattingElements[Index]))) then begin Inc(Index); break; end; end; repeat FListOfActiveFormattingElements[Index] := InsertAnHTMLElement(FListOfActiveFormattingElements[Index].CloneNode()); Inc(Index); until Index >= FListOfActiveFormattingElements.Length; end; procedure THTMLParser.ClearTheListOfActiveFormattingElementsUpToTheLastMarker(); begin Assert(FListOfActiveFormattingElements.Length >= 1); repeat until FListOfActiveFormattingElements.Pop() = Marker; end; procedure THTMLParser.Tokenise(); const kNoAdditionalAllowedCharacter = kEOF; type TCharacterReferenceMode = (crInText, crInAttribute); function ConsumeACharacterReference(out Characters: TUnicodeCodepointArray; out Reconsume: Boolean; const Mode: TCharacterReferenceMode; const AdditionalAllowedCharacter: TUnicodeCodepoint): Boolean; var StartOfCharacterReferenceBookmark: THTMLParser.TInputStream.TBookmark; procedure ParseNumericCharacterReference(); inline; var ShowGenericISO88591Error: Boolean; GivenValue, DigitCount: Cardinal; begin FInputStream.Advance(); GivenValue := 0; DigitCount := 0; case (FInputStream.CurrentCharacter.Value) of $0078, $0058: // &#x... begin // hex digits repeat FInputStream.Advance(); {$PUSH} {$OVERFLOWCHECKS ON} {$RANGECHECKS ON} try case (FInputStream.CurrentCharacter.Value) of Ord('0'): GivenValue := GivenValue * 16 + 0; // $R- Ord('1'): GivenValue := GivenValue * 16 + 1; // $R- Ord('2'): GivenValue := GivenValue * 16 + 2; // $R- Ord('3'): GivenValue := GivenValue * 16 + 3; // $R- Ord('4'): GivenValue := GivenValue * 16 + 4; // $R- Ord('5'): GivenValue := GivenValue * 16 + 5; // $R- Ord('6'): GivenValue := GivenValue * 16 + 6; // $R- Ord('7'): GivenValue := GivenValue * 16 + 7; // $R- Ord('8'): GivenValue := GivenValue * 16 + 8; // $R- Ord('9'): GivenValue := GivenValue * 16 + 9; // $R- Ord('A'), Ord('a'): GivenValue := GivenValue * 16 + 10; // $R- Ord('B'), Ord('b'): GivenValue := GivenValue * 16 + 11; // $R- Ord('C'), Ord('c'): GivenValue := GivenValue * 16 + 12; // $R- Ord('D'), Ord('d'): GivenValue := GivenValue * 16 + 13; // $R- Ord('E'), Ord('e'): GivenValue := GivenValue * 16 + 14; // $R- Ord('F'), Ord('f'): GivenValue := GivenValue * 16 + 15; // $R- else break; end; Inc(DigitCount); except on ERangeError do GivenValue := High(GivenValue); end; {$POP} until forever; end; else begin // decimal digits repeat {$PUSH} {$OVERFLOWCHECKS ON} {$RANGECHECKS ON} try case (FInputStream.CurrentCharacter.Value) of Ord('0'): GivenValue := GivenValue * 10 + 0; // $R- Ord('1'): GivenValue := GivenValue * 10 + 1; // $R- Ord('2'): GivenValue := GivenValue * 10 + 2; // $R- Ord('3'): GivenValue := GivenValue * 10 + 3; // $R- Ord('4'): GivenValue := GivenValue * 10 + 4; // $R- Ord('5'): GivenValue := GivenValue * 10 + 5; // $R- Ord('6'): GivenValue := GivenValue * 10 + 6; // $R- Ord('7'): GivenValue := GivenValue * 10 + 7; // $R- Ord('8'): GivenValue := GivenValue * 10 + 8; // $R- Ord('9'): GivenValue := GivenValue * 10 + 9; // $R- else break; end; Inc(DigitCount); except on ERangeError do GivenValue := High(GivenValue); end; {$POP} FInputStream.Advance(); until forever; end; end; if (DigitCount = 0) then begin {$IFDEF PARSEERROR} ParseError('"&#" used without digits'); {$ENDIF} FInputStream.ReturnToBookmark(StartOfCharacterReferenceBookmark); SetLength(Characters, 0); Result := False; exit; end; if (FInputStream.CurrentCharacter = $003B) then // semicolon begin FInputStream.Advance(); end else begin {$IFDEF PARSEERROR} ParseError('numeric character reference missing trailing semicolon'); {$ENDIF} end; Reconsume := True; SetLength(Characters, 1); ShowGenericISO88591Error := True; case (GivenValue) of $00: begin Characters[0] := $FFFD; ShowGenericISO88591Error := False; {$IFDEF PARSEERROR} ParseError('numeric character reference to U+0000'); {$ENDIF} end; $80: Characters[0] := $20AC; // 81 below $82: Characters[0] := $201A; $83: Characters[0] := $0192; $84: Characters[0] := $201E; $85: Characters[0] := $2026; $86: Characters[0] := $2020; $87: Characters[0] := $2021; $88: Characters[0] := $02C6; $89: Characters[0] := $2030; $8A: Characters[0] := $0160; $8B: Characters[0] := $2039; $8C: Characters[0] := $0152; // 8D below $8E: Characters[0] := $017D; // 8F, 90 below $91: Characters[0] := $2018; $92: Characters[0] := $2019; $93: Characters[0] := $201C; $94: Characters[0] := $201D; $95: Characters[0] := $2022; $96: Characters[0] := $2013; $97: Characters[0] := $2014; $98: Characters[0] := $02DC; $99: Characters[0] := $2122; $9A: Characters[0] := $0161; $9B: Characters[0] := $203A; $9C: Characters[0] := $0153; // 9D below $9E: Characters[0] := $017E; $9F: Characters[0] := $0178; $D800..$DFFF: begin Characters[0] := $FFFD; ShowGenericISO88591Error := False; {$IFDEF PARSEERROR} ParseError('numeric character reference to surrogate'); {$ENDIF} end; $0001..$0008, $000D..$001F, $7F, $81, $8D, $8F, $90, $9D, // this line is $007F..$009F $FDD0..$FDEF, $000B, $FFFE, $FFFF, $1FFFE, $1FFFF, $2FFFE, $2FFFF, $3FFFE, $3FFFF, $4FFFE, $4FFFF, $5FFFE, $5FFFF, $6FFFE, $6FFFF, $7FFFE, $7FFFF, $8FFFE, $8FFFF, $9FFFE, $9FFFF, $AFFFE, $AFFFF, $BFFFE, $BFFFF, $CFFFE, $CFFFF, $DFFFE, $DFFFF, $EFFFE, $EFFFF, $FFFFE, $FFFFF, $10FFFE, $10FFFF: begin Characters[0] := GivenValue; // $R- ShowGenericISO88591Error := False; {$IFDEF PARSEERROR} ParseError('numeric character reference to non-Unicode character'); {$ENDIF} end; else if (GivenValue > $10FFFF) then begin Characters[0] := $FFFD; ShowGenericISO88591Error := False; {$IFDEF PARSEERROR} ParseError('numeric character reference to value above U+10FFFF'); {$ENDIF} end else begin Assert(GivenValue >= Low(Characters[0].Value)); Assert(GivenValue <= High(Characters[0].Value)); Characters[0] := GivenValue; // $R- ShowGenericISO88591Error := False; end; end; if (ShowGenericISO88591Error) then begin {$IFDEF PARSEERROR} ParseError('numeric character reference to control character interpreted as ISO-8859-1 code point'); {$ENDIF} end; end; procedure ParseNamedCharacterReference(); inline; var EndOfLastValidReferenceBookmark: THTMLParser.TInputStream.TBookmark; {$IFDEF PARSEERROR} DidSeeAtLeastOneAlphanumericCharacter: Boolean; {$ENDIF} {$IFOPT C+} DidBookmark: Boolean; {$ENDIF} NamedCharacterReferenceParser: TNamedCharacterReferenceParser; begin NamedCharacterReferenceParser.Init(); {$IFOPT C+} DidBookmark := False; {$ENDIF} while (NamedCharacterReferenceParser.Step(FInputStream.CurrentCharacter) in [ncOngoing, ncOngoingButBookmark]) do begin if (NamedCharacterReferenceParser.LastStepReturnValue = ncOngoingButBookmark) then begin {$IFOPT C+} DidBookmark := True; {$ENDIF} EndOfLastValidReferenceBookmark := FInputStream.GetBookmark(); end; FInputStream.Advance(); end; case (NamedCharacterReferenceParser.LastStepReturnValue) of ncFinishedGood: begin Characters := NamedCharacterReferenceParser.FinalParsedValue; end; ncFinishedMissingSemicolonNeedBacktrack: begin {$IFOPT C+} Assert(DidBookmark); {$ENDIF} if (Mode = crInAttribute) then begin FInputStream.ReturnToBookmark(EndOfLastValidReferenceBookmark); {BOGUS Warning: Local variable "EndOfLastValidReferenceBookmark" does not seem to be initialized} // i hope it's bogus, anyway FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $003D, Ord('0')..Ord('9'), Ord('A')..Ord('Z'), Ord('a')..Ord('z'): begin {$IFDEF PARSEERROR} if (FInputStream.CurrentCharacter = $003D) then ParseError('named character reference in attribute value terminated by equals sign'); {$ENDIF} FInputStream.ReturnToBookmark(StartOfCharacterReferenceBookmark); SetLength(Characters, 0); exit; end; end; end; FInputStream.ReturnToBookmark(EndOfLastValidReferenceBookmark); {BOGUS Warning: Local variable "EndOfLastValidReferenceBookmark" does not seem to be initialized} // i hope it's bogus, anyway {$IFDEF PARSEERROR} if (FInputStream.CurrentCharacter <> kEOF) then ParseError('missing semicolon at end of named character reference (found "' + CodepointToUTF8(FInputStream.CurrentCharacter) + '" instead)') else ParseError('unexpected EOF while parsing named character reference'); {$ENDIF} Characters := NamedCharacterReferenceParser.FinalParsedValue; end; ncFinishedNone: begin FInputStream.ReturnToBookmark(StartOfCharacterReferenceBookmark); Assert(FInputStream.CurrentCharacter = Ord('&'), IntToStr(FInputStream.CurrentCharacter.Value)); SetLength(Characters, 0); {$IFDEF PARSEERROR} DidSeeAtLeastOneAlphanumericCharacter := False; FInputStream.Advance(); repeat case (FInputStream.CurrentCharacter.Value) of Ord('0')..Ord('9'), Ord('A')..Ord('Z'), Ord('a')..Ord('z'): begin DidSeeAtLeastOneAlphanumericCharacter := True; FInputStream.Advance(); end; Ord(';'): begin if (DidSeeAtLeastOneAlphanumericCharacter) then ParseError('not a valid named character reference'); break; end; else break; end; until forever; FInputStream.ReturnToBookmark(StartOfCharacterReferenceBookmark); Assert(FInputStream.CurrentCharacter = Ord('&')); {$ENDIF} end; else Assert(False); end; // beware when adding code here: there's an "exit" above. end; var CurrentCharacter: TUnicodeCodepoint; begin Reconsume := False; Assert(Length(Characters) = 0); {BOGUS Warning: Variable "Characters" does not seem to be initialized} // if we ever make this into a non-blocking streaming parser, this needs to be turned into tokeniser stages StartOfCharacterReferenceBookmark := FInputStream.GetBookmark(); FInputStream.Advance(); CurrentCharacter := FInputStream.CurrentCharacter; if (CurrentCharacter = AdditionalAllowedCharacter) then CurrentCharacter := kEOF; // so we fall through to the first entry in the case below case (CurrentCharacter.Value) of $0009, $000A, $000C, $0020, $003C, $0026, kEOF: begin FInputStream.ReturnToBookmark(StartOfCharacterReferenceBookmark); SetLength(Characters, 0); end; $0023: ParseNumericCharacterReference(); else ParseNamedCharacterReference(); end; Result := Length(Characters) > 0; end; procedure AppendInputNonSpaceCharacter(); inline; begin Assert(FInputStream.CurrentCharacter <> $0000); Assert(not FInputStream.WasManipulated); {$IFOPT C+} Assert(not IsSpaceCharacter(FInputStream.CurrentCharacter)); {$ENDIF} FCurrentToken.AppendSourceNonSpaceCharacter(FInputStream.GetPointer()); {$IFOPT C+} FCurrentToken.FCharStart.AssertIdentity(@FInputStream.Data); {$ENDIF} {$IFOPT C+} FCurrentToken.FCharEnd.AssertIdentity(@FInputStream.Data); {$ENDIF} end; procedure AppendInputSpaceCharacter(); inline; begin {$IFOPT C+} Assert(IsSpaceCharacter(FInputStream.CurrentCharacter)); {$ENDIF} if (FInputStream.WasManipulated) then begin Assert(FInputStream.CurrentCharacter = $000A); FCurrentToken.EmitExtraSpaceCharacter(FInputStream.CurrentCharacter) end else begin FCurrentToken.AppendSourceSpaceCharacter(FInputStream.GetPointer()); {$IFOPT C+} FCurrentToken.FCharStart.AssertIdentity(@FInputStream.Data); {$ENDIF} {$IFOPT C+} FCurrentToken.FCharEnd.AssertIdentity(@FInputStream.Data); {$ENDIF} end; end; procedure AppendBookmarkedCharacter(constref Bookmark: THTMLParser.TInputStream.TBookmark); inline; begin Assert(not Bookmark.WasManipulated); FCurrentToken.AppendSourceNonSpaceCharacter(Bookmark.GetPointer()); {$IFOPT C+} FCurrentToken.FCharStart.AssertIdentity(@FInputStream.Data); {$ENDIF} {$IFOPT C+} FCurrentToken.FCharEnd.AssertIdentity(@FInputStream.Data); {$ENDIF} end; procedure AppendFromBookmarkedCharacterToInputCharacter(constref Bookmark: THTMLParser.TInputStream.TBookmark); inline; begin Assert(not Bookmark.WasManipulated); {$IFOPT C+} Assert(not Bookmark.GetPointer().IsEOF()); {$ENDIF} {$IFOPT C+} Assert(not Bookmark.GetPointer().IsZeroWidth()); {$ENDIF} Assert(FInputStream.CurrentCharacter <> kEOF); Assert(not FInputStream.WasManipulated); {$IFOPT C+} Assert(not FInputStream.GetPointer().IsZeroWidth()); {$ENDIF} FCurrentToken.AppendSourceNonSpaceBetweenBookmarks(Bookmark.GetPointer(), FInputStream.GetPointer()); {$IFOPT C+} FCurrentToken.FCharStart.AssertIdentity(@FInputStream.Data); {$ENDIF} {$IFOPT C+} FCurrentToken.FCharEnd.AssertIdentity(@FInputStream.Data); {$ENDIF} end; procedure AppendFromBookmarkedCharacterToBeforeInputCharacter(constref Bookmark: THTMLParser.TInputStream.TBookmark); inline; var NewEndPointer: TParserStringPointer; begin Assert(not Bookmark.WasManipulated); {$IFOPT C+} Assert(not Bookmark.GetPointer().IsEOF()); {$ENDIF} {$IFOPT C+} Assert(not Bookmark.GetPointer().IsZeroWidth()); {$ENDIF} Assert((not FInputStream.WasManipulated) or (FInputStream.CurrentCharacter = kEOF)); NewEndPointer := FInputStream.GetPointer(); if (FInputStream.CurrentCharacter <> kEOF) then NewEndPointer.SetToZeroWidth(); {$IFOPT C+} Assert(NewEndPointer.IsZeroWidth()); {$ENDIF} FCurrentToken.AppendSourceNonSpaceBetweenBookmarks(Bookmark.GetPointer(), NewEndPointer); {$IFOPT C+} FCurrentToken.FCharStart.AssertIdentity(@FInputStream.Data); {$ENDIF} {$IFOPT C+} FCurrentToken.FCharEnd.AssertIdentity(@FInputStream.Data); {$ENDIF} end; procedure MarkupDeclarationOpenState(); inline; var Bookmark: THTMLParser.TInputStream.TBookmark; procedure BogusComment(); inline; begin {$IFDEF PARSEERROR} {$IFOPT C+} ParseError('bogus comment (started with character ' + FInputStream.GetDebugData() + ')'); {$ELSE} ParseError('bogus comment'); {$ENDIF} {$ENDIF} FInputStream.ReturnToBookmark(Bookmark); FInputStream.Unconsume(); FTokeniserState := tsBogusCommentState; end; procedure TryForRealComment(); inline; begin // seen - FInputStream.Advance(); if (FInputStream.CurrentCharacter = $002D) then // - begin FCurrentToken.PrepareComment(); FTokeniserState := tsCommentStartState; end else begin BogusComment(); end; end; procedure TryForDOCTYPE(); inline; begin // seen Dd FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $004F, $006F: // Oo begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0043, $0063: // Cc begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0054, $0074: // Tt begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0059, $0079: // Yy begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0050, $0070: // Pp begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0045, $0065: // Ee begin FTokeniserState := tsDoctypeState; exit; end; end; end; end; end; end; end; end; end; end; end; end; BogusComment(); end; procedure TryForCDATASection(); inline; begin // seen [ if ((FStackOfOpenElements.Length > 0) and (AdjustedCurrentNode.NamespaceURL <> nsHTML)) then begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0043, $0063: // Cc begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0044, $0064: // Dd begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0041, $0061: // Aa begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0054, $0064: // Tt begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0041, $0061: // Aa begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $005B: // [ begin FTokeniserState := tsCdataSectionState; FCurrentToken.EmitSourceCharacters(); exit; end; end; end; end; end; end; end; end; end; end; end; end; end; BogusComment(); end; begin Bookmark := FInputStream.GetBookmark(); case (FInputStream.CurrentCharacter.Value) of $002D: TryForRealComment(); $0044, $0064: TryForDOCTYPE(); $005B: TryForCDATASection(); else BogusComment(); end; end; {$IFDEF USEROPES} procedure BogusCommentState(); inline; var Started: Boolean; StartOfRun, EndOfRun: TParserStringPointer; procedure Flush(); inline; var TemporaryCutRope: CutRope; begin if (Started) then begin TemporaryCutRope := FInputStream.Extract(StartOfRun, EndOfRun); FCurrentToken.CommentValue.AppendDestructively(TemporaryCutRope); Started := False; end; end; procedure Absorb(); inline; begin if (FInputStream.WasManipulated) then begin Flush(); FCurrentToken.CommentValue.Append(FInputStream.CurrentCharacter); end else begin if (not Started) then begin Started := True; StartOfRun := FInputStream.GetPointer(); end; EndOfRun := FInputStream.GetPointer(); end; end; begin FCurrentToken.PrepareComment(); Assert(FCurrentToken.CommentValue.IsEmpty); Started := False; repeat case (FInputStream.CurrentCharacter.Value) of $003E, kEOF: begin Flush(); break; end; $0000: begin Assert(not FInputStream.WasManipulated); Flush(); FCurrentToken.CommentValue.Append($FFFD); end; $0001..$0008, $000B, $000E..$001F, $007F..$009F, $FDD0..$FDEF, $FFFE, $FFFF, $1FFFE, $1FFFF, $2FFFE, $2FFFF, $3FFFE, $3FFFF, $4FFFE, $4FFFF, $5FFFE, $5FFFF, $6FFFE, $6FFFF, $7FFFE, $7FFFF, $8FFFE, $8FFFF, $9FFFE, $9FFFF, $AFFFE, $AFFFF, $BFFFE, $BFFFF, $CFFFE, $CFFFF, $DFFFE, $DFFFF, $EFFFE, $EFFFF, $FFFFE, $FFFFF, $10FFFE, $10FFFF: begin {$IFDEF PARSEERROR} if (not FInputStream.WasNotedBad) then ParseError('control characters and permanently undefined Unicode characters (noncharacters) are not allowed.'); // not calling FInputStream.NotedThatInputIsBad() since we know we won't reexamine it {$ENDIF} Absorb(); end; else Absorb(); end; FInputStream.Advance(); until forever; FTokeniserState := tsDataState; FCurrentToken.Emit(); if (FInputStream.CurrentCharacter = kEOF) then FInputStream.Unconsume(); end; {$ELSE} procedure BogusCommentState(); inline; const FFFD: TUTF8Sequence = (AsString: #$EF#$BF#$BD); var StartBookmark: THTMLParser.TInputStream.TBookmark; CommentSize, Index: Cardinal; EncodedCharacter: TUTF8Sequence; var StartOfGoodRun: Pointer; LengthOfGoodRun: Cardinal; procedure Flush(); inline; begin if (LengthOfGoodRun > 0) then begin Assert(Index <= Length(FCurrentToken.CommentValue)); Move(StartOfGoodRun^, FCurrentToken.CommentValue[Index], LengthOfGoodRun); Inc(Index, LengthOfGoodRun); LengthOfGoodRun := 0; end; end; procedure Absorb(); inline; begin if (FInputStream.WasManipulated) then begin Flush(); EncodedCharacter := CodepointToUTF8(FInputStream.CurrentCharacter); Assert(Index+EncodedCharacter.Length-1 <= Length(FCurrentToken.CommentValue)); Move(EncodedCharacter.Start, FCurrentToken.CommentValue[Index], EncodedCharacter.Length); Inc(Index, EncodedCharacter.Length); end else begin if (LengthOfGoodRun = 0) then StartOfGoodRun := FInputStream.GetRawPointer(); Inc(LengthOfGoodRun, FInputStream.CurrentCharacterLength); end; end; begin StartBookmark := FInputStream.GetBookmark(); FCurrentToken.PrepareComment(); CommentSize := 0; repeat case (FInputStream.CurrentCharacter.Value) of $003E, kEOF: break; $0000: Inc(CommentSize, FFFD.Length); else Inc(CommentSize, FInputStream.CurrentCharacterLength); end; FInputStream.Advance(); until forever; SetLength(FCurrentToken.CommentValue, CommentSize); FInputStream.ReturnToBookmark(StartBookmark); Index := 1; LengthOfGoodRun := 0; repeat case (FInputStream.CurrentCharacter.Value) of $003E, kEOF: begin Flush(); break; end; $0000: begin Assert(not FInputStream.WasManipulated); Flush(); Assert(Index+FFFD.Length-1 <= Length(FCurrentToken.CommentValue)); Move(FFFD.Start, FCurrentToken.CommentValue[Index], FFFD.Length); Inc(Index, FFFD.Length); end; $0001..$0008, $000B, $000E..$001F, $007F..$009F, $FDD0..$FDEF, $FFFE, $FFFF, $1FFFE, $1FFFF, $2FFFE, $2FFFF, $3FFFE, $3FFFF, $4FFFE, $4FFFF, $5FFFE, $5FFFF, $6FFFE, $6FFFF, $7FFFE, $7FFFF, $8FFFE, $8FFFF, $9FFFE, $9FFFF, $AFFFE, $AFFFF, $BFFFE, $BFFFF, $CFFFE, $CFFFF, $DFFFE, $DFFFF, $EFFFE, $EFFFF, $FFFFE, $FFFFF, $10FFFE, $10FFFF: begin {$IFDEF PARSEERROR} if (not FInputStream.WasNotedBad) then ParseError('control characters and permanently undefined Unicode characters (noncharacters) are not allowed.'); // not calling FInputStream.NotedThatInputIsBad() since we know we won't reexamine it {$ENDIF} Absorb(); end; else Absorb(); end; FInputStream.Advance(); until forever; Assert(LengthOfGoodRun = 0); Assert(Index = CommentSize+1); FTokeniserState := tsDataState; FCurrentToken.Emit(); if (FInputStream.CurrentCharacter = kEOF) then FInputStream.Unconsume(); end; {$ENDIF} procedure CdataSectionState(out Reconsume: Boolean); inline; var StartPointer, EndPointer: TParserStringPointer; begin StartPointer := FInputStream.GetPointer(); repeat case (FInputStream.CurrentCharacter.Value) of kEOF: begin EndPointer := FInputStream.GetPointer(); if (StartPointer < EndPointer) then FCurrentToken.AppendSourceNonSpaceBetweenBookmarks(StartPointer, EndPointer); FTokeniserState := tsDataState; Reconsume := True; exit; end; $0000: // null begin Assert(not FInputStream.WasManipulated); EndPointer := FInputStream.GetPointer(); EndPointer.SetToZeroWidth(); if (StartPointer < EndPointer) then FCurrentToken.AppendSourceNonSpaceBetweenBookmarks(StartPointer, EndPointer); FCurrentToken.EmitNullCharacter(); Reconsume := False; exit; end; $005D: // ] begin Assert(not FInputStream.WasManipulated); EndPointer := FInputStream.GetPointer(); FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $005D: // ] begin repeat FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $005D: // ] begin EndPointer.AdvanceToNext({$IFNDEF USEROPES} FInputStream.Data {$ENDIF}); end; $003E: // > begin EndPointer.SetToZeroWidth(); if (StartPointer < EndPointer) then FCurrentToken.AppendSourceNonSpaceBetweenBookmarks(StartPointer, EndPointer); FCurrentToken.EmitSourceCharacters(); FTokeniserState := tsDataState; Reconsume := False; exit; end; else break; end; until forever; end; end; end; else begin if (FInputStream.WasManipulated) then begin EndPointer := FInputStream.GetPointer(); EndPointer.SetToZeroWidth(); if (StartPointer < EndPointer) then FCurrentToken.AppendSourceNonSpaceBetweenBookmarks(StartPointer, EndPointer); Assert(FInputStream.CurrentCharacter <> $000D); Assert(FInputStream.CurrentCharacter = $000A); // pretty sure this is the only way we can get here case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: FCurrentToken.EmitExtraSpaceCharacter(FInputStream.CurrentCharacter); else FCurrentToken.EmitExtraNonSpaceCharacter(FInputStream.CurrentCharacter); end; Reconsume := False; exit; end; Assert(not FInputStream.WasManipulated); FInputStream.Advance(); end; end; until forever; end; function SkipPUBLIC(): Boolean; inline; var Bookmark: THTMLParser.TInputStream.TBookmark; begin Bookmark := FInputStream.GetBookmark(); case (FInputStream.CurrentCharacter.Value) of $0050, $0070: begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0055, $0075: begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0042, $0062: begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $004C, $006C: begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0049, $0069: begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0043, $0063: begin Result := True; exit; end; end; end; end; end; end; end; end; end; end; end; end; FInputStream.ReturnToBookmark(Bookmark); Result := False; end; function SkipSYSTEM(): Boolean; inline; var Bookmark: THTMLParser.TInputStream.TBookmark; begin Bookmark := FInputStream.GetBookmark(); case (FInputStream.CurrentCharacter.Value) of $0053, $0073: begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0059, $0079: begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0053, $0073: begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0054, $0074: begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $0045, $0065: begin FInputStream.Advance(); case (FInputStream.CurrentCharacter.Value) of $004D, $006D: begin Result := True; exit; end; end; end; end; end; end; end; end; end; end; end; end; FInputStream.ReturnToBookmark(Bookmark); Result := False; end; function CurrentTokenIsAppropriateEndTagToken(): Boolean; begin Assert(FCurrentToken.Kind = tkEndTag); Result := FCurrentToken.DraftTagName = FLastStartTag; end; procedure ConsumeACharacterReferenceInText(); inline; var Reconsume: Boolean; Characters: TUnicodeCodepointArray; begin if (not ConsumeACharacterReference(Characters, Reconsume, crInText, kNoAdditionalAllowedCharacter)) then begin Assert(FInputStream.CurrentCharacter = $0026); AppendInputNonSpaceCharacter(); Assert(not Reconsume); {$IFOPT C+} FCurrentToken.FCharStart.AssertIdentity(@FInputStream.Data); {$ENDIF} {$IFOPT C+} FCurrentToken.FCharEnd.AssertIdentity(@FInputStream.Data); {$ENDIF} end else begin FCurrentToken.EmitExtraAmbiguousCharacters(Characters); if (Reconsume) then FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; end; function ConsumeACharacterReferenceInAttribute(const AdditionalAllowedCharacter: TUnicodeCodepoint): Boolean; inline; var Characters: TUnicodeCodepointArray; begin if (not ConsumeACharacterReference(Characters, Result, crInAttribute, AdditionalAllowedCharacter)) then begin Assert(FInputStream.CurrentCharacter = $0026); FCurrentToken.CurrentAttributeValue.Append(FInputStream.CurrentCharacter); Assert(not Result); end else begin FCurrentToken.CurrentAttributeValue.Append(Characters); end; end; var StartOfPotentialTokenBookmark: THTMLParser.TInputStream.TBookmark; Reconsume: Boolean; begin repeat Assert(not FCurrentToken.Ready); {$IFDEF VERBOSETOKENISER} Writeln('Tokeniser: ', FTokeniserState); {$ENDIF} FInputStream.Advance(); repeat {$IFDEF PARSEERROR} case (FInputStream.CurrentCharacter.Value) of $0001..$0008, $000B, $000E..$001F, $007F..$009F, $FDD0..$FDEF, $FFFE, $FFFF, $1FFFE, $1FFFF, $2FFFE, $2FFFF, $3FFFE, $3FFFF, $4FFFE, $4FFFF, $5FFFE, $5FFFF, $6FFFE, $6FFFF, $7FFFE, $7FFFF, $8FFFE, $8FFFF, $9FFFE, $9FFFF, $AFFFE, $AFFFF, $BFFFE, $BFFFF, $CFFFE, $CFFFF, $DFFFE, $DFFFF, $EFFFE, $EFFFF, $FFFFE, $FFFFF, $10FFFE, $10FFFF: begin if (not FInputStream.WasNotedBad) then begin ParseError('control characters and permanently undefined Unicode characters (noncharacters) are not allowed.'); FInputStream.NotedThatInputIsBad(); end; end; end; {$ENDIF} {$IFDEF INSTRUMENTING} Writeln('TOKENISER: ', FTokeniserState); {$ENDIF INSTRUMENTING} case (FTokeniserState) of // initial state is at the bottom tsDataState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $000D, $0020: AppendInputSpaceCharacter(); $0026: ConsumeACharacterReferenceInText(); $003C: begin StartOfPotentialTokenBookmark := FInputStream.GetBookmark(); FTokeniserState := tsTagOpenState; end; $0000: begin {$IFDEF PARSEERROR} ParseError('U+0000 not valid in text'); {$ENDIF} FCurrentToken.EmitNullCharacter(); end; kEOF: FCurrentToken.EmitEOF(); else AppendInputNonSpaceCharacter(); end; // this state is common so it's been moved up tsTagNameState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: FTokeniserState := tsBeforeAttributeNameState; $002F: FTokeniserState := tsSelfClosingStartTagState; $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; Ord('A')..Ord('Z'): FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in tag name'); {$ENDIF} FCurrentToken.DraftTagName.Append($FFFD); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in tag name'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.RetractTag(); continue; // not emitting anything, so ok to reconsume directly end; else FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter); end; // this state is common so it's been moved up tsAttributeValueDoubleQuotedState: case (FInputStream.CurrentCharacter.Value) of $0022: FTokeniserState := tsAfterAttributeValueQuotedState; $0026: if (ConsumeACharacterReferenceInAttribute($0022)) then continue; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in attribute value'); {$ENDIF} FCurrentToken.CurrentAttributeValue.Append($FFFD); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in attribute value'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.RetractTag(); continue; // not emitting anything, so ok to reconsume directly end; else FCurrentToken.CurrentAttributeValue.Append(FInputStream.CurrentCharacter); end; // common state tsCommentState: case (FInputStream.CurrentCharacter.Value) of $002D: begin FTokeniserState := tsCommentEndDashState; end; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in comment'); {$ENDIF} FCurrentToken.CommentValue.Append($FFFD); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in comment'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin FCurrentToken.CommentValue.Append(FInputStream.CurrentCharacter); end; end; // common state tsTagOpenState: case (FInputStream.CurrentCharacter.Value) of $0021: FTokeniserState := tsMarkupDeclarationOpenState; $002F: FTokeniserState := tsEndTagOpenState; Ord('A')..Ord('Z'): begin FCurrentToken.PrepareStartTag(); FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- FTokeniserState := tsTagNameState; end; Ord('a')..Ord('z'): begin FCurrentToken.PrepareStartTag(); FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter); FTokeniserState := tsTagNameState; end; $003F: begin {$IFDEF PARSEERROR} ParseError('unexpected "?" after "<"'); {$ENDIF} FTokeniserState := tsBogusCommentState; continue; // includes the character that jumped us into the bogus comment state end; else begin {$IFDEF PARSEERROR} ParseError('unescaped "<" in text'); {$ENDIF} FTokeniserState := tsDataState; AppendBookmarkedCharacter(StartOfPotentialTokenBookmark); {BOGUS Warning: Local variable "StartOfPotentialTokenBookmark" does not seem to be initialized} continue; // ok to reconsume directly since we are emitting a character end; end; // common state tsAttributeNameState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: FTokeniserState := tsAfterAttributeNameState; $002F: FTokeniserState := tsSelfClosingStartTagState; $003D: FTokeniserState := tsBeforeAttributeValueState; $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; Ord('A')..Ord('Z'): FCurrentToken.CurrentAttributeName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in attribute name'); {$ENDIF} FCurrentToken.CurrentAttributeName.Append($FFFD); end; $0022, $0027, $003C: begin {$IFDEF PARSEERROR} ParseError('invalid character in attribute name'); {$ENDIF} FCurrentToken.CurrentAttributeName.Append(FInputStream.CurrentCharacter); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in attribute name'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.RetractTag(); continue; // not emitting anything, so ok to reconsume directly end; else FCurrentToken.CurrentAttributeName.Append(FInputStream.CurrentCharacter); end; // common state tsEndTagOpenState: case (FInputStream.CurrentCharacter.Value) of Ord('A')..Ord('Z'): begin FCurrentToken.PrepareEndTag(); FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- FTokeniserState := tsTagNameState; end; Ord('a')..Ord('z'): begin FCurrentToken.PrepareEndTag(); FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter); FTokeniserState := tsTagNameState; end; $003E: begin FCurrentToken.EmitSourceCharacters(); {$IFDEF PARSEERROR} ParseError('</> sequence'); {$ENDIF} FTokeniserState := tsDataState; end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in end tag'); {$ENDIF} FTokeniserState := tsDataState; AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); FInputStream.Unconsume(); // can't just "continue" since we just emitted characters end; else begin {$IFDEF PARSEERROR} ParseError('unexpected characters in end tag'); {$ENDIF} FTokeniserState := tsBogusCommentState; continue; // reconsume this character in the bogus comment state, since otherwise we miss the first one end; end; tsRcdataState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $000D, $0020: AppendInputSpaceCharacter(); $0026: ConsumeACharacterReferenceInText(); $003C: begin StartOfPotentialTokenBookmark := FInputStream.GetBookmark(); FTokeniserState := tsRcdataLessThanSignState; end; $0000: begin {$IFDEF PARSEERROR} ParseError('U+0000 not valid in text'); {$ENDIF} FCurrentToken.EmitExtraNonSpaceCharacter($FFFD); end; kEOF: FCurrentToken.EmitEOF(); else AppendInputNonSpaceCharacter(); end; tsRawtextState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $000D, $0020: AppendInputSpaceCharacter(); $003C: begin StartOfPotentialTokenBookmark := FInputStream.GetBookmark(); FTokeniserState := tsRawtextLessThanSignState; end; $0000: begin {$IFDEF PARSEERROR} ParseError('U+0000 not valid in text'); {$ENDIF} FCurrentToken.EmitExtraNonSpaceCharacter($FFFD); end; kEOF: FCurrentToken.EmitEOF(); else AppendInputNonSpaceCharacter(); end; tsScriptDataState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $000D, $0020: AppendInputSpaceCharacter(); $003C: begin StartOfPotentialTokenBookmark := FInputStream.GetBookmark(); FTokeniserState := tsScriptDataLessThanSignState; end; $0000: begin {$IFDEF PARSEERROR} ParseError('U+0000 not valid in text'); {$ENDIF} FCurrentToken.EmitExtraNonSpaceCharacter($FFFD); end; kEOF: FCurrentToken.EmitEOF(); else AppendInputNonSpaceCharacter(); end; tsPlaintextState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $000D, $0020: AppendInputSpaceCharacter(); $0000: begin {$IFDEF PARSEERROR} ParseError('U+0000 not valid in text'); {$ENDIF} FCurrentToken.EmitExtraNonSpaceCharacter($FFFD); end; kEOF: FCurrentToken.EmitEOF(); else AppendInputNonSpaceCharacter(); end; // tsTagOpenState is earlier // tsEndTagOpenState is earlier // tsTagNameState is near the top tsRcdataLessThanSignState: case (FInputStream.CurrentCharacter.Value) of $002F: FTokeniserState := tsRcdataEndTagOpenState; else begin FTokeniserState := tsRcdataState; AppendBookmarkedCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; tsRcdataEndTagOpenState: case (FInputStream.CurrentCharacter.Value) of Ord('A')..Ord('Z'): begin FCurrentToken.PrepareEndTag(); FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- FTokeniserState := tsRcdataEndTagNameState; end; Ord('a')..Ord('z'): begin FCurrentToken.PrepareEndTag(); FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter); FTokeniserState := tsRcdataEndTagNameState; end; else begin FTokeniserState := tsRcdataState; AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; tsRcdataEndTagNameState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: begin if (CurrentTokenIsAppropriateEndTagToken()) then FTokeniserState := tsBeforeAttributeNameState else begin FTokeniserState := tsRcdataState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; $002F: begin if (CurrentTokenIsAppropriateEndTagToken()) then FTokeniserState := tsSelfClosingStartTagState else begin FTokeniserState := tsRcdataState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; $003E: begin if (CurrentTokenIsAppropriateEndTagToken()) then begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end else begin FTokeniserState := tsRcdataState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; Ord('A')..Ord('Z'): FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- Ord('a')..Ord('z'): FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value); else begin FTokeniserState := tsRcdataState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; tsRawtextLessThanSignState: case (FInputStream.CurrentCharacter.Value) of $002F: FTokeniserState := tsRawtextEndTagOpenState; else begin FTokeniserState := tsRawtextState; AppendBookmarkedCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; tsRawtextEndTagOpenState: case (FInputStream.CurrentCharacter.Value) of Ord('A')..Ord('Z'): begin FCurrentToken.PrepareEndTag(); FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- FTokeniserState := tsRawtextEndTagNameState; end; Ord('a')..Ord('z'): begin FCurrentToken.PrepareEndTag(); FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter); FTokeniserState := tsRawtextEndTagNameState; end; else begin FTokeniserState := tsRawtextState; AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; tsRawtextEndTagNameState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: begin if (CurrentTokenIsAppropriateEndTagToken()) then FTokeniserState := tsBeforeAttributeNameState else begin FTokeniserState := tsRawtextState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; $002F: begin if (CurrentTokenIsAppropriateEndTagToken()) then FTokeniserState := tsSelfClosingStartTagState else begin FTokeniserState := tsRawtextState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; $003E: begin if (CurrentTokenIsAppropriateEndTagToken()) then begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end else begin FTokeniserState := tsRawtextState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; Ord('A')..Ord('Z'): FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- Ord('a')..Ord('z'): FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value); else begin FTokeniserState := tsRawtextState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; tsScriptDataLessThanSignState: case (FInputStream.CurrentCharacter.Value) of $002F: FTokeniserState := tsScriptDataEndTagOpenState; // "/" $0021: // ! begin FTokeniserState := tsScriptDataEscapeStartState; AppendFromBookmarkedCharacterToInputCharacter(StartOfPotentialTokenBookmark); end; else begin FTokeniserState := tsScriptDataState; AppendBookmarkedCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; tsScriptDataEndTagOpenState: case (FInputStream.CurrentCharacter.Value) of Ord('A')..Ord('Z'): begin FCurrentToken.PrepareEndTag(); FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- FTokeniserState := tsScriptDataEndTagNameState; end; Ord('a')..Ord('z'): begin FCurrentToken.PrepareEndTag(); FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter); FTokeniserState := tsScriptDataEndTagNameState; end; else begin FTokeniserState := tsScriptDataState; AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; tsScriptDataEndTagNameState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: begin if (CurrentTokenIsAppropriateEndTagToken()) then FTokeniserState := tsBeforeAttributeNameState else begin FTokeniserState := tsScriptDataState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; $002F: begin if (CurrentTokenIsAppropriateEndTagToken()) then FTokeniserState := tsSelfClosingStartTagState else begin FTokeniserState := tsScriptDataState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; $003E: begin if (CurrentTokenIsAppropriateEndTagToken()) then begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end else begin FTokeniserState := tsScriptDataState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; Ord('A')..Ord('Z'): FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- Ord('a')..Ord('z'): FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value); else begin FTokeniserState := tsScriptDataState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; tsScriptDataEscapeStartState: case (FInputStream.CurrentCharacter.Value) of $002D: begin FTokeniserState := tsScriptDataEscapeStartDashState; AppendInputNonSpaceCharacter(); end; else begin FTokeniserState := tsScriptDataState; continue; // ok to reconsume directly since we are emitting a character end; end; tsScriptDataEscapeStartDashState: case (FInputStream.CurrentCharacter.Value) of $002D: begin FTokeniserState := tsScriptDataEscapedDashDashState; AppendInputNonSpaceCharacter(); end; else begin FTokeniserState := tsScriptDataState; continue; // ok to reconsume directly since we are emitting a character end; end; tsScriptDataEscapedState: case (FInputStream.CurrentCharacter.Value) of $002D: begin FTokeniserState := tsScriptDataEscapedDashState; AppendInputNonSpaceCharacter(); end; $003C: // < begin FTokeniserState := tsScriptDataEscapedLessThanSignState; StartOfPotentialTokenBookmark := FInputStream.GetBookmark(); end; $0000: begin {$IFDEF PARSEERROR} ParseError('U+0000 not valid in text'); {$ENDIF} FCurrentToken.EmitExtraNonSpaceCharacter($FFFD); end; kEOF: begin FTokeniserState := tsDataState; {$IFDEF PARSEERROR} ParseError('unexpected EOF in script'); {$ENDIF} continue; // ok to reconsume directly since we are emitting a character end; $0009, $000A, $000C, $0020: begin AppendInputSpaceCharacter(); end; else begin AppendInputNonSpaceCharacter(); end; end; tsScriptDataEscapedDashState: case (FInputStream.CurrentCharacter.Value) of $002D: begin FTokeniserState := tsScriptDataEscapedDashDashState; AppendInputNonSpaceCharacter(); end; $003C: begin FTokeniserState := tsScriptDataEscapedLessThanSignState; StartOfPotentialTokenBookmark := FInputStream.GetBookmark(); end; $0000: begin {$IFDEF PARSEERROR} ParseError('U+0000 not valid in text'); {$ENDIF} FCurrentToken.EmitExtraNonSpaceCharacter($FFFD); end; kEOF: begin FTokeniserState := tsDataState; {$IFDEF PARSEERROR} ParseError('unexpected EOF in script'); {$ENDIF} continue; // ok to reconsume directly since we are emitting a character end; $0009, $000A, $000C, $0020: begin FTokeniserState := tsScriptDataEscapedState; AppendInputSpaceCharacter(); end; else begin FTokeniserState := tsScriptDataEscapedState; AppendInputNonSpaceCharacter(); end; end; tsScriptDataEscapedDashDashState: case (FInputStream.CurrentCharacter.Value) of $002D: begin AppendInputNonSpaceCharacter(); end; $003C: begin FTokeniserState := tsScriptDataEscapedLessThanSignState; StartOfPotentialTokenBookmark := FInputStream.GetBookmark(); end; $003E: begin FTokeniserState := tsScriptDataState; AppendInputNonSpaceCharacter(); end; $0000: begin {$IFDEF PARSEERROR} ParseError('U+0000 not valid in text'); {$ENDIF} FTokeniserState := tsScriptDataEscapedState; FCurrentToken.EmitExtraNonSpaceCharacter($FFFD); end; kEOF: begin FTokeniserState := tsDataState; {$IFDEF PARSEERROR} ParseError('unexpected EOF in script'); {$ENDIF} continue; // ok to reconsume directly since we are emitting a character end; $0009, $000A, $000C, $0020: begin FTokeniserState := tsScriptDataEscapedState; AppendInputSpaceCharacter(); end; else begin FTokeniserState := tsScriptDataEscapedState; AppendInputNonSpaceCharacter(); end; end; tsScriptDataEscapedLessThanSignState: case (FInputStream.CurrentCharacter.Value) of $002F: begin FTokeniserState := tsScriptDataEscapedEndTagOpenState; end; Ord('A')..Ord('Z'): begin FTemporaryBuffer.Init(); FTemporaryBuffer.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- AppendFromBookmarkedCharacterToInputCharacter(StartOfPotentialTokenBookmark); FTokeniserState := tsScriptDataDoubleEscapeStartState; end; Ord('a')..Ord('z'): begin FTemporaryBuffer.Init(); FTemporaryBuffer.Append(FInputStream.CurrentCharacter); AppendFromBookmarkedCharacterToInputCharacter(StartOfPotentialTokenBookmark); FTokeniserState := tsScriptDataDoubleEscapeStartState; end; else begin FTokeniserState := tsScriptDataEscapedState; AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; tsScriptDataEscapedEndTagOpenState: case (FInputStream.CurrentCharacter.Value) of Ord('A')..Ord('Z'): begin FCurrentToken.PrepareEndTag(); FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- FTokeniserState := tsScriptDataEscapedEndTagNameState; end; Ord('a')..Ord('z'): begin FCurrentToken.PrepareEndTag(); FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter); FTokeniserState := tsScriptDataEscapedEndTagNameState; end; else begin FTokeniserState := tsScriptDataEscapedState; AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; tsScriptDataEscapedEndTagNameState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: begin if (CurrentTokenIsAppropriateEndTagToken()) then FTokeniserState := tsBeforeAttributeNameState else begin FTokeniserState := tsScriptDataEscapedState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; $002F: begin if (CurrentTokenIsAppropriateEndTagToken()) then FTokeniserState := tsSelfClosingStartTagState else begin FTokeniserState := tsScriptDataEscapedState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; $003E: begin if (CurrentTokenIsAppropriateEndTagToken()) then begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end else begin FTokeniserState := tsScriptDataEscapedState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; Ord('A')..Ord('Z'): FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- Ord('a')..Ord('z'): FCurrentToken.DraftTagName.Append(FInputStream.CurrentCharacter.Value); else begin FTokeniserState := tsScriptDataEscapedState; FCurrentToken.RetractTag(); AppendFromBookmarkedCharacterToBeforeInputCharacter(StartOfPotentialTokenBookmark); continue; // ok to reconsume directly since we are emitting a character end; end; tsScriptDataDoubleEscapeStartState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: begin if (FTemporaryBuffer = 'script') then FTokeniserState := tsScriptDataDoubleEscapedState else FTokeniserState := tsScriptDataEscapedState; AppendInputSpaceCharacter(); end; $002F, $003E: begin if (FTemporaryBuffer = 'script') then FTokeniserState := tsScriptDataDoubleEscapedState else FTokeniserState := tsScriptDataEscapedState; AppendInputNonSpaceCharacter(); end; Ord('A')..Ord('Z'): begin FTemporaryBuffer.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- AppendInputNonSpaceCharacter(); end; Ord('a')..Ord('z'): begin FTemporaryBuffer.Append(FInputStream.CurrentCharacter); AppendInputNonSpaceCharacter(); end; else begin FTokeniserState := tsScriptDataEscapedState; continue; // ok to reconsume directly since we are emitting a character end; end; tsScriptDataDoubleEscapedState: case (FInputStream.CurrentCharacter.Value) of $002D: begin FTokeniserState := tsScriptDataDoubleEscapedDashState; AppendInputNonSpaceCharacter(); end; $003C: begin FTokeniserState := tsScriptDataDoubleEscapedLessThanSignState; AppendInputNonSpaceCharacter(); end; $0000: begin {$IFDEF PARSEERROR} ParseError('U+0000 not valid in text'); {$ENDIF} FCurrentToken.EmitExtraNonSpaceCharacter($FFFD); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in script'); {$ENDIF} FTokeniserState := tsDataState; continue; // ok to reconsume directly since we are emitting a character end; $0009, $000A, $000C, $0020: begin AppendInputSpaceCharacter(); end; else begin AppendInputNonSpaceCharacter(); end; end; tsScriptDataDoubleEscapedDashState: case (FInputStream.CurrentCharacter.Value) of $002D: begin FTokeniserState := tsScriptDataDoubleEscapedDashDashState; AppendInputNonSpaceCharacter(); end; $003C: begin FTokeniserState := tsScriptDataDoubleEscapedLessThanSignState; AppendInputNonSpaceCharacter(); end; $0000: begin {$IFDEF PARSEERROR} ParseError('U+0000 not valid in text'); {$ENDIF} FTokeniserState := tsScriptDataDoubleEscapedState; FCurrentToken.EmitExtraNonSpaceCharacter($FFFD); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in script'); {$ENDIF} FTokeniserState := tsDataState; continue; // ok to reconsume directly since we are emitting a character end; $0009, $000A, $000C, $0020: begin FTokeniserState := tsScriptDataDoubleEscapedState; AppendInputSpaceCharacter(); end; else begin FTokeniserState := tsScriptDataDoubleEscapedState; AppendInputNonSpaceCharacter(); end; end; tsScriptDataDoubleEscapedDashDashState: case (FInputStream.CurrentCharacter.Value) of $002D: begin AppendInputNonSpaceCharacter(); end; $003C: begin FTokeniserState := tsScriptDataDoubleEscapedLessThanSignState; AppendInputNonSpaceCharacter(); end; $003E: begin FTokeniserState := tsScriptDataState; AppendInputNonSpaceCharacter(); end; $0000: begin {$IFDEF PARSEERROR} ParseError('U+0000 not valid in text'); {$ENDIF} FTokeniserState := tsScriptDataDoubleEscapedState; FCurrentToken.EmitExtraNonSpaceCharacter($FFFD); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in script'); {$ENDIF} FTokeniserState := tsDataState; continue; // ok to reconsume directly since we are emitting a character end; $0009, $000A, $000C, $0020: begin FTokeniserState := tsScriptDataDoubleEscapedState; AppendInputSpaceCharacter(); end; else begin FTokeniserState := tsScriptDataDoubleEscapedState; AppendInputNonSpaceCharacter(); end; end; tsScriptDataDoubleEscapedLessThanSignState: case (FInputStream.CurrentCharacter.Value) of $002F: begin FTemporaryBuffer.Init(); FTokeniserState := tsScriptDataDoubleEscapeEndState; AppendInputNonSpaceCharacter(); end; else begin FTokeniserState := tsScriptDataDoubleEscapedState; continue; // ok to reconsume directly since we are emitting a character end; end; tsScriptDataDoubleEscapeEndState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: begin if (FTemporaryBuffer = 'script') then FTokeniserState := tsScriptDataEscapedState else FTokeniserState := tsScriptDataDoubleEscapedState; AppendInputSpaceCharacter(); end; $002F, $003E: begin if (FTemporaryBuffer = 'script') then FTokeniserState := tsScriptDataEscapedState else FTokeniserState := tsScriptDataDoubleEscapedState; AppendInputNonSpaceCharacter(); end; Ord('A')..Ord('Z'): begin FTemporaryBuffer.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- AppendInputNonSpaceCharacter(); end; Ord('a')..Ord('z'): begin FTemporaryBuffer.Append(FInputStream.CurrentCharacter); AppendInputNonSpaceCharacter(); end; else begin FTokeniserState := tsScriptDataDoubleEscapedState; continue; // ok to reconsume directly since we are emitting a character end; end; tsBeforeAttributeNameState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: ; $002F: FTokeniserState := tsSelfClosingStartTagState; $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; Ord('A')..Ord('Z'): begin FCurrentToken.PrepareAttribute(); FCurrentToken.CurrentAttributeName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- FTokeniserState := tsAttributeNameState; end; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in attribute name'); {$ENDIF} FCurrentToken.PrepareAttribute(); FCurrentToken.CurrentAttributeName.Append($FFFD); // $R- FTokeniserState := tsAttributeNameState; end; $0022, $0027, $003C, $003D: begin {$IFDEF PARSEERROR} ParseError('invalid character starting attribute name'); {$ENDIF} FCurrentToken.PrepareAttribute(); FCurrentToken.CurrentAttributeName.Append(FInputStream.CurrentCharacter); FTokeniserState := tsAttributeNameState; end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in tag'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.RetractTag(); continue; // not emitting anything, so ok to reconsume directly end; else begin FCurrentToken.PrepareAttribute(); FCurrentToken.CurrentAttributeName.Append(FInputStream.CurrentCharacter); FTokeniserState := tsAttributeNameState; end; end; tsAfterAttributeNameState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: ; $002F: FTokeniserState := tsSelfClosingStartTagState; $003D: FTokeniserState := tsBeforeAttributeValueState; $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; Ord('A')..Ord('Z'): begin FCurrentToken.PrepareAttribute(); FCurrentToken.CurrentAttributeName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- FTokeniserState := tsAttributeNameState; end; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in attribute name'); {$ENDIF} FCurrentToken.PrepareAttribute(); FCurrentToken.CurrentAttributeName.Append($FFFD); // $R- FTokeniserState := tsAttributeNameState; end; $0022, $0027, $003C: begin {$IFDEF PARSEERROR} ParseError('invalid character starting attribute name'); {$ENDIF} FCurrentToken.PrepareAttribute(); FCurrentToken.CurrentAttributeName.Append(FInputStream.CurrentCharacter); FTokeniserState := tsAttributeNameState; end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in attribute name'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.RetractTag(); continue; // not emitting anything, so ok to reconsume directly end; else begin FCurrentToken.PrepareAttribute(); FCurrentToken.CurrentAttributeName.Append(FInputStream.CurrentCharacter); FTokeniserState := tsAttributeNameState; end; end; tsBeforeAttributeValueState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: ; $0022: FTokeniserState := tsAttributeValueDoubleQuotedState; $0026: begin FTokeniserState := tsAttributeValueUnquotedState; continue; // not emitting anything, so ok to reconsume directly end; $0027: FTokeniserState := tsAttributeValueSingleQuotedState; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in attribute value'); {$ENDIF} FCurrentToken.CurrentAttributeValue.Append($FFFD); FTokeniserState := tsAttributeValueUnquotedState; end; $003E: begin {$IFDEF PARSEERROR} ParseError('missing attribute value'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.Emit(); end; $003C, $003D, $0060: begin {$IFDEF PARSEERROR} ParseError('invalid character in attribute value'); {$ENDIF} FCurrentToken.CurrentAttributeValue.Append(FInputStream.CurrentCharacter); FTokeniserState := tsAttributeValueUnquotedState; end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in attribute value'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.RetractTag(); continue; // not emitting anything, so ok to reconsume directly end; else begin FCurrentToken.CurrentAttributeValue.Append(FInputStream.CurrentCharacter); FTokeniserState := tsAttributeValueUnquotedState; end; end; // tsAttributeValueDoubleQuotedState was moved up tsAttributeValueSingleQuotedState: case (FInputStream.CurrentCharacter.Value) of $0027: FTokeniserState := tsAfterAttributeValueQuotedState; $0026: if (ConsumeACharacterReferenceInAttribute($0027)) then continue; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in attribute value'); {$ENDIF} FCurrentToken.CurrentAttributeValue.Append($FFFD); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in attribute value'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.RetractTag(); continue; // not emitting anything, so ok to reconsume directly end; else FCurrentToken.CurrentAttributeValue.Append(FInputStream.CurrentCharacter); end; tsAttributeValueUnquotedState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: FTokeniserState := tsBeforeAttributeNameState; $0026: if (ConsumeACharacterReferenceInAttribute($003E)) then continue; $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in attribute value'); {$ENDIF} FCurrentToken.CurrentAttributeValue.Append($FFFD); end; $0022, $0027, $003C, $003D, $0060: begin {$IFDEF PARSEERROR} ParseError('invalid character in attribute value'); {$ENDIF} FCurrentToken.CurrentAttributeValue.Append(FInputStream.CurrentCharacter); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in attribute value'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.RetractTag(); continue; // not emitting anything, so ok to reconsume directly end; else FCurrentToken.CurrentAttributeValue.Append(FInputStream.CurrentCharacter); end; tsAfterAttributeValueQuotedState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: FTokeniserState := tsBeforeAttributeNameState; $002F: FTokeniserState := tsSelfClosingStartTagState; $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in attribute value'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.RetractTag(); continue; // not emitting anything, so ok to reconsume directly end; else begin {$IFDEF PARSEERROR} ParseError('unexpected character after attribute'); {$ENDIF} FTokeniserState := tsBeforeAttributeNameState; continue; // not emitting anything, so ok to reconsume directly end; end; tsSelfClosingStartTagState: case (FInputStream.CurrentCharacter.Value) of $003E: begin FCurrentToken.SelfClosingFlag := True; FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in start tag'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.RetractTag(); continue; // not emitting anything, so ok to reconsume directly end; else begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in start tag'); {$ENDIF} FTokeniserState := tsBeforeAttributeNameState; continue; // not emitting anything, so ok to reconsume directly end; end; tsBogusCommentState: BogusCommentState(); tsMarkupDeclarationOpenState: MarkupDeclarationOpenState(); tsCommentStartState: case (FInputStream.CurrentCharacter.Value) of $002D: begin FTokeniserState := tsCommentStartDashState; end; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in comment'); {$ENDIF} FCurrentToken.CommentValue.Append($FFFD); FTokeniserState := tsCommentState; end; $003E: begin {$IFDEF PARSEERROR} ParseError('unexpected <!--> form'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in comment'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin FCurrentToken.CommentValue.Append(FInputStream.CurrentCharacter); FTokeniserState := tsCommentState; end; end; tsCommentStartDashState: case (FInputStream.CurrentCharacter.Value) of $002D: begin FTokeniserState := tsCommentEndState; end; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in comment'); {$ENDIF} FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append($FFFD); FTokeniserState := tsCommentState; end; $003E: begin {$IFDEF PARSEERROR} ParseError('unexpected <!---> form'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in comment'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append(FInputStream.CurrentCharacter); FTokeniserState := tsCommentState; end; end; // tsCommentState is earlier tsCommentEndDashState: case (FInputStream.CurrentCharacter.Value) of $002D: begin FTokeniserState := tsCommentEndState; end; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in comment'); {$ENDIF} FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append($FFFD); FTokeniserState := tsCommentState; end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in comment'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append(FInputStream.CurrentCharacter); FTokeniserState := tsCommentState; end; end; tsCommentEndState: case (FInputStream.CurrentCharacter.Value) of $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in comment'); {$ENDIF} FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append($FFFD); FTokeniserState := tsCommentState; end; $0021: begin {$IFDEF PARSEERROR} ParseError('unexpected ! after -- in comment'); {$ENDIF} FTokeniserState := tsCommentEndBangState; end; $002D: begin {$IFDEF PARSEERROR} ParseError('unexpected --- in comment'); {$ENDIF} FCurrentToken.CommentValue.Append($002D); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in comment'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin {$IFDEF PARSEERROR} ParseError('unexpected -- in comment'); {$ENDIF} FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append(FInputStream.CurrentCharacter); FTokeniserState := tsCommentState; end; end; tsCommentEndBangState: case (FInputStream.CurrentCharacter.Value) of $002D: begin FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append($0021); FTokeniserState := tsCommentEndDashState; end; $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in comment'); {$ENDIF} FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append($0021); FCurrentToken.CommentValue.Append($FFFD); FTokeniserState := tsCommentState; end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in comment'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append($002D); FCurrentToken.CommentValue.Append($0021); FCurrentToken.CommentValue.Append(FInputStream.CurrentCharacter); FTokeniserState := tsCommentState; end; end; tsDoctypeState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: FTokeniserState := tsBeforeDoctypeNameState; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in DOCTYPE'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.PrepareDOCTYPE(); FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin {$IFDEF PARSEERROR} ParseError('unexpected character in DOCTYPE'); {$ENDIF} FTokeniserState := tsBeforeDoctypeNameState; continue; // not emitting anything, so ok to reconsume directly end; end; tsBeforeDoctypeNameState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: ; Ord('A')..Ord('Z'): begin FCurrentToken.PrepareDOCTYPE(); FCurrentToken.DOCTYPENamePresent := True; FCurrentToken.DOCTYPEName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- FTokeniserState := tsDoctypeNameState; end; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected null in DOCTYPE name'); {$ENDIF} FCurrentToken.PrepareDOCTYPE(); FCurrentToken.DOCTYPENamePresent := True; FCurrentToken.DOCTYPEName.Append($FFFD); FTokeniserState := tsDoctypeNameState; end; $003E: begin {$IFDEF PARSEERROR} ParseError('missing name in DOCTYPE'); {$ENDIF} FCurrentToken.PrepareDOCTYPE(); FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in DOCTYPE before name'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.PrepareDOCTYPE(); FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin FCurrentToken.PrepareDOCTYPE(); FCurrentToken.DOCTYPENamePresent := True; FCurrentToken.DOCTYPEName.Append(FInputStream.CurrentCharacter); FTokeniserState := tsDoctypeNameState; end; end; tsDoctypeNameState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: FTokeniserState := tsAfterDoctypeNameState; $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; Ord('A')..Ord('Z'): FCurrentToken.DOCTYPEName.Append(FInputStream.CurrentCharacter.Value + $0020); // $R- $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected null in DOCTYPE name'); {$ENDIF} FCurrentToken.DOCTYPEName.Append($FFFD); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF after DOCTYPE name'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else FCurrentToken.DOCTYPEName.Append(FInputStream.CurrentCharacter); end; tsAfterDoctypeNameState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: ; $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF after DOCTYPE name'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin if (SkipPUBLIC()) then begin FTokeniserState := tsAfterDoctypePublicKeywordState; end else if (SkipSYSTEM()) then begin FTokeniserState := tsAfterDoctypeSystemKeywordState; end else begin {$IFDEF PARSEERROR} ParseError('unexpected characters after DOCTYPE name'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsBogusDoctypeState; end; end; end; tsAfterDoctypePublicKeywordState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: FTokeniserState := tsBeforeDoctypePublicIdentifierState; $0022: begin {$IFDEF PARSEERROR} ParseError('missing whitespace in DOCTYPE after PUBLIC keyword'); {$ENDIF} FCurrentToken.PublicIDPresent := True; FTokeniserState := tsDoctypePublicIdentifierDoubleQuotedState; end; $0027: begin {$IFDEF PARSEERROR} ParseError('missing whitespace in DOCTYPE after PUBLIC keyword'); {$ENDIF} FCurrentToken.PublicIDPresent := True; FTokeniserState := tsDoctypePublicIdentifierSingleQuotedState; end; $003E: begin {$IFDEF PARSEERROR} ParseError('missing identifier in DOCTYPE after PUBLIC keyword'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in DOCTYPE after PUBLIC keyword'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin {$IFDEF PARSEERROR} ParseError('unexpected characters in DOCTYPE after PUBLIC keyword'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsBogusDoctypeState; end; end; tsBeforeDoctypePublicIdentifierState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: ; $0022: begin FCurrentToken.PublicIDPresent := True; FTokeniserState := tsDoctypePublicIdentifierDoubleQuotedState; end; $0027: begin FCurrentToken.PublicIDPresent := True; FTokeniserState := tsDoctypePublicIdentifierSingleQuotedState; end; $003E: begin {$IFDEF PARSEERROR} ParseError('missing identifier in DOCTYPE after PUBLIC keyword'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in DOCTYPE after PUBLIC keyword'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin {$IFDEF PARSEERROR} ParseError('unexpected characters in DOCTYPE after PUBLIC keyword'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsBogusDoctypeState; end; end; tsDoctypePublicIdentifierDoubleQuotedState: case (FInputStream.CurrentCharacter.Value) of $0022: FTokeniserState := tsAfterDoctypePublicIdentifierState; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in DOCTYPE public identifier'); {$ENDIF} FCurrentToken.PublicID.Append($FFFD); end; $003E: begin {$IFDEF PARSEERROR} ParseError('unexpected end of DOCTYPE in public identifier'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in DOCTYPE in public identifier'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else FCurrentToken.PublicID.Append(FInputStream.CurrentCharacter); end; tsDoctypePublicIdentifierSingleQuotedState: case (FInputStream.CurrentCharacter.Value) of $0027: FTokeniserState := tsAfterDoctypePublicIdentifierState; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in DOCTYPE public identifier'); {$ENDIF} FCurrentToken.PublicID.Append($FFFD); end; $003E: begin {$IFDEF PARSEERROR} ParseError('unexpected end of DOCTYPE in public identifier'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in DOCTYPE in public identifier'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else FCurrentToken.PublicID.Append(FInputStream.CurrentCharacter); end; tsAfterDoctypePublicIdentifierState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: FTokeniserState := tsBetweenDoctypePublicAndSystemIdentifiersState; $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; $0022: begin {$IFDEF PARSEERROR} ParseError('missing whitespace in DOCTYPE after public identifier'); {$ENDIF} FCurrentToken.SystemIDPresent := True; FTokeniserState := tsDoctypeSystemIdentifierDoubleQuotedState; end; $0027: begin {$IFDEF PARSEERROR} ParseError('missing whitespace in DOCTYPE after public identifier'); {$ENDIF} FCurrentToken.SystemIDPresent := True; FTokeniserState := tsDoctypeSystemIdentifierSingleQuotedState; end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in DOCTYPE after public identifier'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin {$IFDEF PARSEERROR} ParseError('unexpected characters in DOCTYPE after public identifier'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsBogusDoctypeState; end; end; tsBetweenDoctypePublicAndSystemIdentifiersState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: ; $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; $0022: begin FCurrentToken.SystemIDPresent := True; FTokeniserState := tsDoctypeSystemIdentifierDoubleQuotedState; end; $0027: begin FCurrentToken.SystemIDPresent := True; FTokeniserState := tsDoctypeSystemIdentifierSingleQuotedState; end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in DOCTYPE after public identifier'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin {$IFDEF PARSEERROR} ParseError('unexpected characters in DOCTYPE after public identifier'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsBogusDoctypeState; end; end; tsAfterDoctypeSystemKeywordState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: FTokeniserState := tsBeforeDoctypeSystemIdentifierState; $0022: begin {$IFDEF PARSEERROR} ParseError('missing whitespace in DOCTYPE after SYSTEM keyword'); {$ENDIF} FCurrentToken.SystemIDPresent := True; FTokeniserState := tsDoctypeSystemIdentifierDoubleQuotedState; end; $0027: begin {$IFDEF PARSEERROR} ParseError('missing whitespace in DOCTYPE after SYSTEM keyword'); {$ENDIF} FCurrentToken.SystemIDPresent := True; FTokeniserState := tsDoctypeSystemIdentifierSingleQuotedState; end; $003E: begin {$IFDEF PARSEERROR} ParseError('missing identifier in DOCTYPE after SYSTEM keyword'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in DOCTYPE after SYSTEM keyword'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin {$IFDEF PARSEERROR} ParseError('unexpected characters in DOCTYPE after SYSTEM keyword'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsBogusDoctypeState; end; end; tsBeforeDoctypeSystemIdentifierState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: ; $0022: begin FCurrentToken.SystemIDPresent := True; FTokeniserState := tsDoctypeSystemIdentifierDoubleQuotedState; end; $0027: begin FCurrentToken.SystemIDPresent := True; FTokeniserState := tsDoctypeSystemIdentifierSingleQuotedState; end; $003E: begin {$IFDEF PARSEERROR} ParseError('missing identifier in DOCTYPE after SYSTEM keyword'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in DOCTYPE after SYSTEM keyword'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin {$IFDEF PARSEERROR} ParseError('unexpected characters in DOCTYPE after SYSTEM keyword'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsBogusDoctypeState; end; end; tsDoctypeSystemIdentifierDoubleQuotedState: case (FInputStream.CurrentCharacter.Value) of $0022: FTokeniserState := tsAfterDoctypeSystemIdentifierState; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in DOCTYPE system identifier'); {$ENDIF} FCurrentToken.SystemID.Append($FFFD); end; $003E: begin {$IFDEF PARSEERROR} ParseError('unexpected end of DOCTYPE in system identifier'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in DOCTYPE in system identifier'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else FCurrentToken.SystemID.Append(FInputStream.CurrentCharacter); end; tsDoctypeSystemIdentifierSingleQuotedState: case (FInputStream.CurrentCharacter.Value) of $0027: FTokeniserState := tsAfterDoctypeSystemIdentifierState; $0000: begin {$IFDEF PARSEERROR} ParseError('unexpected U+0000 in DOCTYPE system identifier'); {$ENDIF} FCurrentToken.SystemID.Append($FFFD); end; $003E: begin {$IFDEF PARSEERROR} ParseError('unexpected end of DOCTYPE in system identifier'); {$ENDIF} FCurrentToken.ForceQuirksFlag := True; FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in DOCTYPE in system identifier'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else FCurrentToken.SystemID.Append(FInputStream.CurrentCharacter); end; tsAfterDoctypeSystemIdentifierState: case (FInputStream.CurrentCharacter.Value) of $0009, $000A, $000C, $0020: ; $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF in DOCTYPE after system identifier'); {$ENDIF} FTokeniserState := tsDataState; FCurrentToken.ForceQuirksFlag := True; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; else begin {$IFDEF PARSEERROR} ParseError('unexpected characters in DOCTYPE after system identifier'); {$ENDIF} FTokeniserState := tsBogusDoctypeState; end; end; tsBogusDoctypeState: case (FInputStream.CurrentCharacter.Value) of $003E: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); end; kEOF: begin FTokeniserState := tsDataState; FCurrentToken.Emit(); FInputStream.Unconsume(); // can't just "continue" since we need to emit something first end; end; tsCdataSectionState: begin CdataSectionState(Reconsume); if (Reconsume) then continue; end; // less seen states tsInitialState: begin FTokeniserState := tsDataState; case (FInputStream.CurrentCharacter.Value) of $FEFF: break; // consume next character else continue; // reconsume end; end; else Assert(False); end; break; until forever; until FCurrentToken.Ready; Assert(FCurrentToken.Ready); Assert(FCurrentToken.Kind <> tkNone); end; function THTMLParser.GetCurrentNode(): TElement; begin Assert(FStackOfOpenElements.Length > 0); Result := FStackOfOpenElements.Last; end; function THTMLParser.GetAdjustedCurrentNode(): TElement; begin if ((FStackOfOpenElements.Length = 1) and (FFragmentParsingMode)) then begin Result := FContextElement; end else begin Assert(FStackOfOpenElements.Length > 0); Result := FStackOfOpenElements.Last; end; end; procedure THTMLParser.InsertNodeAtAppropriatePlaceForInsertingANode(const Node: TNode; Target: TElement = nil); var LastTable: TElement; Index: Cardinal; begin Assert(FStackOfOpenElements.Length > 0); Assert(Assigned(Node)); Assert(not (Node is TDocument)); Assert(not (Node is TText)); if (not Assigned(Target)) then Target := CurrentNode; if (FFosterParenting and Target.HasProperties(propHTML or propFosterParent)) then begin Index := FStackOfOpenElements.Length; Assert(Index > 1); repeat Dec(Index); if (FStackOfOpenElements[Index].IsIdentity(nsHTML, eTemplate)) then begin FStackOfOpenElements[Index].AppendChild(Node); exit; end else if (FStackOfOpenElements[Index].IsIdentity(nsHTML, eTable)) then begin LastTable := FStackOfOpenElements[Index]; if (Assigned(LastTable.ParentNode)) then begin if (LastTable.ParentNode is TElement) then begin (LastTable.ParentNode as TElement).InsertBefore(Node, LastTable); end; end else begin Assert(Index > 0); FStackOfOpenElements[Index-1].AppendChild(Node); // $R- end; exit; end; until (Index = 1); FStackOfOpenElements[0].AppendChild(Node); end else begin Target.AppendChild(Node); end; end; function THTMLParser.CreateAnElementFor(constref Token: TToken; constref Namespace: TCanonicalString): TElement; var CachedAttributeValue: UTF8String; begin Assert(Token.Kind in [tkStartTag, tkEndTag]); if (Namespace = nsHTML) then Result := ConstructHTMLElement(Token.TagName, Token.TakeAttributes()) else if (Namespace = nsMathML) then begin Result := ConstructMathMLElement(Token.TagName, Token.TakeAttributes()); if (Result.LocalName = eAnnotationXML) then begin CachedAttributeValue := ASCIILowerCase(Result.GetAttribute('encoding').AsString); if ((CachedAttributeValue = 'text/html') or (CachedAttributeValue = 'application/xhtml+xml')) then Result.AddProperty(propHTMLIntegrationPoint); end; end else if (Namespace = nsSVG) then Result := ConstructSVGElement(Token.TagName, Token.TakeAttributes()) else Result := TElement.Create(Namespace, Token.TagName, Token.TakeAttributes()); Assert(Assigned(Result)); end; function THTMLParser.InsertAForeignElementFor(constref Token: TToken; constref Namespace: TCanonicalString): TElement; begin Result := CreateAnElementFor(Token, Namespace); InsertNodeAtAppropriatePlaceForInsertingANode(Result); FStackOfOpenElements.Push(Result); end; function THTMLParser.InsertAForeignElement(const Element: TElement): TElement; begin Result := Element; InsertNodeAtAppropriatePlaceForInsertingANode(Element); FStackOfOpenElements.Push(Element); end; function THTMLParser.InsertAnHTMLElementFor(constref Token: TToken): TElement; begin Result := InsertAForeignElementFor(Token, nsHTML); end; function THTMLParser.InsertAnHTMLElement(const Element: TElement): TElement; begin Result := InsertAForeignElement(Element); end; // WARNING, THIS PROCEDURE IS EXACTLY THE SAME AS THE NEXT ONE, EDIT WITH CARE procedure THTMLParser.InsertCharacters(var Data: TCutParserString); var Index: Cardinal; Container: TElement; begin {$IFDEF VERBOSETEXT} if (DebugNow) then Writeln('InsertCharacters(''', Data, ''')'); {$ENDIF} Assert(not Data.IsEmpty); Assert(FStackOfOpenElements.Length > 0); if (FFosterParenting and CurrentNode.HasProperties(propHTML or propFosterParent)) then begin {$IFDEF VERBOSETEXT} if (DebugNow) then Writeln(' Foster Parenting...'); {$ENDIF} Container := nil; Index := FStackOfOpenElements.Length; Assert(Index > 1); repeat Dec(Index); if (FStackOfOpenElements[Index].IsIdentity(nsHTML, eTemplate)) then begin Container := FStackOfOpenElements[Index]; break; end else if (FStackOfOpenElements[Index].IsIdentity(nsHTML, eTable)) then begin if (Assigned(FStackOfOpenElements[Index].ParentNode)) then begin Container := FStackOfOpenElements[Index]; if (Container.ParentNode is TElement) then begin if (Assigned(Container.PreviousSibling) and (Container.PreviousSibling is TText)) then (Container.PreviousSibling as TText).AppendDataDestructively(Data) else (Container.ParentNode as TElement).InsertBefore(TText.CreateDestructively(Data), Container); end; // else it's a TDocument, do nothing exit; end else begin break; end; end; until (Index = 1); Assert(Index > 0); if (not Assigned(Container)) then Container := FStackOfOpenElements[Index-1]; // $R- end else begin Container := CurrentNode; end; {$IFDEF VERBOSETEXT} if (DebugNow) then begin Writeln(' Going to insert in ', Container.LocalName.AsString, ', whose parent is ', (Container.ParentNode as TElement).LocalName.AsString, ' and it has:'); for Index := 0 to (Container.ParentNode as TElement).ChildNodes.Length-1 do begin if ((Container.ParentNode as TElement).ChildNodes[Index] is TElement) then Writeln(' container child ', Index, ' <', ((Container.ParentNode as TElement).ChildNodes[Index] as TElement).LocalName.AsString, '>') else if ((Container.ParentNode as TElement).ChildNodes[Index] is TText) then Writeln(' container child ', Index, ' "', ((Container.ParentNode as TElement).ChildNodes[Index] as TText).Data, '"') else Writeln(' container child ', Index, ' ', (Container.ParentNode as TElement).ChildNodes[Index].ClassName); end; end; {$ENDIF} Assert(Assigned(Container)); if (Assigned(Container.LastChild) and (Container.LastChild is TText)) then begin {$IFDEF VERBOSETEXT} if (DebugNow) then Writeln(' Going to append to the text node at the end of that node.'); {$ENDIF} (Container.LastChild as TText).AppendDataDestructively(Data) end else begin {$IFDEF VERBOSETEXT} if (DebugNow) then Writeln(' Appending a new text node at the end of that node.'); {$ENDIF} Container.AppendChild(TText.CreateDestructively(Data)); end; {$IFDEF VERBOSETEXT} if (DebugNow) then begin Writeln(' Ok, the container now has the following children:'); for Index := 0 to Container.ChildNodes.Length-1 do begin if (Container.ChildNodes[Index] is TElement) then Writeln(' container child ', Index, ' <', (Container.ChildNodes[Index] as TElement).LocalName.AsString, '>') else if (Container.ChildNodes[Index] is TText) then Writeln(' container child ', Index, ' "', (Container.ChildNodes[Index] as TText).Data, '"') else Writeln(' container child ', Index, ' ', Container.ChildNodes[Index].ClassName); end; end; if (DebugNow) then Writeln(' DOM is now:'#10, SerialiseDOMForTestOutput(FDocument)); {$ENDIF} end; // WARNING, THIS PROCEDURE IS EXACTLY THE SAME AS THE PREVIOUS ONE, EDIT WITH CARE {$IFDEF USEROPES} procedure THTMLParser.InsertCharacters(var Data: TParserString); var Index: Cardinal; Container: TElement; begin {$IFDEF VERBOSETEXT} if (DebugNow) then Writeln('InsertCharacters(''', Data, ''')'); {$ENDIF} Assert(not Data.IsEmpty); Assert(FStackOfOpenElements.Length > 0); if (FFosterParenting and CurrentNode.HasProperties(propHTML or propFosterParent)) then begin {$IFDEF VERBOSETEXT} if (DebugNow) then Writeln(' Foster Parenting...'); {$ENDIF} Container := nil; Index := FStackOfOpenElements.Length; Assert(Index > 1); repeat Dec(Index); if (FStackOfOpenElements[Index].IsIdentity(nsHTML, eTemplate)) then begin Container := FStackOfOpenElements[Index]; break; end else if (FStackOfOpenElements[Index].IsIdentity(nsHTML, eTable)) then begin if (Assigned(FStackOfOpenElements[Index].ParentNode)) then begin Container := FStackOfOpenElements[Index]; if (Container.ParentNode is TElement) then begin if (Assigned(Container.PreviousSibling) and (Container.PreviousSibling is TText)) then (Container.PreviousSibling as TText).AppendDataDestructively(Data) else (Container.ParentNode as TElement).InsertBefore(TText.CreateDestructively(Data), Container); end; // else it's a TDocument, do nothing exit; end else begin break; end; end; until (Index = 1); Assert(Index > 0); if (not Assigned(Container)) then Container := FStackOfOpenElements[Index-1]; // $R- end else begin Container := CurrentNode; end; {$IFDEF VERBOSETEXT} if (DebugNow) then begin Writeln(' Going to insert in ', Container.LocalName.AsString, ', whose parent is ', (Container.ParentNode as TElement).LocalName.AsString, ' and it has:'); for Index := 0 to (Container.ParentNode as TElement).ChildNodes.Length-1 do begin if ((Container.ParentNode as TElement).ChildNodes[Index] is TElement) then Writeln(' container child ', Index, ' <', ((Container.ParentNode as TElement).ChildNodes[Index] as TElement).LocalName.AsString, '>') else if ((Container.ParentNode as TElement).ChildNodes[Index] is TText) then Writeln(' container child ', Index, ' "', ((Container.ParentNode as TElement).ChildNodes[Index] as TText).Data, '"') else Writeln(' container child ', Index, ' ', (Container.ParentNode as TElement).ChildNodes[Index].ClassName); end; end; {$ENDIF} Assert(Assigned(Container)); if (Assigned(Container.LastChild) and (Container.LastChild is TText)) then begin {$IFDEF VERBOSETEXT} if (DebugNow) then Writeln(' Going to append to the text node at the end of that node.'); {$ENDIF} (Container.LastChild as TText).AppendDataDestructively(Data) end else begin {$IFDEF VERBOSETEXT} if (DebugNow) then Writeln(' Appending a new text node at the end of that node.'); {$ENDIF} Container.AppendChild(TText.CreateDestructively(Data)); end; {$IFDEF VERBOSETEXT} if (DebugNow) then begin Writeln(' Ok, the container now has the following children:'); for Index := 0 to Container.ChildNodes.Length-1 do begin if (Container.ChildNodes[Index] is TElement) then Writeln(' container child ', Index, ' <', (Container.ChildNodes[Index] as TElement).LocalName.AsString, '>') else if (Container.ChildNodes[Index] is TText) then Writeln(' container child ', Index, ' "', (Container.ChildNodes[Index] as TText).Data, '"') else Writeln(' container child ', Index, ' ', Container.ChildNodes[Index].ClassName); end; end; if (DebugNow) then Writeln(' DOM is now:'#10, SerialiseDOMForTestOutput(FDocument)); {$ENDIF} end; {$ENDIF} procedure THTMLParser.InsertCharacters(const Data: UTF8String); var Placeholder: TCutParserString; begin Placeholder := TCutParserString.CreateFrom(Data); InsertCharacters(Placeholder); Assert(Placeholder.IsEmpty); end; procedure THTMLParser.InsertCharacters(const Data: TUnicodeCodepointArray); var Placeholder: TCutParserString; begin Placeholder := TCutParserString.CreateFrom(Data); InsertCharacters(Placeholder); Assert(Placeholder.IsEmpty); end; procedure THTMLParser.InsertCharactersFor(constref Token: TToken); var Placeholder: TCutParserString; begin Assert(Token.Kind = tkSourceCharacters); Placeholder := Token.ExtractSourceCharacters(FInputStream.Data); InsertCharacters(Placeholder); end; procedure THTMLParser.InsertLeadingSpacesFor(var Token: TToken); var Placeholder: TCutParserString; begin Assert(Token.Kind = tkSourceCharacters); Placeholder := Token.ExtractLeadingSpaces(FInputStream.Data); InsertCharacters(Placeholder); end; function THTMLParser.CreateACommentFor(var Token: TToken): TComment; begin Result := TComment.CreateDestructively(Token.CommentValue); // http://bugs.freepascal.org/view.php?id=26403 end; procedure THTMLParser.InsertAComment(var Token: TToken); begin InsertNodeAtAppropriatePlaceForInsertingANode(CreateACommentFor(Token)); // http://bugs.freepascal.org/view.php?id=26403 end; procedure THTMLParser.ResetTheInsertionModeAppropriately(); var Last: Boolean; Node, Ancestor: TElement; NodeIndex, AncestorIndex: Cardinal; begin Assert(FStackOfOpenElements.Length > 0); Last := False; NodeIndex := FStackOfOpenElements.Length; repeat Dec(NodeIndex); if (NodeIndex = 0) then begin Last := True; // XXX could make this go faster by making the root <html> the FContextElement when not FFragmentParsingMode if (FFragmentParsingMode) then Node := FContextElement else Node := FStackOfOpenElements[NodeIndex]; end else begin Node := FStackOfOpenElements[NodeIndex]; end; Assert(Assigned(Node)); if (Node.NamespaceURL = nsHTML) then begin if (Node.LocalName = eSelect) then begin if (not Last) then begin AncestorIndex := NodeIndex; while (AncestorIndex > 0) do begin Dec(AncestorIndex); Ancestor := FStackOfOpenElements[AncestorIndex]; if (Ancestor.NamespaceURL = nsHTML) then begin if (Ancestor.LocalName = eTemplate) then break; if (Ancestor.LocalName = eTable) then begin FInsertionMode := @TheInSelectInTableInsertionMode; exit; end; end; end; end; FInsertionMode := @TheInSelectInsertionMode; exit; end else if (Node.HasProperties(propTableCell)) then // td, th begin if (not Last) then begin FInsertionMode := @TheInCellInsertionMode; exit; end; end else if (Node.LocalName = eTR) then begin FInsertionMode := @TheInRowInsertionMode; exit; end else if (Node.HasProperties(propTableSection)) then // tbody, thead, tfoot begin FInsertionMode := @TheInTableBodyInsertionMode; exit; end else if (Node.LocalName = eCaption) then begin FInsertionMode := @TheInCaptionInsertionMode; exit; end else if (Node.LocalName = eColGroup) then begin FInsertionMode := @TheInColumnGroupInsertionMode; exit; end else if (Node.LocalName = eTable) then begin FInsertionMode := @TheInTableInsertionMode; exit; end else if (Node.LocalName = eTemplate) then begin FInsertionMode := FStackOfTemplateInsertionModes.Last; exit; end else if (Node.LocalName = eHead) then begin if (not Last) then begin FInsertionMode := @TheInHeadInsertionMode; exit; end; end else if (Node.LocalName = eBody) then begin FInsertionMode := @TheInBodyInsertionMode; exit; end else if (Node.LocalName = eFrameset) then begin FInsertionMode := @TheInFramesetInsertionMode; exit; end else if (Node.LocalName = eHTML) then begin if (not Assigned(FHeadElementPointer)) then FInsertionMode := @TheBeforeHeadInsertionMode else FInsertionMode := @TheAfterHeadInsertionMode; exit; end; end; until Last; FInsertionMode := @TheInBodyInsertionMode; end; procedure THTMLParser.GenericRCDataElementParsingAlgorithm(constref Token: TToken); begin InsertAnHTMLElementFor(Token); FTokeniserState := tsRcdataState; FOriginalInsertionMode := FInsertionMode; FInsertionMode := @TheTextInsertionMode; end; procedure THTMLParser.GenericRawTextElementParsingAlgorithm(constref Token: TToken); begin InsertAnHTMLElementFor(Token); FTokeniserState := tsRawtextState; FOriginalInsertionMode := FInsertionMode; FInsertionMode := @TheTextInsertionMode; end; procedure THTMLParser.GenerateImpliedEndTags(); begin while (CurrentNode.HasProperties(propBodyImpliedEndTag)) do FStackOfOpenElements.Pop(); end; procedure THTMLParser.GenerateAllImpliedEndTagsThoroughly(); begin while (CurrentNode.HasProperties(propTemplateImpliedEndTag)) do FStackOfOpenElements.Pop(); end; procedure THTMLParser.GenerateImpliedEndTagsExceptFor(constref Exception: TCanonicalString); begin while (CurrentNode.HasProperties(propBodyImpliedEndTag) and not CurrentNode.IsIdentity(nsHTML, Exception)) do FStackOfOpenElements.Pop(); end; procedure THTMLParser.TheInitialInsertionMode(var Token: TToken); var RawPublicID, RawSystemID: UTF8String; ConvertedPublicID, ConvertedSystemID: UTF8String; function PublicIDIsQuirkyID(): Boolean; begin Assert(Token.PublicIDPresent); Result := ((ConvertedPublicID = '-//w3o//dtd w3 html strict 3.0//en//') or (ConvertedPublicID = '-/w3c/dtd html 4.0 transitional/en') or (ConvertedPublicID = 'html') or PrefixMatch(ConvertedPublicID, '+//silmaril//dtd html pro v0r11 19970101//') or PrefixMatch(ConvertedPublicID, '-//advasoft ltd//dtd html 3.0 aswedit + extensions//') or PrefixMatch(ConvertedPublicID, '-//as//dtd html 3.0 aswedit + extensions//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html 2.0 level 1//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html 2.0 level 2//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html 2.0 strict level 1//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html 2.0 strict level 2//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html 2.0 strict//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html 2.0//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html 2.1e//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html 3.0//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html 3.2 final//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html 3.2//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html 3//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html level 0//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html level 1//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html level 2//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html level 3//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html strict level 0//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html strict level 1//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html strict level 2//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html strict level 3//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html strict//') or PrefixMatch(ConvertedPublicID, '-//ietf//dtd html//') or PrefixMatch(ConvertedPublicID, '-//metrius//dtd metrius presentational//') or PrefixMatch(ConvertedPublicID, '-//microsoft//dtd internet explorer 2.0 html strict//') or PrefixMatch(ConvertedPublicID, '-//microsoft//dtd internet explorer 2.0 html//') or PrefixMatch(ConvertedPublicID, '-//microsoft//dtd internet explorer 2.0 tables//') or PrefixMatch(ConvertedPublicID, '-//microsoft//dtd internet explorer 3.0 html strict//') or PrefixMatch(ConvertedPublicID, '-//microsoft//dtd internet explorer 3.0 html//') or PrefixMatch(ConvertedPublicID, '-//microsoft//dtd internet explorer 3.0 tables//') or PrefixMatch(ConvertedPublicID, '-//netscape comm. corp.//dtd html//') or PrefixMatch(ConvertedPublicID, '-//netscape comm. corp.//dtd strict html//') or PrefixMatch(ConvertedPublicID, '-//o''reilly and associates//dtd html 2.0//') or PrefixMatch(ConvertedPublicID, '-//o''reilly and associates//dtd html extended 1.0//') or PrefixMatch(ConvertedPublicID, '-//o''reilly and associates//dtd html extended relaxed 1.0//') or PrefixMatch(ConvertedPublicID, '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//') or PrefixMatch(ConvertedPublicID, '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//') or PrefixMatch(ConvertedPublicID, '-//spyglass//dtd html 2.0 extended//') or PrefixMatch(ConvertedPublicID, '-//sq//dtd html 2.0 hotmetal + extensions//') or PrefixMatch(ConvertedPublicID, '-//sun microsystems corp.//dtd hotjava html//') or PrefixMatch(ConvertedPublicID, '-//sun microsystems corp.//dtd hotjava strict html//') or PrefixMatch(ConvertedPublicID, '-//w3c//dtd html 3 1995-03-24//') or PrefixMatch(ConvertedPublicID, '-//w3c//dtd html 3.2 draft//') or PrefixMatch(ConvertedPublicID, '-//w3c//dtd html 3.2 final//') or PrefixMatch(ConvertedPublicID, '-//w3c//dtd html 3.2//') or PrefixMatch(ConvertedPublicID, '-//w3c//dtd html 3.2s draft//') or PrefixMatch(ConvertedPublicID, '-//w3c//dtd html 4.0 frameset//') or PrefixMatch(ConvertedPublicID, '-//w3c//dtd html 4.0 transitional//') or PrefixMatch(ConvertedPublicID, '-//w3c//dtd html experimental 19960712//') or PrefixMatch(ConvertedPublicID, '-//w3c//dtd html experimental 970421//') or PrefixMatch(ConvertedPublicID, '-//w3c//dtd w3 html//') or PrefixMatch(ConvertedPublicID, '-//w3o//dtd w3 html 3.0//') or PrefixMatch(ConvertedPublicID, '-//webtechs//dtd mozilla html 2.0//') or PrefixMatch(ConvertedPublicID, '-//webtechs//dtd mozilla html//') or ((not Token.SystemIDPresent) and (PrefixMatch(ConvertedPublicID, '-//w3c//dtd html 4.01 frameset//') or (PrefixMatch(ConvertedPublicID, '-//w3c//dtd html 4.01 transitional//'))))); end; function SystemIDIsQuirkyID(): Boolean; begin Assert(Token.SystemIDPresent); Result := ConvertedSystemID = 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd'; end; function PublicIDIsLimitedQuirkyID(): Boolean; begin Assert(Token.PublicIDPresent); Result := (PrefixMatch(ConvertedPublicID, '-//w3c//dtd xhtml 1.0 frameset//') or PrefixMatch(ConvertedPublicID, '-//w3c//dtd xhtml 1.0 transitional//') or (Token.SystemIDPresent and (PrefixMatch(ConvertedPublicID, '-//w3c//dtd html 4.01 frameset//') or (PrefixMatch(ConvertedPublicID, '-//w3c//dtd html 4.01 transitional//'))))); end; var SelectedDocumentMode: TDocument.TDocumentMode; DOCTYPENameIsHTML: Boolean; begin Assert(Assigned(FDocument)); case (Token.Kind) of tkSourceCharacters: begin if (ssHaveNonSpace in Token.SpaceState) then begin if (ssHaveLeadingSpace in Token.SpaceState) then Token.SkipLeadingSpaces(FInputStream.Data); // ignore spaces // fall through to "anything else" clause end else exit; // ignore spaces end; tkExtraSpaceCharacter: exit; // ignore spaces tkComment: begin FDocument.AppendChild(CreateACommentFor(Token)); exit; end; tkDOCTYPE: begin Assert(Token.DOCTYPENamePresent xor (Token.DOCTYPEName.IsEmpty)); Assert(Token.PublicIDPresent or (Token.PublicID.IsEmpty)); Assert(Token.SystemIDPresent or (Token.SystemID.IsEmpty)); DOCTYPENameIsHTML := Token.DOCTYPENamePresent and (Token.DOCTYPEName.AsString = 'html'); RawPublicID := Token.PublicID.AsString; ConvertedPublicID := ASCIILowerCase(RawPublicID); RawSystemID := Token.SystemID.AsString; ConvertedSystemID := ASCIILowerCase(RawSystemID); {$IFDEF PARSEERROR} if (((not DOCTYPENameIsHTML) or (Token.PublicIDPresent) or (Token.SystemIDPresent and (RawSystemID <> 'about:legacy-compat'))) and not ((DOCTYPENameIsHTML and (RawPublicID = '-//W3C//DTD HTML 4.0//EN') and ((not Token.SystemIDPresent) or (RawSystemID = 'http://www.w3.org/TR/REC-html40/strict.dtd'))) or (DOCTYPENameIsHTML and (RawPublicID = '-//W3C//DTD HTML 4.01//EN') and ((not Token.SystemIDPresent) or (RawSystemID = 'http://www.w3.org/TR/html4/strict.dtd'))) or (DOCTYPENameIsHTML and (RawPublicID = '-//W3C//DTD XHTML 1.0 Strict//EN') and (RawSystemID = 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd')) or (DOCTYPENameIsHTML and (RawPublicID = '-//W3C//DTD XHTML 1.1//EN') and (RawSystemID = 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd')))) then ParseError('bad DOCTYPE'); {$ENDIF} if ((Token.ForceQuirksFlag) or (not DOCTYPENameIsHTML) or (Token.PublicIDPresent and PublicIDIsQuirkyID()) or (Token.SystemIDPresent and SystemIDIsQuirkyID())) then SelectedDocumentMode := dmQuirksMode else if (Token.PublicIDPresent and PublicIDIsLimitedQuirkyID()) then SelectedDocumentMode := dmLimitedQuirksMode else SelectedDocumentMode := dmNoQuirksMode; FDocument.AppendChild(TDocumentType.CreateDestructively(Token.DOCTYPEName, Token.PublicID, Token.SystemID)); FDocument.SetDocumentMode(SelectedDocumentMode); FInsertionMode := @TheBeforeHTMLInsertionMode; exit; end; end; // anything else: {$IFDEF PARSEERROR} ParseError('missing DOCTYPE'); {$ENDIF} FDocument.SetDocumentMode(dmQuirksMode); FInsertionMode := @TheBeforeHTMLInsertionMode; TreeConstructionDispatcher(Token); end; procedure THTMLParser.TheBeforeHTMLInsertionMode(var Token: TToken); var Element: TElement; begin Assert(Assigned(FDocument)); case (Token.Kind) of tkDOCTYPE: begin {$IFDEF PARSEERROR} ParseError('unexpected DOCTYPE'); {$ENDIF} exit; end; tkComment: begin FDocument.AppendChild(CreateACommentFor(Token)); // http://bugs.freepascal.org/view.php?id=26403 exit; end; tkSourceCharacters: begin if (ssHaveNonSpace in Token.SpaceState) then begin if (ssHaveLeadingSpace in Token.SpaceState) then Token.SkipLeadingSpaces(FInputStream.Data); // ignore spaces // fall through to "anything else" clause end else exit; // ignore spaces end; tkExtraSpaceCharacter: exit; // ignore spaces tkStartTag: if (Token.TagName = eHTML) then begin Element := CreateAnElementFor(Token, nsHTML); FDocument.AppendChild(Element); FStackOfOpenElements.Push(Element); FInsertionMode := @TheBeforeHeadInsertionMode; exit; end; tkEndTag: if ((Token.TagName <> eHead) and (Token.TagName <> eBody) and (Token.TagName <> eHTML) and (Token.TagName <> eBR)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag'); {$ENDIF} exit; end; end; // anything else Element := ConstructHTMLElement(eHTML); FDocument.AppendChild(Element); FStackOfOpenElements.Push(Element); FInsertionMode := @TheBeforeHeadInsertionMode; TreeConstructionDispatcher(Token); end; procedure THTMLParser.TheBeforeHeadInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of tkSourceCharacters: begin if (ssHaveNonSpace in Token.SpaceState) then begin if (ssHaveLeadingSpace in Token.SpaceState) then Token.SkipLeadingSpaces(FInputStream.Data); // ignore spaces // fall through to "anything else" clause end else exit; // ignore spaces end; tkExtraSpaceCharacter: exit; // ignore spaces tkComment: begin InsertAComment(Token); exit; end; tkDOCTYPE: begin {$IFDEF PARSEERROR} ParseError('unexpected DOCTYPE'); {$ENDIF} exit; end; tkStartTag: if (Token.TagName = eHTML) then begin TheInBodyInsertionMode(Token); exit; end else if (Token.TagName = eHead) then begin FHeadElementPointer := InsertAnHTMLElementFor(Token); FInsertionMode := @TheInHeadInsertionMode; exit; end; tkEndTag: if ((Token.TagName <> eHead) and (Token.TagName <> eBody) and (Token.TagName <> eHTML) and (Token.TagName <> eBR)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag'); {$ENDIF} exit; end; end; // anything else FHeadElementPointer := InsertAnHTMLElement(ConstructHTMLElement(eHead)); FInsertionMode := @TheInHeadInsertionMode; TreeConstructionDispatcher(Token); end; procedure THTMLParser.TheInHeadInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of tkSourceCharacters: begin if (ssHaveNonSpace in Token.SpaceState) then begin if (ssHaveLeadingSpace in Token.SpaceState) then InsertLeadingSpacesFor(Token); // http://bugs.freepascal.org/view.php?id=26403 // fall through to "anything else" clause end else begin InsertCharactersFor(Token); exit; end; end; tkExtraSpaceCharacter: begin InsertCharacters(Token.ExtraChars); exit; end; tkComment: begin InsertAComment(Token); exit; end; tkDOCTYPE: begin {$IFDEF PARSEERROR} ParseError('unexpected DOCTYPE'); {$ENDIF} exit; end; tkStartTag: if (Token.TagName = eHTML) then begin TheInBodyInsertionMode(Token); exit; end else if ((Token.TagName = eBase) or (Token.TagName = eBaseFont) or (Token.TagName = eBGSound) or (Token.TagName = eLink) or (Token.TagName = eMeta)) then // <meta>'s special encoding logic is not supported begin InsertAnHTMLElementFor(Token); FStackOfOpenElements.Pop(); {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} exit; end else if (Token.TagName = eTitle) then begin GenericRCDataElementParsingAlgorithm(Token); exit; end else if ((Token.TagName = eNoFrames) or (Token.TagName = eStyle) or ((Token.TagName = eNoScript) and (FScriptingFlag))) then begin GenericRawTextElementParsingAlgorithm(Token); exit; end else if ((Token.TagName = eNoScript) and (not FScriptingFlag)) then begin InsertAnHTMLElementFor(Token); FInsertionMode := @TheInHeadNoScriptInsertionMode; exit; end else if (Token.TagName = eTemplate) then begin InsertAnHTMLElementFor(Token); InsertMarkerAtEndOfListOfActiveFormattingElements(); FFramesetOkFlag := False; FInsertionMode := @TheInTemplateInsertionMode; FStackOfTemplateInsertionModes.Push(@TheInTemplateInsertionMode); exit; end else if (Token.TagName = eScript) then begin // script execution is not supported, so script-specific logic is skipped // this means it simplifies down to just the following line: InsertAnHTMLElementFor(Token); FTokeniserState := tsScriptDataState; FOriginalInsertionMode := FInsertionMode; FInsertionMode := @TheTextInsertionMode; exit; end else if (Token.TagName = eHead) then begin {$IFDEF PARSEERROR} ParseError('unexpected head start tag'); {$ENDIF} exit; end; tkEndTag: if (Token.TagName = eHead) then begin FStackOfOpenElements.Pop(); FInsertionMode := @TheAfterHeadInsertionMode; exit; end else if (Token.TagName = eTemplate) then begin if (not StackOfOpenElementsHas(nsHTML, eTemplate)) then begin {$IFDEF PARSEERROR} ParseError('unexpected template end tag'); {$ENDIF} exit; end; GenerateAllImpliedEndTagsThoroughly(); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, eTemplate)) then ParseError('mismatched template end tag'); {$ENDIF} while (not FStackOfOpenElements.Pop().IsIdentity(nsHTML, eTemplate)) do ; ClearTheListOfActiveFormattingElementsUpToTheLastMarker(); FStackOfTemplateInsertionModes.Pop(); ResetTheInsertionModeAppropriately(); exit; end else if ((Token.TagName <> eBody) and (Token.TagName <> eHTML) and (Token.TagName <> eBR)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag'); {$ENDIF} exit; end; end; // anything else Assert(CurrentNode.IsIdentity(nsHTML, eHead)); FStackOfOpenElements.Pop(); FInsertionMode := @TheAfterHeadInsertionMode; TreeConstructionDispatcher(Token); end; procedure THTMLParser.TheInHeadNoScriptInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of tkSourceCharacters: begin // from "in head" mode if (ssHaveNonSpace in Token.SpaceState) then begin if (ssHaveLeadingSpace in Token.SpaceState) then InsertLeadingSpacesFor(Token); // http://bugs.freepascal.org/view.php?id=26403 // fall through to "anything else" clause end else begin InsertCharactersFor(Token); exit; end; end; tkExtraSpaceCharacter: begin // from "in head" mode InsertCharacters(Token.ExtraChars); exit; end; tkComment: begin // from "in head" mode InsertAComment(Token); exit; end; tkDOCTYPE: begin {$IFDEF PARSEERROR} ParseError('unexpected DOCTYPE'); {$ENDIF} exit; end; tkStartTag: if (Token.TagName = eHTML) then begin TheInBodyInsertionMode(Token); exit; end else if ((Token.TagName = eBaseFont) or (Token.TagName = eBGSound) or (Token.TagName = eLink) or (Token.TagName = eMeta) or (Token.TagName = eNoScript) or (Token.TagName = eStyle)) then // <meta>'s special encoding logic is not supported begin // from "in head" mode InsertAnHTMLElementFor(Token); FStackOfOpenElements.Pop(); {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} exit; end else if ((Token.TagName = eHead) or (Token.TagName = eNoScript)) then begin {$IFDEF PARSEERROR} ParseError('unexpected start tag in head noscript'); {$ENDIF} exit; end; tkEndTag: if (Token.TagName = eNoScript) then begin Assert(CurrentNode.IsIdentity(nsHTML, eNoScript)); FStackOfOpenElements.Pop(); Assert(CurrentNode.IsIdentity(nsHTML, eHead)); FInsertionMode := @TheInHeadInsertionMode; exit; end else if (Token.TagName <> eBR) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag in head noscript'); {$ENDIF} exit; end; end; // anything else {$IFDEF PARSEERROR} ParseError('unexpected token in head noscript'); {$ENDIF} Assert(CurrentNode.IsIdentity(nsHTML, eNoScript)); FStackOfOpenElements.Pop(); Assert(CurrentNode.IsIdentity(nsHTML, eHead)); FInsertionMode := @TheInHeadInsertionMode; TreeConstructionDispatcher(Token); end; procedure THTMLParser.TheAfterHeadInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of tkSourceCharacters: begin if (ssHaveNonSpace in Token.SpaceState) then begin if (ssHaveLeadingSpace in Token.SpaceState) then InsertLeadingSpacesFor(Token); // http://bugs.freepascal.org/view.php?id=26403 // fall through to "anything else" clause end else begin InsertCharactersFor(Token); exit; end; end; tkExtraSpaceCharacter: begin InsertCharacters(Token.ExtraChars); exit; end; tkComment: begin InsertAComment(Token); exit; end; tkDOCTYPE: begin {$IFDEF PARSEERROR} ParseError('unexpected DOCTYPE'); {$ENDIF} exit; end; tkStartTag: if (Token.TagName = eHTML) then begin TheInBodyInsertionMode(Token); exit; end else if (Token.TagName = eBody) then begin InsertAnHTMLElementFor(Token); FFramesetOkFlag := False; FInsertionMode := @TheInBodyInsertionMode; exit; end else if (Token.TagName = eFrameset) then begin InsertAnHTMLElementFor(Token); FInsertionMode := @TheInFramesetInsertionMode; exit; end else if ((Token.TagName = eBase) or (Token.TagName = eBaseFont) or (Token.TagName = eBGSound) or (Token.TagName = eLink) or (Token.TagName = eMeta) or (Token.TagName = eNoFrames) or (Token.TagName = eScript) or (Token.TagName = eStyle) or (Token.TagName = eTemplate) or (Token.TagName = eTitle)) then begin Assert(Assigned(FHeadElementPointer)); {$IFDEF PARSEERROR} ParseError('unexpected start tag after head element'); {$ENDIF} FStackOfOpenElements.Push(FHeadElementPointer); TheInHeadInsertionMode(Token); FStackOfOpenElements.Remove(FHeadElementPointer); exit; end else if (Token.TagName = eHead) then begin {$IFDEF PARSEERROR} ParseError('unexpected head start tag'); {$ENDIF} exit; end; tkEndTag: if (Token.TagName = eTemplate) then begin TheInHeadInsertionMode(Token); exit; end else if ((Token.TagName <> eBody) and (Token.TagName <> eHTML) and (Token.TagName <> eBR)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag'); {$ENDIF} exit; end; end; // anything else Assert(CurrentNode.IsIdentity(nsHTML, eHTML)); InsertAnHTMLElement(ConstructHTMLElement(eBody)); FInsertionMode := @TheInBodyInsertionMode; TreeConstructionDispatcher(Token); end; procedure THTMLParser.TheInBodyInsertionMode(var Token: TToken); procedure CloseAPElement(); begin GenerateImpliedEndTagsExceptFor(eP); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, eP)) then ParseError('parse error while closing p element'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eP); end; procedure AnyOtherEndTag(); var Index: Cardinal; begin Assert(FStackOfOpenElements.Length > 0); Index := FStackOfOpenElements.Length-1; // $R- repeat if (FStackOfOpenElements[Index].IsIdentity(nsHTML, Token.TagName)) then begin GenerateImpliedEndTagsExceptFor(Token.TagName); {$IFDEF PARSEERROR} if (Index <> FStackOfOpenElements.Length-1) then ParseError('unexpected end tag'); {$ENDIF} Assert(FStackOfOpenElements.Length > Index); repeat FStackOfOpenElements.Pop(); until FStackOfOpenElements.Length <= Index; exit; end else if (FStackOfOpenElements[Index].HasProperties(propSpecial)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag'); {$ENDIF} exit; end; Assert(Index > 0); Dec(Index); until forever; end; procedure CallAdoptionAgency(constref Subject: TCanonicalString); var OuterLoopCounter, InnerLoopCounter, FormattingElementIndexInList, FormattingElementIndexInStack, FurthestBlockIndexInStack, Bookmark, NodeIndexInStack, NodeIndexInList, LastNodeIndexInStack: Cardinal; FormattingElement, FurthestBlock, CommonAncestor, NewNode, LastNode: TElement; NodeIsInList: Boolean; {$IFDEF VERBOSEAAA} DebugIndex: Integer; {$ENDIF} begin {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln('AAA for ', Subject.AsString); {$ENDIF} if (CurrentNode.IsIdentity(nsHTML, Subject) and (not FListOfActiveFormattingElements.Contains(CurrentNode))) then begin {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln('AAA-exit1'); {$ENDIF} FStackOfOpenElements.Pop(); exit; end; if (FListOfActiveFormattingElements.Length = 0) then begin {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln('AAA-exit2'); {$ENDIF} AnyOtherEndTag(); exit; end; {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln('AAA: Starting Outer Loop'); {$ENDIF} OuterLoopCounter := 0; while (OuterLoopCounter < 8) do // outer loop begin Inc(OuterLoopCounter); {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' OuterLoopCounter: ', OuterLoopCounter); {$ENDIF} Assert(FListOfActiveFormattingElements.Length > 0); {$IFDEF VERBOSEAAA} if (DebugNow) then begin Write(' FListOfActiveFormattingElements:'); for DebugIndex := 0 to FListOfActiveFormattingElements.Length-1 do // $R- if (FListOfActiveFormattingElements[DebugIndex] = Marker) then Write(' [marker]') else Write(' ', FListOfActiveFormattingElements[DebugIndex].LocalName.AsString); Writeln(); Write(' FStackOfOpenElements:'); for DebugIndex := 0 to FStackOfOpenElements.Length-1 do // $R- Write(' ', FStackOfOpenElements[DebugIndex].LocalName.AsString); Writeln(); end; {$ENDIF} FormattingElementIndexInList := FListOfActiveFormattingElements.Length-1; // $R- {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' FormattingElementIndexInList starting as: ', FormattingElementIndexInList); {$ENDIF} repeat if (FListOfActiveFormattingElements[FormattingElementIndexInList] = Marker) then begin {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln('AAA-exit3a - formatting element not between last marker and end of list'); {$ENDIF} AnyOtherEndTag(); exit; end; if (FListOfActiveFormattingElements[FormattingElementIndexInList].IsIdentity(nsHTML, Subject)) then break; if (FormattingElementIndexInList = 0) then begin {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln('AAA-exit3b - formatting element not in list (no markers)'); {$ENDIF} AnyOtherEndTag(); exit; end; Dec(FormattingElementIndexInList); until forever; {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' FormattingElementIndexInList changed to: ', FormattingElementIndexInList); {$ENDIF} FormattingElement := FListOfActiveFormattingElements[FormattingElementIndexInList]; {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' FormattingElement: ', FormattingElement.LocalName.AsString); {$ENDIF} if (not FStackOfOpenElements.Contains(FormattingElement, FormattingElementIndexInStack)) then begin {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln('AAA-exit4'); {$ENDIF} {$IFDEF PARSEERROR} ParseError('adoption problem'); {$ENDIF} FListOfActiveFormattingElements.RemoveAt(FormattingElementIndexInList); exit; end; Assert(FormattingElementIndexInStack < FStackOfOpenElements.Length); Assert(FormattingElementIndexInStack > 0); // 0 should be the <html> node if (not StackOfOpenElementsHasInScope(Token.TagName)) then begin {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln('AAA-exit5'); {$ENDIF} {$IFDEF PARSEERROR} ParseError('adoption problem'); {$ENDIF} exit; end; {$IFDEF PARSEERROR} if (FormattingElement <> CurrentNode) then ParseError('unexpected end tag'); {$ENDIF} Assert(FormattingElementIndexInStack < High(FurthestBlockIndexInStack)); FurthestBlockIndexInStack := FormattingElementIndexInStack+1; // $R- FurthestBlock := nil; // in case we don't find one while ((FurthestBlockIndexInStack < FStackOfOpenElements.Length) and (not FStackOfOpenElements[FurthestBlockIndexInStack].HasProperties(propSpecial))) do Inc(FurthestBlockIndexInStack); if (FurthestBlockIndexInStack >= FStackOfOpenElements.Length) then begin {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' there is no furthest block'); {$ENDIF} FStackOfOpenElements.Length := FormattingElementIndexInStack; // pop it and all subsequent nodes from the stack FListOfActiveFormattingElements.RemoveAt(FormattingElementIndexInList); {$IFDEF VERBOSEAAA} if (DebugNow) then begin Write(' FListOfActiveFormattingElements:'); for DebugIndex := 0 to FListOfActiveFormattingElements.Length-1 do // $R- if (FListOfActiveFormattingElements[DebugIndex] = Marker) then Write(' [marker]') else Write(' ', FListOfActiveFormattingElements[DebugIndex].LocalName.AsString); Writeln(); Write(' FStackOfOpenElements:'); for DebugIndex := 0 to FStackOfOpenElements.Length-1 do // $R- Write(' ', FStackOfOpenElements[DebugIndex].LocalName.AsString); Writeln(); end; {$ENDIF} {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln('AAA-exit7'); {$ENDIF} exit; end; FurthestBlock := FStackOfOpenElements[FurthestBlockIndexInStack]; {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' FurthestBlock: ', FurthestBlock.LocalName.AsString); {$ENDIF} CommonAncestor := FStackOfOpenElements[FormattingElementIndexInStack-1]; // $R- {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' CommonAncestor: ', CommonAncestor.LocalName.AsString); {$ENDIF} Bookmark := FormattingElementIndexInList; {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Bookmark: ', Bookmark); {$ENDIF} NodeIndexInStack := FurthestBlockIndexInStack; LastNodeIndexInStack := FurthestBlockIndexInStack; InnerLoopCounter := 0; {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Starting Inner Loop'); {$ENDIF} repeat Inc(InnerLoopCounter); {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' InnerLoopCounter: ', InnerLoopCounter); {$ENDIF} {$IFDEF VERBOSEAAA} if (DebugNow) then begin Write(' FListOfActiveFormattingElements:'); for DebugIndex := 0 to FListOfActiveFormattingElements.Length-1 do // $R- if (FListOfActiveFormattingElements[DebugIndex] = Marker) then Write(' [marker]') else Write(' ', FListOfActiveFormattingElements[DebugIndex].LocalName.AsString); Writeln(); Write(' FStackOfOpenElements:'); for DebugIndex := 0 to FStackOfOpenElements.Length-1 do // $R- Write(' ', FStackOfOpenElements[DebugIndex].LocalName.AsString); Writeln(); end; {$ENDIF} {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Node: ', FStackOfOpenElements[NodeIndexInStack].LocalName.AsString); {$ENDIF} {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' LastNode: ', FStackOfOpenElements[LastNodeIndexInStack].LocalName.AsString); {$ENDIF} {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Letting node be the previous node...'); {$ENDIF} Dec(NodeIndexInStack); {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Node: ', FStackOfOpenElements[NodeIndexInStack].LocalName.AsString); {$ENDIF} {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' LastNode: ', FStackOfOpenElements[LastNodeIndexInStack].LocalName.AsString); {$ENDIF} if (NodeIndexInStack = FormattingElementIndexInStack) then begin {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Reached Node = Formatting Element case, ending inner loop'); {$ENDIF} break; end; NodeIsInList := FListOfActiveFormattingElements.Contains(FStackOfOpenElements[NodeIndexInStack], NodeIndexInList); {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Node is in list: ', NodeIsInList); {$ENDIF} if (NodeIsInList and (InnerLoopCounter > 3)) then begin {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' ...and inner loop counter is more than three, so removing from list'); {$ENDIF} Assert(NodeIndexInList < FListOfActiveFormattingElements.Length); FListOfActiveFormattingElements.RemoveAt(NodeIndexInList); Assert(NodeIndexInList <= Bookmark); // if (NodeIndexInList <= Bookmark) then Dec(Bookmark); NodeIsInList := False; end; if (not NodeIsInList) then begin {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' node not in list, so doing that and relooping'); {$ENDIF} FStackOfOpenElements.RemoveAt(NodeIndexInStack); Assert(FormattingElementIndexInStack < NodeIndexInStack); Assert(FurthestBlockIndexInStack > NodeIndexInStack); Dec(FurthestBlockIndexInStack); Assert(FStackOfOpenElements[FurthestBlockIndexInStack] = FurthestBlock); Assert(LastNodeIndexInStack > NodeIndexInStack); Dec(LastNodeIndexInStack); continue; end; {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' going to create a new node'); {$ENDIF} Assert(FListOfActiveFormattingElements[NodeIndexInList] = FStackOfOpenElements[NodeIndexInStack]); NewNode := FStackOfOpenElements[NodeIndexInStack].CloneNode(); {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' created a new ', NewNode.LocalName.AsString); {$ENDIF} FListOfActiveFormattingElements[NodeIndexInList] := NewNode; {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' replaced it in the list at index ', NodeIndexInList); {$ENDIF} FStackOfOpenElements[NodeIndexInStack] := NewNode; {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' replaced it in the stack at index ', NodeIndexInStack); {$ENDIF} if (LastNodeIndexInStack = FurthestBlockIndexInStack) then begin Assert(NodeIndexInList < High(Bookmark)); Bookmark := NodeIndexInList; // $R- {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' New Bookmark: ', Bookmark); {$ENDIF} end; LastNode := FStackOfOpenElements[LastNodeIndexInStack]; {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Inserting Last Node (', LastNode.LocalName.AsString, ') into Node (', NewNode.LocalName.AsString, '): ', Bookmark); {$ENDIF} if (Assigned(LastNode.ParentNode)) then LastNode.Remove(); NewNode.AppendChild(LastNode); LastNodeIndexInStack := NodeIndexInStack; until forever; {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Done with inner loop'); {$ENDIF} {$IFDEF VERBOSEAAA} if (DebugNow) then begin Write(' FListOfActiveFormattingElements:'); for DebugIndex := 0 to FListOfActiveFormattingElements.Length-1 do // $R- if (FListOfActiveFormattingElements[DebugIndex] = Marker) then Write(' [marker]') else Write(' ', FListOfActiveFormattingElements[DebugIndex].LocalName.AsString); Writeln(); Write(' FStackOfOpenElements:'); for DebugIndex := 0 to FStackOfOpenElements.Length-1 do // $R- Write(' ', FStackOfOpenElements[DebugIndex].LocalName.AsString); Writeln(); end; {$ENDIF} Assert(Assigned(CommonAncestor)); if (Assigned(FStackOfOpenElements[LastNodeIndexInStack].ParentNode)) then FStackOfOpenElements[LastNodeIndexInStack].Remove(); {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Inserting LastNode (', FStackOfOpenElements[LastNodeIndexInStack].LocalName.AsString, ') into CommonAncestor (', CommonAncestor.LocalName.AsString, ')'); {$ENDIF} InsertNodeAtAppropriatePlaceForInsertingANode(FStackOfOpenElements[LastNodeIndexInStack], CommonAncestor); NewNode := FormattingElement.CloneNode(); {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Created ', NewNode.LocalName.AsString); {$ENDIF} Assert(Assigned(FurthestBlock)); {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Swapping children from FurthestBlock to that new node'); {$ENDIF} NewNode.SwapChildNodes(FurthestBlock); {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Appending the new node to FurthestBlock'); {$ENDIF} FurthestBlock.AppendChild(NewNode); Assert(FListOfActiveFormattingElements[FormattingElementIndexInList] = FormattingElement); {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' FListOfActiveFormattingElements.RemoveShiftLeftInsert(): Removing from ', FormattingElementIndexInList, ' and inserting at ', Bookmark, ' -- array length: ', FListOfActiveFormattingElements.Length); {$ENDIF} FListOfActiveFormattingElements.RemoveShiftLeftInsert(FormattingElementIndexInList, Bookmark, NewNode); {$IFDEF VERBOSEAAA} if (DebugNow) then begin Write(' FListOfActiveFormattingElements:'); for DebugIndex := 0 to FListOfActiveFormattingElements.Length-1 do // $R- if (FListOfActiveFormattingElements[DebugIndex] = Marker) then Write(' [marker]') else Write(' ', FListOfActiveFormattingElements[DebugIndex].LocalName.AsString); Writeln(); end; {$ENDIF} Assert(FurthestBlockIndexInStack < High(FurthestBlockIndexInStack)); {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' FStackOfOpenElements.RemoveShiftLeftInsert(): Removing from ', FormattingElementIndexInStack, ' and inserting at ', FurthestBlockIndexInStack, ' -- array length: ', FStackOfOpenElements.Length); {$ENDIF} FStackOfOpenElements.RemoveShiftLeftInsert(FormattingElementIndexInStack, FurthestBlockIndexInStack, NewNode); // $R- {$IFDEF VERBOSEAAA} if (DebugNow) then begin Write(' FStackOfOpenElements:'); for DebugIndex := 0 to FStackOfOpenElements.Length-1 do // $R- Write(' ', FStackOfOpenElements[DebugIndex].LocalName.AsString); Writeln(); end; {$ENDIF} {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Done shifting things around...'); {$ENDIF} {$IFDEF VERBOSEAAA} if (DebugNow) then begin Write(' FListOfActiveFormattingElements:'); for DebugIndex := 0 to FListOfActiveFormattingElements.Length-1 do // $R- if (FListOfActiveFormattingElements[DebugIndex] = Marker) then Write(' [marker]') else Write(' ', FListOfActiveFormattingElements[DebugIndex].LocalName.AsString); Writeln(); Write(' FStackOfOpenElements:'); for DebugIndex := 0 to FStackOfOpenElements.Length-1 do // $R- Write(' ', FStackOfOpenElements[DebugIndex].LocalName.AsString); Writeln(); end; {$ENDIF} end; {$IFDEF VERBOSEAAA} if (DebugNow) then Writeln(' Done with outer loop'); {$ENDIF} end; var Attributes: TElement.TAttributeHashTable; HTMLElement, BodyElement, NewElement, OldElement, Node: TElement; AttributeName, TemporaryString: UTF8String; Index: Cardinal; TemporaryAttributeValue: TParserString; begin Assert(Assigned(FDocument)); {$IFDEF INSTRUMENTING} Writeln('INBODY: ', Token.Kind); if (Token.Kind = tkStartTag) then Writeln('INBODY START TAG: ', Token.TagName.AsString); if (Token.Kind = tkEndTag) then Writeln('INBODY END TAG: ', Token.TagName.AsString); {$ENDIF} case (Token.Kind) of // the states here are in order of most common to least common on some test input tkSourceCharacters: begin ReconstructTheActiveFormattingElements(); InsertCharactersFor(Token); if (ssHaveNonSpace in Token.SpaceState) then FFramesetOkFlag := False; end; tkStartTag: // the conditionals here are in order of most common to least // common on some test input. only the most common // conditionals are hoisted up here; the rest are left in the // original spec order below (<code> was about 60 times more // common than <hr>, the least-common hoisted start tag) if (Token.TagName = eCode) then begin ReconstructTheActiveFormattingElements(); PushOntoTheListOfActiveFormattingElements(InsertAnHTMLElementFor(Token)); end else if (Token.TagName = eSpan) then begin // any other start tag ReconstructTheActiveFormattingElements(); InsertAnHTMLElementFor(Token); end else if (Token.TagName = eP) then begin if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); InsertAnHTMLElementFor(Token); end else if (Token.TagName = eVar) then begin // any other start tag ReconstructTheActiveFormattingElements(); InsertAnHTMLElementFor(Token); end else if (Token.TagName = eLI) then begin FFramesetOkFlag := False; Assert(FStackOfOpenElements.Length > 0); Index := FStackOfOpenElements.Length-1; // $R- repeat if (FStackOfOpenElements[Index].IsIdentity(nsHTML, eLI)) then begin GenerateImpliedEndTagsExceptFor(eLI); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, eLI)) then ParseError('unexpected li start tag'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eLI); break; end else if (FStackOfOpenElements[Index].HasProperties(propSpecialish)) then begin break; end else begin Assert(Index > 0); Dec(Index); end; until forever; if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); InsertAnHTMLElementFor(Token); end else if (Token.TagName = eDfn) then begin // any other start tag ReconstructTheActiveFormattingElements(); InsertAnHTMLElementFor(Token); end else if ((Token.TagName = eDD) or (Token.TagName = eDT)) then begin FFramesetOkFlag := False; Assert(FStackOfOpenElements.Length > 0); Index := FStackOfOpenElements.Length-1; // $R- repeat if (FStackOfOpenElements[Index].IsIdentity(nsHTML, eDD)) then begin GenerateImpliedEndTagsExceptFor(eDD); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, eDD)) then ParseError('unexpected li start tag'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eDD); break; end else if (FStackOfOpenElements[Index].IsIdentity(nsHTML, eDT)) then begin GenerateImpliedEndTagsExceptFor(eDT); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, eDT)) then ParseError('unexpected li start tag'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eDT); break; end else if (FStackOfOpenElements[Index].HasProperties(propSpecialish)) then begin break; end else begin Assert(Index > 0); Dec(Index); end; until forever; if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); InsertAnHTMLElementFor(Token); end else if (Token.TagName = eI) then begin ReconstructTheActiveFormattingElements(); PushOntoTheListOfActiveFormattingElements(InsertAnHTMLElementFor(Token)); end else if (Token.TagName = eDiv) then begin if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); InsertAnHTMLElementFor(Token); end else if (Token.TagName = eA) then begin if (FListOfActiveFormattingElements.Length > 0) then begin Index := FListOfActiveFormattingElements.Length; repeat Assert(Index > 0); Dec(Index); // $R- if (FListOfActiveFormattingElements[Index] = Marker) then begin break; end else if (FListOfActiveFormattingElements[Index].IsIdentity(nsHTML, eA)) then begin {$IFDEF PARSEERROR} ParseError('unexpected a start tag in a element'); {$ENDIF} OldElement := FListOfActiveFormattingElements[Index]; CallAdoptionAgency(eA); // OldElement might not have been removed from the list and stack, so force-remove them (these are expensive no-ops if the element is gone now): FListOfActiveFormattingElements.Remove(OldElement); FStackOfOpenElements.Remove(OldElement); break; end; until (Index = 0); end; ReconstructTheActiveFormattingElements(); PushOntoTheListOfActiveFormattingElements(InsertAnHTMLElementFor(Token)); end else if (Token.TagName = ePre) then begin if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); InsertAnHTMLElementFor(Token); FOriginalInsertionMode := FInsertionMode; FInsertionMode := @TheSkipNewLineInsertionMode; FFramesetOkFlag := False; end else if ((Token.TagName = eOL) or (Token.TagName = eDL)) then begin if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); InsertAnHTMLElementFor(Token); end else if (Token.TagName = eHR) then begin if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); InsertAnHTMLElementFor(Token); FStackOfOpenElements.Pop(); {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} FFramesetOkFlag := false; end else // remaining conditionals in no particular order if (Token.TagName = eHTML) then begin {$IFDEF PARSEERROR} ParseError('unexpected html start tag'); {$ENDIF} if (StackOfOpenElementsHas(nsHTML, eTemplate)) then exit; Attributes := Token.TakeAttributes(); if (Assigned(Attributes)) then begin HTMLElement := FStackOfOpenElements[0]; Assert(HTMLElement is THTMLHTMLElement); for AttributeName in Attributes do if (not HTMLElement.HasAttribute(AttributeName)) then begin TemporaryAttributeValue := Attributes[AttributeName]; HTMLElement.SetAttributeDestructively(AttributeName, TemporaryAttributeValue); end; Attributes.Free(); end; end else if ((Token.TagName = eBase) or (Token.TagName = eBaseFont) or (Token.TagName = eBGSound) or (Token.TagName = eLink) or (Token.TagName = eMeta) or (Token.TagName = eNoFrames) or (Token.TagName = eScript) or (Token.TagName = eStyle) or (Token.TagName = eTemplate) or (Token.TagName = eTitle)) then begin TheInHeadInsertionMode(Token); end else if (Token.TagName = eBody) then begin {$IFDEF PARSEERROR} ParseError('unexpected body start tag'); {$ENDIF} if ((FStackOfOpenElements.Length < 2) or (not FStackOfOpenElements[1].IsIdentity(nsHTML, eBody)) or (StackOfOpenElementsHas(nsHTML, eTemplate))) then exit; // ignore the token FFramesetOkFlag := False; Attributes := Token.TakeAttributes(); if (Assigned(Attributes)) then begin BodyElement := FStackOfOpenElements[1]; Assert(BodyElement is THTMLBodyElement); for AttributeName in Attributes do if (not BodyElement.HasAttribute(AttributeName)) then begin TemporaryAttributeValue := Attributes[AttributeName]; BodyElement.SetAttributeDestructively(AttributeName, TemporaryAttributeValue); end; Attributes.Free(); end; end else if (Token.TagName = eFrameset) then begin {$IFDEF PARSEERROR} ParseError('unexpected body frameset start tag'); {$ENDIF} if ((FStackOfOpenElements.Length < 2) or (not FStackOfOpenElements[1].IsIdentity(nsHTML, eBody))) then exit; // ignore the token if (not FFramesetOkFlag) then exit; // ignore the token BodyElement := FStackOfOpenElements[1]; Assert(Assigned(BodyElement.ParentNode)); BodyElement.Remove(); while (FStackOfOpenElements.Length > 1) do FStackOfOpenElements.Pop(); BodyElement.Free(); {$IFOPT C+} BodyElement := nil; {$ENDIF} InsertAnHTMLElementFor(Token); FInsertionMode := @TheInFramesetInsertionMode; end else if ((Token.TagName = eAddress) or (Token.TagName = eArticle) or (Token.TagName = eAside) or (Token.TagName = eBlockQuote) or (Token.TagName = eCenter) or (Token.TagName = eDetails) or (Token.TagName = eDialog) or (Token.TagName = eDir) or //(Token.TagName = eDiv) or // hoisted higher //(Token.TagName = eDL) or // hoisted higher (Token.TagName = eFieldSet) or (Token.TagName = eFigCaption) or (Token.TagName = eFigure) or (Token.TagName = eFooter) or (Token.TagName = eHeader) or (Token.TagName = eHGroup) or (Token.TagName = eMain) or (Token.TagName = eMenu) or (Token.TagName = eNav) or //(Token.TagName = eOL) or // hoisted higher //(Token.TagName = eP) or // hoisted higher (Token.TagName = eSection) or (Token.TagName = eSummary) or (Token.TagName = eUL)) then begin if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); InsertAnHTMLElementFor(Token); end else if ((Token.TagName = eH1) or (Token.TagName = eH2) or (Token.TagName = eH3) or (Token.TagName = eH4) or (Token.TagName = eH5) or (Token.TagName = eH6)) then begin if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); if (CurrentNode.HasProperties(propHeading)) then begin {$IFDEF PARSEERROR} ParseError('unexpected nesting of h1-h6 elements'); {$ENDIF} FStackOfOpenElements.Pop(); end; InsertAnHTMLElementFor(Token); end else if (//(Token.TagName = ePre) or // hoisted (Token.TagName = eListing)) then begin if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); InsertAnHTMLElementFor(Token); FOriginalInsertionMode := FInsertionMode; FInsertionMode := @TheSkipNewLineInsertionMode; FFramesetOkFlag := False; end else if (Token.TagName = eForm) then begin if (Assigned(FFormElementPointer) and (not StackOfOpenElementsHas(nsHTML, eTemplate))) then begin {$IFDEF PARSEERROR} ParseError('unexpected form element start tag'); {$ENDIF} end else begin if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); NewElement := InsertAnHTMLElementFor(Token); if (not StackOfOpenElementsHas(nsHTML, eTemplate)) then FFormElementPointer := NewElement; end; end else if (Token.TagName = ePlaintext) then begin if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); InsertAnHTMLElementFor(Token); FTokeniserState := tsPlaintextState; end else if (Token.TagName = eButton) then begin if (StackOfOpenElementsHasInScope(eButton)) then begin {$IFDEF PARSEERROR} ParseError('unexpected button start tag'); {$ENDIF} GenerateImpliedEndTags(); repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eButton); end; ReconstructTheActiveFormattingElements(); InsertAnHTMLElementFor(Token); FFramesetOkFlag := False; end else if ((Token.TagName = eB) or (Token.TagName = eBig) or //(Token.TagName = eCode) or // hoisted higher (Token.TagName = eEm) or (Token.TagName = eFont) or //(Token.TagName = eI) or // hoisted higher (Token.TagName = eS) or (Token.TagName = eSmall) or (Token.TagName = eStrike) or (Token.TagName = eStrong) or (Token.TagName = eTT) or (Token.TagName = eU)) then begin ReconstructTheActiveFormattingElements(); PushOntoTheListOfActiveFormattingElements(InsertAnHTMLElementFor(Token)); end else if (Token.TagName = eNoBr) then begin ReconstructTheActiveFormattingElements(); if (StackOfOpenElementsHasInScope(eNoBr)) then begin {$IFDEF PARSEERROR} ParseError('unexpected nobr start tag'); {$ENDIF} CallAdoptionAgency(eNoBr); ReconstructTheActiveFormattingElements(); end; PushOntoTheListOfActiveFormattingElements(InsertAnHTMLElementFor(Token)); end else if ((Token.TagName = eApplet) or (Token.TagName = eMarquee) or (Token.TagName = eObject)) then begin ReconstructTheActiveFormattingElements(); InsertAnHTMLElementFor(Token); InsertMarkerAtEndOfListOfActiveFormattingElements(); FFramesetOkFlag := False; end else if (Token.TagName = eTable) then begin if ((FDocument.DocumentMode <> dmQuirksMode) and (StackOfOpenElementsHasInButtonScope(eP))) then CloseAPElement(); InsertAnHTMLElementFor(Token); FFramesetOkFlag := False; FInsertionMode := @TheInTableInsertionMode; end else if ((Token.TagName = eArea) or (Token.TagName = eBr) or (Token.TagName = eEmbed) or (Token.TagName = eImg) or (Token.TagName = eKeygen) or (Token.TagName = eWBr)) then begin ReconstructTheActiveFormattingElements(); InsertAnHTMLElementFor(Token); FStackOfOpenElements.Pop(); {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} FFramesetOkFlag := False; end else if (Token.TagName = eInput) then begin ReconstructTheActiveFormattingElements(); NewElement := InsertAnHTMLElementFor(Token); FStackOfOpenElements.Pop(); {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} // XXX Should cache this on the element as a property when creating it if ((not NewElement.HasAttribute('type')) or (ASCIILowerCase(NewElement.GetAttribute('type').AsString) <> 'hidden')) then FFramesetOkFlag := False; end else if ((Token.TagName = eMenuItem) or (Token.TagName = eParam) or (Token.TagName = eSource) or (Token.TagName = eTrack)) then begin InsertAnHTMLElementFor(Token); FStackOfOpenElements.Pop(); {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} end else if (Token.TagName = eImage) then begin {$IFDEF PARSEERROR} ParseError('unexpected image start tag'); {$ENDIF} Token.TagName := eImg; TreeConstructionDispatcher(Token); end else if (Token.TagName = eIsIndex) then begin {$IFDEF PARSEERROR} ParseError('unexpected isindex start tag'); {$ENDIF} if ((not StackOfOpenElementsHas(nsHTML, eTemplate)) and (Assigned(FFormElementPointer))) then exit; {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} FFramesetOkFlag := False; if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); NewElement := InsertAnHTMLElement(ConstructHTMLElement(eForm)); Assert(not Assigned(FFormElementPointer)); if (not StackOfOpenElementsHas(nsHTML, eTemplate)) then FFormElementPointer := NewElement; Attributes := Token.TakeAttributes(); if (Assigned(Attributes) and Attributes.Has('action')) then begin TemporaryAttributeValue := Attributes['action']; NewElement.SetAttributeDestructively('action', TemporaryAttributeValue); Attributes.Remove('action'); end; InsertAnHTMLElement(ConstructHTMLElement(eHR)); FStackOfOpenElements.Pop(); ReconstructTheActiveFormattingElements(); InsertAnHTMLElement(ConstructHTMLElement(eLabel)); if (Assigned(Attributes) and Attributes.Has('prompt')) then begin TemporaryAttributeValue := Attributes['prompt']; // InsertCharacters(TemporaryAttributeValue); Assert(not FFosterParenting); Assert(CurrentNode.IsIdentity(nsHTML, eLabel)); (CurrentNode as TElement).AppendChild(TText.CreateDestructively(TemporaryAttributeValue)); Attributes.Remove('prompt'); end else InsertCharacters('This is a searchable index. Enter search keywords: '); if (not Assigned(Attributes)) then Attributes := TElement.TAttributeHashTable.Create(1); TemporaryAttributeValue := Default(TParserString); TemporaryString := 'isindex'; TemporaryAttributeValue.Append(@TemporaryString); Attributes['name'] := TemporaryAttributeValue; InsertAnHTMLElement(ConstructHTMLElement(eInput, Attributes)); FStackOfOpenElements.Pop(); // InsertCharacters(''); Assert(CurrentNode.IsIdentity(nsHTML, eLabel)); FStackOfOpenElements.Pop(); InsertAnHTMLElement(ConstructHTMLElement(eHR)); FStackOfOpenElements.Pop(); Assert(CurrentNode = NewElement); FStackOfOpenElements.Pop(); if (not StackOfOpenElementsHas(nsHTML, eTemplate)) then begin Assert(FFormElementPointer = NewElement); FFormElementPointer := nil; end; end else if (Token.TagName = eTextArea) then begin InsertAnHTMLElementFor(Token); FTokeniserState := tsRcdataState; FOriginalInsertionMode := FInsertionMode; FFramesetOkFlag := false; FInsertionMode := @TheSkipNewLineThenTextInsertionMode; end else if (Token.TagName = eXMP) then begin if (StackOfOpenElementsHasInButtonScope(eP)) then CloseAPElement(); ReconstructTheActiveFormattingElements(); FFramesetOkFlag := False; GenericRawTextElementParsingAlgorithm(Token); end else if (Token.TagName = eIFrame) then begin FFramesetOkFlag := False; GenericRawTextElementParsingAlgorithm(Token); end else if ((Token.TagName = eNoEmbed) or ((Token.TagName = eNoScript) and (FScriptingFlag))) then begin GenericRawTextElementParsingAlgorithm(Token); end else if (Token.TagName = eSelect) then begin ReconstructTheActiveFormattingElements(); InsertAnHTMLElementFor(Token); FFramesetOkFlag := False; if ((FInsertionMode = @TheInTableInsertionMode) or (FInsertionMode = @TheInCaptionInsertionMode) or (FInsertionMode = @TheInTableBodyInsertionMode) or (FInsertionMode = @TheInRowInsertionMode) or (FInsertionMode = @TheInCellInsertionMode)) then FInsertionMode := @TheInSelectInTableInsertionMode else FInsertionMode := @TheInSelectInsertionMode; end else if ((Token.TagName = eOptGroup) or (Token.TagName = eOption)) then begin if (CurrentNode.IsIdentity(nsHTML, eOption)) then FStackOfOpenElements.Pop(); ReconstructTheActiveFormattingElements(); InsertAnHTMLElementFor(Token); end else if ((Token.TagName = eRP) or (Token.TagName = eRT)) then begin if (StackOfOpenElementsHasInScope(eRuby)) then GenerateImpliedEndTags(); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, eRuby)) then ParseError('unexpected start tag'); {$ENDIF} InsertAnHTMLElementFor(Token); end else if ((Token.TagName = eMath)) then begin ReconstructTheActiveFormattingElements(); Token.AdjustMathMLAttributes(); Token.AdjustForeignAttributes(); InsertAForeignElementFor(Token, nsMathML); if (Token.SelfClosingFlag) then begin FStackOfOpenElements.Pop(); {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} end; end else if ((Token.TagName = eSVG)) then begin ReconstructTheActiveFormattingElements(); Token.AdjustSVGAttributes(); Token.AdjustForeignAttributes(); InsertAForeignElementFor(Token, nsSVG); if (Token.SelfClosingFlag) then begin FStackOfOpenElements.Pop(); {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} end; end else if ((Token.TagName = eCaption) or (Token.TagName = eCol) or (Token.TagName = eColGroup) or (Token.TagName = eFrame) or (Token.TagName = eHead) or (Token.TagName = eTBody) or (Token.TagName = eTD) or (Token.TagName = eTFoot) or (Token.TagName = eTH) or (Token.TagName = eTHead) or (Token.TagName = eTR)) then begin {$IFDEF PARSEERROR} ParseError('unexpected start tag'); {$ENDIF} end else begin // any other start tag ReconstructTheActiveFormattingElements(); InsertAnHTMLElementFor(Token); if (FProprietaryVoids.Contains(Token.TagName)) then begin FStackOfOpenElements.Pop(); {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} end; end; tkEndTag: // in this section things are hoisted also if (Token.TagName = eCode) then begin CallAdoptionAgency(Token.TagName); end else if (Token.TagName = eSpan) then begin // any other end tag AnyOtherEndTag(); end else if (Token.TagName = eP) then begin if (not StackOfOpenElementsHasInButtonScope(eP)) then begin {$IFDEF PARSEERROR} ParseError('unexpected p end tag'); {$ENDIF} InsertAnHTMLElement(ConstructHTMLElement(eP)); end; CloseAPElement(); end else if (Token.TagName = eVar) then begin // any other end tag AnyOtherEndTag(); end else if (Token.TagName = eLI) then begin if (not StackOfOpenElementsHasInListItemScope(eLI)) then begin {$IFDEF PARSEERROR} ParseError('unexpected li end tag'); {$ENDIF} end else begin GenerateImpliedEndTagsExceptFor(eLI); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, eLI)) then ParseError('unexpected li end tag'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eLI); end; end else if (Token.TagName = eDfn) then begin // any other end tag AnyOtherEndTag(); end else if ((Token.TagName = eDD) or (Token.TagName = eDT)) then begin if (not StackOfOpenElementsHasInScope(Token.TagName)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag'); {$ENDIF} end else begin GenerateImpliedEndTagsExceptFor(Token.TagName); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, Token.TagName)) then ParseError('unexpected end tag'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, Token.TagName); end; end else if (Token.TagName = eI) then begin CallAdoptionAgency(Token.TagName); end else if ((Token.TagName = eDiv) or (Token.TagName = ePre) or (Token.TagName = eOL) or (Token.TagName = eDL)) then begin if (not StackOfOpenElementsHasInScope(Token.TagName)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag'); {$ENDIF} end else begin GenerateImpliedEndTags(); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, Token.TagName)) then ParseError('unexpected end tag'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, Token.TagName); end; end else if (Token.TagName = eA) then // this one really should be between div and pre above begin CallAdoptionAgency(Token.TagName); end else // remainder are in spec order if (Token.TagName = eTemplate) then begin TheInHeadInsertionMode(Token); end else if (Token.TagName = eBody) then begin if (not StackOfOpenElementsHasInScope(eBody)) then begin {$IFDEF PARSEERROR} ParseError('unexpected body end tag'); {$ENDIF} end else begin {$IFDEF PARSEERROR} if (StackOfOpenElementsHasElementOtherThan(propEOFImpliedEndTag)) then ParseError('unexpected body end tag'); {$ENDIF} FInsertionMode := @TheAfterBodyInsertionMode; end; end else if (Token.TagName = eHTML) then begin if (not StackOfOpenElementsHasInScope(eBody)) then begin {$IFDEF PARSEERROR} ParseError('unexpected html end tag'); {$ENDIF} end else begin {$IFDEF PARSEERROR} if (StackOfOpenElementsHasElementOtherThan(propEOFImpliedEndTag)) then ParseError('unexpected html end tag'); {$ENDIF} FInsertionMode := @TheAfterBodyInsertionMode; TreeConstructionDispatcher(Token); end; end else if ((Token.TagName = eAddress) or (Token.TagName = eArticle) or (Token.TagName = eAside) or (Token.TagName = eBlockQuote) or (Token.TagName = eButton) or (Token.TagName = eCenter) or (Token.TagName = eDetails) or (Token.TagName = eDialog) or (Token.TagName = eDir) or //(Token.TagName = eDiv) or // hoisted //(Token.TagName = eDL) or // hoisted (Token.TagName = eFieldSet) or (Token.TagName = eFigCaption) or (Token.TagName = eFigure) or (Token.TagName = eFooter) or (Token.TagName = eHeader) or (Token.TagName = eHGroup) or (Token.TagName = eListing) or (Token.TagName = eMain) or (Token.TagName = eMenu) or (Token.TagName = eNav) or //(Token.TagName = eOL) or // hoisted //(Token.TagName = ePre) or // hoisted (Token.TagName = eSection) or (Token.TagName = eSummary) or (Token.TagName = eUL)) then begin if (not StackOfOpenElementsHasInScope(Token.TagName)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag'); {$ENDIF} end else begin GenerateImpliedEndTags(); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, Token.TagName)) then ParseError('unexpected end tag'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, Token.TagName); end; end else if (Token.TagName = eForm) then begin if (not StackOfOpenElementsHas(nsHTML, eTemplate)) then begin Node := FFormElementPointer; FFormElementPointer := nil; if ((not Assigned(Node)) or (not StackOfOpenElementsHasInScope(Node))) then begin {$IFDEF PARSEERROR} ParseError('unexpected form end tag'); {$ENDIF} exit; end; GenerateImpliedEndTags(); {$IFDEF PARSEERROR} if (CurrentNode <> Node) then ParseError('unexpected form end tag'); {$ENDIF} FStackOfOpenElements.Remove(Node); end else begin if (not StackOfOpenElementsHasInScope(eForm)) then begin {$IFDEF PARSEERROR} ParseError('unexpected form end tag'); {$ENDIF} exit; end; GenerateImpliedEndTags(); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, eTable)) then ParseError('unexpected form end tag'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eTable); end; end else if ((Token.TagName = eH1) or (Token.TagName = eH2) or (Token.TagName = eH3) or (Token.TagName = eH4) or (Token.TagName = eH5) or (Token.TagName = eH6)) then begin if (not StackOfOpenElementsHasInScope(propHeading)) then begin {$IFDEF PARSEERROR} ParseError('unexpected heading end tag'); {$ENDIF} end else begin GenerateImpliedEndTags(); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, Token.TagName)) then ParseError('unexpected heading end tag'); {$ENDIF} repeat until FStackOfOpenElements.Pop().HasProperties(propHeading); end; end else // if (Token.TagName = eSarcasm) then // begin // DeepBreath(); // AnyOtherEndTag(); // end // else if (//(Token.TagName = eA) or // hoisted (Token.TagName = eB) or (Token.TagName = eBig) or //(Token.TagName = eCode) or // hoisted (Token.TagName = eEm) or (Token.TagName = eFont) or //(Token.TagName = eI) or // hoisted (Token.TagName = eNoBr) or (Token.TagName = eS) or (Token.TagName = eSmall) or (Token.TagName = eStrike) or (Token.TagName = eStrong) or (Token.TagName = eTT) or (Token.TagName = eU)) then begin CallAdoptionAgency(Token.TagName); end else if ((Token.TagName = eApplet) or (Token.TagName = eMarquee) or (Token.TagName = eObject)) then begin if (not StackOfOpenElementsHasInScope(Token.TagName)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag'); {$ENDIF} end else begin GenerateImpliedEndTags(); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, Token.TagName)) then ParseError('unexpected end tag'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, Token.TagName); ClearTheListOfActiveFormattingElementsUpToTheLastMarker(); end; end else if (Token.TagName = eBr) then begin {$IFDEF PARSEERROR} ParseError('unexpected br end tag'); {$ENDIF} Token.TakeAttributes().Free(); ReconstructTheActiveFormattingElements(); InsertAnHTMLElementFor(Token); FStackOfOpenElements.Pop(); FFramesetOkFlag := False; end else begin // any other end tag AnyOtherEndTag(); end; tkExtraCharacters: begin ReconstructTheActiveFormattingElements(); InsertCharacters(Token.ExtraChars); FFramesetOkFlag := False; end; tkComment: begin InsertAComment(Token); end; // remaining states didn't happen often enough to matter {$IFDEF PARSEERROR} tkNullCharacter: ParseError('unexpected null in text'); {$ENDIF} tkExtraSpaceCharacter: begin ReconstructTheActiveFormattingElements(); InsertCharacters(Token.ExtraChars); end; {$IFDEF PARSEERROR} tkDOCTYPE: ParseError('unexpected DOCTYPE'); {$ENDIF} tkEOF: begin if (FStackOfTemplateInsertionModes.Length > 0) then begin TheInTemplateInsertionMode(Token); end else begin {$IFDEF PARSEERROR} if (StackOfOpenElementsHasElementOtherThan(propEOFImpliedEndTag)) then ParseError('unexpected end of file'); {$ENDIF} // and then we stop parsing end; end; {$IFDEF PARSEERROR} else Assert(False); {$ENDIF} end; end; procedure THTMLParser.TheTextInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); Assert(Assigned(FOriginalInsertionMode)); case (Token.Kind) of tkSourceCharacters: begin InsertCharactersFor(Token); end; tkExtraCharacters, tkExtraSpaceCharacter: begin InsertCharacters(Token.ExtraChars); end; tkEOF: begin {$IFDEF PARSEERROR} ParseError('unexpected EOF'); {$ENDIF} FStackOfOpenElements.Pop(); FInsertionMode := FOriginalInsertionMode; {$IFOPT C+} FOriginalInsertionMode := nil; {$ENDIF} TreeConstructionDispatcher(Token); // http://bugs.freepascal.org/view.php?id=26403 end; tkEndTag: begin FStackOfOpenElements.Pop(); FInsertionMode := FOriginalInsertionMode; {$IFOPT C+} FOriginalInsertionMode := nil; {$ENDIF} end; else Assert(False); // tkComment, tkDOCTYPE, tkNullCharacter, tkStartTag end; end; procedure THTMLParser.TheInTableInsertionMode(var Token: TToken); procedure ClearTheStackBackToATableContext(); inline; begin while (not CurrentNode.HasProperties(propTableScope)) do FStackOfOpenElements.Pop(); end; begin {$IFDEF VERBOSETABLE} if (DebugNow) then Writeln('"in table" with token kind ', Token.Kind); {$ENDIF} Assert(Assigned(FDocument)); case (Token.Kind) of tkNullCharacter, tkSourceCharacters, tkExtraCharacters, tkExtraSpaceCharacter: begin if (CurrentNode.HasProperties(propFosterParent)) then begin FPendingTableCharacterTokensList := Default(TParserString); FPendingTableCharacterTokensListHasNonSpaces := False; FOriginalInsertionMode := FInsertionMode; FInsertionMode := @TheInTableTextInsertionMode; TreeConstructionDispatcher(Token); // http://bugs.freepascal.org/view.php?id=26403 exit; end; // otherwise, treat as anything else below end; tkComment: begin InsertAComment(Token); exit; end; tkDOCTYPE: begin {$IFDEF PARSEERROR} ParseError('unexpected DOCTYPE'); {$ENDIF} exit; end; tkStartTag: if (Token.TagName = eCaption) then begin ClearTheStackBackToATableContext(); InsertMarkerAtEndOfListOfActiveFormattingElements(); InsertAnHTMLElementFor(Token); FInsertionMode := @TheInCaptionInsertionMode; exit; end else if (Token.TagName = eColGroup) then begin ClearTheStackBackToATableContext(); InsertAnHTMLElementFor(Token); FInsertionMode := @TheInColumnGroupInsertionMode; exit; end else if (Token.TagName = eCol) then begin ClearTheStackBackToATableContext(); InsertAnHTMLElement(ConstructHTMLElement(eColGroup)); FInsertionMode := @TheInColumnGroupInsertionMode; TreeConstructionDispatcher(Token); exit; end else if ((Token.TagName = eTBody) or (Token.TagName = eTFoot) or (Token.TagName = eTHead)) then begin ClearTheStackBackToATableContext(); InsertAnHTMLElementFor(Token); FInsertionMode := @TheInTableBodyInsertionMode; exit; end else if ((Token.TagName = eTD) or (Token.TagName = eTH) or (Token.TagName = eTR)) then begin ClearTheStackBackToATableContext(); InsertAnHTMLElement(ConstructHTMLElement(eTBody)); FInsertionMode := @TheInTableBodyInsertionMode; TreeConstructionDispatcher(Token); exit; end else if (Token.TagName = eTable) then begin {$IFDEF PARSEERROR} ParseError('unexpected table start tag in table'); {$ENDIF} if (StackOfOpenElementsHasInTableScope(eTable)) then begin repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eTable); ResetTheInsertionModeAppropriately(); TreeConstructionDispatcher(Token); end; exit; end else if ((Token.TagName = eStyle) or (Token.TagName = eScript) or (Token.TagName = eTemplate)) then begin TheInHeadInsertionMode(Token); exit; end else if (Token.TagName = eInput) then begin if (ASCIILowerCase(Token.GetAttribute('type')) = 'hidden') then begin {$IFDEF PARSEERROR} ParseError('unexpected input start tag in table'); {$ENDIF} InsertAnHTMLElementFor(Token); FStackOfOpenElements.Pop(); {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} exit; end; end else if (Token.TagName = eForm) then begin {$IFDEF PARSEERROR} ParseError('unexpected form start tag in table'); {$ENDIF} if ((not StackOfOpenElementsHas(nsHTML, eTemplate)) and (not Assigned(FFormElementPointer))) then begin FFormElementPointer := InsertAnHTMLElementFor(Token); FStackOfOpenElements.Pop(); end; exit; end; tkEndTag: if (Token.TagName = eTable) then begin if (not StackOfOpenElementsHasInTableScope(eTable)) then begin {$IFDEF PARSEERROR} ParseError('unexpected table end tag'); {$ENDIF} end else begin repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eTable); ResetTheInsertionModeAppropriately(); end; exit; end else if ((Token.TagName = eBody) or (Token.TagName = eCaption) or (Token.TagName = eCol) or (Token.TagName = eColGroup) or (Token.TagName = eHTML) or (Token.TagName = eTBody) or (Token.TagName = eTD) or (Token.TagName = eTFoot) or (Token.TagName = eTH) or (Token.TagName = eTHead) or (Token.TagName = eTR)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag in table'); {$ENDIF} exit; end else if (Token.TagName = eTemplate) then begin TheInHeadInsertionMode(Token); exit; end; tkEOF: begin TheInBodyInsertionMode(Token); exit; end; else Assert(False); end; // anything else {$IFDEF PARSEERROR} case (Token.Kind) of tkSourceCharacters: ParseError('unexpected character token in table', Token.GetCharacterCount(FInputStream.Data)); tkExtraSpaceCharacter, tkExtraCharacters: ParseError('unexpected character token in table', Length(Token.ExtraChars)); // $R- tkNullCharacter: ParseError('unexpected null in table'); else ParseError('unexpected token in table - foster parenting'); end; {$ENDIF} Assert(not FFosterParenting); FFosterParenting := True; TheInBodyInsertionMode(Token); Assert(FFosterParenting); FFosterParenting := False; end; procedure THTMLParser.TheInTableTextInsertionMode(var Token: TToken); var Placeholder: TCutParserString; begin Assert(Assigned(FDocument)); Assert(Assigned(FOriginalInsertionMode)); {$IFDEF VERBOSETABLE} if (DebugNow) then Writeln('"in table text" with token kind ', Token.Kind); {$ENDIF} case (Token.Kind) of tkNullCharacter: {$IFDEF PARSEERROR} ParseError('unexpected null in table') {$ENDIF}; tkSourceCharacters: begin Placeholder := Token.ExtractSourceCharacters(FInputStream.Data); FPendingTableCharacterTokensList.AppendDestructively(Placeholder); if (ssHaveNonSpace in Token.SpaceState) then FPendingTableCharacterTokensListHasNonSpaces := True; end; tkExtraCharacters: begin FPendingTableCharacterTokensList.Append(Token.ExtraChars); FPendingTableCharacterTokensListHasNonSpaces := True; end; tkExtraSpaceCharacter: begin FPendingTableCharacterTokensList.Append(Token.ExtraChars); end; else begin {$IFDEF VERBOSETABLE} if (DebugNow) then Writeln('FPendingTableCharacterTokensList: "', FPendingTableCharacterTokensList, '"'); {$ENDIF} if (FPendingTableCharacterTokensListHasNonSpaces) then begin // inlined copy of the "anything else" entry in the "in table" insertion mode {$IFDEF PARSEERROR} // XXX This should really be optimised somehow ParseError('unexpected text in table', Length(FPendingTableCharacterTokensList.AsString)); // $R- {$ENDIF} Assert(not FFosterParenting); FFosterParenting := True; // inline copy of the "any other character token" entry in the "in body" insertion mode begin ReconstructTheActiveFormattingElements(); InsertCharacters(FPendingTableCharacterTokensList); Assert(not FFramesetOkFlag); end; // back to the "anything else" entry in the "in table" insertion mode Assert(FFosterParenting); FFosterParenting := False; end else InsertCharacters(FPendingTableCharacterTokensList); Assert(Assigned(FOriginalInsertionMode)); FInsertionMode := FOriginalInsertionMode; {$IFOPT C+} FOriginalInsertionMode := nil; {$ENDIF} TreeConstructionDispatcher(Token); end; end; end; procedure THTMLParser.TheInCaptionInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of tkStartTag: if ((Token.TagName = eCaption) or (Token.TagName = eCol) or (Token.TagName = eColGroup) or (Token.TagName = eTBody) or (Token.TagName = eTD) or (Token.TagName = eTFoot) or (Token.TagName = eTH) or (Token.TagName = eTHead) or (Token.TagName = eTR)) then begin if (not StackOfOpenElementsHasInTableScope(eCaption)) then begin {$IFDEF PARSEERROR} ParseError('unexpected start tag in caption'); {$ENDIF} exit; end; GenerateImpliedEndTags(); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, eCaption)) then ParseError('unexpected start tag in caption'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eCaption); ClearTheListOfActiveFormattingElementsUpToTheLastMarker(); FInsertionMode := @TheInTableInsertionMode; TreeConstructionDispatcher(Token); // http://bugs.freepascal.org/view.php?id=26403 exit; end; tkEndTag: if (Token.TagName = eCaption) then begin if (not StackOfOpenElementsHasInTableScope(eCaption)) then begin {$IFDEF PARSEERROR} ParseError('unexpected caption end tag in caption'); {$ENDIF} exit; end; GenerateImpliedEndTags(); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, eCaption)) then ParseError('unexpected caption end tag in caption'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eCaption); ClearTheListOfActiveFormattingElementsUpToTheLastMarker(); FInsertionMode := @TheInTableInsertionMode; exit; end else if (Token.TagName = eTable) then begin if (not StackOfOpenElementsHasInTableScope(eCaption)) then begin {$IFDEF PARSEERROR} ParseError('unexpected table end tag in caption'); {$ENDIF} exit; end; GenerateImpliedEndTags(); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, eCaption)) then ParseError('unexpected table end tag in caption'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eCaption); ClearTheListOfActiveFormattingElementsUpToTheLastMarker(); FInsertionMode := @TheInTableInsertionMode; TreeConstructionDispatcher(Token); exit; end else if ((Token.TagName = eBody) or (Token.TagName = eCol) or (Token.TagName = eColGroup) or (Token.TagName = eHTML) or (Token.TagName = eTBody) or (Token.TagName = eTD) or (Token.TagName = eTFoot) or (Token.TagName = eTH) or (Token.TagName = eTHead) or (Token.TagName = eTR)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag in caption'); {$ENDIF} exit; end; end; // anything else TheInBodyInsertionMode(Token); end; procedure THTMLParser.TheInColumnGroupInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of tkSourceCharacters: begin if (ssHaveNonSpace in Token.SpaceState) then begin if (ssHaveLeadingSpace in Token.SpaceState) then InsertLeadingSpacesFor(Token); // http://bugs.freepascal.org/view.php?id=26403 // fall through to "anything else" clause end else begin InsertCharactersFor(Token); exit; end; end; tkExtraSpaceCharacter: begin InsertCharacters(Token.ExtraChars); exit; end; tkComment: begin InsertAComment(Token); exit; end; tkDOCTYPE: begin {$IFDEF PARSEERROR} ParseError('unexpected DOCTYPE'); {$ENDIF} exit; end; tkStartTag: if (Token.TagName = eHTML) then begin TheInBodyInsertionMode(Token); exit; end else if (Token.TagName = eCol) then begin InsertAnHTMLElementFor(Token); FStackOfOpenElements.Pop(); {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} exit; end else if (Token.TagName = eTemplate) then begin TheInHeadInsertionMode(Token); exit; end; tkEndTag: if (Token.TagName = eColGroup) then begin if (not CurrentNode.IsIdentity(nsHTML, eColGroup)) then begin {$IFDEF PARSEERROR} ParseError('unexpected colgroup end tag'); {$ENDIF} end else begin FStackOfOpenElements.Pop(); FInsertionMode := @TheInTableInsertionMode; end; exit; end else if (Token.TagName = eCol) then begin {$IFDEF PARSEERROR} ParseError('unexpected col end tag'); {$ENDIF} exit; end else if (Token.TagName = eTemplate) then begin TheInHeadInsertionMode(Token); exit; end; tkEOF: begin TheInBodyInsertionMode(Token); exit; end; else Assert(False); end; // anything else if (not CurrentNode.IsIdentity(nsHTML, eColGroup)) then begin {$IFDEF PARSEERROR} ParseError('unexpected token'); {$ENDIF} end else begin FStackOfOpenElements.Pop(); FInsertionMode := @TheInTableInsertionMode; TreeConstructionDispatcher(Token); end; end; procedure THTMLParser.TheInTableBodyInsertionMode(var Token: TToken); procedure ClearTheStackBackToATableBodyContext(); inline; begin while (not CurrentNode.HasProperties(propTBodyContext)) do FStackOfOpenElements.Pop(); end; begin Assert(Assigned(FDocument)); case (Token.Kind) of tkStartTag: if (Token.TagName = eTR) then begin ClearTheStackBackToATableBodyContext(); InsertAnHTMLElementFor(Token); FInsertionMode := @TheInRowInsertionMode; exit; end else if ((Token.TagName = eTH) or (Token.TagName = eTD)) then begin {$IFDEF PARSEERROR} ParseError('unexpected cell start tag in table body'); {$ENDIF} ClearTheStackBackToATableBodyContext(); InsertAnHTMLElement(ConstructHTMLElement(eTR)); FInsertionMode := @TheInRowInsertionMode; TreeConstructionDispatcher(Token); // http://bugs.freepascal.org/view.php?id=26403 exit; end else if ((Token.TagName = eCaption) or (Token.TagName = eCol) or (Token.TagName = eColGroup) or (Token.TagName = eTBody) or (Token.TagName = eTFoot) or (Token.TagName = eTHead)) then begin if (not StackOfOpenElementsHasInTableScope(propTableSection)) then begin {$IFDEF PARSEERROR} ParseError('unexpected start tag in table body'); {$ENDIF} exit; end; ClearTheStackBackToATableBodyContext(); Assert(CurrentNode.HasProperties(propTableSection)); FStackOfOpenElements.Pop(); FInsertionMode := @TheInTableInsertionMode; TreeConstructionDispatcher(Token); exit; end; tkEndTag: if ((Token.TagName = eTBody) or (Token.TagName = eTFoot) or (Token.TagName = eTHead)) then begin if (not StackOfOpenElementsHasInTableScope(Token.TagName)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag in table body'); {$ENDIF} exit; end; ClearTheStackBackToATableBodyContext(); Assert(CurrentNode.IsIdentity(nsHTML, Token.TagName)); FStackOfOpenElements.Pop(); FInsertionMode := @TheInTableInsertionMode; exit; end else if (Token.TagName = eTable) then begin if (not StackOfOpenElementsHasInTableScope(propTableSection)) then begin {$IFDEF PARSEERROR} ParseError('unexpected table end tag in table body'); {$ENDIF} exit; end; ClearTheStackBackToATableBodyContext(); Assert(CurrentNode.HasProperties(propTableSection)); FStackOfOpenElements.Pop(); FInsertionMode := @TheInTableInsertionMode; TreeConstructionDispatcher(Token); exit; end else if ((Token.TagName = eBody) or (Token.TagName = eCaption) or (Token.TagName = eCol) or (Token.TagName = eColGroup) or (Token.TagName = eHTML) or (Token.TagName = eTD) or (Token.TagName = eTH) or (Token.TagName = eTR)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag in table body'); {$ENDIF} exit; end; end; // anything else TheInTableInsertionMode(Token); end; procedure THTMLParser.TheInRowInsertionMode(var Token: TToken); procedure ClearTheStackBackToATableRowContext(); inline; begin while (not CurrentNode.HasProperties(propTRContext)) do FStackOfOpenElements.Pop(); end; procedure CloseRow(); begin ClearTheStackBackToATableRowContext(); Assert(CurrentNode.IsIdentity(nsHTML, eTR)); FStackOfOpenElements.Pop(); FInsertionMode := @TheInTableBodyInsertionMode; end; begin Assert(Assigned(FDocument)); case (Token.Kind) of tkStartTag: if ((Token.TagName = eTH) or (Token.TagName = eTD)) then begin ClearTheStackBackToATableRowContext(); InsertAnHTMLElementFor(Token); FInsertionMode := @TheInCellInsertionMode; InsertMarkerAtEndOfListOfActiveFormattingElements(); exit; end else if ((Token.TagName = eCaption) or (Token.TagName = eCol) or (Token.TagName = eColGroup) or (Token.TagName = eTBody) or (Token.TagName = eTFoot) or (Token.TagName = eTHead) or (Token.TagName = eTR)) then begin if (not StackOfOpenElementsHasInTableScope(eTR)) then begin {$IFDEF PARSEERROR} ParseError('unexpected start tag in table row'); {$ENDIF} end else begin CloseRow(); TreeConstructionDispatcher(Token); // http://bugs.freepascal.org/view.php?id=26403 end; exit; end; tkEndTag: if (Token.TagName = eTR) then begin if (not StackOfOpenElementsHasInTableScope(eTR)) then begin {$IFDEF PARSEERROR} ParseError('unexpected tr end tag in table row'); {$ENDIF} end else begin CloseRow(); end; exit; end else if (Token.TagName = eTable) then begin if (not StackOfOpenElementsHasInTableScope(eTR)) then begin {$IFDEF PARSEERROR} ParseError('unexpected table end tag in table row'); {$ENDIF} end else begin CloseRow(); TreeConstructionDispatcher(Token); end; exit; end else if ((Token.TagName = eTBody) or (Token.TagName = eTFoot) or (Token.TagName = eTHead)) then begin if (not StackOfOpenElementsHasInTableScope(Token.TagName)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag in table row'); {$ENDIF} end else if (StackOfOpenElementsHasInTableScope(eTR)) then begin CloseRow(); TreeConstructionDispatcher(Token); end; exit; end else if ((Token.TagName = eBody) or (Token.TagName = eCaption) or (Token.TagName = eCol) or (Token.TagName = eColGroup) or (Token.TagName = eHTML) or (Token.TagName = eTD) or (Token.TagName = eTH)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag in table row'); {$ENDIF} exit; end; end; // anything else TheInTableBodyInsertionMode(Token); end; procedure THTMLParser.TheInCellInsertionMode(var Token: TToken); procedure CloseTheCell(); inline; begin Assert(StackOfOpenElementsHasInTableScope(eTD) xor StackOfOpenElementsHasInTableScope(eTH)); GenerateImpliedEndTags(); {$IFDEF PARSEERROR} if (not CurrentNode.HasProperties(propTableCell)) then ParseError('forcibly closing cell'); {$ENDIF} repeat until FStackOfOpenElements.Pop().HasProperties(propTableCell); ClearTheListOfActiveFormattingElementsUpToTheLastMarker(); FInsertionMode := @TheInRowInsertionMode; end; begin Assert(Assigned(FDocument)); case (Token.Kind) of tkStartTag: if ((Token.TagName = eCaption) or (Token.TagName = eCol) or (Token.TagName = eColGroup) or (Token.TagName = eTBody) or (Token.TagName = eTD) or (Token.TagName = eTFoot) or (Token.TagName = eTH) or (Token.TagName = eTHead) or (Token.TagName = eTR)) then begin if (not StackOfOpenElementsHasInTableScope(propTableCell)) then begin {$IFDEF PARSEERROR} ParseError('unexpected start tag in table cell'); {$ENDIF} end else begin CloseTheCell(); TreeConstructionDispatcher(Token); // http://bugs.freepascal.org/view.php?id=26403 end; exit; end; tkEndTag: if ((Token.TagName = eTD) or (Token.TagName = eTH)) then begin if (not StackOfOpenElementsHasInTableScope(Token.TagName)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag in table cell'); {$ENDIF} end else begin GenerateImpliedEndTags(); {$IFDEF PARSEERROR} if (not CurrentNode.IsIdentity(nsHTML, Token.TagName)) then ParseError('unexpected end tag in table cell'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, Token.TagName); ClearTheListOfActiveFormattingElementsUpToTheLastMarker(); FInsertionMode := @TheInRowInsertionMode; end; exit; end else if ((Token.TagName = eBody) or (Token.TagName = eCaption) or (Token.TagName = eCol) or (Token.TagName = eColGroup) or (Token.TagName = eHTML)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag in table cell'); {$ENDIF} exit; end else if ((Token.TagName = eTable) or (Token.TagName = eTBody) or (Token.TagName = eTFoot) or (Token.TagName = eTHead) or (Token.TagName = eTR)) then begin if (not StackOfOpenElementsHasInTableScope(Token.TagName)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag in table cell'); {$ENDIF} end else begin CloseTheCell(); TreeConstructionDispatcher(Token); end; exit; end; end; // anything else TheInBodyInsertionMode(Token); end; procedure THTMLParser.TheInSelectInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of tkNullCharacter: begin {$IFDEF PARSEERROR} ParseError('unexpected null in select'); {$ENDIF} exit; end; tkSourceCharacters: begin InsertCharactersFor(Token); exit; end; tkExtraCharacters, tkExtraSpaceCharacter: begin InsertCharacters(Token.ExtraChars); exit; end; tkComment: begin InsertAComment(Token); // http://bugs.freepascal.org/view.php?id=26403 exit; end; tkDOCTYPE: begin {$IFDEF PARSEERROR} ParseError('unexpected DOCTYPE'); {$ENDIF} exit; end; tkStartTag: if (Token.TagName = eHTML) then begin TheInBodyInsertionMode(Token); exit; end else if (Token.TagName = eOption) then begin if (CurrentNode.IsIdentity(nsHTML, eOption)) then FStackOfOpenElements.Pop(); InsertAnHTMLElementFor(Token); exit; end else if (Token.TagName = eOptGroup) then begin if (CurrentNode.IsIdentity(nsHTML, eOption)) then FStackOfOpenElements.Pop(); if (CurrentNode.IsIdentity(nsHTML, eOptGroup)) then FStackOfOpenElements.Pop(); InsertAnHTMLElementFor(Token); exit; end else if (Token.TagName = eSelect) then begin {$IFDEF PARSEERROR} ParseError('unexpected select start tag in select'); {$ENDIF} if (StackOfOpenElementsHasInSelectScope(eSelect)) then begin repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eSelect); ResetTheInsertionModeAppropriately(); end; exit; end else if ((Token.TagName = eInput) or (Token.TagName = eKeygen) or (Token.TagName = eTextArea)) then begin {$IFDEF PARSEERROR} ParseError('unexpected start tag in select'); {$ENDIF} if (StackOfOpenElementsHasInSelectScope(eSelect)) then begin repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eSelect); ResetTheInsertionModeAppropriately(); TreeConstructionDispatcher(Token); end; exit; end else if ((Token.TagName = eScript) or (Token.TagName = eTemplate)) then begin TheInHeadInsertionMode(Token); exit; end; tkEndTag: if (Token.TagName = eOptGroup) then begin Assert(FStackOfOpenElements.Length >= 2); if (CurrentNode.IsIdentity(nsHTML, eOption) and FStackOfOpenElements[FStackOfOpenElements.Length-2].IsIdentity(nsHTML, eOptGroup)) then // $R- FStackOfOpenElements.Pop(); if (CurrentNode.IsIdentity(nsHTML, eOptGroup)) then FStackOfOpenElements.Pop() {$IFDEF PARSEERROR} else ParseError('unexpected optgroup end tag in select') {$ENDIF}; exit; end else if (Token.TagName = eOption) then begin if (CurrentNode.IsIdentity(nsHTML, eOption)) then FStackOfOpenElements.Pop() {$IFDEF PARSEERROR} else ParseError('unexpected option end tag in select') {$ENDIF}; exit; end else if (Token.TagName = eSelect) then begin if (not StackOfOpenElementsHasInSelectScope(eSelect)) then begin {$IFDEF PARSEERROR} ParseError('unexpected select start tag in select') {$ENDIF} end else begin repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eSelect); ResetTheInsertionModeAppropriately(); end; exit; end else if (Token.TagName = eTemplate) then begin TheInHeadInsertionMode(Token); exit; end; tkEOF: begin TheInBodyInsertionMode(Token); exit; end; else Assert(False); end; // anything else {$IFDEF PARSEERROR} ParseError('unexpected token in select'); {$ENDIF} end; procedure THTMLParser.TheInSelectInTableInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of tkStartTag: if ((Token.TagName = eCaption) or (Token.TagName = eTable) or (Token.TagName = eTBody) or (Token.TagName = eTFoot) or (Token.TagName = eTHead) or (Token.TagName = eTR) or (Token.TagName = eTD) or (Token.TagName = eTH)) then begin {$IFDEF PARSEERROR} ParseError('unexpected start tag in select'); {$ENDIF} repeat until FStackOfOpenElements.Pop.IsIdentity(nsHTML, eSelect); ResetTheInsertionModeAppropriately(); TreeConstructionDispatcher(Token); // http://bugs.freepascal.org/view.php?id=26403 exit; end; tkEndTag: if ((Token.TagName = eCaption) or (Token.TagName = eTable) or (Token.TagName = eTBody) or (Token.TagName = eTFoot) or (Token.TagName = eTHead) or (Token.TagName = eTR) or (Token.TagName = eTD) or (Token.TagName = eTH)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end tag in select'); {$ENDIF} if (StackOfOpenElementsHasInTableScope(Token.TagName)) then begin repeat until FStackOfOpenElements.Pop.IsIdentity(nsHTML, eSelect); ResetTheInsertionModeAppropriately(); TreeConstructionDispatcher(Token); end; exit; end; end; // anything else TheInSelectInsertionMode(Token); end; procedure THTMLParser.TheInTemplateInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of tkNullCharacter, tkSourceCharacters, tkExtraSpaceCharacter, tkExtraCharacters, tkComment, tkDOCTYPE: TheInBodyInsertionMode(Token); // http://bugs.freepascal.org/view.php?id=26403 tkStartTag: if ((Token.TagName = eBase) or (Token.TagName = eBaseFont) or (Token.TagName = eBGSound) or (Token.TagName = eLink) or (Token.TagName = eMeta) or (Token.TagName = eNoFrames) or (Token.TagName = eScript) or (Token.TagName = eStyle) or (Token.TagName = eTemplate) or (Token.TagName = eTitle)) then begin TheInHeadInsertionMode(Token); end else if ((Token.TagName = eCaption) or (Token.TagName = eColGroup) or (Token.TagName = eTBody) or (Token.TagName = eTFoot) or (Token.TagName = eTHead)) then begin FStackOfTemplateInsertionModes.Pop(); FStackOfTemplateInsertionModes.Push(@TheInTableInsertionMode); FInsertionMode := @TheInTableInsertionMode; TreeConstructionDispatcher(Token); end else if (Token.TagName = eCol) then begin FStackOfTemplateInsertionModes.Pop(); FStackOfTemplateInsertionModes.Push(@TheInColumnGroupInsertionMode); FInsertionMode := @TheInColumnGroupInsertionMode; TreeConstructionDispatcher(Token); end else if (Token.TagName = eTR) then begin FStackOfTemplateInsertionModes.Pop(); FStackOfTemplateInsertionModes.Push(@TheInTableBodyInsertionMode); FInsertionMode := @TheInTableBodyInsertionMode; TreeConstructionDispatcher(Token); end else if ((Token.TagName = eTD) or (Token.TagName = eTH)) then begin FStackOfTemplateInsertionModes.Pop(); FStackOfTemplateInsertionModes.Push(@TheInRowInsertionMode); FInsertionMode := @TheInRowInsertionMode; TreeConstructionDispatcher(Token); end else begin FStackOfTemplateInsertionModes.Pop(); FStackOfTemplateInsertionModes.Push(@TheInBodyInsertionMode); FInsertionMode := @TheInBodyInsertionMode; TreeConstructionDispatcher(Token); end; tkEndTag: if (Token.TagName = eTemplate) then begin TheInHeadInsertionMode(Token); end else begin {$IFDEF PARSEERROR} ParseError('unexpected token in template'); {$ENDIF} end; tkEOF: begin if (StackOfOpenElementsHas(nsHTML, eTemplate)) then begin {$IFDEF PARSEERROR} ParseError('unexpected end of file in template'); {$ENDIF} repeat until FStackOfOpenElements.Pop().IsIdentity(nsHTML, eTemplate); ClearTheListOfActiveFormattingElementsUpToTheLastMarker(); FStackOfTemplateInsertionModes.Pop(); ResetTheInsertionModeAppropriately(); TreeConstructionDispatcher(Token); end; // else we just stop parsing end; else Assert(False); end; end; procedure THTMLParser.TheAfterBodyInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of tkSourceCharacters: begin if (ssHaveNonSpace in Token.SpaceState) then begin if (ssHaveLeadingSpace in Token.SpaceState) then begin ReconstructTheActiveFormattingElements(); InsertLeadingSpacesFor(Token); // http://bugs.freepascal.org/view.php?id=26403 end; // fall through to "anything else" clause end else begin ReconstructTheActiveFormattingElements(); InsertCharactersFor(Token); exit; end; end; tkExtraSpaceCharacter: begin ReconstructTheActiveFormattingElements(); InsertCharacters(Token.ExtraChars); exit; end; tkComment: begin FStackOfOpenElements[0].AppendChild(CreateACommentFor(Token)); exit; end; tkDOCTYPE: begin {$IFDEF PARSEERROR} ParseError('unexpected DOCTYPE'); {$ENDIF} exit; end; tkStartTag: if (Token.TagName = eHTML) then begin TheInBodyInsertionMode(Token); exit; end; tkEndTag: if (Token.TagName = eHTML) then begin if (FFragmentParsingMode) then begin {$IFDEF PARSEERROR} ParseError('unexpected html end tag in fragment parser') {$ENDIF} end else FInsertionMode := @TheAfterAfterBodyInsertionMode; exit; end; tkEOF: begin // and then we stop parsing exit; end; else Assert(False); end; // anything else {$IFDEF PARSEERROR} ParseError('unexpected token after html'); {$ENDIF} FInsertionMode := @TheInBodyInsertionMode; TreeConstructionDispatcher(Token); end; procedure THTMLParser.TheInFramesetInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of {$IFDEF PARSEERROR} tkNullCharacter: ParseError('unexpected null'); {$ENDIF} tkSourceCharacters: begin if (ssHaveNonSpace in Token.SpaceState) then begin if (ssHaveLeadingSpace in Token.SpaceState) then InsertLeadingSpacesFor(Token); // http://bugs.freepascal.org/view.php?id=26403 repeat {$IFDEF PARSEERROR} ParseError('unexpected character token', Token.SkipLeadingNonSpaces(FInputStream.Data)); {$ELSE} Token.SkipLeadingNonSpaces(FInputStream.Data); {$ENDIF} if (ssHaveLeadingSpace in Token.SpaceState) then begin InsertLeadingSpacesFor(Token); end else break; until forever; end else begin InsertCharactersFor(Token); end; end; tkExtraSpaceCharacter: InsertCharacters(Token.ExtraChars); {$IFDEF PARSEERROR} tkExtraCharacters: ParseError('unexpected character token', Length(Token.ExtraChars)); {$ENDIF} // $R- tkComment: InsertAComment(Token); {$IFDEF PARSEERROR} tkDOCTYPE: ParseError('unexpected DOCTYPE'); {$ENDIF} tkStartTag: if (Token.TagName = eHTML) then begin TheInBodyInsertionMode(Token); end else if (Token.TagName = eFrameSet) then begin InsertAnHTMLElementFor(Token); end else if (Token.TagName = eFrame) then begin InsertAnHTMLElementFor(Token); FStackOfOpenElements.Pop(); {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} end else if (Token.TagName = eNoFrames) then begin TheInHeadInsertionMode(Token); end else begin {$IFDEF PARSEERROR} ParseError('unexpected start tag token'); {$ENDIF} end; tkEndTag: if (Token.TagName = eFrameSet) then begin if (FStackOfOpenElements.Length = 1) then begin Assert(CurrentNode.IsIdentity(nsHTML, eHTML)); {$IFDEF PARSEERROR} ParseError('unexpected frameset end tag'); {$ENDIF} end else begin FStackOfOpenElements.Pop(); if ((not FFragmentParsingMode) and (not CurrentNode.IsIdentity(nsHTML, eFrameSet))) then FInsertionMode := @TheAfterFramesetInsertionMode; end; end else begin {$IFDEF PARSEERROR} ParseError('unexpected end tag token'); {$ENDIF} end; tkEOF: begin {$IFDEF PARSEERROR} if (FStackOfOpenElements.Length <> 1) then ParseError('unexpected end of file') else Assert(CurrentNode.IsIdentity(nsHTML, eHTML)); {$ENDIF} // and then we stop parsing end; {$IFDEF PARSEERROR} else Assert(False); {$ENDIF} end; end; procedure THTMLParser.TheAfterFramesetInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of {$IFDEF PARSEERROR} tkNullCharacter: ParseError('unexpected character token after frameset'); {$ENDIF} tkSourceCharacters: begin if (ssHaveNonSpace in Token.SpaceState) then begin if (ssHaveLeadingSpace in Token.SpaceState) then InsertLeadingSpacesFor(Token); // http://bugs.freepascal.org/view.php?id=26403 repeat {$IFDEF PARSEERROR} ParseError('unexpected character token after frameset', Token.SkipLeadingNonSpaces(FInputStream.Data)); {$ELSE} Token.SkipLeadingNonSpaces(FInputStream.Data); {$ENDIF} if (ssHaveLeadingSpace in Token.SpaceState) then InsertLeadingSpacesFor(Token) else break; until forever; end else begin InsertCharactersFor(Token); end; end; tkExtraSpaceCharacter: InsertCharacters(Token.ExtraChars); {$IFDEF PARSEERROR} tkExtraCharacters: ParseError('unexpected character token after frameset', Length(Token.ExtraChars)); {$ENDIF} // $R- tkComment: InsertAComment(Token); {$IFDEF PARSEERROR} tkDOCTYPE: ParseError('unexpected DOCTYPE'); {$ENDIF} tkStartTag: if (Token.TagName = eHTML) then begin TheInBodyInsertionMode(Token); end else if (Token.TagName = eNoFrames) then begin TheInHeadInsertionMode(Token); end else begin {$IFDEF PARSEERROR} ParseError('unexpected start tag token after frameset'); {$ENDIF} end; tkEndTag: if (Token.TagName = eHTML) then begin FInsertionMode := @TheAfterAfterFramesetInsertionMode; end else begin {$IFDEF PARSEERROR} ParseError('unexpected end tag token after frameset'); {$ENDIF} end; tkEOF: ; // and then we stop parsing {$IFDEF PARSEERROR} else Assert(False); {$ENDIF} end; end; procedure THTMLParser.TheAfterAfterBodyInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of tkSourceCharacters: begin if (ssHaveNonSpace in Token.SpaceState) then begin if (ssHaveLeadingSpace in Token.SpaceState) then begin ReconstructTheActiveFormattingElements(); InsertLeadingSpacesFor(Token); // http://bugs.freepascal.org/view.php?id=26403 end; // fall through to "anything else" clause end else begin ReconstructTheActiveFormattingElements(); InsertCharactersFor(Token); exit; end; end; tkExtraSpaceCharacter: begin ReconstructTheActiveFormattingElements(); InsertCharacters(Token.ExtraChars); exit; end; tkComment: begin FDocument.AppendChild(CreateACommentFor(Token)); exit; end; tkDOCTYPE: begin {$IFDEF PARSEERROR} ParseError('unexpected DOCTYPE'); {$ENDIF} exit; end; tkStartTag: if (Token.TagName = eHTML) then begin TheInBodyInsertionMode(Token); exit; end else if (Token.TagName = eNoFrames) then begin TheInHeadInsertionMode(Token); exit; end; tkEOF: begin // and then we stop parsing exit; end; else Assert(Token.Kind = tkEndTag); end; // anything else {$IFDEF PARSEERROR} ParseError('unexpected token after html'); {$ENDIF} FInsertionMode := @TheInBodyInsertionMode; TreeConstructionDispatcher(Token); end; procedure THTMLParser.TheAfterAfterFramesetInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); case (Token.Kind) of tkSourceCharacters: begin if (ssHaveNonSpace in Token.SpaceState) then begin if (ssHaveLeadingSpace in Token.SpaceState) then InsertLeadingSpacesFor(Token); // http://bugs.freepascal.org/view.php?id=26403 repeat {$IFDEF PARSEERROR} ParseError('unexpected character token after html after frameset', Token.SkipLeadingNonSpaces(FInputStream.Data)); {$ELSE} Token.SkipLeadingNonSpaces(FInputStream.Data); {$ENDIF} if (ssHaveLeadingSpace in Token.SpaceState) then InsertLeadingSpacesFor(Token) else exit; until forever; end else begin InsertCharactersFor(Token); exit; end; end; tkExtraSpaceCharacter: begin ReconstructTheActiveFormattingElements(); InsertCharacters(Token.ExtraChars); exit; end; tkComment: begin FDocument.AppendChild(CreateACommentFor(Token)); exit; end; tkDOCTYPE: begin {$IFDEF PARSEERROR} ParseError('unexpected DOCTYPE'); {$ENDIF} exit; end; tkStartTag: if (Token.TagName = eHTML) then begin TheInBodyInsertionMode(Token); exit; end else if (Token.TagName = eNoFrames) then begin TheInHeadInsertionMode(Token); exit; end; tkEOF: begin // and then we stop parsing exit; end; else Assert(Token.Kind = tkEndTag); end; // anything else {$IFDEF PARSEERROR} ParseError('unexpected token after html after frameset'); {$ENDIF} end; procedure THTMLParser.TheSkipNewLineInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); FInsertionMode := FOriginalInsertionMode; case (Token.Kind) of tkSourceCharacters: begin if (not Token.SkipOneLeadingNewline(FInputStream.Data)) then exit; end; tkExtraSpaceCharacter: begin Assert(Length(Token.ExtraChars) = 1); if (Token.ExtraChars[0] = $000A) then exit; // skip the one newline character end; end; TreeConstructionDispatcher(Token); end; procedure THTMLParser.TheSkipNewLineThenTextInsertionMode(var Token: TToken); begin Assert(Assigned(FDocument)); FInsertionMode := @TheTextInsertionMode; case (Token.Kind) of tkSourceCharacters: begin if (not Token.SkipOneLeadingNewline(FInputStream.Data)) then exit; end; tkExtraSpaceCharacter: begin Assert(Length(Token.ExtraChars) = 1); if (Token.ExtraChars[0] = $000A) then exit; // skip the one newline character end; end; TreeConstructionDispatcher(Token); end; procedure THTMLParser.TheRulesForParsingTokensInForeignContent(var Token: TToken); procedure AnyOtherStartTag(); begin if (AdjustedCurrentNode.NamespaceURL = nsMathML) then begin Token.AdjustMathMLAttributes(); end else if (AdjustedCurrentNode.NamespaceURL = nsSVG) then begin // tag name adjustment is done by ConstructSVGElement() in webdom.pas Token.AdjustSVGAttributes(); end; Token.AdjustForeignAttributes(); InsertAForeignElementFor(Token, AdjustedCurrentNode.NamespaceURL); if (Token.SelfClosingFlag) then begin FStackOfOpenElements.Pop(); {$IFDEF PARSEERROR} Token.AcknowledgeSelfClosingFlag(); {$ENDIF} // note: <script/> here is handled like any other foreign void start tag, since we don't support scripts end; end; var NodeIndex: Cardinal; Node: TXMLElement; Placeholder: TUnicodeCodepointArray; begin Assert(Assigned(FDocument)); case (Token.Kind) of tkNullCharacter: begin {$IFDEF PARSEERROR} ParseError('unexpected null in foreign content'); {$ENDIF} SetLength(Placeholder, 1); Placeholder[0] := $FFFD; InsertCharacters(Placeholder); end; tkSourceCharacters: begin InsertCharactersFor(Token); if (ssHaveNonSpace in Token.SpaceState) then FFramesetOkFlag := False; end; tkExtraCharacters: begin InsertCharacters(Token.ExtraChars); FFramesetOkFlag := False; end; tkExtraSpaceCharacter: begin InsertCharacters(Token.ExtraChars); end; tkComment: InsertAComment(Token); // http://bugs.freepascal.org/view.php?id=26403 {$IFDEF PARSEERROR} tkDOCTYPE: ParseError('unexpected DOCTYPE'); {$ENDIF} tkStartTag: if ((Token.TagName = eB) or (Token.TagName = eBig) or (Token.TagName = eBlockQuote) or (Token.TagName = eBody) or (Token.TagName = eBr) or (Token.TagName = eCenter) or (Token.TagName = eCode) or (Token.TagName = eDD) or (Token.TagName = eDiv) or (Token.TagName = eDL) or (Token.TagName = eDT) or (Token.TagName = eEm) or (Token.TagName = eEmbed) or (Token.TagName = eH1) or (Token.TagName = eH2) or (Token.TagName = eH3) or (Token.TagName = eH4) or (Token.TagName = eH5) or (Token.TagName = eH6) or (Token.TagName = eHead) or (Token.TagName = eHR) or (Token.TagName = eI) or (Token.TagName = eImg) or (Token.TagName = eLI) or (Token.TagName = eListing) or (Token.TagName = eMenu) or (Token.TagName = eMeta) or (Token.TagName = eNoBr) or (Token.TagName = eOL) or (Token.TagName = eP) or (Token.TagName = ePre) or (Token.TagName = eRuby) or (Token.TagName = eS) or (Token.TagName = eSmall) or (Token.TagName = eSpan) or (Token.TagName = eStrong) or (Token.TagName = eStrike) or (Token.TagName = eSub) or (Token.TagName = eSup) or (Token.TagName = eTable) or (Token.TagName = eTT) or (Token.TagName = eU) or (Token.TagName = eUL) or (Token.TagName = eVar) or ((Token.TagName = eFont) and (Token.HasAttributes(['color', 'face', 'size'])))) then begin {$IFDEF PARSEERROR} ParseError('unexpected HTML-like start tag token in foreign content'); {$ENDIF} if (FFragmentParsingMode) then begin AnyOtherStartTag(); end else begin repeat FStackOfOpenElements.Pop(); until CurrentNode.HasSomeProperties(propMathMLTextIntegrationPoint or propHTMLIntegrationPoint or propHTML); TreeConstructionDispatcher(Token); end; end else AnyOtherStartTag(); tkEndTag: begin // note: </script> is handled like any other end tag, since we don't support scripts NodeIndex := FStackOfOpenElements.Length-1; // $R- Assert(FStackOfOpenElements[NodeIndex] is TXMLElement); Node := FStackOfOpenElements[NodeIndex] as TXMLElement; {$IFDEF PARSEERROR} if (Node.LowerCaseTagName <> Token.TagName) then ParseError('unexpected end tag'); {$ENDIF} repeat if (NodeIndex = 0) then break; if (Node.LowerCaseTagName = Token.TagName) then begin repeat until FStackOfOpenElements.Pop() = Node; exit; end; Dec(NodeIndex); if (FStackOfOpenElements[NodeIndex].NamespaceURL = nsHTML) then begin FInsertionMode(Token); break; end; Assert(FStackOfOpenElements[NodeIndex] is TXMLElement); Node := FStackOfOpenElements[NodeIndex] as TXMLElement; until forever; end; {$IFDEF PARSEERROR} else Assert(False); {$ENDIF} end; end; end.
41.782154
269
0.561071
fc4715571859d03f9e19266908814f82b16a3abc
3,995
dfm
Pascal
DataView/DataGrabber.DataView.cxGrid.dfm
atkins126/DataGrabber
9cb944d3adb88cbf7b2c0a2a88510acc7b34253b
[ "Apache-2.0" ]
17
2017-09-14T05:45:24.000Z
2021-08-09T19:14:03.000Z
DataView/DataGrabber.DataView.cxGrid.dfm
atkins126/DataGrabber
9cb944d3adb88cbf7b2c0a2a88510acc7b34253b
[ "Apache-2.0" ]
null
null
null
DataView/DataGrabber.DataView.cxGrid.dfm
atkins126/DataGrabber
9cb944d3adb88cbf7b2c0a2a88510acc7b34253b
[ "Apache-2.0" ]
10
2017-11-14T05:13:57.000Z
2022-01-16T10:50:39.000Z
inherited frmcxGrid: TfrmcxGrid ClientHeight = 319 ClientWidth = 695 Font.Name = 'Se' ExplicitWidth = 695 ExplicitHeight = 319 PixelsPerInch = 96 TextHeight = 14 object grdMain: TcxGrid [0] Left = 0 Top = 0 Width = 695 Height = 319 Align = alClient BevelInner = bvNone BevelOuter = bvNone BorderStyle = cxcbsNone Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Calibri' Font.Style = [] ParentFont = False TabOrder = 0 LevelTabs.Slants.Positions = [] LevelTabs.Style = 6 LookAndFeel.Kind = lfStandard LookAndFeel.NativeStyle = True LookAndFeel.ScrollbarMode = sbmDefault object tvwMain: TcxGridDBTableView Navigator.Buttons.ConfirmDelete = True Navigator.Buttons.CustomButtons = <> Navigator.Buttons.Append.Visible = True Navigator.InfoPanel.Visible = True Navigator.Visible = True FilterBox.MRUItemsListDropDownCount = 10 FindPanel.ApplyInputDelay = 500 FindPanel.DisplayMode = fpdmManual FindPanel.MRUItemsListCount = 100 FindPanel.MRUItemsListDropDownCount = 20 FindPanel.Position = fppBottom OnCustomDrawCell = tvwMainCustomDrawCell DataController.DataSource = dscMain DataController.MultiThreadedOptions.Filtering = bTrue DataController.MultiThreadedOptions.Sorting = bTrue DataController.Options = [dcoAssignGroupingValues, dcoAssignMasterDetailKeys, dcoSaveExpanding, dcoSortByDisplayText, dcoFocusTopRowAfterSorting, dcoImmediatePost, dcoInsertOnNewItemRowFocusing] DataController.Summary.DefaultGroupSummaryItems = < item Format = '0' Kind = skCount VisibleForCustomization = False end> DataController.Summary.FooterSummaryItems = <> DataController.Summary.SummaryGroups = <> DataController.Summary.Options = [soMultipleSelectedRecords] DateTimeHandling.Filters = [dtfRelativeDays, dtfRelativeDayPeriods, dtfRelativeWeeks, dtfRelativeMonths, dtfRelativeYears, dtfPastFuture, dtfMonths, dtfYears] EditForm.DefaultColumnCount = 6 EditForm.ItemHotTrack = True EditForm.DefaultStretch = fsHorizontal Filtering.ColumnFilteredItemsList = True Filtering.ColumnMRUItemsListCount = 10 Filtering.ColumnPopup.MaxDropDownItemCount = 30 FilterRow.ApplyInputDelay = 500 OptionsBehavior.CellHints = True OptionsBehavior.FocusCellOnTab = True OptionsBehavior.FocusFirstCellOnNewRecord = True OptionsBehavior.GoToNextCellOnEnter = True OptionsBehavior.IncSearch = True OptionsBehavior.NavigatorHints = True OptionsBehavior.BestFitMaxRecordCount = 100 OptionsBehavior.ColumnMergedGrouping = True OptionsBehavior.ImmediateEditor = False OptionsBehavior.ShowLockedStateImageOptions.BestFit = lsimImmediate OptionsBehavior.PullFocusing = True OptionsCustomize.ColumnHiding = True OptionsCustomize.ColumnsQuickCustomization = True OptionsCustomize.DataRowSizing = True OptionsCustomize.GroupRowSizing = True OptionsData.Appending = True OptionsSelection.MultiSelect = True OptionsSelection.CellMultiSelect = True OptionsSelection.InvertSelect = False OptionsView.CellEndEllipsis = True OptionsView.FocusRect = False OptionsView.ExpandButtonsForEmptyDetails = False OptionsView.GridLineColor = clSilver OptionsView.HeaderAutoHeight = True OptionsView.HeaderEndEllipsis = True OptionsView.Indicator = True OnCustomDrawColumnHeader = tvwMainCustomDrawColumnHeader OnCustomDrawGroupSummaryCell = tvwMainCustomDrawGroupSummaryCell end object grlMain: TcxGridLevel GridView = tvwMain Options.TabsForEmptyDetails = False end end object ppmMain: TcxGridPopupMenu Grid = grdMain PopupMenus = <> AlwaysFireOnPopup = True Left = 464 Top = 248 end end
37.688679
200
0.733166
fc35f6b2d80b7af2ce884d10ee772455e8a020bb
5,988
pas
Pascal
ConsAgendamentoDoPacientePesquisaPacienteU.pas
phiwamoto/phMed
c72b1d521389edbf48f74e763dfc9d8db145936c
[ "Apache-2.0" ]
null
null
null
ConsAgendamentoDoPacientePesquisaPacienteU.pas
phiwamoto/phMed
c72b1d521389edbf48f74e763dfc9d8db145936c
[ "Apache-2.0" ]
null
null
null
ConsAgendamentoDoPacientePesquisaPacienteU.pas
phiwamoto/phMed
c72b1d521389edbf48f74e763dfc9d8db145936c
[ "Apache-2.0" ]
null
null
null
unit ConsAgendamentoDoPacientePesquisaPacienteU; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, XTelaShowModalU, StdCtrls, ExtCtrls, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Menus, cxButtons, cxControls, cxContainer, cxEdit, dxSkinsCore, dxSkinsDefaultPainters, cxTextEdit, cxStyles, dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, DB, cxDBData, DBClient, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid; type TConsAgendamentoDoPacientePesquisaPacienteF = class(TXTelaShowModalF) BtnSelecionar: TcxButton; BtnCancelar: TcxButton; LblNome: TLabel; EdtNome: TcxTextEdit; DsPesquisa: TDataSource; CdsPesquisa: TClientDataSet; CdsPesquisaIDPACIENTE: TIntegerField; CdsPesquisaIDCIDADE: TIntegerField; CdsPesquisaIDSITUACAOREGISTRO: TSmallintField; CdsPesquisaDATAINCLUSAO: TDateField; CdsPesquisaDATANASCIMENTO: TDateField; CdsPesquisaNUMERO: TIntegerField; CdsPesquisaESTADOCIVIL: TStringField; CdsPesquisaSEXO: TStringField; CdsPesquisaOBSERVACAO: TStringField; CdsPesquisaNOME: TStringField; CdsPesquisaENDERECO: TStringField; CdsPesquisaBAIRRO: TStringField; CdsPesquisaEMAIL: TStringField; CdsPesquisaCOMPLEMENTO: TStringField; CdsPesquisaRG: TStringField; CdsPesquisaCPF: TStringField; CdsPesquisaTELEFONE1: TStringField; CdsPesquisaTELEFONE2: TStringField; CdsPesquisaCEP: TStringField; CdsPesquisaIDADE: TIntegerField; CdsPesquisaCIDADEUF: TStringField; CdsPesquisaSITUACAOREGISTRO: TStringField; GridPesquisa: TcxGrid; GridPesquisaDBTableView1: TcxGridDBTableView; GridPesquisaDBTableView1IDPACIENTE: TcxGridDBColumn; GridPesquisaDBTableView1SEXO: TcxGridDBColumn; GridPesquisaDBTableView1CPF: TcxGridDBColumn; GridPesquisaDBTableView1NOME: TcxGridDBColumn; GridPesquisaDBTableView1IDADE: TcxGridDBColumn; GridPesquisaDBTableView1TELEFONE1: TcxGridDBColumn; GridPesquisaDBTableView1CIDADEUF: TcxGridDBColumn; GridPesquisaLevel1: TcxGridLevel; procedure BtnSelecionarClick(Sender: TObject); procedure BtnCancelarClick(Sender: TObject); procedure EdtNomeKeyPress(Sender: TObject; var Key: Char); procedure FormShow(Sender: TObject); private { Private declarations } public { Public declarations } class function executa: Integer; static; procedure executaPesquisa; end; var ConsAgendamentoDoPacientePesquisaPacienteF: TConsAgendamentoDoPacientePesquisaPacienteF; implementation uses DmConexaoU; {$R *.dfm} procedure TConsAgendamentoDoPacientePesquisaPacienteF.BtnCancelarClick(Sender: TObject); begin inherited; ModalResult := mrCancel; end; procedure TConsAgendamentoDoPacientePesquisaPacienteF.BtnSelecionarClick(Sender: TObject); begin inherited; ModalResult := mrOk; end; procedure TConsAgendamentoDoPacientePesquisaPacienteF.EdtNomeKeyPress( Sender: TObject; var Key: Char); begin inherited; if Key = #13 then if EdtNome.Focused then executaPesquisa; end; class function TConsAgendamentoDoPacientePesquisaPacienteF.executa(): Integer; begin Result := 0; ConsAgendamentoDoPacientePesquisaPacienteF := TConsAgendamentoDoPacientePesquisaPacienteF.Create(nil); try ConsAgendamentoDoPacientePesquisaPacienteF.CdsPesquisa.Close; ConsAgendamentoDoPacientePesquisaPacienteF.ShowModal; if ConsAgendamentoDoPacientePesquisaPacienteF.ModalResult = mrOk then begin Result := ConsAgendamentoDoPacientePesquisaPacienteF.CdsPesquisaIDPACIENTE.AsInteger; end; finally ConsAgendamentoDoPacientePesquisaPacienteF.CdsPesquisa.Close; ConsAgendamentoDoPacientePesquisaPacienteF.Release; ConsAgendamentoDoPacientePesquisaPacienteF := nil; end; end; procedure TConsAgendamentoDoPacientePesquisaPacienteF.executaPesquisa; begin if Trim(EdtNome.Text) = EmptyStr then begin Exit; end; Self.CdsPesquisa.Close; Self.CdsPesquisa.CommandText := ' SELECT PAC.* ' +' ,CAST(LEFT( (( (CURRENT_DATE - PAC.DATANASCIMENTO)-1 ) / 365.25), 3) AS INT) AS IDADE ' +' ,(CID.CIDADE || '' - '' || CID.UF) AS CIDADEUF ' +' ,SRE.DESCRICAO AS SITUACAOREGISTRO ' +' FROM PACIENTE PAC ' +' LEFT JOIN CIDADE CID ON (CID.IDCIDADE = PAC.IDCIDADE) ' +' JOIN SITUACAOREGISTRO SRE ON (SRE.IDSITUACAOREGISTRO = PAC.IDSITUACAOREGISTRO) ' +' WHERE 1 = 1 ' ; if Trim(EdtNome.Text) <> EmptyStr then begin Self.CdsPesquisa.CommandText := Self.CdsPesquisa.CommandText + ' AND PAC.NOME LIKE ''%'+EdtNome.Text+'%'' '; end; (* if Trim(EdtTelefones.Text) <> EmptyStr then begin Self.CdsPesquisa.CommandText := Self.CdsPesquisa.CommandText + ' AND ( PAC.TELEFONE1 LIKE ''%'+EdtTelefones.Text+'%'' OR PAC.TELEFONE2 LIKE ''%'+EdtTelefones.Text+'%'' ) '; end; if Trim(EdtCidadeUF.Text) <> EmptyStr then begin Self.CdsPesquisa.CommandText := Self.CdsPesquisa.CommandText + ' AND ( CID.CIDADE LIKE ''%'+EdtCidadeUF.Text+'%'' OR CID.UF LIKE ''%'+EdtCidadeUF.Text+'%'' ) '; end; if CbSexo.Text <> 'Todos' then begin Self.CdsPesquisa.CommandText := Self.CdsPesquisa.CommandText + ' AND ( PAC.SEXO LIKE ''%'+CbSexo.Text+'%'' ) '; end; if CbSituacao.Text <> 'Todos' then begin if CbSituacao.Text = 'Ativo' then Self.CdsPesquisa.CommandText := Self.CdsPesquisa.CommandText + ' AND ( PAC.IDSITUACAOREGISTRO = 1 ) '; if CbSituacao.Text = 'Inativo' then Self.CdsPesquisa.CommandText := Self.CdsPesquisa.CommandText + ' AND ( PAC.IDSITUACAOREGISTRO = 0 ) '; end; *) Self.CdsPesquisa.CommandText := Self.CdsPesquisa.CommandText + ' ORDER BY PAC.NOME '; Self.CdsPesquisa.Open; end; procedure TConsAgendamentoDoPacientePesquisaPacienteF.FormShow(Sender: TObject); begin inherited; setNextValue(False); end; end.
32.02139
146
0.750835
47dc9addd335d2e6166abd35eb9ef971e2b6ae2e
1,431
pas
Pascal
tests/Helper.DUnitAssert.pas
bogdanpolak/delphi-dataproxy
fef7a3a3c5256788ae9f52f105b7a1c1b841f466
[ "MIT" ]
13
2019-01-25T06:08:45.000Z
2022-01-26T07:56:09.000Z
tests/Helper.DUnitAssert.pas
bogdanpolak/delphi-dataproxy
fef7a3a3c5256788ae9f52f105b7a1c1b841f466
[ "MIT" ]
70
2019-01-17T21:57:42.000Z
2020-03-09T19:36:57.000Z
tests/Helper.DUnitAssert.pas
bogdanpolak/delphi-dataproxy
fef7a3a3c5256788ae9f52f105b7a1c1b841f466
[ "MIT" ]
4
2019-08-02T14:24:19.000Z
2020-11-11T02:56:42.000Z
unit Helper.DUnitAssert; interface uses System.SysUtils, System.Classes, System.Math, DUnitX.TestFramework; type TAssertHelper = class helper for Assert class procedure AreMemosEqual(const expectedStrings: string; const actualStrings: string); end; implementation function FindDiffrence(const s1: string; const s2: string): integer; var j: integer; begin if s1 = s2 then Exit(0); for j := 1 to Min(s1.Length, s2.Length) do if s1[j] <> s2[j] then Exit(j); Result := Min(s1.Length, s2.Length); end; class procedure TAssertHelper.AreMemosEqual(const expectedStrings: string; const actualStrings: string); var slActual: TStringList; slExpected: TStringList; i: integer; aPos: integer; begin slActual := TStringList.Create; slExpected := TStringList.Create; try slActual.Text := actualStrings; slExpected.Text := expectedStrings; Assert.AreEqual(slExpected.Count, slActual.Count, Format('(diffrent number of lines)', [slExpected.Count, slActual.Count])); for i := 0 to slExpected.Count - 1 do if slExpected[i] <> slActual[i] then begin aPos := FindDiffrence(slExpected[i], slActual[i]); Assert.Fail (Format('in line: %d at pos: %d, expected |%s| is not equal to actual |%s|', [i + 1, aPos, slExpected[i], slActual[i]])); end; finally slActual.Free; slExpected.Free; end; end; end.
23.459016
86
0.672956
47984c32a0f6d55b94d08a9e37b29062a90be953
38
pas
Pascal
Test/FailureScripts/debugbreak.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
1
2022-02-18T22:14:44.000Z
2022-02-18T22:14:44.000Z
Test/FailureScripts/debugbreak.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
null
null
null
Test/FailureScripts/debugbreak.pas
synapsea/DW-Script
b36c2e57f0285c217f8f0cae8e4e158d21127163
[ "Condor-1.1" ]
null
null
null
DebugBreak; DebugBreak(); DebugBreak(;
12.666667
13
0.789474
fc3cd21c00dde7d5d8e128a02c72ec6213ba8c8c
607
dfm
Pascal
ConexaoDM.dfm
PauloHenrique7010/RestServerDelphi
50f5b5ee1aa715bfbfbbcc7dc27a10c0ecff9db4
[ "Apache-2.0" ]
null
null
null
ConexaoDM.dfm
PauloHenrique7010/RestServerDelphi
50f5b5ee1aa715bfbfbbcc7dc27a10c0ecff9db4
[ "Apache-2.0" ]
null
null
null
ConexaoDM.dfm
PauloHenrique7010/RestServerDelphi
50f5b5ee1aa715bfbfbbcc7dc27a10c0ecff9db4
[ "Apache-2.0" ]
null
null
null
object ConexaoDtm: TConexaoDtm OldCreateOrder = False OnCreate = DataModuleCreate Height = 150 Width = 215 object Conexao: TFDConnection Params.Strings = ( 'Database=atendimento_dk' 'Password=' 'User_Name=' 'Server=localhost' 'DriverID=MySQL') LoginPrompt = False Left = 32 Top = 24 end object qryAtendimento: TFDQuery Connection = Conexao SQL.Strings = ( 'select cod_atendimento, ' ' dt_atendimento, ' ' hr_atendimento,' ' assunto' 'from atendimento') Left = 136 Top = 32 end end
20.931034
33
0.604613
47a5f768010c53fd64cd886a6c3ffc5eed30efad
2,028
pas
Pascal
Win32.Acid.b/abThreads.pas
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
2
2021-02-04T06:47:45.000Z
2021-07-28T10:02:10.000Z
Win32.Acid.b/abThreads.pas
TheWover/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
Win32.Acid.b/abThreads.pas
TheWover/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
unit abThreads; interface uses Windows; type TThread = class; TThreadProcedure = procedure(Thread: TThread); TSynchronizeProcedure = procedure; TThread = class private FThreadHandle: longword; FThreadID: longword; FExitCode: longword; FTerminated: boolean; FExecute: TThreadProcedure; FData: pointer; protected public constructor Create(ThreadProcedure: TThreadProcedure; CreationFlags: Cardinal); destructor Destroy; override; procedure Synchronize(Synchronize: TSynchronizeProcedure); procedure Lock; procedure Unlock; property Terminated: Boolean read FTerminated write FTerminated; property ThreadHandle: LongWord read FThreadHandle; property ThreadID: LongWord read FThreadID; property ExitCode: LongWord read FExitCode; property Data: Pointer read FData write FData; end; implementation var ThreadLock: TRTLCriticalSection; procedure ThreadWrapper(Thread: TThread); var ExitCode: dword; begin Thread.FTerminated := False; try Thread.FExecute(Thread); finally GetExitCodeThread(Thread.FThreadHandle, ExitCode); Thread.FExitCode := ExitCode; Thread.FTerminated := True; ExitThread(ExitCode); end; end; constructor TThread.Create(ThreadProcedure: TThreadProcedure; CreationFlags: Cardinal); begin inherited Create; FExitCode := 0; FExecute := ThreadProcedure; FThreadHandle := BeginThread(nil, 0, @ThreadWrapper, Pointer(Self), CreationFlags, FThreadID); end; destructor TThread.Destroy; begin inherited; CloseHandle(FThreadHandle); end; procedure TThread.Synchronize(Synchronize: TSynchronizeProcedure); begin EnterCriticalSection(ThreadLock); try Synchronize; finally LeaveCriticalSection(ThreadLock); end; end; procedure TThread.Lock; begin EnterCriticalSection(ThreadLock); end; procedure TThread.Unlock; begin LeaveCriticalSection(ThreadLock); end; initialization InitializeCriticalSection(ThreadLock); finalization DeleteCriticalSection(ThreadLock); end.
21.574468
96
0.764793
fcbac48367ccfffb69265e005fc7f398ddeec01d
578
dpr
Pascal
LoadTester/LoadTester.dpr
lhengen/hcUpdateFramework
6da48de012d8b67dae41945dac8cbc64570f7372
[ "Apache-2.0" ]
11
2021-01-12T00:46:01.000Z
2022-02-27T00:46:44.000Z
LoadTester/LoadTester.dpr
lhengen/hcUpdateFramework
6da48de012d8b67dae41945dac8cbc64570f7372
[ "Apache-2.0" ]
null
null
null
LoadTester/LoadTester.dpr
lhengen/hcUpdateFramework
6da48de012d8b67dae41945dac8cbc64570f7372
[ "Apache-2.0" ]
4
2021-01-13T20:06:10.000Z
2022-02-26T22:44:33.000Z
program LoadTester; uses FastMM4, Vcl.Forms, fmMain in 'fmMain.pas' {frmMain}, unClientUpdateThread in 'unClientUpdateThread.pas', unUpdateClient in '..\Common\unUpdateClient.pas', hcUpdateConsts in '..\Common\hcUpdateConsts.pas', unIUpdateService in '..\Common\unIUpdateService.pas', unPath in '..\Common\unPath.pas', unWebServiceFileUtils in '..\Common\unWebServiceFileUtils.pas'; {$R *.res} begin Application.Initialize; Application.MainFormOnTaskbar := True; Application.CreateForm(TfrmMain, frmMain); Application.Run; end.
26.272727
66
0.721453
c32d39cbf1cfb57980fea9759018efdd5dd58318
1,630
dpr
Pascal
contrib/mORMot/SyNode/_SynodePluginTemplate.dpr
Razor12911/bms2xtool
0493cf895a9dbbd9f2316a3256202bcc41d9079c
[ "MIT" ]
11
2022-01-17T22:05:37.000Z
2022-02-23T19:18:19.000Z
contrib/mORMot/SyNode/_SynodePluginTemplate.dpr
Razor12911/xtool
4797195ad310e8f6dc2eae8eb86fe14683f77cf0
[ "MIT" ]
1
2022-02-17T07:17:16.000Z
2022-02-17T07:17:16.000Z
contrib/mORMot/SyNode/_SynodePluginTemplate.dpr
Razor12911/bms2xtool
0493cf895a9dbbd9f2316a3256202bcc41d9079c
[ "MIT" ]
2
2020-08-18T09:42:33.000Z
2021-04-22T08:15:27.000Z
{ New Plugin instruction: 1. Open this project 2. Use SaveAs for saving your new project to your own directory 3. Declare new descendant of TCustomSMPlugin and override methods Init and UnInit 4. Change in *.dpr file TCustomSMPlugin to your class } library EmptyPlugin; uses FastMM4, SysUtils, Classes, Windows, SyNodeAPI, PluginUtils in '..\PluginUtils\PluginUtils.pas'; const MAX_THREADS = 256; PluginType: TCustomSMPluginType = TCustomSMPlugin; //In real realization you must declare you own class child of TCustomSMPlugin and override methods Init and UnInit var ThreadRecs: array[0..MAX_THREADS] of TThreadRec; threadCounter: integer; function InitPlugin(cx: PJSContext; exports_: PJSRootedObject; require: PJSRootedObject; module: PJSRootedObject; __filename: PWideChar; __dirname: PWideChar): boolean; cdecl; var l: integer; begin l := InterlockedIncrement(threadCounter); if l>=MAX_THREADS then raise Exception.Create('Too many thread. Max is 256'); ThreadRecs[l].threadID := GetCurrentThreadId; ThreadRecs[l].plugin := PluginType.Create(cx, exports_, require, module, __filename, __dirname); result := true; end; function UnInitPlugin(): boolean; cdecl; var i: integer; begin for I := 0 to MAX_THREADS - 1 do if ThreadRecs[i].threadID = GetCurrentThreadId then begin ThreadRecs[i].threadID := 0; FreeAndNil(ThreadRecs[i].plugin); end; result := true; end; exports InitPlugin; exports UnInitPlugin; begin IsMultiThread := True; //!!IMPORTANT for FastMM threadCounter := -1; FillMemory(@ThreadRecs[0], SizeOf(ThreadRecs), 0); end.
27.166667
175
0.739877
fc8eba59ef63f41a442dcc6f9b84ba5d53192244
13,347
pas
Pascal
reference-platform/support/AdvInt64Matches.pas
novakjf2000/FHIRServer
a47873825e94cd6cdfa1a077f02e0960098bbefa
[ "BSD-3-Clause" ]
1
2018-01-08T06:40:02.000Z
2018-01-08T06:40:02.000Z
reference-platform/support/AdvInt64Matches.pas
novakjf2000/FHIRServer
a47873825e94cd6cdfa1a077f02e0960098bbefa
[ "BSD-3-Clause" ]
null
null
null
reference-platform/support/AdvInt64Matches.pas
novakjf2000/FHIRServer
a47873825e94cd6cdfa1a077f02e0960098bbefa
[ "BSD-3-Clause" ]
null
null
null
Unit AdvInt64Matches; { Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 HOLDER 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. } Interface Uses MemorySupport, StringSupport, MathSupport, AdvObjects, AdvItems, AdvFilers; Type TAdvInt64MatchKey = Int64; TAdvInt64MatchValue = Int64; TAdvInt64MatchItem = Record Key : TAdvInt64MatchKey; Value : TAdvInt64MatchValue; End; PAdvIntegerMatchItem = ^TAdvInt64MatchItem; TAdvInt64MatchItems = Array[0..(MaxInt Div SizeOf(TAdvInt64MatchItem)) - 1] Of TAdvInt64MatchItem; PAdvIntegerMatchItems = ^TAdvInt64MatchItems; TAdvInt64Match = Class(TAdvItems) Private FMatches : PAdvIntegerMatchItems; FDefault : TAdvInt64MatchValue; FForced : Boolean; Function GetKey(iIndex: Integer): TAdvInt64MatchKey; Procedure SetKey(iIndex: Integer; Const iValue: TAdvInt64MatchKey); Function GetValue(iIndex: Integer): TAdvInt64MatchValue; Procedure SetValue(iIndex: Integer; Const iValue: TAdvInt64MatchValue); Function GetMatch(iKey : TAdvInt64MatchKey): TAdvInt64MatchValue; Procedure SetMatch(iKey: TAdvInt64MatchKey; Const iValue: TAdvInt64MatchValue); Function GetPair(iIndex: Integer): TAdvInt64MatchItem; Procedure SetPair(iIndex: Integer; Const Value: TAdvInt64MatchItem); Protected Function GetItem(iIndex : Integer) : Pointer; Override; Procedure SetItem(iIndex: Integer; pValue: Pointer); Override; Procedure LoadItem(oFiler : TAdvFiler; iIndex : Integer); Override; Procedure SaveItem(oFiler : TAdvFiler; iIndex : Integer); Override; Procedure AssignItem(oItems : TAdvItems; iIndex : Integer); Override; Procedure InternalResize(iValue : Integer); Override; Procedure InternalCopy(iSource, iTarget, iCount : Integer); Override; Procedure InternalEmpty(iIndex, iLength : Integer); Override; Procedure InternalInsert(iIndex : Integer); Overload; Override; Procedure InternalExchange(iA, iB : Integer); Overload; Override; Function CompareByKey(pA, pB : Pointer): Integer; Function CompareByValue(pA, pB : Pointer): Integer; Function CompareByKeyValue(pA, pB : Pointer) : Integer; Procedure DefaultCompare(Out aCompare : TAdvItemsCompare); Overload; Override; Function CapacityLimit : Integer; Override; Function Find(Const aKey : TAdvInt64MatchKey; Const aValue: TAdvInt64MatchValue; Out iIndex : Integer; aCompare : TAdvItemsCompare = Nil) : Boolean; Function FindByKey(Const aKey : TAdvInt64MatchKey; Out iIndex : Integer; aCompare : TAdvItemsCompare = Nil) : Boolean; Public Function Link : TAdvInt64Match; Function Add(aKey : TAdvInt64MatchKey; aValue : TAdvInt64MatchValue): Integer; Procedure Insert(iIndex : Integer; iKey : TAdvInt64MatchKey; iValue : TAdvInt64MatchValue); Function IndexByKey(aKey : TAdvInt64MatchKey) : Integer; Function IndexByKeyValue(Const aKey : TAdvInt64MatchKey; Const aValue : TAdvInt64MatchValue) : Integer; Function ExistsByKey(aKey : TAdvInt64MatchKey) : Boolean; Function ExistsByKeyValue(Const aKey : TAdvInt64MatchKey; Const aValue : TAdvInt64MatchValue) : Boolean; Function EqualTo(Const oIntegerMatch : TAdvInt64Match) : Boolean; Procedure DeleteByKey(aKey : TAdvInt64MatchKey); Procedure ForceIncrementByKey(Const aKey : TAdvInt64MatchKey); Procedure SortedByKey; Procedure SortedByValue; Procedure SortedByKeyValue; Property Matches[iKey : TAdvInt64MatchKey] : TAdvInt64MatchValue Read GetMatch Write SetMatch; Default; Property KeyByIndex[iIndex : Integer] : TAdvInt64MatchKey Read GetKey Write SetKey; Property ValueByIndex[iIndex : Integer] : TAdvInt64MatchValue Read GetValue Write SetValue; Property Pairs[iIndex : Integer] : TAdvInt64MatchItem Read GetPair Write SetPair; Property Forced : Boolean Read FForced Write FForced; Property Default : TAdvInt64MatchValue Read FDefault Write FDefault; End; Implementation Function TAdvInt64Match.Link : TAdvInt64Match; Begin Result := TAdvInt64Match(Inherited Link); End; Function TAdvInt64Match.CompareByKey(pA, pB: Pointer): Integer; Begin Result := IntegerCompare(PAdvIntegerMatchItem(pA)^.Key, PAdvIntegerMatchItem(pB)^.Key); End; Function TAdvInt64Match.CompareByValue(pA, pB: Pointer): Integer; Begin Result := IntegerCompare(PAdvIntegerMatchItem(pA)^.Value, PAdvIntegerMatchItem(pB)^.Value); End; Function TAdvInt64Match.CompareByKeyValue(pA, pB: Pointer): Integer; Begin Result := CompareByKey(pA, pB); If Result = 0 Then Result := CompareByValue(pA, pB); End; Procedure TAdvInt64Match.DefaultCompare(Out aCompare: TAdvItemsCompare); Begin aCompare := {$IFDEF FPC}@{$ENDIF}CompareByKey; End; Procedure TAdvInt64Match.LoadItem(oFiler: TAdvFiler; iIndex: Integer); Var iKey : TAdvInt64MatchKey; iValue : TAdvInt64MatchValue; Begin oFiler['Match'].DefineBegin; oFiler['Key'].DefineInteger(iKey); oFiler['Value'].DefineInteger(iValue); oFiler['Match'].DefineEnd; Add(iKey, iValue); End; Procedure TAdvInt64Match.SaveItem(oFiler: TAdvFiler; iIndex: Integer); Begin oFiler['Match'].DefineBegin; oFiler['Key'].DefineInteger(FMatches^[iIndex].Key); oFiler['Value'].DefineInteger(FMatches^[iIndex].Value); oFiler['Match'].DefineEnd; End; Procedure TAdvInt64Match.AssignItem(oItems: TAdvItems; iIndex: Integer); Begin Inherited; FMatches^[iIndex] := TAdvInt64Match(oItems).FMatches^[iIndex]; End; Procedure TAdvInt64Match.InternalEmpty(iIndex, iLength: Integer); Begin Inherited; MemoryZero(Pointer(NativeUInt(FMatches) + (iIndex * SizeOf(TAdvInt64MatchItem))), (iLength * SizeOf(TAdvInt64MatchItem))); End; Procedure TAdvInt64Match.InternalResize(iValue : Integer); Begin Inherited; MemoryResize(FMatches, Capacity * SizeOf(TAdvInt64MatchItem), iValue * SizeOf(TAdvInt64MatchItem)); End; Procedure TAdvInt64Match.InternalCopy(iSource, iTarget, iCount: Integer); Begin MemoryMove(@FMatches^[iSource], @FMatches^[iTarget], iCount * SizeOf(TAdvInt64MatchItem)); End; Function TAdvInt64Match.IndexByKey(aKey : TAdvInt64MatchKey): Integer; Begin If Not FindByKey(aKey, Result, {$IFDEF FPC}@{$ENDIF}CompareByKey) Then Result := -1; End; Function TAdvInt64Match.IndexByKeyValue(Const aKey : TAdvInt64MatchKey; Const aValue : TAdvInt64MatchValue) : Integer; Begin If Not Find(aKey, aValue, Result, {$IFDEF FPC}@{$ENDIF}CompareByKeyValue) Then Result := -1; End; Function TAdvInt64Match.ExistsByKey(aKey : TAdvInt64MatchKey): Boolean; Begin Result := ExistsByIndex(IndexByKey(aKey)); End; Function TAdvInt64Match.ExistsByKeyValue(Const aKey : TAdvInt64MatchKey; Const aValue : TAdvInt64MatchValue) : Boolean; Begin Result := ExistsByIndex(IndexByKeyValue(aKey, aValue)); End; Function TAdvInt64Match.Add(aKey : TAdvInt64MatchKey; aValue : TAdvInt64MatchValue): Integer; Begin Result := -1; If Not IsAllowDuplicates And Find(aKey, aValue, Result) Then Begin If IsPreventDuplicates Then RaiseError('Add', StringFormat('Key already exists in list (%s=%s)', [aKey, aValue])); // Result is the index of the existing key End Else Begin If Not IsSorted Then Result := Count Else If (Result < 0) Then Find(aKey, aValue, Result); Insert(Result, aKey, aValue); End; End; Procedure TAdvInt64Match.Insert(iIndex: Integer; iKey : TAdvInt64MatchKey; iValue : TAdvInt64MatchValue); Begin InternalInsert(iIndex); FMatches^[iIndex].Key := iKey; FMatches^[iIndex].Value := iValue; End; Procedure TAdvInt64Match.InternalInsert(iIndex: Integer); Begin Inherited; FMatches^[iIndex].Key := 0; FMatches^[iIndex].Value := 0; End; Procedure TAdvInt64Match.InternalExchange(iA, iB : Integer); Var aTemp : TAdvInt64MatchItem; pA : Pointer; pB : Pointer; Begin pA := @FMatches^[iA]; pB := @FMatches^[iB]; aTemp := PAdvIntegerMatchItem(pA)^; PAdvIntegerMatchItem(pA)^ := PAdvIntegerMatchItem(pB)^; PAdvIntegerMatchItem(pB)^ := aTemp; End; Function TAdvInt64Match.GetItem(iIndex: Integer): Pointer; Begin Assert(ValidateIndex('GetItem', iIndex)); Result := @FMatches^[iIndex]; End; Procedure TAdvInt64Match.SetItem(iIndex: Integer; pValue: Pointer); Begin Assert(ValidateIndex('SetItem', iIndex)); FMatches^[iIndex] := PAdvIntegerMatchItem(pValue)^; End; Function TAdvInt64Match.GetKey(iIndex: Integer): TAdvInt64MatchKey; Begin Assert(ValidateIndex('GetKey', iIndex)); Result := FMatches^[iIndex].Key; End; Procedure TAdvInt64Match.SetKey(iIndex: Integer; Const iValue: TAdvInt64MatchKey); Begin Assert(ValidateIndex('SetKey', iIndex)); FMatches^[iIndex].Key := iValue; End; Function TAdvInt64Match.GetValue(iIndex: Integer): TAdvInt64MatchValue; Begin Assert(ValidateIndex('GetValue', iIndex)); Result := FMatches^[iIndex].Value; End; Procedure TAdvInt64Match.SetValue(iIndex: Integer; Const iValue: TAdvInt64MatchValue); Begin Assert(ValidateIndex('SetValue', iIndex)); FMatches^[iIndex].Value := iValue; End; Function TAdvInt64Match.GetPair(iIndex: Integer): TAdvInt64MatchItem; Begin Assert(ValidateIndex('GetPair', iIndex)); Result := FMatches^[iIndex]; End; Procedure TAdvInt64Match.SetPair(iIndex: Integer; Const Value: TAdvInt64MatchItem); Begin Assert(ValidateIndex('SetPair', iIndex)); FMatches^[iIndex] := Value; End; Function TAdvInt64Match.GetMatch(iKey : TAdvInt64MatchKey): TAdvInt64MatchValue; Var iIndex : Integer; Begin iIndex := IndexByKey(iKey); If ExistsByIndex(iIndex) Then Result := ValueByIndex[iIndex] Else Begin Result := FDefault; If Not FForced Then RaiseError('GetMatch', 'Unable to get the value for the specified key.'); End; End; Procedure TAdvInt64Match.SetMatch(iKey : TAdvInt64MatchKey; Const iValue: TAdvInt64MatchValue); Var iIndex : Integer; Begin iIndex := IndexByKey(iKey); If ExistsByIndex(iIndex) Then ValueByIndex[iIndex] := iValue Else If FForced Then Add(iKey, iValue) Else RaiseError('SetMatch', 'Unable to set the value for the specified key.'); End; Function TAdvInt64Match.CapacityLimit : Integer; Begin Result := High(TAdvInt64MatchItems); End; Function TAdvInt64Match.Find(Const aKey: TAdvInt64MatchKey; Const aValue: TAdvInt64MatchValue; Out iIndex: Integer; aCompare: TAdvItemsCompare): Boolean; Var aItem : TAdvInt64MatchItem; Begin aItem.Key := aKey; aItem.Value := aValue; Result := Inherited Find(@aItem, iIndex, aCompare); End; Function TAdvInt64Match.FindByKey(Const aKey: TAdvInt64MatchKey; Out iIndex: Integer; aCompare: TAdvItemsCompare): Boolean; Begin Result := Find(aKey, 0, iIndex, aCompare); End; Procedure TAdvInt64Match.SortedByKey; Begin SortedBy({$IFDEF FPC}@{$ENDIF}CompareByKey); End; Procedure TAdvInt64Match.SortedByValue; Begin SortedBy({$IFDEF FPC}@{$ENDIF}CompareByValue); End; Procedure TAdvInt64Match.SortedByKeyValue; Begin SortedBy({$IFDEF FPC}@{$ENDIF}CompareByKeyValue); End; Procedure TAdvInt64Match.ForceIncrementByKey(Const aKey: TAdvInt64MatchKey); Var iIndex : Integer; Begin If Not FindByKey(aKey, iIndex) Then Insert(iIndex, aKey, 1) Else ValueByIndex[iIndex] := ValueByIndex[iIndex] + 1; End; Procedure TAdvInt64Match.DeleteByKey(aKey: TAdvInt64MatchKey); Begin DeleteByIndex(IndexByKey(aKey)); End; Function TAdvInt64Match.EqualTo(Const oIntegerMatch : TAdvInt64Match) : Boolean; Var aPair : TAdvInt64MatchItem; iIndex : Integer; Begin Result := oIntegerMatch.Count = Count; iIndex := 0; While Result And ExistsByIndex(iIndex) Do Begin aPair := Pairs[iIndex]; Result := oIntegerMatch.ExistsByKeyValue(aPair.Key, aPair.Value); Inc(iIndex); End; End; End. // AdvIntegerMatches //
27.981132
154
0.744961
fcf2fef048771607cff9ccfbdcb7f4a2b676ba44
2,808
pas
Pascal
dependencies/scriptgate/Androidapi.JNI.SGWebClient.pas
Zawuza/hybrid-example
203e5db40b788a6d8b1cf653eeb52df1991e65ea
[ "Apache-2.0" ]
9
2017-11-12T04:17:41.000Z
2020-04-27T22:39:57.000Z
dependencies/scriptgate/Androidapi.JNI.SGWebClient.pas
Zawuza/hybrid-example
203e5db40b788a6d8b1cf653eeb52df1991e65ea
[ "Apache-2.0" ]
null
null
null
dependencies/scriptgate/Androidapi.JNI.SGWebClient.pas
Zawuza/hybrid-example
203e5db40b788a6d8b1cf653eeb52df1991e65ea
[ "Apache-2.0" ]
1
2018-02-27T18:57:25.000Z
2018-02-27T18:57:25.000Z
(* * THIS FILE DO NOT RECREATE by Java2OP.exe !!!!! * THIS IS HAND-MADE ! * BECAUSE Java2OP IS FAILED ! *) unit Androidapi.JNI.SGWebClient; // (* {$IFNDEF ANDROID} {$WARNINGS OFF 1011} interface implementation end. {$ENDIF} // *) interface uses Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.Webkit, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.Os, Androidapi.JNI.Net; type JSGWebClient = interface;//jp.serialgames.WebClient JSGWebClientClass = interface(JWebViewClientClass) ['{EF3AD3BB-A754-48BF-AAF7-08F96F695E51}'] {class} function init: JSGWebClient; cdecl; overload; end; [JavaSignature('jp/serialgames/SGWebClient')] JSGWebClient = interface(JWebViewClient) ['{2CA265FA-191F-4BCC-8E77-9FEF883428E5}'] function getWebView: JWebView; cdecl; function getHash: Integer; cdecl; function getMessage1: JMessage; cdecl; function getMessage2: JMessage; cdecl; function getBitmap: JBitmap; cdecl; function getHttpAuthHandler: JHttpAuthHandler; cdecl; function getSslErrorHandler: JSslErrorHandler; cdecl; function getSslError: JSslError; cdecl; function getKeyEvent: JKeyEvent; cdecl; procedure setWebView(view: JWebView); cdecl; procedure doUpdateVisitedHistory( view: JWebView; url: JString; isReload: Boolean); cdecl; procedure onFormResubmission( view: JWebView; dontResend: JMessage; resend: JMessage); cdecl; procedure onLoadResource(view: JWebView; url: JString); cdecl; procedure onPageFinished(view: JWebView; url: JString); cdecl; procedure onPageStarted( view: JWebView; url: JString; favicon: JBitmap); cdecl; procedure onReceivedError( view: JWebView; errorCode: Integer; description: JString; failingUrl: JString); cdecl; procedure onReceivedHttpAuthRequest( view: JWebView; handler: JHttpAuthHandler; host: JString; realm: JString); cdecl; procedure onReceivedSslError( view: JWebView; handler: JSslErrorHandler; error: JSslError ); procedure onScaleChanged( view: JWebView; oldScale: Single; newScale: Single); cdecl; procedure onUnhandledKeyEvent(view: JWebView; event: JKeyEvent); cdecl; function shouldOverrideKeyEvent( view: JWebView; event: JKeyEvent): Boolean; cdecl; function shouldOverrideUrlLoading( view: JWebView; url: JString): Boolean; cdecl; end; TJSGWebClient = class(TJavaGenericImport<JSGWebClientClass, JSGWebClient>) end; implementation procedure RegisterTypes; begin TRegTypes.RegisterType( 'Androidapi.JNI.SGWebClient.JSGWebClient', TypeInfo(Androidapi.JNI.SGWebClient.JSGWebClient)); end; initialization RegisterTypes; end.
25.761468
76
0.712251
c382b9c2af65d572ef092aa888603ea571a44b7b
2,321
pas
Pascal
Examples/Source/motiongraphics/mainform.pas
joecare99/Public
9eee060fbdd32bab33cf65044602976ac83f4b83
[ "MIT" ]
11
2017-06-17T05:13:45.000Z
2021-07-11T13:18:48.000Z
Examples/Source/motiongraphics/mainform.pas
joecare99/Public
9eee060fbdd32bab33cf65044602976ac83f4b83
[ "MIT" ]
2
2019-03-05T12:52:40.000Z
2021-12-03T12:34:26.000Z
Examples/Source/motiongraphics/mainform.pas
joecare99/Public
9eee060fbdd32bab33cf65044602976ac83f4b83
[ "MIT" ]
6
2017-09-07T09:10:09.000Z
2022-02-19T20:19:58.000Z
unit mainform; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, ComCtrls; type { TForm1 } TForm1 = class(TForm) Label1: TLabel; timerRedraw: TTimer; trackSpeed: TTrackBar; procedure FormPaint(Sender: TObject); procedure timerRedrawTimer(Sender: TObject); procedure trackSpeedChange(Sender: TObject); private { private declarations } public { public declarations } CurStep: Double; procedure RotatePolygon(var APoints: array of TPoint; AAngle: Double); function RotatePoint(APoint, ACenter: TPoint; AAngle: Double): TPoint; end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure TForm1.timerRedrawTimer(Sender: TObject); begin CurStep := CurStep + 0.1; if CurStep > 360 then CurStep := 0; Form1.Invalidate; end; procedure TForm1.trackSpeedChange(Sender: TObject); begin timerRedraw.Interval := 1000 div trackSpeed.Position; end; procedure TForm1.RotatePolygon(var APoints: array of TPoint; AAngle: Double); var lCenter: TPoint; i: Integer; begin lCenter := Point(0, 0); for i := 0 to Length(APoints)-1 do begin lCenter.X := lCenter.X + APoints[i].X; lCenter.Y := lCenter.Y + APoints[i].Y; end; lCenter.X := lCenter.X div Length(APoints); lCenter.Y := lCenter.Y div Length(APoints); for i := 0 to Length(APoints)-1 do APoints[i] := RotatePoint(APoints[i], lCenter, AAngle); end; function TForm1.RotatePoint(APoint, ACenter: TPoint; AAngle: Double): TPoint; var dx, dy: Double; begin dx := (ACenter.Y * Sin(AAngle)) - (ACenter.X * Cos(AAngle)) + ACenter.X; dy := -(ACenter.X * Sin(AAngle)) - (ACenter.Y * Cos(AAngle)) + ACenter.Y; Result.X := Round((APoint.X * Cos(AAngle)) - (APoint.Y * Sin(AAngle)) + dx); Result.Y := Round((APoint.X * Sin(AAngle)) + (APoint.Y * Cos(AAngle)) + dy); end; procedure TForm1.FormPaint(Sender: TObject); var lPoints: array[0..2] of TPoint; begin lPoints[0].X := 100; lPoints[0].Y := 100; lPoints[1].X := 200; lPoints[1].Y := 0; lPoints[2].X := 200; lPoints[2].Y := 200; RotatePolygon(lPoints, CurStep); Canvas.Polygon(lPoints); // trackSpeed.Invalidate; end; end.
23.927835
79
0.647135
4794527aa3c5beb91cef978cfe3b74d41fd16958
10,977
dpr
Pascal
Examples/Simple/Circles.dpr
kant/AggPasMod
6acc4502e9108ae105b55992800d0a3a505fb033
[ "OLDAP-2.4", "OLDAP-2.3" ]
69
2015-06-07T10:45:24.000Z
2022-02-17T06:47:12.000Z
Examples/Simple/Circles.dpr
kant/AggPasMod
6acc4502e9108ae105b55992800d0a3a505fb033
[ "OLDAP-2.4", "OLDAP-2.3" ]
15
2015-08-28T07:28:58.000Z
2020-04-10T22:16:57.000Z
Examples/Simple/Circles.dpr
kant/AggPasMod
6acc4502e9108ae105b55992800d0a3a505fb033
[ "OLDAP-2.4", "OLDAP-2.3" ]
28
2015-06-11T05:04:57.000Z
2021-05-28T10:52:15.000Z
program Circles; // AggPas 2.4 RM3 Demo application // Note: Press F1 key on run to see more info about this demo {$I AggCompiler.inc} { DEFINE AGG_GRAY8 } {$DEFINE AGG_BGR24 } { DEFINE AGG_Rgb24 } { DEFINE AGG_BGRA32 } { DEFINE AGG_RgbA32 } { DEFINE AGG_ARGB32 } { DEFINE AGG_ABGR32 } { DEFINE AGG_Rgb565 } { DEFINE AGG_Rgb555 } {$WARNINGS ON} {$HINTS ON} uses {$IFDEF USE_FASTMM4} FastMM4, {$ENDIF} SysUtils, AggPlatformSupport, // please add the path to this file manually AggBasics in '..\..\Source\AggBasics.pas', AggMath in '..\..\Source\AggMath.pas', AggControl in '..\..\Source\Controls\AggControl.pas', AggSliderControl in '..\..\Source\Controls\AggSliderControl.pas', AggScaleControl in '..\..\Source\Controls\AggScaleControl.pas', AggRasterizerScanLineAA in '..\..\Source\AggRasterizerScanLineAA.pas', AggScanLine in '..\..\Source\AggScanLine.pas', AggScanLinePacked in '..\..\Source\AggScanLinePacked.pas', AggRendererBase in '..\..\Source\AggRendererBase.pas', AggRendererScanLine in '..\..\Source\AggRendererScanLine.pas', AggRenderScanLines in '..\..\Source\AggRenderScanLines.pas', AggBSpline in '..\..\Source\AggBSpline.pas', AggEllipse in '..\..\Source\AggEllipse.pas', AggConvTransform in '..\..\Source\AggConvTransform.pas', AggTransAffine in '..\..\Source\AggTransAffine.pas', AggGsvText in '..\..\Source\AggGsvText.pas' {$I Pixel_Formats.inc } const CFlipY = True; CDefaultNumPoints = 10000; CStartWidth = 400; CStartHeight = 400; CSplineRedX: TAggParallelogram = (0, 0.2, 0.4, 0.910484, 0.957258, 1); CSplineRedY: TAggParallelogram = (1, 0.8, 0.6, 0.066667, 0.169697, 0.6); CSplineGreenX: TAggParallelogram = (0, 0.292244, 0.485655, 0.564859, 0.795607, 1); CSplineGreenY: TAggParallelogram = (0, 0.607260, 0.964065, 0.892558, 0.435571, 0); CSplineBlueX: TAggParallelogram = (0, 0.055045, 0.143034, 0.433082, 0.764859, 1); CSplineBlueY: TAggParallelogram = (0.385480, 0.128493, 0.021416, 0.271507, 0.713974, 1); type PScatterPoint = ^TScatterPoint; TScatterPoint = record X, Y, Z: Double; Color: TAggColor; end; TAggApplication = class(TPlatformSupport) private FNumPoints: Cardinal; FPoints: PScatterPoint; FScaleCtrlZ: TScaleControl; FSliderControlSel: TAggControlSlider; FSliderControlSize: TAggControlSlider; FSplineR, FSplineG, FSplineB: TAggBSpline; FPixelFormat: TAggPixelFormatProcessor; public constructor Create(PixelFormat: TPixelFormat; FlipY: Boolean; NumPoints: Cardinal); destructor Destroy; override; procedure Generate; procedure OnInit; override; procedure OnDraw; override; procedure OnIdle; override; procedure OnMouseButtonDown(X, Y: Integer; Flags: TMouseKeyboardFlags); override; procedure OnKey(X, Y: Integer; Key: Cardinal; Flags: TMouseKeyboardFlags); override; end; { TAggApplication } constructor TAggApplication.Create(PixelFormat: TPixelFormat; FlipY: Boolean; NumPoints: Cardinal); begin inherited Create(PixelFormat, FlipY); CPixelFormat(FPixelFormat, RenderingBufferWindow); FNumPoints := NumPoints; AggGetMem(Pointer(FPoints), NumPoints * SizeOf(TScatterPoint)); FScaleCtrlZ := TScaleControl.Create(5, 5, CStartWidth - 5, 12, not FlipY); FSliderControlSel := TAggControlSlider.Create(5, 20, CStartWidth - 5, 27, not FlipY); FSliderControlSize := TAggControlSlider.Create(5, 35, CStartWidth - 5, 42, not FlipY); FSplineR := TAggBSpline.Create; FSplineG := TAggBSpline.Create; FSplineB := TAggBSpline.Create; FSplineR.Init(6, @CSplineRedX, @CSplineRedY); FSplineG.Init(6, @CSplineGreenX, @CSplineGreenY); FSplineB.Init(6, @CSplineBlueX, @CSplineBlueY); AddControl(FScaleCtrlZ); AddControl(FSliderControlSel); AddControl(FSliderControlSize); FSliderControlSize.Caption := 'Size'; FSliderControlSel.Caption := 'Selectivity'; end; destructor TAggApplication.Destroy; begin FSplineR.Free; FSplineG.Free; FSplineB.Free; FScaleCtrlZ.Free; FSliderControlSel.Free; FSliderControlSize.Free; AggFreeMem(Pointer(FPoints), FNumPoints * SizeOf(TScatterPoint)); FPixelFormat.Free; inherited; end; procedure TAggApplication.Generate; var I: Cardinal; Rx, Ry, Z, Dist, Angle: Double; ScatterPnt, Pnt: TPointDouble; begin Rx := InitialWidth / 3.5; Ry := InitialHeight / 3.5; for I := 0 to FNumPoints - 1 do begin Z := RandomMinMax(0.0, 1.0); PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)).Z := Z; SinCosScale(Z * 2.0 * Pi, Pnt.Y, Pnt.X, Ry, Rx); Dist := RandomMinMax(0.0, Rx * 0.5); Angle := RandomMinMax(0.0, Pi * 2.0); SinCos(Angle, ScatterPnt.Y, ScatterPnt.X); PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)).X := InitialWidth * 0.5 + Pnt.X + ScatterPnt.X * Dist; PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)).Y := InitialHeight * 0.5 + Pnt.Y + ScatterPnt.Y * Dist; PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)) .Color.FromRgbaDouble(FSplineR.Get(Z) * 0.8, FSplineG.Get(Z) * 0.8, FSplineB.Get(Z) * 0.8, 1.0); end; end; procedure TAggApplication.OnInit; begin Generate; end; procedure TAggApplication.OnDraw; var Ras: TAggRasterizerScanLineAA; Sl: TAggScanLinePacked8; RendererBase: TAggRendererBase; RenScan: TAggRendererScanLineAASolid; Circle: TAggCircle; T1: TAggConvTransform; Rgba, Temp: TAggColor; I, NumDrawn: Cardinal; Z, Alpha: Double; ScatterPoint: PScatterPoint; Txt: TAggGsvText; TxtOutline: TAggGsvTextOutline; begin // Initialize structures Ras := TAggRasterizerScanLineAA.Create; Sl := TAggScanLinePacked8.Create; RendererBase := TAggRendererBase.Create(FPixelFormat); try RenScan := TAggRendererScanLineAASolid.Create(RendererBase); try RendererBase.Clear(CRgba8White); // Draw circles Circle := TAggCircle.Create; T1 := TAggConvTransform.Create(Circle, GetTransAffineResizing); NumDrawn := 0; for I := 0 to FNumPoints - 1 do begin ScatterPoint := FPoints; Inc(ScatterPoint, I); Z := ScatterPoint^.Z; Alpha := 1.0; if Z < FScaleCtrlZ.GetValue1 then Alpha := 1.0 - (FScaleCtrlZ.GetValue1 - Z) * FSliderControlSel.Value * 100.0; if Z > FScaleCtrlZ.GetValue2 then Alpha := 1.0 - (Z - FScaleCtrlZ.GetValue2) * FSliderControlSel.Value * 100.0; if Alpha > 1.0 then Alpha := 1.0; if Alpha < 0.0 then Continue; Circle.Initialize(PPointDouble(ScatterPoint)^, FSliderControlSize.Value * 5.0, 8); Ras.AddPath(T1); Temp := ScatterPoint^.Color; Rgba.FromRgbInteger(Temp.Rgba8.R, Temp.Rgba8.G, Temp.Rgba8.B, Alpha); RenScan.SetColor(@Rgba); RenderScanLines(Ras, Sl, RenScan); Inc(NumDrawn); end; // Render the controls RenderControl(Ras, Sl, RenScan, FScaleCtrlZ); RenderControl(Ras, Sl, RenScan, FSliderControlSel); RenderControl(Ras, Sl, RenScan, FSliderControlSize); // Render the Text Txt := TAggGsvText.Create; Txt.SetSize(15.0); Txt.SetText(Format('%08u', [NumDrawn])); Txt.SetStartPoint(10.0, InitialHeight - 20.0); TxtOutline := TAggGsvTextOutline.Create(Txt, GetTransAffineResizing); Ras.AddPath(TxtOutline); RenScan.SetColor(CRgba8Black); RenderScanLines(Ras, Sl, RenScan); // Free AGG resources T1.Free; Ras.Free; Sl.Free; Circle.Free; Txt.Free; TxtOutline.Free; finally RenScan.Free; end; finally RendererBase.Free; end; end; procedure TAggApplication.OnIdle; var I: Cardinal; begin for I := 0 to FNumPoints - 1 do begin PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)).X := PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)).X + RandomMinMax(0, FSliderControlSel.Value) - FSliderControlSel.Value * 0.5; PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)).Y := PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)).Y + RandomMinMax(0, FSliderControlSel.Value) - FSliderControlSel.Value * 0.5; PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)).Z := PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)).Z + RandomMinMax(0, FSliderControlSel.Value * 0.01) - FSliderControlSel.Value * 0.005; if PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)).Z < 0.0 then PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)).Z := 0.0; if PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)).Z > 1.0 then PScatterPoint(PtrComp(FPoints) + I * SizeOf(TScatterPoint)).Z := 1.0; end; ForceRedraw; end; procedure TAggApplication.OnMouseButtonDown(X, Y: Integer; Flags: TMouseKeyboardFlags); begin if mkfMouseLeft in Flags then begin Generate; ForceRedraw; end; if mkfMouseRight in Flags then WaitMode := not WaitMode; end; procedure TAggApplication.OnKey(X, Y: Integer; Key: Cardinal; Flags: TMouseKeyboardFlags); begin if Key = Cardinal(kcF1) then DisplayMessage('This example just demonstrates that AGG can be used in ' + 'different scatter plot apllications. There''s a number of small ' + 'circles drawn. You can change the parameters of drawing, watching ' + 'for the performance and the number of circles simultaneously ' + 'rendered. Note, that the circles are drawn with High quality, ' + 'possibly translucent, and with subpixel accuracy.'#13#13 + 'How to play with:'#13#13 + 'Press the left mouse button to generate a new set of points. '#13 + 'Press the right mouse button to make the points randomly change ' + 'their coordinates.'#13#13 + 'Note: F2 key saves current "screenshot" file in this demo''s ' + 'directory.'); end; var Err: Integer; NumPoints: Cardinal; begin NumPoints := CDefaultNumPoints; if ParamCount > 0 then begin Val(ParamStr(1), NumPoints, Err); if NumPoints <= 0 then NumPoints := CDefaultNumPoints; if NumPoints > 20000 then NumPoints := 20000; end; with TAggApplication.Create(CPixFormat, CFlipY, NumPoints) do try Caption := 'AGG Drawing random circles - A scatter plot prototype (F1-Help)'; if Init(CStartWidth, CStartHeight, [wfResize, wfKeepAspectRatio]) then Run; finally Free; end; end.
27.511278
82
0.656737
47a3f5688abc671bf2984a73c5a267bd2eb50a64
2,955
pas
Pascal
samples/a8/demoeffects/twister.pas
zbyti/Mad-Pascal
546cae9724828f93047080109488be7d0d07d47e
[ "MIT" ]
1
2021-12-15T23:47:19.000Z
2021-12-15T23:47:19.000Z
samples/a8/demoeffects/twister.pas
michalkolodziejski/Mad-Pascal
0a7a1e2f379e50b0a23878b0d881ff3407269ed6
[ "MIT" ]
null
null
null
samples/a8/demoeffects/twister.pas
michalkolodziejski/Mad-Pascal
0a7a1e2f379e50b0a23878b0d881ff3407269ed6
[ "MIT" ]
null
null
null
// Twister uses crt, graph, fastmath; var sine: array [0..255] of byte absolute $0600; mv, mv2: byte; LineAdr: word; const height = 96 div 2; cx = 48; procedure h_line(x0,x1: byte; c: byte); assembler; asm { txa:pha lda c :2 asl @ sta color tay lda left,y sta fill mwa LineAdr ztmp lda x0 ; left edge and #3 tax lda lmask,x sta lmsk eor #$ff sta _lmsk txa add #0 color equ *-1 tax lda left,x sta lcol lda x0 :2 lsr @ tay sty lf lda x1 ; right edge and #3 tax lda rmask,x sta rmsk eor #$ff sta _rmsk txa add color tax lda right,x sta rcol lda x1 :2 lsr @ tay sty rg ldy #0 lf equ *-1 cpy rg beq piksel lda (ztmp),y and #0 lmsk equ *-1 ora #0 lcol equ *-1 sta (ztmp),y iny lda #0 fill equ *-1 loop cpy #0 rg equ *-1 bcs stop sta (ztmp),y iny bne loop stop lda (ztmp),y and #0 rmsk equ *-1 ora #0 rcol equ *-1 sta (ztmp),y jmp exit lmask dta %00000000 dta %11000000 dta %11110000 dta %11111100 left :4 brk dta %01010101 dta %00010101 dta %00000101 dta %00000001 dta %10101010 dta %00101010 dta %00001010 dta %00000010 dta %11111111 rmask dta %00111111 dta %00001111 dta %00000011 right :4 brk dta %01000000 dta %01010000 dta %01010100 dta %01010101 dta %10000000 dta %10100000 dta %10101000 dta %10101010 dta %11000000 dta %11110000 dta %11111100 dta %11111111 piksel lda fill and #0 _lmsk equ *-1 and #0 _rmsk equ *-1 ora (ztmp),y sta (ztmp),y exit pla:tax }; end; procedure Twister(adY: byte); var x1,x2,x3,x4: byte; minx, maxx, a, i: byte; begin LineAdr := DPeek(88) + adY; for a := 0 to height-1 do begin i:=sine[a + mv2] + sine[mv]; x1 := cx + sine[i] shr 1; x2 := cx + sine[byte(i + 64)] shr 1; x3 := cx + sine[byte(i + 128)] shr 1; x4 := cx + sine[byte(i + 192)] shr 1; minx:=x1; // if x1<minx then minx:=x1; if x2<minx then minx:=x2; if x3<minx then minx:=x3; if x4<minx then minx:=x4; maxx:=x1; // if x1>=maxx then maxx:=x1; if x2>=maxx then maxx:=x2; if x3>=maxx then maxx:=x3; if x4>=maxx then maxx:=x4; dec(minx); inc(maxx); H_line(minx-6, minx, 0); // clear left/right twister border H_line(maxx, maxx+6, 0); if x1<x2 then H_line(x1,x2, 1); if x2<x3 then H_line(x2,x3, 2); if x3<x4 then H_line(x3,x4, 3); if x4<x1 then H_line(x4,x1, 2); inc(LineAdr, 80); end; end; begin InitGraph(7 + 16); Poke(708, $c6); Poke(709, $76); Poke(710, $f6); FillSinLow(@sine); // initialize SINUS table mv:=0; mv2:=65; repeat pause; Twister(0); inc(mv, 2); dec(mv2, 3); Twister(40); inc(mv, 3); dec(mv2, 2); until keypressed; end.
12.061224
64
0.553638
fcca74239b30ad0c1f4e962d5cd36da342131b45
2,145
pas
Pascal
uFileVersion.pas
agebhar1/sim8008-shared
3f0b4adfe247936489ca97ad9ae778f9cfef71ee
[ "MIT" ]
null
null
null
uFileVersion.pas
agebhar1/sim8008-shared
3f0b4adfe247936489ca97ad9ae778f9cfef71ee
[ "MIT" ]
null
null
null
uFileVersion.pas
agebhar1/sim8008-shared
3f0b4adfe247936489ca97ad9ae778f9cfef71ee
[ "MIT" ]
null
null
null
unit uFileVersion; interface uses Windows, SysUtils; function GetFileVersion(pFile: PChar; var wMajor, wMinor, wRelease, wBuild: Word): Boolean; function GetProductVersion(pFile: PChar; var wMajor, wMinor, wRelease, wBuild: Word): Boolean; implementation function GetFileVersion(pFile: PChar; var wMajor, wMinor, wRelease, wBuild: Word): Boolean; var puLength, pHandle, InfoLength: Cardinal; MoreData, Data: Pointer; FileInfo: VS_FIXEDFILEINFO; begin Result:= False; wMajor:= 0; wMinor:= 0; wRelease:= 0; wBuild:= 0; InfoLength:= GetFileVersionInfoSize(pFile,pHandle); GetMem(Data,InfoLength); if GetFileVersionInfo(pFile,0,InfoLength,Data) then if VerQueryValue(Data,'\',MoreData,puLength) then try Move(MoreData^,FileInfo,SizeOf(FileInfo)); wMajor:= HiWord(FileInfo.dwFileVersionMS); wMinor:= LoWord(FileInfo.dwFileVersionMS); wRelease:= HiWord(FileInfo.dwFileVersionLS); wBuild:= LoWord(FileInfo.dwFileVersionLS); Result:= True; except FreeMem(Data); Exit; end; FreeMem(Data); end; function GetProductVersion(pFile: PChar; var wMajor, wMinor, wRelease, wBuild: Word): Boolean; var puLength, pHandle, InfoLength: Cardinal; MoreData, Data: Pointer; FileInfo: VS_FIXEDFILEINFO; begin Result:= False; wMajor:= 0; wMinor:= 0; wRelease:= 0; wBuild:= 0; InfoLength:= GetFileVersionInfoSize(pFile,pHandle); GetMem(Data,InfoLength); if GetFileVersionInfo(pFile,0,InfoLength,Data) then if VerQueryValue(Data,'\',MoreData,puLength) then try Move(MoreData^,FileInfo,SizeOf(FileInfo)); wMajor:= HiWord(FileInfo.dwProductVersionMS); wMinor:= LoWord(FileInfo.dwProductVersionMS); wRelease:= HiWord(FileInfo.dwProductVersionLS); wBuild:= LoWord(FileInfo.dwProductVersionLS); Result:= True; except FreeMem(Data); Exit; end; FreeMem(Data); end; end.
27.5
61
0.636364
fc8fbc2265d481dd75d3d23c4f6e3c78cc5ad388
1,819
dfm
Pascal
RVSEdit.dfm
rubiot/lazrichview
8ce4deff06bb75abe07aee60c22a9e68ba888326
[ "MIT" ]
10
2018-01-14T15:06:14.000Z
2021-12-03T20:36:02.000Z
RVSEdit.dfm
rubiot/lazrichview
8ce4deff06bb75abe07aee60c22a9e68ba888326
[ "MIT" ]
1
2017-06-16T08:03:00.000Z
2017-06-17T17:56:47.000Z
RVSEdit.dfm
rubiot/lazrichview
8ce4deff06bb75abe07aee60c22a9e68ba888326
[ "MIT" ]
5
2018-05-17T17:28:13.000Z
2021-11-12T11:02:28.000Z
object frmRVSEdit: TfrmRVSEdit Left = 104 Top = 31 BorderIcons = [biSystemMenu] BorderStyle = bsDialog Caption = 'RichView Styles Editor' ClientHeight = 370 ClientWidth = 402 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = True OnActivate = FormActivate OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object Bevel1: TBevel Left = 7 Top = 326 Width = 386 Height = 6 Shape = bsBottomLine end object Label1: TLabel Left = 8 Top = 7 Width = 55 Height = 13 Caption = 'Text Styles:' end object btnOk: TButton Left = 321 Top = 339 Width = 75 Height = 25 Caption = 'Close' Default = True ModalResult = 1 TabOrder = 3 end object btnDel: TButton Left = 319 Top = 69 Width = 75 Height = 25 Caption = 'Delete' TabOrder = 2 OnClick = btnDelClick end object btnEdit: TButton Left = 319 Top = 41 Width = 75 Height = 25 Caption = 'Edit...' TabOrder = 1 OnClick = btnEditClick end object btnAdd: TButton Left = 319 Top = 13 Width = 75 Height = 25 Caption = 'Add' TabOrder = 0 OnClick = btnAddClick end object tv: TTreeView Left = 8 Top = 23 Width = 306 Height = 218 HideSelection = False Indent = 19 ReadOnly = True ShowRoot = False TabOrder = 4 OnChange = tvChange end object panPreview: TPanel Left = 6 Top = 247 Width = 390 Height = 78 BevelInner = bvRaised BevelOuter = bvLowered Caption = 'Style Preview' TabOrder = 5 end end
19.351064
37
0.57669
83ce5f6a2891303980b1a473ecfab50e178e05d8
4,224
pas
Pascal
TestBed/TestBedShared/Tests/UCompoundShapes.pas
FMXExpress/box2d-firemonkey
56ef507717fcaadbfa4353429788f938c1d78eaf
[ "MIT" ]
19
2015-01-04T10:52:35.000Z
2021-08-09T19:12:33.000Z
TestBed/TestBedShared/Tests/UCompoundShapes.pas
amikey/box2d-firemonkey
56ef507717fcaadbfa4353429788f938c1d78eaf
[ "MIT" ]
1
2016-10-28T10:14:23.000Z
2016-10-28T10:14:23.000Z
TestBed/TestBedShared/Tests/UCompoundShapes.pas
amikey/box2d-firemonkey
56ef507717fcaadbfa4353429788f938c1d78eaf
[ "MIT" ]
13
2015-05-03T07:14:42.000Z
2021-08-09T18:06:58.000Z
unit UCompoundShapes; interface {$I ..\..\Physics2D\Physics2D.inc} uses uTestBed, UPhysics2DTypes, UPhysics2D, SysUtils; type TCompoundShapes = class(TTester) public constructor Create; override; end; implementation { TCompoundShapes } constructor TCompoundShapes.Create; var i: Integer; bd: Tb2BodyDef; body: Tb2Body; edge: Tb2EdgeShape; polygon1, polygon2, triangle1, triangle2, bottom, left, right: Tb2PolygonShape; circle1, circle2: Tb2CircleShape; xf1, xf2: Tb2Transform; vertices: array[0..2] of TVector2; begin inherited; begin bd := Tb2BodyDef.Create; SetValue(bd.position, 0.0, 0.0); body := m_world.CreateBody(bd); edge := Tb2EdgeShape.Create; edge.SetVertices(MakeVector(50.0, 0.0), MakeVector(-50.0, 0.0)); body.CreateFixture(edge, 0.0); end; begin circle1 := Tb2CircleShape.Create; circle1.m_radius := 0.5; SetValue(circle1.m_p, -0.5, 0.5); circle2 := Tb2CircleShape.Create; circle2.m_radius := 0.5; SetValue(circle2.m_p, 0.5, 0.5); bd := Tb2BodyDef.Create; bd.bodyType := b2_dynamicBody; for i := 0 to 9 do begin SetValue(bd.position, RandomFloat(-0.1, 0.1) + 5.0, 1.05 + 2.5 * i); bd.angle := RandomFloat(-Pi, Pi); body := m_world.CreateBody(bd, False); body.CreateFixture(circle1, 2.0, False, False); body.CreateFixture(circle2, 0.0, False); end; bd.Free; circle1.Free; circle2.Free; end; begin polygon1 := Tb2PolygonShape.Create; polygon1.SetAsBox(0.25, 0.5); polygon2 := Tb2PolygonShape.Create; polygon2.SetAsBox(0.25, 0.5, MakeVector(0.0, -0.5), 0.5 * Pi); bd := Tb2BodyDef.Create; bd.bodyType := b2_dynamicBody; for i := 0 to 9 do begin SetValue(bd.position, RandomFloat(-0.1, 0.1) - 5.0, 1.05 + 2.5 * i); bd.angle := RandomFloat(-Pi, Pi); body := m_world.CreateBody(bd, False); body.CreateFixture(polygon1, 2.0, False, False); body.CreateFixture(polygon2, 2.0, False); end; bd.Free; polygon1.Free; polygon2.Free; end; begin {$IFDEF OP_OVERLOAD} xf1.q.SetAngle(0.3524 * Pi); xf1.p := xf1.q.GetXAxis; {$ELSE} SetAngle(xf1.q, 0.3524 * Pi); xf1.p := GetXAxis(xf1.q); {$ENDIF} triangle1 := Tb2PolygonShape.Create; vertices[0] := b2Mul(xf1, MakeVector(-1.0, 0.0)); vertices[1] := b2Mul(xf1, MakeVector(1.0, 0.0)); vertices[2] := b2Mul(xf1, MakeVector(0.0, 0.5)); triangle1.SetVertices(@vertices[0], 3); {$IFDEF OP_OVERLOAD} xf2.q.SetAngle(-0.3524 * Pi); xf2.p := -xf2.q.GetXAxis; {$ELSE} SetAngle(xf2.q, -0.3524 * Pi); xf2.p := Negative(GetXAxis(xf2.q)); {$ENDIF} triangle2 := Tb2PolygonShape.Create; vertices[0] := b2Mul(xf2, MakeVector(-1.0, 0.0)); vertices[1] := b2Mul(xf2, MakeVector(1.0, 0.0)); vertices[2] := b2Mul(xf2, MakeVector(0.0, 0.5)); triangle2.SetVertices(@vertices[0], 3); bd := Tb2BodyDef.Create; bd.bodyType := b2_dynamicBody; for i := 0 to 9 do begin SetValue(bd.position, RandomFloat(-0.1, 0.1), 2.05 + 2.5 * i); bd.angle := 0.0; body := m_world.CreateBody(bd, False); body.CreateFixture(triangle1, 2.0, False, False); body.CreateFixture(triangle2, 2.0, False); end; triangle1.Free; triangle2.Free; bd.Free; end; begin bottom := Tb2PolygonShape.Create; bottom.SetAsBox( 1.5, 0.15 ); left := Tb2PolygonShape.Create; left.SetAsBox(0.15, 2.7, MakeVector(-1.45, 2.35), 0.2); right := Tb2PolygonShape.Create; right.SetAsBox(0.15, 2.7, MakeVector(1.45, 2.35), -0.2); bd := Tb2BodyDef.Create; bd.bodyType := b2_dynamicBody; SetValue(bd.position, 0.0, 2.0); body := m_world.CreateBody(bd); body.CreateFixture(bottom, 4.0, True, False); body.CreateFixture(left, 4.0, True, False); body.CreateFixture(right, 4.0); end; end; initialization RegisterTestEntry('Compound Shapes', TCompoundShapes); end.
27.076923
82
0.594934
4739e2bfe56d9a51c797ca58a34e1bf782f7cb30
48,509
pas
Pascal
SQLserver/uDatabaseMaint.pas
Evosi/ThinkSQL
f6bc3fac81f0703be6c36f2976c092c55cb9e0e7
[ "BSD-3-Clause" ]
4
2018-05-01T20:29:14.000Z
2019-12-01T15:44:05.000Z
SQLserver/uDatabaseMaint.pas
Evosi/ThinkSQL
f6bc3fac81f0703be6c36f2976c092c55cb9e0e7
[ "BSD-3-Clause" ]
null
null
null
SQLserver/uDatabaseMaint.pas
Evosi/ThinkSQL
f6bc3fac81f0703be6c36f2976c092c55cb9e0e7
[ "BSD-3-Clause" ]
4
2019-11-26T18:47:26.000Z
2021-06-25T06:06:18.000Z
unit uDatabaseMaint; { ThinkSQL Relational Database Management System Copyright © 2000-2012 Greg Gaughan See LICENCE.txt for details } interface uses uStmt,uGlobal,IdTCPConnection; function CatalogBackup(st:Tstmt;connection:TIdTCPConnection;targetName:string):integer; implementation uses {$IFDEF Debug_Log} uLog, {$ENDIF} SysUtils,uServer,uDatabase,uTransaction, uRelation, uFile, uHeapFile, uHashIndexFile, uPage, uOS, uGlobalDef, classes{for TList}, uParser, uMarshalGlobal {in '..\Odbc\uMarshalGlobal.pas'} {for se* error constants}, uProcessor ,uEvsHelpers; const where='uDatabaseMaint'; function copySystemTables(st:Tstmt;connection:TIdTCPConnection;targetTran:TTransaction;targetDB:TDB):integer; {Copy sysTable (and allocate table space for each table, updating the start page in each row) sysColumn sysIndex (and allocate index space for each index, updating the start page in each row) sysIndexColumn ignoring these tables themselves which are taken to already exist. Note: based on garbageCollector.execute } const routine=':copySystemTables'; var i:integer; res:integer; sysTableR, targetSysTableR:TRelation; //generic system table references targetdbFile:TDBFile; r:TRelation; isView:boolean; viewDefinition:string; rnoMore,noMore:boolean; schema_name:string; table_auth_id:integer; //auth_id of table schema owner => table owner crippledStartPage:integer; startPage:PageId; //note: many of these are used for more than one table below table_schema_id,table_table_Id:integer; filename,tableName,tableType,indexName:string; indexType:string; tableName_null,filename_null,startPage_null,table_table_Id_null:boolean; indexType_null,tableType_null,dummy_null:boolean; sysSchemaR:TObject; //Trelation sysTableName:string; tableId,indexId:integer; sysTableId,sysColumnId,sysIndexId,sysIndexColumnId:integer; copiedRid:Trid; newStart:PageId; sysIndexList:TList; begin result:=fail; //assume failure try //to avoid strange crash when r fails to open & then tries to free twice... {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,formatDateTime('"Table copy starting at "c',now),vDebugLow); {$ENDIF} {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy starting as %d with earliest active transaction of %d',[Ttransaction(st.owner).sysStmt.Wt.tranId,Ttransaction(st.owner).sysStmt.Rt.tranId]),vDebugLow); {$ENDIF} sysIndexList:=TList.create; r:=TRelation.create; sysTableR:=TRelation.create; targetSysTableR:=TRelation.create; try sysTableId:=0; sysColumnId:=0; sysIndexId:=0; sysIndexColumnId:=0; {1. sysTable} sysTableName:=sysTable_table; if sysTableR.open(Ttransaction(st.owner).sysStmt,nil,sysCatalogDefinitionSchemaName,sysTableName,isView,viewDefinition)=ok then begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy opened %s',[sysTableName]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to open %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed opening %s',[sysTableName])); exit; //abort end; noMore:=False; {Open the target sysTable} if targetSysTableR.open(targetTran.sysStmt,nil,sysCatalogDefinitionSchemaName,sysTableName,isView,viewDefinition)=ok then begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format('Table copy opened %s on %s',[sysTableName,targetTran.db.dbname]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format('Table copy failed to open target %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed opening target %s',[sysTableName])); exit; //abort end; if not noMore then if sysTableR.scanStart(Ttransaction(st.owner).sysStmt)<>ok then begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to start scan on %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed accessing %s',[sysTableName])); exit; //abort end; {Process loop} while (not noMore) do begin if sysTableR.ScanNext(Ttransaction(st.owner).sysStmt,noMore)=ok then begin if not noMore then begin if st.status=ssCancelled then begin result:=Cancelled; exit; end; sysTableR.fTuple.GetInteger(ord(st_Table_Id),tableId,dummy_null); sysTableR.fTuple.GetString(ord(st_Table_Type),tableType,tableType_null); sysTableR.fTuple.GetString(ord(st_Table_Name),tableName,tableName_null); {We must skip the tables which already exist} //Note: assume start pages are same! if tableName=sysTable_table then begin assert(sysTableId=0,'sysTable already processed'); sysTableId:=tableId; continue; //skip end; if tableName=sysColumn_table then begin assert(sysColumnId=0,'sysColumn already processed'); sysColumnId:=tableId; continue; //skip end; if tableName=sysIndex_table then begin assert(sysIndexId=0,'sysIndex already processed'); sysIndexId:=tableId; continue; //skip end; if tableName=sysIndexColumn_table then begin assert(sysIndexColumnId=0,'sysIndexColumn already processed'); sysIndexColumnId:=tableId; continue; //skip end; {First create the table space} newStart:=0; //=n/a, e.g. view or virtual table if tableType<>ttView then begin //base table begin {Create space for the table in the target database (code copied from Trelation.creatNew)} targetdbFile:=THeapFile.create; //todo: use a class pointer instead of hardcoding THeapFile here...? targetdbFile.createFile(targetTran.sysStmt,tableName{not used}); newStart:=targetdbFile.startPage; targetdbFile.free; targetdbFile:=nil; {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy created target space for: %s.%s starting at page %d',[schema_name,tableName,newStart]),vDebugLow); {$ENDIF} end; end; //else view = no storage {Now we can copy the sysTable row to the target sysTable, with any new table start page} //Note: upgrade mapping logic would go here targetSysTableR.fTuple.clear(targetTran.sysStmt); for i:=0 to sysTableR.fTuple.ColCount-1 do if (i=ord(st_First_page)) and (newStart<>0) then targetSysTableR.fTuple.SetBigInt(i,newStart,False) else targetSysTableR.fTuple.CopyColDataDeep(i,st{->source db},sysTableR.fTuple,i,true); targetSysTableR.fTuple.insert(targetTran.sysStmt,copiedRid); {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format(' copied row to %d:%d: %s',[copiedRid.pid,copiedRid.sid,targetSysTableR.fTuple.Show(targetTran.sysStmt)]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy finished scan of %s',[sysTableName]),vDebugLow); {$ENDIF} end; end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to scan next on %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed reading %s',[sysTableName])); exit; //abort end; end; {process loop} sysTableR.scanStop(Ttransaction(st.owner).sysStmt); sysTableR.Close; targetSysTableR.Close; {2. sysColumn} sysTableName:=sysColumn_table; if sysTableR.open(Ttransaction(st.owner).sysStmt,nil,sysCatalogDefinitionSchemaName,sysTableName,isView,viewDefinition)=ok then begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy opened %s',[sysTableName]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to open %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed opening %s',[sysTableName])); exit; //abort end; noMore:=False; {Open the target sysColumn} if targetSysTableR.open(targetTran.sysStmt,nil,sysCatalogDefinitionSchemaName,sysTableName,isView,viewDefinition)=ok then begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format('Table copy opened %s',[sysTableName]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format('Table copy failed to open %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed opening target %s',[sysTableName])); exit; //abort end; if not noMore then if sysTableR.scanStart(Ttransaction(st.owner).sysStmt)<>ok then begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to start scan on %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed accessing %s',[sysTableName])); exit; //abort end; {Process loop} while (not noMore) do begin if sysTableR.ScanNext(Ttransaction(st.owner).sysStmt,noMore)=ok then begin if not noMore then begin if st.status=ssCancelled then begin result:=Cancelled; exit; end; sysTableR.fTuple.GetInteger(ord(sc_Table_id),tableId,dummy_null); {We must skip the entries for the tables which already exist} if tableId in [sysTableId, sysColumnId, sysIndexId, sysIndexColumnId] then continue; //skip {Copy the sysColumn row to the target sysColumn} //Note: upgrade mapping logic woud go here targetSysTableR.fTuple.clear(targetTran.sysStmt); for i:=0 to sysTableR.fTuple.ColCount-1 do targetSysTableR.fTuple.CopyColDataDeep(i,st{->source db},sysTableR.fTuple,i,true); targetSysTableR.fTuple.insert(targetTran.sysStmt,copiedRid); {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format(' copied row to %d:%d: %s',[copiedRid.pid,copiedRid.sid,targetSysTableR.fTuple.Show(targetTran.sysStmt)]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy finished scan of %s',[sysTableName]),vDebugLow); {$ENDIF} end; end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to scan next on %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed reading %s',[sysTableName])); exit; //abort end; end; {process loop} sysTableR.scanStop(Ttransaction(st.owner).sysStmt); sysTableR.Close; targetSysTableR.Close; {3. sysIndex} sysTableName:=sysIndex_table; if sysTableR.open(Ttransaction(st.owner).sysStmt,nil,sysCatalogDefinitionSchemaName,sysTableName,isView,viewDefinition)=ok then begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy opened %s',[sysTableName]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to open %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed opening %s',[sysTableName])); exit; //abort end; noMore:=False; {Open the target sysIndex} if targetSysTableR.open(targetTran.sysStmt,nil,sysCatalogDefinitionSchemaName,sysTableName,isView,viewDefinition)=ok then begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format('Table copy opened %s',[sysTableName]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format('Table copy failed to open %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed opening target %s',[sysTableName])); exit; //abort end; if not noMore then if sysTableR.scanStart(Ttransaction(st.owner).sysStmt)<>ok then begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to start scan on %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed accessing %s',[sysTableName])); exit; //abort end; {Process loop} while (not noMore) do begin if sysTableR.ScanNext(Ttransaction(st.owner).sysStmt,noMore)=ok then begin if not noMore then begin if st.status=ssCancelled then begin result:=Cancelled; exit; end; sysTableR.fTuple.GetInteger(ord(si_index_id),indexId,dummy_null); sysTableR.fTuple.GetString(ord(si_index_name),indexName,dummy_null); sysTableR.fTuple.GetInteger(ord(si_table_id),tableId,dummy_null); sysTableR.fTuple.GetString(ord(si_index_type),indexType,dummy_null); {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Index (for table %d) %s: ',[tableId,indexName]),vDebugLow); {$ENDIF} {We should't skip entries for the tables which already exist, since the emptyDB has no index entries but we must because the data for these tables is either: already copied (sysTable, sysColumn) or about to be copied (sysIndex, sysIndexColumn) So the best bet will be to skip these kinds of system indexes and re-create them via SQL at the end of the backup routine...} if tableId in [sysTableId, sysColumnId, sysIndexId, sysIndexColumnId] then begin sysIndexList.Add(pointer(indexId)); //note the index_id to skip the indexColumns in the next section continue; //skip end; //todo: do skip entries which are unfinished e.g. isBeingBuilt? {First create the index space} begin {Create space for the index in the target database (code copied from createIndex/Trelation.createNewIndex)} newStart:=0; if indexType=itHash then begin targetdbFile:=THashIndexFile.create; //todo: use a class pointer instead of hardcoding THashIndexFile here...? targetdbFile.createFile(targetTran.sysStmt,indexName{not used?}); //todo check result! newStart:=targetdbFile.startPage; targetdbFile.free; targetdbFile:=nil; {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format(' Table copy created target space for: %s.%s starting at %d',[schema_name,indexName,newStart]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format(' Unknown index type %s',[indexType]),vAssertion); {$ENDIF} if connection<>nil then connection.WriteLn(format('Unknown index type %d',[indexType])); exit; //abort end; end; {Now we can copy the sysIndex row to the target sysIndex} //note: upgrade mapping logic would go here targetSysTableR.fTuple.clear(targetTran.sysStmt); for i:=0 to sysTableR.fTuple.ColCount-1 do if i=ord(si_first_page) then targetSysTableR.fTuple.SetBigInt(i,newStart,False) else targetSysTableR.fTuple.CopyColDataDeep(i,st{->source db},sysTableR.fTuple,i,true); targetSysTableR.fTuple.insert(targetTran.sysStmt,copiedRid); {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format(' copied row to %d:%d: %s',[copiedRid.pid,copiedRid.sid,targetSysTableR.fTuple.Show(targetTran.sysStmt)]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy finished scan of %s',[sysTableName]),vDebugLow); {$ENDIF} end; end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to scan next on %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed reading %s',[sysTableName])); exit; //abort end; end; {process loop} sysTableR.scanStop(Ttransaction(st.owner).sysStmt); sysTableR.Close; targetSysTableR.Close; {4. sysIndexColumn} sysTableName:=sysIndexColumn_table; if sysTableR.open(Ttransaction(st.owner).sysStmt,nil,sysCatalogDefinitionSchemaName,sysTableName,isView,viewDefinition)=ok then begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy opened %s',[sysTableName]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to open %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed opening %s',[sysTableName])); exit; //abort end; noMore:=False; {Open the target sysIndexColumn} if targetSysTableR.open(targetTran.sysStmt,nil,sysCatalogDefinitionSchemaName,sysTableName,isView,viewDefinition)=ok then begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format('Table copy opened %s',[sysTableName]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format('Table copy failed to open %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed opening target %s',[sysTableName])); exit; //abort end; if not noMore then if sysTableR.scanStart(Ttransaction(st.owner).sysStmt)<>ok then begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to start scan on %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed accessing %s',[sysTableName])); exit; //abort end; {Process loop} while (not noMore) do begin if sysTableR.ScanNext(Ttransaction(st.owner).sysStmt,noMore)=ok then begin if not noMore then begin if st.status=ssCancelled then begin result:=Cancelled; exit; end; sysTableR.fTuple.GetInteger(ord(sic_index_id),indexId,dummy_null); {We must skip the entries for the indexes for the tables which already exist} if sysIndexList.IndexOf(pointer(indexId))<>-1 then continue; //skip {Copy the sysIndexColumn row to the target sysIndexColumn} //note: upgrade mapping logic would go here targetSysTableR.fTuple.clear(targetTran.sysStmt); for i:=0 to sysTableR.fTuple.ColCount-1 do targetSysTableR.fTuple.CopyColDataDeep(i,st{->source db},sysTableR.fTuple,i,true); targetSysTableR.fTuple.insert(targetTran.sysStmt,copiedRid); {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format(' copied row to %d:%d: %s',[copiedRid.pid,copiedRid.sid,targetSysTableR.fTuple.Show(targetTran.sysStmt)]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy finished scan of %s',[sysTableName]),vDebugLow); {$ENDIF} end; end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to scan next on %s',[sysTableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed reading %s',[sysTableName])); exit; //abort end; end; {process loop} sysTableR.scanStop(Ttransaction(st.owner).sysStmt); sysTableR.Close; targetSysTableR.Close; result:=ok; finally sysIndexList.free; if targetsysTableR<>nil then begin targetsysTableR.free; targetsysTableR:=nil; end; if sysTableR<>nil then begin sysTableR.free; sysTableR:=nil; end; if r<>nil then begin r.free; r:=nil; end; end; {try} except //log message? //terminate; end;{try} end; {copySystemTables} function copyTables(st:Tstmt;connection:TIdTCPConnection;targetTran:TTransaction;targetDB:TDB):integer; {Loops through sysTable copying the contents of each table In doing this, we remove all old versions of rows and leave a database written by 1 transaction. (skips the sysTable/sysColumn/sysIndex/sysIndexColumn tables - they have already been dealt with skips sysTran/sysTranStmt - these will be reset skips virtual tables - no real rows are stored) Note: based on garbageCollector.execute //todo continue if fails... } const routine=':copyTables'; var i:integer; res:integer; sysTableR:TRelation; r,targetr:TRelation; isView:boolean; viewDefinition:string; rnoMore,noMore:boolean; schema_name:string; table_auth_id:integer; //auth_id of table schema owner => table owner crippledStartPage:integer; bigStartPage:int64; startPage:PageId; //note: many of these are used for more than one table below table_schema_id,table_table_Id:integer; filename,tableName,tableType:string; indexType:string; tableName_null,filename_null,startPage_null,table_table_Id_null:boolean; indexType_null,tableType_null,dummy_null:boolean; sysSchemaR:TObject; //Trelation copiedRid:Trid; begin result:=fail; //assume failure try //to avoid strange crash when r fails to open & then tries to free twice... {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,formatDateTime('"Table copy starting at "c',now),vDebugLow); {$ENDIF} {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy starting as %d with earliest active transaction of %d',[Ttransaction(st.owner).sysStmt.Wt.tranId,Ttransaction(st.owner).sysStmt.Rt.tranId]),vDebugLow); {$ENDIF} r:=TRelation.create; targetr:=TRelation.create; sysTableR:=TRelation.create; try {Try to open sysTable} if sysTableR.open(Ttransaction(st.owner).sysStmt,nil,sysCatalogDefinitionSchemaName,sysTable_table,isView,viewDefinition)=ok then begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy opened %s',[sysTable_table]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to open %s',[sysTable_table]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed opening %s',[sysTable_table])); exit; //abort end; noMore:=False; {Main loop} //while not terminated do begin if not noMore then if sysTableR.scanStart(Ttransaction(st.owner).sysStmt)<>ok then begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to start scan on %s',[sysTable_table]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed accessing %s',[sysTable_table])); exit; //abort end; {Process loop} while (not noMore) do begin if sysTableR.ScanNext(Ttransaction(st.owner).sysStmt,noMore)=ok then begin if not noMore then begin sysTableR.fTuple.GetString(ord(st_Table_Type),tableType,tableType_null); {todo if in-progress = skip to last table/page} if tableType<>ttView then begin //base table {Try to open relation} sysTableR.fTuple.GetInteger(ord(st_Schema_id),table_schema_id,dummy_null); //when we use dummy_null we assume these can never be null, or at least if they are then the value is sensibly 0 {We need to read the schema name} if Ttransaction(st.owner).db.catalogRelationStart(Ttransaction(st.owner).sysStmt,sysSchema,sysSchemaR)=ok then begin try if Ttransaction(st.owner).db.findCatalogEntryByInteger(Ttransaction(st.owner).sysStmt,sysSchemaR,ord(ss_schema_id),table_schema_id)=ok then begin with (sysSchemaR as TRelation) do begin fTuple.GetString(ord(ss_schema_name),schema_name,dummy_null); //when we use dummy_null we assume these can never be null, or at least if they are then the value is sensibly 0 fTuple.GetInteger(ord(ss_auth_id),table_auth_Id,dummy_null); //when we use dummy_null we assume these can never be null, or at least if they are then the value is sensibly 0 //todo major/minor versions {$IFDEF DEBUGDETAIL} {$IFDEF DEBUG_LOG} //log.add(tr.sysStmt.who,where+routine,format('Found schema %s owner=%d (from table)',[schema_name,table_auth_id]),vDebugLow); {$ENDIF} {$ENDIF} end; {with} end else begin //schema not found {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Failed finding table schema details %d',[table_schema_id]),vError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed finding table schema details (%d)',[table_schema_id])); continue; //abort - try next relation end; finally if Ttransaction(st.owner).db.catalogRelationStop(Ttransaction(st.owner).sysStmt,sysSchema,sysSchemaR)<>ok then {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Failed releasing catalog relation %d',[ord(sysSchema)]),vError); {$ELSE} ; {$ENDIF} end; {try} end else begin //couldn't get access to sysSchema {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Unable to access catalog relation %d to find %s',[ord(sysSchema),schema_name]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed accessing table schema details (%d)',[table_schema_id])); continue; //abort - try next relation end; sysTableR.fTuple.GetString(ord(st_Table_Name),tableName,tableName_null); {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table %s.%s: ',[schema_name,tableName]),vDebugLow); {$ENDIF} {Skip the following which have already been copied} if tableName=sysTable_table then continue; //skip if tableName=sysColumn_table then continue; //skip if tableName=sysIndex_table then continue; //skip if tableName=sysIndexColumn_table then continue; //skip {Skip the following which have already been reset} if tableName='sysTran' then //todo use table number or constant... continue; //skip if tableName='sysTranStmt' then //todo use table number or constant... continue; //skip {Skip the following which are virtual tables} if uppercase(tableName)=uppercase(sysTransaction_table) then continue; //skip if uppercase(tableName)=uppercase(sysServer_table) then continue; //skip if uppercase(tableName)=uppercase(sysStatusGroup_table) then continue; //skip if uppercase(tableName)=uppercase(sysStatus_table) then continue; //skip if uppercase(tableName)=uppercase(sysServerStatus_table) then continue; //skip if uppercase(tableName)=uppercase(sysCatalog_table) then continue; //skip if uppercase(tableName)=uppercase(sysServerCatalog_table) then continue; //skip {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format(' Table copy processing: %s.%s ',[schema_name,tableName]),vDebugLow); {$ENDIF} sysTableR.fTuple.GetString(ord(st_file),filename,filename_null); sysTableR.fTuple.GetBigInt(ord(st_first_page),bigStartPage,startPage_null); StartPage:=bigStartPage; sysTableR.fTuple.GetInteger(ord(st_table_id),table_Table_Id,table_table_Id_null); {Note: we use relation here to gain access to all associated indexes} if r.open(Ttransaction(st.owner).sysStmt,nil,schema_name,tableName,isView,viewDefinition)=ok then begin try {$IFDEF DEBUGDETAIL} {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format(' Table copy opened %s',[tableName]),vDebugLow); {$ENDIF} {$ENDIF} {Open the target table} if targetr.open(targetTran.sysStmt,nil,schema_name,tableName,isView,viewDefinition)=ok then begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format(' Table copy opened %s on %s',[tableName,targetTran.db.dbname]),vDebugLow); {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format(' Table copy failed to open %s',[tableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed opening target table %s',[tableName])); exit; //abort end; if r.scanStart(Ttransaction(st.owner).sysStmt)<>ok then begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format(' Table copy failed to start scan on %s',[tableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed accessing table %s',[tableName])); continue; //abort - try next relation end; rNoMore:=False; i:=0; while (not rNoMore) do begin {todo! if stmt.status=ssCancelled then begin result:=Cancelled; exit; end; } res:=r.ScanNext(Ttransaction(st.owner).sysStmt,rNoMore); {Note: this table copy scans through the whole db file and fills the buffer with pages only we need, possibly throwing other pages out note: we must set these buffer frames to 'flush immediately' somehow... scan policy? } if res<>fail then begin if not rNoMore then begin //todo if sysCatalog/INFORMATION_SCHEMA_CATALOG_NAME then change name to new target if st.status=ssCancelled then begin result:=Cancelled; exit; end; {Now we can copy the table row to the target table, with the new table start page} //note: upgrade mapping logic would go here {Notes: We read blob data from source disk into memory and then write to target, rather than trying to write blocks from source->target because we may be able to write bigger blocks to our fresh target (or take advantage of updated blob storage, e.g. compression) } targetr.fTuple.clear(targetTran.sysStmt); for i:=0 to r.fTuple.ColCount-1 do targetr.fTuple.CopyColDataDeep(i,st{->source db},r.fTuple,i,true{deep blob}); //note: shallow copy should be fine (& faster) except blobs need to be deep to read across catalogs! if targetr.fTuple.insert(targetTran.sysStmt,copiedRid)<>ok then begin if connection<>nil then connection.WriteLn(format('Failed copying row (%d) of table %s, continuing',[i,tableName])); end else {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format(' copied row to %d:%d: %s',[copiedRid.pid,copiedRid.sid,targetr.fTuple.Show(targetTran.sysStmt)]),vDebugLow); {$ELSE} ; {$ENDIF} inc(i); //todo flush checkpoint=table-id:page-id (e.g. every 10/100 pages or so) end; //else no more end; end; {while scan} {$IFDEF DEBUGDETAIL} {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format(' Table copy counted %d rows',[i]),vDebugLow); {$ENDIF} {$ENDIF} //{Flush all pages to save any de-allocations and garbage collections} //(targetTran.db.owner as TDBServer).buffer.flushAllPages(targetTran.sysStmt); finally r.scanStop(Ttransaction(st.owner).sysStmt); r.close; targetr.Close; end; {try} end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format(' Table copy failed to open %s',[tableName]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed opening table %s',[tableName])); //continue... end; end; //else view = no storage end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy finished scan of %s',[sysTable_table]),vDebugLow); {$ENDIF} end; end else begin {$IFDEF DEBUG_LOG} log.add(Ttransaction(st.owner).sysStmt.who,where+routine,format('Table copy failed to scan next on %s',[sysTable_table]),vDebugError); {$ENDIF} if connection<>nil then connection.WriteLn(format('Failed finding next table',[nil])); exit; //abort end; sleepOS(0); //relinquish rest of time slice - we'll return immediately if nothing else to do end; {process loop} sysTableR.scanStop(Ttransaction(st.owner).sysStmt); end; {main loop} result:=ok; finally if sysTableR<>nil then begin sysTableR.Close; sysTableR.free; sysTableR:=nil; end; if targetr<>nil then begin targetr.free; targetr:=nil; end; if r<>nil then begin r.free; r:=nil; end; end; {try} except //log message //terminate; end;{try} end; {copyTables} function CatalogBackup(st:Tstmt;connection:TIdTCPConnection;targetName:string):integer; {Copies the stmt's source catalog into a new one (compressing etc. as we go) Closes the target file when done. IN: st the current statement (pointing to a current source catalog) connection the connection - not used (was for debugging) targetName the destination catalog name RETURN: ok, else fail: -2=target is already attached to the server (could be self!) Assumes: caller is ok with targetName being overwritten (if we find it's not open) } const routine=':CatalogBackup'; //tempTargetName='catalog_backup_test'; debugStampId:StampId=(tranId:MAX_CARDINAL-100;stmtId:MAX_CARDINAL-100); //todo replace with formula for max(tranId type) //Note: no need when comparing to compare stmtId var targetDB:TDB; targetTran:TTransaction; tempResult,resultRowCount:integer; begin result:=fail; //Note: in future, the target may be CSV/XML files etc. leave flexible/portable (but security issues) //Note: in future, the source may use an old uDatabase unit to be able read read old structures {Check targetName is not open} if (Ttransaction(st.owner).db.owner as TDBserver).findDB(targetName)<>nil then begin {$IFDEF DEBUG_LOG} log.add(st.who,where+routine,'Target database is already open on this server',vDebug); {$ENDIF} st.addError(seTargetDatabaseIsAlreadyOpen,seTargetDatabaseIsAlreadyOpenText); result:=-2; exit; end; {Create the new target database on our server} targetDB:=(Ttransaction(st.owner).db.owner as TDBserver).addDB(targetName); if targetDB<>nil then begin try targetTran:=TTransaction.Create; try {Note: we set these based on database.createDB so we can insert into sysTran later} targetTran.CatalogId:=1; //default MAIN catalog targetTran.AuthId:=SYSTEM_AUTHID; //_SYSTEM authId targetTran.AuthName:=SYSTEM_AUTHNAME; //=>'_SYSTEM' targetTran.SchemaId:=sysCatalogDefinitionSchemaId; targetTran.SchemaName:=sysCatalogDefinitionSchemaName; targetTran.tranRt:=MaxStampId; //avoid auto-tran-start failure targetTran.SynchroniseStmts(true); targetTran.connectToDB(targetDB); //todo check result (leave connected at end though) result:=targetDB.createDB(targetName,True{emptyDB}); //=>ok result if result=ok then begin if targetDB.openDB(targetName,True{emptyDB})=ok then begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,'Opened new target database',vDebug); {$ENDIF} targetDB.status; //debug report {$IFDEF Debug_Log} (targetDB.owner as TDBserver).buffer.status; {$ENDIF} result:=copySystemTables(st,connection,targetTran,targetDB); if result<>ok then begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,'Failed to copy system tables to new target database',vdebugError); {$ENDIF} //todo discard partial db catalog? exit; //abort end; {$IFDEF DEBUG_LOG} //targetTran.thread:=Ttransaction(st.owner).thread; //needed for debug table... remove! ////ExecSQL(targetTran.sysStmt,'DEBUG table sysTable',connection,resultRowCount); //ExecSQL(targetTran.sysStmt,'DEBUG table sysColumn',connection,resultRowCount); ////ExecSQL(targetTran.sysStmt,'SELECT * from sysColumn',connection,resultRowCount); {$ENDIF} {Add initial entry to sysTran to allow database to be restarted} tempresult:=PrepareSQL(targetTran.sysStmt,nil, 'INSERT INTO '{'+sysCatalogDefinitionSchemaName+'.}+'sysTran VALUES (1,''N'') '); if tempresult=ok then tempresult:=ExecutePlan(targetTran.sysStmt,resultRowCount); if tempresult<>ok then {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,' Failed inserting sysTran row: ',vAssertion) {$ENDIF} else {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,' Inserted sysTran row',vdebugMedium); {$ELSE} ; {$ENDIF} if UnPreparePlan(targetTran.sysStmt)<>ok then {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,format('Error unpreparing existing plan',[nil]),vDebugError); {$ELSE} ; {$ENDIF} end else begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,'Failed to open new target database',vdebugError); {$ENDIF} //todo discard partial db catalog? result:=fail; exit; //abort end; end; result:=ok; finally //todo remove tr.rollback if not committed targetTran.tranRt:=InvalidStampId; //Note: assumes 'not in a transaction'=>InvalidTranId targetTran.SynchroniseStmts(true); targetTran.free; //this will disconnectFromDB etc. end; {try} finally (Ttransaction(st.owner).db.owner as TDBserver).removeDB(targetDB); end; {try} end; //else fail: log error! {Now re-open the new target and copy all the non-metadata rows Note: createInformationSchema is not called, i.e. we copy the source's information_schema} targetDB:=(Ttransaction(st.owner).db.owner as TDBserver).addDB(targetName); if targetDB<>nil then begin try targetTran:=TTransaction.Create; try {Note: we set these based on database.createDB so we can insert into sysTran later} targetTran.CatalogId:=1; //default MAIN catalog targetTran.AuthId:=SYSTEM_AUTHID; //_SYSTEM authId targetTran.AuthName:=SYSTEM_AUTHNAME; //=>'_SYSTEM' targetTran.SchemaId:=sysCatalogDefinitionSchemaId; targetTran.SchemaName:=sysCatalogDefinitionSchemaName; targetTran.tranRt:=MaxStampId; //avoid auto-tran-start failure targetTran.SynchroniseStmts(true); targetTran.connectToDB(targetDB); //todo check result (leave connected at end though) if targetDB.openDB(targetName,False)=ok then begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,'Re-opened new target database',vDebug); {$ENDIF} targetDB.status; //debug report {$IFDEF Debug_Log} (targetDB.owner as TDBserver).buffer.status; {$ENDIF} result:=copyTables(st,connection,targetTran,targetDB); if result<>ok then begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,'Failed to copy user tables to new target database',vdebugError); {$ENDIF} //todo discard partial db catalog? result:=fail; exit; //abort end; {Now recreate any indexes for [sysTableId, sysColumnId, sysIndexId, sysIndexColumnId] These will have different table_id's to the ones in the source catalog. (we need to do it after user tables are copied because we need sysGenerator (etc?) - no downside? user table copy shouldn't be any slower? except opening target relations might be slow...) } if targetDB.createSysIndexes(targetTran.sysStmt)<ok then //creates indexes for sysTable, sysColumn, sysIndex, sysIndexColumn (returns last index_id) begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,'Failed to rebuild system indexes on new target database',vdebugError); {$ENDIF} //todo discard partial db catalog? result:=fail; exit; //abort //todo!! carry on? end; end else begin {$IFDEF DEBUG_LOG} log.add(targetTran.sysStmt.who,where+routine,'Failed to re-open new target database',vdebugError); {$ENDIF} //todo discard partial db catalog? result:=fail; exit; //abort end; finally targetTran.free; //this will disconnectFromDB etc. end; {try} finally {We disconnect the pristine backup from the server, i.e. offline it} (Ttransaction(st.owner).db.owner as TDBserver).removeDB(targetDB); end; {try} end; //else fail: log error! end; {CatalogBackup} end.
41.710232
230
0.603702
c30f1faf92b8f9ecbfd4677acea4cf68df39e406
429
pas
Pascal
source/FMX.DockFramework.DockMessages.pas
ivanovsergeyminsk/FMX-DockFramework
1e0873572f3c89767cf346a14036f46b996942e5
[ "MIT" ]
1
2021-07-04T04:29:53.000Z
2021-07-04T04:29:53.000Z
source/FMX.DockFramework.DockMessages.pas
ivanovsergeyminsk/FMX-DockFramework
1e0873572f3c89767cf346a14036f46b996942e5
[ "MIT" ]
null
null
null
source/FMX.DockFramework.DockMessages.pas
ivanovsergeyminsk/FMX-DockFramework
1e0873572f3c89767cf346a14036f46b996942e5
[ "MIT" ]
4
2020-09-15T19:57:43.000Z
2021-12-15T04:37:24.000Z
unit FMX.DockFramework.DockMessages; interface uses System.Messaging, FMX.Controls, FMX.DockFramework.DockTypes ; type TMessageControlFocused = class(System.Messaging.TMessage<TControl>); TDockMessageMoving = class(System.Messaging.TMessage<TDockMove>); TDockMessageMoved = class(System.Messaging.TMessage<TDockMove>); TDockMessageDock = class(System.Messaging.TMessage<TDockDock>); implementation end.
19.5
70
0.785548
fc79711ceadc3481efe4b21b4366778ee9538d5d
373
pas
Pascal
input/test11.pas
junaaaaloo/CMPILER-FINAL-MP
f2ab1e79e6c008eb6b4423777e95fa473f78f29b
[ "MIT" ]
null
null
null
input/test11.pas
junaaaaloo/CMPILER-FINAL-MP
f2ab1e79e6c008eb6b4423777e95fa473f78f29b
[ "MIT" ]
null
null
null
input/test11.pas
junaaaaloo/CMPILER-FINAL-MP
f2ab1e79e6c008eb6b4423777e95fa473f78f29b
[ "MIT" ]
null
null
null
program test11; var a, b: integer; function printSquare(x, y: integer):integer; var a, b: integer; begin for a := 1 to x do begin for b := 1 to y do begin write('* ') end; writeln(); end; end; begin write('Enter length: '); readln(a); write('Enter width: '); readln(b); printSquare(a, b); end.
15.541667
44
0.520107
cdb4c412db8c1f615dd786e0ee040344496492f9
798
pas
Pascal
2. Struktur Pengulangan/menghitung_jumlah_deret.pas
belajarstatistik/Algoritma-Pemrograman
4f33b359254db167b6107757d35d50d391d836e2
[ "MIT" ]
null
null
null
2. Struktur Pengulangan/menghitung_jumlah_deret.pas
belajarstatistik/Algoritma-Pemrograman
4f33b359254db167b6107757d35d50d391d836e2
[ "MIT" ]
null
null
null
2. Struktur Pengulangan/menghitung_jumlah_deret.pas
belajarstatistik/Algoritma-Pemrograman
4f33b359254db167b6107757d35d50d391d836e2
[ "MIT" ]
null
null
null
program menghitung_jumlah_deret; uses crt; var angka,n,jumlah:integer; begin clrscr; write('Masukkan angka = ');readln(n); writeln('====: writeln('Menghitung deret angka 1 sampai dengan ',n); writeln(' ====='); ==='); jumlah:=0; angka:=1; while angka<=n do begin writeln(angka); jumlah:=jumlah + angka; angka:=angka + 1; end; writeln('====: writeln ('Jumlah deret adalah = ',jumlah); writeln(' =====' ); '); readln; end.
30.692308
62
0.347118
fc70bdb6a2c88f535a692a788336eb65c4ce34ac
908
pas
Pascal
examples/language/StatementWhile.pas
azrael11/GamePascal
e3c2811651b103fb7db691f3cc9697f949cf723b
[ "RSA-MD" ]
1
2020-07-20T11:22:36.000Z
2020-07-20T11:22:36.000Z
examples/language/StatementWhile.pas
azrael11/GamePascal
e3c2811651b103fb7db691f3cc9697f949cf723b
[ "RSA-MD" ]
null
null
null
examples/language/StatementWhile.pas
azrael11/GamePascal
e3c2811651b103fb7db691f3cc9697f949cf723b
[ "RSA-MD" ]
1
2020-07-20T11:22:37.000Z
2020-07-20T11:22:37.000Z
{$REGION 'Project Directives'} // Modual Info {$CONSOLEAPP} {$MODULENAME "..\bin\"} {.$EXEICON ".\bin\arc\icons\icon.ico"} {.$SEARCHPATH "path1;path2;path3"} {.$ENABLERUNTIMETHEMES} {.$HIGHDPIAWARE} // Version Infp {.$ADDVERSIONINFO} {.$COMPANYNAME "Company XYZ"} {.$FILEVERSION "1.0.0.0"} {.$FILEDESCRIPTION "Demo XYZ"} {.$INTERNALNAME "Demo XYZ"} {.$LEGALCOPYRIGHT "Copyright (c) 2015 Company XYZ"} {.$LEGALTRADEMARK "All Rights Reserved."} {.$ORIGINALFILENAME "DemoXYZ.exe"} {.$PRODUCTNAME "Demo XYZ"} {.$PRODUCTVERSION "1.0.0.0"} {.$COMMENTS "http://companyxyz.com"} {$ENDREGION} program Demo; uses SysUtils, GamePascal; var X: Double; begin X := 2.3; while X < 7.6 do begin WriteLn(X:5:2); X := X + 2.1; end; Con_Pause(CON_LF+'Press any key to continue...'); end.
21.619048
57
0.579295
fc7d1994882f3bec54a4f21e2c27baf4bfa41f9f
3,943
pas
Pascal
Base/Apus.GeoIP.pas
Gofrettin/ApusGameEngine
b56072b797664cf53a189747b17dbf03f17075a1
[ "BSD-3-Clause" ]
124
2020-03-05T07:57:43.000Z
2022-03-28T07:59:26.000Z
Base/Apus.GeoIP.pas
Gofrettin/ApusGameEngine
b56072b797664cf53a189747b17dbf03f17075a1
[ "BSD-3-Clause" ]
null
null
null
Base/Apus.GeoIP.pas
Gofrettin/ApusGameEngine
b56072b797664cf53a189747b17dbf03f17075a1
[ "BSD-3-Clause" ]
20
2020-03-07T21:42:14.000Z
2022-03-31T00:33:25.000Z
 // Copyright (C) Apus Software, Ivan Polyacov (ivan@apus-software.com) // This file is licensed under the terms of BSD-3 license (see license.txt) // This file is a part of the Apus Base Library (http://apus-software.com/engine/#base) {$R-} unit Apus.GeoIP; interface // Load GeoIP database (if path=nil then try current dir or use ENV{GeoIP}) procedure InitGeoIP(path:string=''); // Not thread-safe! Either use from the same thread or use own protection function GetCountryByIP(ip:cardinal):string; implementation uses {$IFDEF MSWINDOWS}WinSock, {$ELSE}Sockets,{$ENDIF} Apus.MyServis,SysUtils; type TRange=record ip,mask:cardinal; countryCode:integer; end; TCountry=record id:integer; short:string[3]; full:string[50]; end; var initialized:TDatetime; crSect:TMyCriticalSection; lastPath:string; ranges:array of TRange; countries:array of TCountry; lastError:string; procedure LoadMaxMindDB(path:string); var st:string; fm:byte; f:text; sa:StringArr; cnt,i,j:integer; begin initialized:=0; try fm:=filemode; fileMode:=fmOpenRead; // Load countries assign(f,path+'GeoLite2-Country-Locations-en.csv'); reset(f); readln(f); cnt:=0; SetLength(countries,1000); while not eof(f) do begin readln(f,st); sa:=StringArr(split(',',st,'"')); countries[cnt].id:=StrToIntDef(sa[0],0); countries[cnt].short:=sa[4]; countries[cnt].full:=sa[5]; inc(cnt); end; close(f); SetLength(countries,cnt); // Load ranges assign(f,path+'GeoLite2-Country-Blocks-IPv4.csv'); reset(f); readln(f); cnt:=0; SetLength(ranges,1000000); while not eof(f) do begin readln(f,st); sa:=split(',',st); st:=sa[0]; i:=pos('/',st); if i>0 then begin j:=StrToInt(copy(st,i+1,2)); SetLength(st,i-1); end; ranges[cnt].ip:=ntohl(StrToIp(st)); ranges[cnt].mask:=$FFFFFFFF shl (32-j); if sa[1]<>'' then ranges[cnt].countryCode:=StrToIntDef(sa[1],0) else ranges[cnt].countryCode:=StrToIntDef(sa[2],0); inc(cnt); end; close(f); SetLength(ranges,cnt); fileMode:=fm; initialized:=now; lastPath:=path; except on e:exception do lastError:='Load error 1: '+intToStr(cnt)+' '+st+' msg: '+e.message; end; end; procedure TryLoadDB(path:string); begin if path='' then exit; if path[length(path)-1]<>'\' then path:=path+'\'; if FileExists(path+'GeoLite2-Country-Blocks-IPv4.csv') then LoadMaxMindDB(path); end; procedure InitGeoIP(path:string); begin if initialized>0 then exit; EnterCriticalSection(crSect); try if path='' then path:=GetCurrentDir; TryLoadDB(path); if initialized=0 then begin path:=GetEnvironmentVariable('GeoIP'); if path<>'' then TryLoadDB(path); end; finally LeaveCriticalSection(crSect); end; end; function GetCountryByIP(ip:cardinal):string; var a,b,c,code:integer; begin result:='??'; if initialized=0 then exit; // too old -> reload? if now>initialized+1 then InitGeoIP(lastPath); ip:=ntohl(ip); crSect.Enter; try // Find range a:=0; b:=length(ranges)-1; while a<b do begin c:=(a+b) div 2+1; if ip<ranges[c].ip then b:=c-1 else a:=c; end; if ranges[a].ip<>ip and ranges[a].mask then exit; // Find country code:=ranges[a].countryCode; a:=0; b:=length(countries)-1; while a<b do begin c:=(a+b) div 2+1; if code<countries[c].id then b:=c-1 else a:=c; end; if countries[a].id=code then result:=countries[a].short; finally crSect.Leave; end; end; initialization initialized:=0; InitCritSect(crSect,'GeoIP',300); finalization DeleteCritSect(crSect); end.
24.64375
91
0.612478
47f0e3a2e502babe8cf8ba0b7d7fcdab14b66987
4,143
pas
Pascal
test/test_rect_pack.pas
visualdoj/stb
8521af68c38e5ecb2f6e55dd0cc120cd74803a99
[ "Unlicense" ]
1
2022-03-21T21:11:57.000Z
2022-03-21T21:11:57.000Z
test/test_rect_pack.pas
visualdoj/stb
8521af68c38e5ecb2f6e55dd0cc120cd74803a99
[ "Unlicense" ]
null
null
null
test/test_rect_pack.pas
visualdoj/stb
8521af68c38e5ecb2f6e55dd0cc120cd74803a99
[ "Unlicense" ]
null
null
null
{$MODE FPC} {$MODESWITCH DEFAULTPARAMETERS} {$MODESWITCH OUT} {$MODESWITCH RESULT} uses stb_rect_pack in '../stb_rect_pack.pas'; var TestCase: record Name: AnsiString; W, H: PtrInt; N: PtrInt; Rects: array of record W, H: PtrInt; end; end; context: stbrp_context; nodes: array of stbrp_node; rects: array of stbrp_rect; function ReadS(var F: TextFile; out S: AnsiString): Boolean; begin {$I-} Readln(F, S); {$I+} if IOResult <> 0 then begin Writeln(stderr, 'ERROR: could not read ', TestCase.Name); Exit(False); end; Exit(True); end; function ReadI(var F: TextFile; out I: PtrInt): Boolean; begin {$I-} Read(F, I); {$I+} if IOResult <> 0 then begin Writeln(stderr, 'ERROR: could not read ', TestCase.Name); Exit(False); end; Exit(True); end; function ReadTestCase(const FileName: AnsiString): Boolean; var F: TextFile; S: AnsiString; I: LongInt; begin TestCase.Name := FileName; Assign(F, FileName); {$I-} Reset(F); {$I+} if IOResult <> 0 then begin Writeln(stderr, 'ERROR: could not open ', FileName); Exit(False); end; repeat if not ReadS(F, S) then Exit(False); until S = ''; if (not ReadI(F, TestCase.W)) or (not ReadI(F, TestCase.H)) or (not ReadI(F, TestCase.N)) then Exit(False); SetLength(TestCase.Rects, TestCase.N); for I := 0 to TestCase.N - 1 do begin if (not ReadI(F, TestCase.Rects[I].W)) or (not ReadI(F, TestCase.Rects[I].H)) then Exit(False); end; Close(F); Exit(True); end; function PackedByIndex(Index: LongInt): Boolean; var I: LongInt; begin for I := 0 to High(rects) do begin if rects[I].id = 45670000 + Index then begin if (rects[I].w <> TestCase.Rects[I].W) or (rects[I].h <> TestCase.Rects[I].H) then Exit(False); Exit(True); end; end; Exit(False); end; function Intersects1(A, B, C, D: PtrInt): Boolean; begin if B <= C then Exit(False); if D <= A then Exit(False); Exit(True); end; function Intersects(A, B: Pstbrp_rect): Boolean; begin Result := Intersects1(A^.x, A^.x + A^.w, B^.x, B^.x + B^.w) and Intersects1(A^.y, A^.y + A^.h, B^.y, B^.y + B^.h); end; function CheckResultIsCorrect: Boolean; var I, J: LongInt; begin Result := True; for I := 0 to High(rects) do begin if not PackedByIndex(I) then begin Writeln('FAILURE:', TestCase.Name, ': rect ', I, ' not found in result'); Result := False; end; if not rects[I].was_packed then begin Writeln('FAILURE:', TestCase.Name, ': rect ', rects[I].id - 45670000, ' was not packed'); Result := False; end; if (PtrInt(rects[I].x) < 0) or (PtrInt(rects[I].y) < 0) or (rects[I].x + rects[I].w > TestCase.W) or (rects[I].y + rects[I].h > TestCase.H) then begin Writeln('FAILURE:', TestCase.Name, ': rect ', rects[I].id - 45670000, ' does not fit into sheet'); Result := False; end; for J := I + 1 to High(rects) do begin if Intersects(@rects[I], @rects[J]) then begin Writeln('FAILURE:', TestCase.Name, ': rects ', rects[I].id - 45670000, ' and ', rects[J].id - 45670000, ' overlapped'); Result := False; end; end; end; end; function RunTestCase(const FileName: AnsiString): Boolean; var I: LongInt; begin if not ReadTestCase('data/rect_pack/example.txt') then Exit(False); SetLength(nodes, TestCase.W); stbrp_init_target(@context, TestCase.W, TestCase.H, @nodes[0], Length(nodes)); SetLength(rects, TestCase.N); for I := 0 to TestCase.N - 1 do begin rects[I].id := 45670000 + I; rects[I].w := TestCase.Rects[I].W; rects[I].h := TestCase.Rects[I].H; end; if not stbrp_pack_rects(@context, @rects[0], Length(rects)) then begin Writeln(stderr, 'FAILURE: could not solve ', TestCase.Name); Exit(False); end; if not CheckResultIsCorrect then begin Writeln(stderr, 'FAILURE: incorrect result ', TestCase.Name); Exit(False); end; Exit(True); end; var all_ok: Boolean = True; begin all_ok := all_ok and RunTestCase('data/rect_pack/example.txt'); if not all_ok then Halt(1); end.
23.016667
154
0.623944
c375a609a550015689ab6b303ba478548c982712
15,544
pas
Pascal
Components/JVCL/install/JVCLInstall/PageBuilder.pas
sabatex/Delphi
0efbe6eb38bf8aa2bf269d1866741266e90b9cbf
[ "MIT" ]
null
null
null
Components/JVCL/install/JVCLInstall/PageBuilder.pas
sabatex/Delphi
0efbe6eb38bf8aa2bf269d1866741266e90b9cbf
[ "MIT" ]
null
null
null
Components/JVCL/install/JVCLInstall/PageBuilder.pas
sabatex/Delphi
0efbe6eb38bf8aa2bf269d1866741266e90b9cbf
[ "MIT" ]
1
2019-12-24T08:39:18.000Z
2019-12-24T08:39:18.000Z
{----------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: PageBuilder.pas, released on 2004-03-29. The Initial Developer of the Original Code is Andreas Hausladen (Andreas dott Hausladen att gmx dott de) Portions created by Andreas Hausladen are Copyright (C) 2004 Andreas Hausladen. All Rights Reserved. Contributor(s): - You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.sourceforge.net Known Issues: -----------------------------------------------------------------------------} // $Id: PageBuilder.pas,v 1.10 2004/12/30 00:11:10 ahuser Exp $ unit PageBuilder; {$I jvcl.inc} interface uses Windows, SysUtils, Classes, Controls, Forms, Graphics, StdCtrls, ExtCtrls, ComCtrls, ActnList, JvWizard, Core; function CreatePage(Page: TJvWizardInteriorPage; Inst: IInstallerPage): TWinControl; { returns the active control } function PreparePage(Page: TJvWizardInteriorPage; Inst: IInstallerPage): TPanel; procedure DestroyPage(Page: TJvWizardInteriorPage); implementation uses Main, Utils; function CreateWelcomePage(Page: TJvWizardInteriorPage; Inst: IWelcomePage): TWinControl; forward; { returns the active control } function CreateMultiChoosePage(Page: TJvWizardInteriorPage; Inst: IMultiChoosePage): TWinControl; forward; { returns the active control } function CreateSingleChoosePage(Page: TJvWizardInteriorPage; Inst: ISingleChoosePage): TWinControl; forward; { returns the active control } function CreateSummaryPage(Page: TJvWizardInteriorPage; Inst: ISummaryPage): TWinControl; forward; { returns the active control } type TSingleChooseOptionClick = class(TComponent) public Index: Integer; Page: ISingleChoosePage; procedure Click(Sender: TObject); end; TMultiChooseCheckBoxClick = class(TComponent) public Index: Integer; Page: IMultiChoosePage; procedure Click(Sender: TObject); end; procedure TSingleChooseOptionClick.Click(Sender: TObject); begin Page.SetSelectedOption(Index); end; procedure TMultiChooseCheckBoxClick.Click(Sender: TObject); begin Page.SetCheckBox(Index, (Sender as TCheckBox).Checked); end; function GetDefaultCheckBoxSize: TSize; begin {$IFDEF VCL} with TBitmap.Create do try Handle := LoadBitmap(0, PChar(OBM_CHECKBOXES)); Result.cx := Width div 4; Result.cy := Height div 3; finally Free; end; {$ENDIF VCL} {$IFDEF VisualCLX} Result.cx := 12; Result.cy := 12; {$ENDIF VisualCLX} end; // ----------------------------------------------------------------------------- function CreateLayoutPanel(Parent: TWinControl; const Name: string; const BoundsRect: TRect): TPanel; begin Result := TPanel.Create(Parent); Result.Name := Name; Result.BevelInner := bvNone; Result.BevelOuter := bvNone; Result.BoundsRect := BoundsRect; Result.Caption := ''; Result.Parent := Parent; end; function PreparePage(Page: TJvWizardInteriorPage; Inst: IInstallerPage): TPanel; var Title, SubTitle: WideString; begin // caption Title := ''; SubTitle := ''; Inst.Title(Title, SubTitle); Page.Title.Text := Title; Page.Subtitle.Text := SubTitle; Page.Caption := Title; Page.Header.Title.Indent := 5; Page.Header.Subtitle.Indent := 5; Page.Header.Visible := (Title <> '') or (SubTitle <> ''); Result := nil; end; function CreatePage(Page: TJvWizardInteriorPage; Inst: IInstallerPage): TWinControl; var Y: Integer; PageClient: TPanel; FocusControl: TWinControl; begin Result := nil; if (Page.FindComponent('piPageClient') <> nil) and not Supports(Inst, ISummaryPage) then // do not localize Exit; if Supports(Inst, ISummaryPage) then Page.FindComponent('piPageClient').Free; if Page.Header.Visible then Y := Page.Header.Height else Y := 0; PageClient := CreateLayoutPanel(Page, 'piPageClient', // do not localize Rect(0, Y, Page.ClientWidth, Page.ClientHeight)); if Supports(Inst, IWelcomePage) then Result := CreateWelcomePage(Page, Inst as IWelcomePage) else if Supports(Inst, ISingleChoosePage) then Result := CreateSingleChoosePage(Page, Inst as ISingleChoosePage) else if Supports(Inst, IMultiChoosePage) then Result := CreateMultiChoosePage(Page, Inst as IMultiChoosePage) else if Supports(Inst, ISummaryPage) then Result := CreateSummaryPage(Page, Inst as ISummaryPage) ; // maybe the user wants some extra controls if Supports(Inst, IUserDefinedPage) then begin FocusControl := (Inst as IUserDefinedPage).SetupPage(PageClient); if FocusControl <> nil then Result := FocusControl; end; end; procedure DestroyPage(Page: TJvWizardInteriorPage); procedure RemoveActionLists(Owner: TComponent); var i: Integer; begin for i := Owner.ComponentCount - 1 downto 0 do RemoveActionLists(Owner.Components[i]); if (Owner is TCustomActionList) then Owner.Free; end; var Panel: TPanel; begin Panel := TPanel(Page.FindComponent('piPageClient')); // do not localize if Panel <> nil then begin RemoveActionLists(Panel); // Bug in VCL does not remove the action list from the frame's actionlist list. Panel.Free; end; end; function CreateSingleChooseControls(Parent: TWinControl; Inst: ISingleChoosePage; var LockedHorzOrientation: THorzOrientation): TWinControl; var Options: TStrings; i, AbsH, X, Y, ps: Integer; RadioButton: TRadioButton; ItemIndex: Integer; S: string; HorzOrientation: THorzOrientation; Width, tmpWidth: Integer; Canvas: TControlCanvas; begin Result := nil; Options := TStringList.Create; Canvas := TControlCanvas.Create; try Canvas.Control := Parent; // RadioButtons HorzOrientation := hoDefault; Inst.Options(Options, HorzOrientation); case LockedHorzOrientation of hoLeft: HorzOrientation := hoRight; hoRight: HorzOrientation := hoLeft; hoCenter: Exit; // error end; if HorzOrientation = hoDefault then HorzOrientation := hoLeft; LockedHorzOrientation := HorzOrientation; if Options.Count > 0 then begin ItemIndex := Inst.GetSelectedOption; // find text with largest width Width := 0; for i := 0 to Options.Count - 1 do begin S := Options[i]; if S <> '' then begin ps := Pos('|', S); if ps = 0 then ps := Length(S) + 1; tmpWidth := Canvas.TextWidth(Copy(S, 1, ps - 1)); if tmpWidth > Width then Width := tmpWidth; end; end; Inc(Width, GetDefaultCheckBoxSize.cx*4 div 2); // add checkbox size if HorzOrientation = hoLeft then X := 8 else if HorzOrientation = hoCenter then X := (Parent.ClientWidth - Width) div 2 else X := Parent.ClientWidth - 8 - Width; // create radion buttons AbsH := (Parent.ClientHeight - 8) div Options.Count; Y := 8; for i := 0 to Options.Count - 1 do begin S := Options[i]; if S <> '' then begin ps := Pos('|', S); if ps = 0 then ps := Length(S) + 1; RadioButton := TRadioButton.Create(Parent); RadioButton.Name := 'piOption_' + IntToStr(i); // do not localize RadioButton.Left := X; RadioButton.Top := Y; RadioButton.Caption := Copy(S, 1, ps - 1); RadioButton.Hint := Copy(S, ps + 1, MaxInt); RadioButton.ShowHint := RadioButton.Hint <> ''; RadioButton.Parent := Parent; RadioButton.ClientWidth := Width; with TSingleChooseOptionClick.Create(Parent) do begin Page := Inst; Index := i; RadioButton.OnClick := Click; end; if i = ItemIndex then begin if Result = nil then Result := RadioButton; RadioButton.Checked := True; end; Inst.SetupRadioButton(i, RadioButton); end; Inc(Y, AbsH); end; end; finally Options.Free; Canvas.Free; end; end; function CreateMultiChooseControls(Parent: TWinControl; Inst: IMultiChoosePage; var LockedHorzOrientation: THorzOrientation): TWinControl; var CheckBoxes: TStrings; i, AbsH, X, Y, ps: Integer; CheckBox: TCheckBox; S: string; HorzOrientation: THorzOrientation; Width, tmpWidth: Integer; Canvas: TControlCanvas; begin Result := nil; CheckBoxes := TStringList.Create; Canvas := TControlCanvas.Create; try Canvas.Control := Parent; HorzOrientation := hoDefault; Inst.CheckBoxes(CheckBoxes, HorzOrientation); case LockedHorzOrientation of hoLeft: HorzOrientation := hoRight; hoRight: HorzOrientation := hoLeft; hoCenter: Exit; // error end; if HorzOrientation = hoDefault then HorzOrientation := hoLeft; LockedHorzOrientation := HorzOrientation; if CheckBoxes.Count > 0 then begin // find text with largest width Width := 0; for i := 0 to CheckBoxes.Count - 1 do begin S := CheckBoxes[i]; if S <> '' then begin ps := Pos('|', S); if ps = 0 then ps := Length(S) + 1; tmpWidth := Canvas.TextWidth(Copy(S, 1, ps - 1)); if tmpWidth > Width then Width := tmpWidth; end; end; Inc(Width, GetDefaultCheckBoxSize.cx*4 div 2); // add checkbox size if HorzOrientation = hoLeft then X := 8 else if HorzOrientation = hoCenter then X := (Parent.ClientWidth - Width) div 2 else X := Parent.ClientWidth - 8 - Width; // create check boxes AbsH := (Parent.ClientHeight - 8) div CheckBoxes.Count; Y := 8; for i := 0 to CheckBoxes.Count - 1 do begin S := CheckBoxes[i]; if S <> '' then begin ps := Pos('|', S); if ps = 0 then ps := Length(S) + 1; CheckBox := TCheckBox.Create(Parent); CheckBox.Name := 'piCheckBox_' + IntToStr(i); CheckBox.Left := X; CheckBox.Top := Y; CheckBox.Caption := Copy(S, 1, ps - 1); CheckBox.Hint := Copy(S, ps + 1, MaxInt); CheckBox.ShowHint := CheckBox.Hint <> ''; CheckBox.Parent := Parent; CheckBox.ClientWidth := Width; with TMultiChooseCheckBoxClick.Create(Parent) do begin Page := Inst; Index := i; CheckBox.OnClick := Click; end; if Result = nil then Result := CheckBox; CheckBox.Checked := Inst.GetCheckBox(i); Inst.SetupCheckBox(i, CheckBox); end; Inc(Y, AbsH); end; end; finally CheckBoxes.Free; Canvas.Free; end; end; function CreateWelcomePage(Page: TJvWizardInteriorPage; Inst: IWelcomePage): TWinControl; var Text: WideString; Memo: TMemo; PageClient, ControlsPanel: TPanel; Y: Integer; HorzOrientation: THorzOrientation; MultiChoosePage: IMultiChoosePage; begin PageClient := TPanel(Page.FindComponent('piPageClient')); // do not localize Text := Inst.Text; if Text <> '' then begin Memo := TMemo.Create(PageClient); Memo.Parent := PageClient; Memo.Name := 'piPageMemo'; // do not localize Memo.Left := 8; Memo.Top := 8; Memo.Width := PageClient.ClientWidth - Memo.Left * 2; Memo.Height := (PageClient.ClientHeight - Memo.Top * 2) * 2 div 3; Memo.ReadOnly := True; Memo.Font.Name := 'Arial'; Memo.Lines.Text := Text; Memo.ScrollBars := ssVertical; Memo.Visible := True; Y := Memo.Top + Memo.Height; end else Y := 0; ControlsPanel := CreateLayoutPanel(PageClient, 'piControlsPanel', // do not localize Rect(0, Y, PageClient.ClientWidth, PageClient.ClientHeight)); HorzOrientation := hoDefault; Result := CreateSingleChooseControls(ControlsPanel, Inst, HorzOrientation); if Supports(Inst, IMultiChoosePage, MultiChoosePage) then CreateMultiChooseControls(ControlsPanel, MultiChoosePage, HorzOrientation); end; function CreateSingleChoosePage(Page: TJvWizardInteriorPage; Inst: ISingleChoosePage): TWinControl; var PageClient: TPanel; HortOrientation: THorzOrientation; begin PageClient := TPanel(Page.FindComponent('piPageClient')); // do not localize HortOrientation := hoDefault; Result := CreateSingleChooseControls(PageClient, Inst, HortOrientation); end; function CreateMultiChoosePage(Page: TJvWizardInteriorPage; Inst: IMultiChoosePage): TWinControl; var PageClient: TPanel; HortOrientation: THorzOrientation; begin PageClient := TPanel(Page.FindComponent('piPageClient')); // do not localize HortOrientation := hoDefault; Result := CreateMultiChooseControls(PageClient, Inst, HortOrientation); end; function CreateSummaryPage(Page: TJvWizardInteriorPage; Inst: ISummaryPage): TWinControl; var PageClient: TPanel; ListView: TListView; Actions, Comments: TStrings; I, MaxWidth, TextWidth, Count, ActionsWidth: Integer; ListItem: TListItem; begin PageClient := TPanel(Page.FindComponent('piPageClient')); // do not localize ListView := TListView.Create(PageClient); ListView.Parent := PageClient; ListView.SetBounds(8, 8, PageClient.ClientWidth - 8 * 2, PageClient.ClientHeight - 8 * 2); ListView.ReadOnly := True; ListView.ViewStyle := vsReport; ListView.RowSelect := True; ListView.ShowColumnHeaders := False; ListView.SmallImages := FormMain.ImageList; MaxWidth := 150; ActionsWidth := 0; Actions := TStringList.Create; Comments := TStringList.Create; ListView.Items.BeginUpdate; try Inst.GetSummary(Actions, Comments); Count := Actions.Count; if Count < Comments.Count then Count := Comments.Count; for I := 0 to Count - 1 do begin ListItem := ListView.Items.Add; if I >= Actions.Count then begin ListItem.Caption := ''; end else begin ListItem.Caption := Actions[I]; TextWidth := ListView.Canvas.TextWidth(Actions[I]); if TextWidth > ActionsWidth then ActionsWidth := TextWidth; end; if ListItem.Caption = '' then ListItem.ImageIndex := -1 else ListItem.ImageIndex := 0; if I >= Comments.Count then ListItem.SubItems.Add('') else begin ListItem.SubItems.Add(Comments[I]); TextWidth := ListView.Canvas.TextWidth(Comments[I]); if MaxWidth < TextWidth then MaxWidth := TextWidth; end; end; ListView.Columns.Add.Width := ActionsWidth+30; // +30 to cope for the bullet width if ListView.ClientWidth < MaxWidth + 50 then ListView.Columns.Add.Width := MaxWidth + 50 else ListView.Columns.Add.AutoSize := True; ListView.Width := ListView.Width + 1; // force AutoSize finally ListView.Items.EndUpdate; Actions.Free; Comments.Free; end; Result := ListView; end; end.
28.261818
109
0.651248
853d7224cf2278f5caae58b032755ef5e711ce30
14,870
pas
Pascal
graphics/0274.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
11
2015-12-12T05:13:15.000Z
2020-10-14T13:32:08.000Z
graphics/0274.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
null
null
null
graphics/0274.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
8
2017-05-05T05:24:01.000Z
2021-07-03T20:30:09.000Z
{Jaco van Niekerk sparky@lantic.co.za} {Any comments, whatever, please mail!} {Please note : I take NO responsibility on the effect of the code } { I've tested it on many machines, so I can't see any } { reason why it should not work on yours. } {worm hole in 320x200} {$N+} program wormhole; uses crt; {for keypressed} var circle_x : array[1..80, 0..61] of integer; circle_y : array[1..80, 0..61] of integer; cposx, xposy : array[1..80, 0..61] of integer; relpos_x : array[1..80] of integer; relpos_y : array[1..80] of integer; vscreen : pointer; procedure calc_circles; var deg, x, y, c : integer; begin for c:=1 to 80 do begin relpos_x[c]:=0; relpos_y[c]:=0; for deg:=0 to 60 do begin x:=round(c*3*cos(deg*pi/30)); y:=round(c*3*sin(deg*pi/30)); circle_x[c, deg]:=160+x; circle_y[c, deg]:=100+y; end; end; end; procedure copyw(source : pointer; dest : pointer; cnt : word);assembler; asm les di, [dest] push ds lds si, [source] mov cx, [cnt] cld rep movsw pop ds end; procedure clrdw(source : pointer; cnt : word);assembler; asm les di, [source] mov cx, [cnt] db $66; xor ax, ax {xor eax, eax} db $66; rep stosw {rep storsdw} end; procedure waitretrace;assembler; asm {this waits for a vertical retrace, exiting when it occurs} mov dx,3DAh @loop1: in al,dx and al,08h jnz @loop1 @loop2: in al,dx and al,08h jz @loop2 end; var xp, yp, i, j, sg, os, new_y, new_x : word; cx, cy, dx, dy : real; tx, ty : integer; mpos : integer; begin randomize; if maxavail<64000 then begin writeln('Not enough memory!'); halt(1); end; getmem(vscreen, 64000); calc_circles; sg:=seg(vscreen^); os:=ofs(vscreen^); cx:=0; cy:=0; dx:=0; dy:=0; tx:=random(20)-10; ty:=random(20)-10; asm mov ax, 13h; int 10h; end; port[$3c8]:=1; for i:=1 to 80 do begin port[$3c9]:=round(i*0.7); port[$3c9]:=round(i*0.7); port[$3c9]:=round(i*0.7); end; repeat {clear screen} clrdw(vscreen, 16000); {update offset buffer} for i:=80 downto 1 do begin relpos_x[i]:=relpos_x[i-1]; relpos_y[i]:=relpos_y[i-1]; end; {create "new" circle} if cx>tx then dx:=dx-0.55 else if cx<tx then dx:=dx+0.55; if cy>ty then dy:=dy-0.55 else if cy<ty then dy:=dy+0.55; if sqr(cx-tx)+sqr(cy-ty)<200 then begin tx:=random(80)-30; ty:=random(50)-25; end; cx:=cx+dx; cy:=cy+dy; {speed control} if dx>5 then dx:=5; if dx<-5 then dx:=-5; if dy>5 then dy:=5; if dy<-5 then dy:=-5; {update new circle} relpos_x[1]:=round(cx); relpos_y[1]:=round(cy); {plot circles} for i:=1 to 80 do for j:=0 to 60 do begin new_x:=circle_x[i][j] + relpos_x[i]; new_y:=circle_y[i][j] + relpos_y[i]; if (new_x>0) and (new_x<320) and (new_y>0) and (new_y<200) then mem[sg:os+new_y shl 6+new_y shl 8+new_x]:=i; end; {blast to screen} waitretrace; copyw(vscreen, ptr($a000,0000), 32000); until (keypressed); asm mov ax, 03h; int 10h; end; freemem(vscreen, 64000); end. --Message-Boundary-5639 Content-type: text/plain; charset=US-ASCII Content-transfer-encoding: 7BIT Content-description: Text from file 'SIMBA.PAS' { By Jaco van Niekerk - sparky@lantic.co.za (Any problems, feel free to mail me) {Please note : I take NO responsibility on the effect of the code } { I've tested it on many machines, so I can't see any } { reason why it should not work on yours. } {The wonders of the VGA card} {$N+} program run_around; uses crt; type header = record manufacturer : byte; version : byte; encoding : byte; bits_per_pixel : byte; xmin, ymin, xmax, ymax : integer; hdpi, vdpi : integer; colormap : array[0..47] of byte; reserved : byte; nplanes : byte; bytes_per_line : integer; palette_info : integer; hscreensize, vscreensize : integer; dummy : array[0..53] of byte; end; const width : byte = 80; {80 * 8 = 640} fade = 20; spin = 200; procedure initmode; {320x200 chain4 off} begin {first go to chain-4 mode} asm mov ah, 0 mov al, 13h int 10h end; {turn chain-4 bit off} port[$3c4]:=$4; {index 2} port[$3c5]:=port[$3c5] and $f7; {now set bit 3 to zero} {turn off word mode} port[$3d4]:=$17; {index 17} port[$3d5]:=port[$3d5] or $40; {turn off double word mode} port[$3d4]:=$14; {index 14} port[$3d5]:=0; {set logical screen width} port[$3d4]:=$13; port[$3d5]:=width; {clear the video memory} portw[$3c4]:=$0f02; fillchar(mem[$a000:000],65535,0); end; procedure moveto(x, y : word); var offset : word; begin offset:=width*2*y+(x div 4); port[$3d4]:=$c; port[$3d5]:=hi(offset); port[$3d4]:=$d; port[$3d5]:=lo(offset); {smooth panning compatible} port[$3c0]:=$13 or $20; port[$3c0]:=(x mod 4) shl 1; end; procedure putpixel(x, y : word; col : byte);assembler; asm mov ax, 0a000h mov es, ax {video address in es} mov dx, 03c4h {mov register value into dx} mov al, 02h {we want index 2} mov ah, 01h {from here on, calculate the correct plane} mov cx, [x] and cx, 3 shl ah, cl out dx, ax {one port write} mov ax, [y] {calculate address} shl ax, 1 shl ax, 4 mov di, ax shl ax, 2 add di, ax mov ax, [x] shr ax, 2 add di, ax mov al, [col] mov [es:di], al {plot the colour} end; function getpixel(x, y : word):byte;assembler; asm mov ax, 0a000h mov es, ax mov dx, $3ce {prepare port word} mov bx, [x] and bx, 3 mov ah, bl mov al, 04h out dx, ax {write ax to port dx} mov ax, [y] {calculate address} shl ax, 1 shl ax, 4 mov di, ax shl ax, 2 add di, ax mov ax, [x] shr ax, 2 add di, ax mov al, [es:di] {get the colour} end; function pcxbackground(fname : string):boolean; {INPUT : filename of 256 colour pcx image } {OUTPUT : TRUE if image load successful } {OTHER : either loads pcx file or not, fades palette in } const dskbufsize = 8192; var hdrb : header; palb : array[0..767] of byte; var {general vars} f : file; eb, dta, rle, ecode : byte; dx, dy, i, j : word; tot, mc : longint; {global cashread vars} dskbuf : array[0..dskbufsize-1] of byte; cnt, cursize : word; function casheread : byte; begin {cashread routine} if cnt=cursize then {read ahead} begin blockread(f, dskbuf, dskbufsize, cursize); cnt:=0; end; cnt:=cnt+1; casheread:=dskbuf[cnt-1]; end; begin assign(f, fname); {$I-} reset(f, 1); {$I+} eb:=ioresult; if eb=0 then begin {set up globals} port[$3c8]:=0; for i:=0 to 767 do port[$3c9]:=0; cnt:=0; cursize:=0; ecode:=0; if filesize(f)<1920 then ecode:=3; if ecode=0 then begin {pcx header} blockread(f, hdrb, 128); {256 colour palette} seek(f, filesize(f)-768); blockread(f, palb, 768); seek(f, 128); {actual data} end; {complete encoding test} with hdrb do begin if manufacturer<>10 then ecode:=3; if encoding<>1 then ecode:=3; if bits_per_pixel<>8 then ecode:=3; if nplanes<>1 then ecode:=3; end; if ecode<>3 then begin {calc needy vars} dx:=(hdrb.xmax-hdrb.xmin)+1; dy:=(hdrb.ymax-hdrb.ymin)+1; tot:=longint(dx) * longint(dy); mc:=0; while (mc<tot) and (ecode=0) do begin dta:=casheread; if (dta and $c0) = $c0 then begin {run-length-encoding} rle:=casheread; dta:=dta and $3f; for i:=0 to dta-1 do putpixel((mc+i) mod dx, (mc+i) div dx, rle); inc(mc, dta); end else begin {no compression} putpixel(mc mod dx, mc div dx, dta); inc(mc); end; end; close(f); { for j:=0 to 100 do begin} j:=100; port[$3c8]:=0; for i:=0 to 767 do port[$3c9]:=round(palb[i]*j/100) div 4; { end; } pcxbackground:=true; end; end else pcxbackground:=false; end; procedure waitretrace;assembler; asm mov dx,3DAh @loop1: in al,dx and al,08h jnz @loop1 @loop2: in al,dx and al,08h jz @loop2 end; var i, j, k : word; x, y, deg, w : real; f : file; c : array[0..768] of real; begin initmode; {any 640x400 pcx file, 8bit} if pcxbackground('yourfile.pcx') then begin x:=0; y:=0; deg:=0; while keypressed do readkey; repeat moveto(round(160+x), round(100+y)); x:=160*sin(deg*2)*cos(deg); y:=100*sin(deg/2)*sin(deg); deg:=deg+0.001; until keypressed; end; asm mov ah, 0 mov al, 03h int 10h end; end. --Message-Boundary-5639 Content-type: text/plain; charset=US-ASCII Content-transfer-encoding: 7BIT Content-description: Text from file 'RS232.PAS' { By Jaco van Niekerk - sparky@lantic.co.za (Any problems, feel free to mail me) Unit to handle RS232 communication Set the COM ports up with open_serial Shut down with close_serial recieve_byte and send_byte fot the communication } {Please note : I take NO responsibility on the effect of the code } { I've tested it on many machines, so I can't see any } { reason why it should not work on yours. } unit rs232; interface const COM_1 = $3f8; COM_2 = $2f8; SER_BAUD_600 = 192; SER_BAUD_1200 = 96; SER_BAUD_2400 = 48; SER_BAUD_9600 = 12; SER_BAUD_19200 = 6; SER_BAUD_115200 = 1; SER_STOP_1 = 0; SER_STOP_2 = 4; SER_BITS_5 = 0; SER_BITS_6 = 1; SER_BITS_7 = 2; SER_BITS_8 = 3; PARITY_NONE = 0; PARITY_ODD = 8; PARITY_EVEN = 24; var chars_waiting : integer; procedure open_serial(port_base, baud, configuration : word); procedure close_serial; function receive_byte:byte; procedure send_byte(thingy : byte); implementation uses dos; const Max_buffer_size = 8192; {8kb circular buffer} {these variables CAN NOT be implemented as locals {and must therefore be declared global} var open_port : word; serial_lock : byte; old_int_mask : byte; old_handler : procedure; my_buffer : array[0..Max_buffer_size-1] of byte; buf_read, buf_write : integer; procedure my_handler;interrupt; var my_byte : byte; begin serial_lock:=1; {lock the buffer} my_byte:=port[open_port + 0]; {get byte from harware port} my_buffer[buf_write]:=my_byte; {put byte into software buffer} buf_write:=(buf_write+1) mod Max_buffer_size; {add + wrap around} inc(chars_waiting); {one more byte} port[$20]:=$20; {let PIC know, we are done!} serial_lock:=0; {unlock buffer} end; procedure close_serial; begin {disable required interrupts} port[open_port + 4]:=0; port[open_port + 1]:=0; port[$21]:=old_int_mask; {give controll back to old handler} if (open_port = COM_1) then setintvec($0c, addr(old_handler)) else setintvec($0b, addr(old_handler)); end; procedure open_serial(port_base, baud, configuration : word); begin {set up global variables} open_port:=port_base; buf_read:=0; buf_write:=0; chars_waiting:=0; {set the baud rate} port[open_port + 3]:=128; port[open_port + 0]:=baud and 255; {lsb} port[open_port + 1]:=(baud shr 8) and 255; {msb} {set the configuration} port[open_port + 3]:=configuration; {setup interrupts and enable them} port[open_port + 4]:=8; {enable interrupts} port[open_port + 1]:=1; {interrupt CPU for char received} {now, take control!} if (open_port = COM_1) then begin getintvec($0c, @old_handler); setintvec($0c, addr(my_handler)); end else begin getintvec($0b, @old_handler); setintvec($0b, addr(my_handler)); end; {tell mr. PIC} old_int_mask:=port[$21]; if (open_port = COM_1) then port[$21]:=old_int_mask and $ef else port[$21]:=old_int_mask and $e7; end; function receive_byte:byte; var ret_this : byte; begin while (serial_lock = 1) do; if (chars_waiting>0) then begin ret_this:=my_buffer[buf_read]; {get next byte} buf_read:=(buf_read+1) mod Max_buffer_size; {add + wrap around} dec(chars_waiting); {one less byte} end else ret_this:=0; receive_byte:=ret_this; end; procedure send_byte(thingy : byte); begin {pole line-status-register for "ready to send"} while not((port[open_port + 5] and $20)=$20) do {nothing}; {interrupts has to be disbaled while sending is in progress} {unfortunatly this makes full-duplex communications not possible} asm cli end; port[open_port + 0]:=thingy; asm sti end; end; begin end. 
27.184644
79
0.527303
f1df93bb81574b20e61f7d8f2577f225013b2c01
13,064
pas
Pascal
Server/ClosureManager.pas
novakjf2000/FHIRServer
a47873825e94cd6cdfa1a077f02e0960098bbefa
[ "BSD-3-Clause" ]
1
2018-01-08T06:40:02.000Z
2018-01-08T06:40:02.000Z
Server/ClosureManager.pas
novakjf2000/FHIRServer
a47873825e94cd6cdfa1a077f02e0960098bbefa
[ "BSD-3-Clause" ]
null
null
null
Server/ClosureManager.pas
novakjf2000/FHIRServer
a47873825e94cd6cdfa1a077f02e0960098bbefa
[ "BSD-3-Clause" ]
null
null
null
unit ClosureManager; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 HOLDER 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. } interface Uses SysUtils, Generics.Collections, StringSupport, kCritSct, AdvObjects, AdvGenerics, KDBManager, FHIRResources, FHIRTypes, FHIRUtilities, TerminologyServerStore; Type TSubsumptionMatch = class (TAdvObject) private FKeySrc: integer; FcodeSrc: String; FuriSrc: String; FKeyTgt: integer; FcodeTgt: String; FuriTgt: String; public Constructor Create(keysrc : integer; urisrc, codesrc : String; keytgt : integer; uritgt, codetgt : String); property KeySrc : integer read FKeySrc write FKeySrc; property uriSrc : String read FuriSrc write FuriSrc; property codeSrc : String read FcodeSrc write FcodeSrc; property KeyTgt : integer read FKeyTgt write FKeyTgt; property uriTgt : String read FuriTgt write FuriTgt; property codeTgt : String read FcodeTgt write FcodeTgt; end; TClosureManager = class (TAdvObject) private FStore : TTerminologyServerStore; // not linked, as this is the owner FName : String; FKey : integer; FLock : TCriticalSection; FVersion : integer; function GetConceptKey(conn : TKDBConnection; uri, code : String) : integer; procedure processEntryInternal(conn: TKDBConnection; ClosureEntryKey, ConceptKey: integer; uri, code : String; map : TFHIRConceptMap); function getGroup(map: TFHIRConceptMap; source, target: String): TFHIRConceptMapGroup; public Constructor Create(name : String; key, version : integer; store : TTerminologyServerStore); Destructor Destroy; override; function Link : TClosureManager; overload; Property Version : Integer read FVersion; procedure Init(conn : TKDBConnection); // this is a split mode implementation, for performance - the subsumption is calculated in the background function enterCode(conn: TKDBConnection; uri, code: String): integer; procedure processEntry(conn: TKDBConnection; ClosureEntryKey, ConceptKey: integer; uri, code: String); // this is the inline variant; subsumption is determined immediately procedure processConcepts(conn: TKDBConnection; codings : TAdvList<TFHIRCoding>; map : TFHIRConceptMap); procedure reRun(conn: TKDBConnection; map : TFHIRConceptMap; version : integer); end; implementation { TClosureManager } constructor TClosureManager.Create(name: String; key, version : integer; store : TTerminologyServerStore); begin inherited Create; FLock := TCriticalSection.Create('Closure Table '+name); FName := name; FKey := key; FVersion := Version; FStore := store; end; procedure TClosureManager.Init(conn: TKDBConnection); begin if FKey = 0 then begin Fkey := FStore.nextClosureKey; FVersion := 0; conn.ExecSQL('insert into Closures (ClosureKey, Name, Version) values ('+inttostr(Fkey)+', '''+FName+''', 0)'); end else conn.ExecSQL('delete from ClosureEntries where ClosureKey = '+inttostr(Fkey)); end; function TClosureManager.Link: TClosureManager; begin result := TClosureManager(inherited Link); end; function TClosureManager.GetConceptKey(conn: TKDBConnection; uri, code: String): integer; begin result := conn.CountSQL('select ConceptKey from Concepts where URL = '''+SQLWrapString(uri)+''' and Code = '''+SQLWrapString(code)+''''); if result = 0 then begin result := FStore.NextConceptKey; conn.execSQL('insert into Concepts (ConceptKey, URL, Code, NeedsIndexing) values ('+inttostr(result)+', '''+SQLWrapString(uri)+''', '''+SQLWrapString(code)+''', 1)'); end; end; destructor TClosureManager.Destroy; begin FLock.Free; inherited; end; function TClosureManager.enterCode(conn: TKDBConnection; uri, code: String): integer; begin result := GetConceptKey(conn, uri, code); // now, check that it is in the closure if conn.CountSQL('select Count(*) from ClosureEntries where ClosureKey = '+inttostr(FKey)+' and SubsumesKey = '+inttostr(result)) = 0 then begin // enter it into the closure table conn.ExecSQL('insert into ClosureEntries (ClosureEntryKey, ClosureKey, SubsumesKey, SubsumedKey, IndexedVersion) values ('+inttostr(FStore.NextClosureEntryKey)+', '+inttostr(FKey)+', '+inttostr(result)+', '+inttostr(result)+', 0)'); end; end; procedure TClosureManager.processEntry(conn: TKDBConnection; ClosureEntryKey, ConceptKey: integer; uri, code : String); begin FLock.Lock; try inc(FVersion); processEntryInternal(conn, ClosureEntryKey, ConceptKey, uri, code, nil); conn.ExecSQL('Update ClosureEntries set IndexedVersion = '+inttostr(FVersion)+' where ClosureEntryKey = '+inttostr(ClosureEntryKey)); conn.ExecSQL('update Closures set Version = '+inttostr(FVersion)+' where ClosureKey = '+inttostr(FKey)); finally FLock.Unlock; end; end; procedure TClosureManager.processConcepts(conn: TKDBConnection; codings : TAdvList<TFHIRCoding>; map : TFHIRConceptMap); var coding : TFHIRCoding; ck, cek : integer; begin FLock.Lock; try inc(FVersion); map.version := inttostr(FVersion); for coding in codings do begin ck := GetConceptKey(conn, coding.system, coding.code); if conn.CountSQL('select Count(*) from ClosureEntries where ClosureKey = '+inttostr(FKey)+' and SubsumesKey = '+inttostr(ck)) = 0 then begin // enter it into the closure table cek := FStore.NextClosureEntryKey; conn.ExecSQL('insert into ClosureEntries (ClosureEntryKey, ClosureKey, SubsumesKey, SubsumedKey, IndexedVersion) values ('+inttostr(cek)+', '+inttostr(FKey)+', '+inttostr(ck)+', '+inttostr(ck)+', '+inttostr(FVersion)+')'); //now, check the subsumes.... processEntryInternal(conn, cek, ck, coding.system, coding.code, map); end; end; conn.ExecSQL('update Closures set Version = '+inttostr(FVersion)+' where ClosureKey = '+inttostr(FKey)); finally FLock.Unlock; end; end; procedure TClosureManager.processEntryInternal(conn: TKDBConnection; ClosureEntryKey, ConceptKey: integer; uri, code : String; map : TFHIRConceptMap); var matches : TAdvList<TSubsumptionMatch>; match : TSubsumptionMatch; group, g : TFhirConceptMapGroup; element, e : TFhirConceptMapGroupElement; target, t : TFhirConceptMapGroupElementTarget; begin group := nil; matches := TAdvList<TSubsumptionMatch>.create; try conn.SQL := 'select ConceptKey, URL, Code from Concepts where ConceptKey in (select SubsumesKey from ClosureEntries where ClosureKey = '+inttostr(FKey)+' and ClosureEntryKey <> '+inttostr(ClosureEntryKey)+')'; conn.prepare; conn.execute; while conn.fetchnext do begin try if FStore.subsumes(uri, code, conn.ColStringByName['URL'], conn.ColStringByName['Code']) then matches.Add(TSubsumptionMatch.Create(ConceptKey, uri, code, conn.colIntegerByName['ConceptKey'], conn.ColStringByName['URL'], conn.ColStringByName['Code'])) else if FStore.subsumes(conn.ColStringByName['URL'], conn.ColStringByName['Code'], uri, code) then matches.Add(TSubsumptionMatch.Create(conn.colIntegerByName['ConceptKey'], conn.ColStringByName['URL'], conn.ColStringByName['Code'], ConceptKey, uri, code)); except // not much we can do but ignore this? end; end; conn.Terminate; if matches.Count > 0 then begin for match in matches do begin conn.execSQL('Insert into ClosureEntries (ClosureEntryKey, ClosureKey, SubsumesKey, SubsumedKey, IndexedVersion) values '+ '('+inttostr(FStore.NextClosureEntryKey)+', '+inttostr(FKey)+', '+inttostr(match.KeySrc)+', '+inttostr(match.KeyTgt)+', '+inttostr(FVersion)+')'); if (map <> nil) then begin element := nil; {$IFDEF FHIR2} for e in g.elementList do if (e.system = match.uriSrc) and (e.code = match.codeSrc) then {$ELSE} for g in map.groupList do for e in g.elementList do if (g.source = match.uriSrc) and (e.code = match.codeSrc) then {$ENDIF} begin group := g; element := e; end; target := nil; if (element <> nil) then for t in element.targetList do {$IFDEF FHIR2} if (t.system = match.uriTgt) and (t.code = match.codeTgt) then {$ELSE} if (group.target = match.uriTgt) and (t.code = match.codeTgt) then {$ENDIF} target := t; if (target = nil) then begin if element = nil then begin group := getGroup(map, match.uriSrc, match.uritgt); element := group.elementList.Append; {$IFDEF FHIR2} element.system := match.uriSrc; {$ENDIF} element.code := match.codeSrc; end; target := element.targetList.Append; {$IFDEF FHIR2} target.system := match.uriTgt; {$ENDIF} target.code := match.codetgt; target.equivalence := ConceptMapEquivalenceSpecializes; end; end; end; end; finally matches.Free; end; end; function TClosureManager.getGroup(map: TFHIRConceptMap; source, target: String): TFHIRConceptMapGroup; var g : TFHIRConceptMapGroup; begin {$IFDEF FHIR2} result := map; {$ELSE} for g in map.groupList do if (g.source = source) and (g.target = target) then exit(g); g := map.groupList.Append; g.source := source; g.target := target; exit(g); {$ENDIF} end; procedure TClosureManager.reRun(conn: TKDBConnection; map: TFHIRConceptMap; version: integer); var key : String; elements : TAdvMap<TFhirConceptMapGroupElement>; element : TFhirConceptMapGroupElement; target : TFhirConceptMapGroupElementTarget; begin elements := TAdvMap<TFhirConceptMapGroupElement>.create; try conn.SQL := 'Select ClosureEntryKey, src.URL as UrlSrc, src.Code as CodeSrc, tgt.URL as UrlTgt, tgt.Code as CodeTgt '+ 'from ClosureEntries, Concepts as src, Concepts as tgt '+ 'where ClosureEntries.ClosureKey = '+inttostr(FKey)+' and ClosureEntries.SubsumesKey <> ClosureEntries.SubsumedKey and src.ConceptKey = ClosureEntries.SubsumesKey and tgt.ConceptKey = ClosureEntries.SubsumedKey'; conn.prepare; conn.execute; while conn.FetchNext do begin key := conn.ColStringByName['UrlSrc']+'||'+conn.ColStringByName['CodeSrc']; if elements.ContainsKey(key) then element := elements[key] else begin element := getGroup(map, conn.ColStringByName['UrlSrc'], conn.ColStringByName['UrlTgt']).elementList.Append; {$IFDEF FHIR2} element.system := conn.ColStringByName['UrlSrc']; {$ENDIF} elements.Add(key, element.link); element.code := conn.ColStringByName['CodeSrc']; target := element.targetList.Append; {$IFDEF FHIR2} target.system := conn.ColStringByName['UrlTgt']; {$ENDIF} target.code := conn.ColStringByName['CodeTgt']; target.equivalence := ConceptMapEquivalenceSubsumes; end; end; conn.terminate; finally elements.Free; end; end; { TSubsumptionMatch } constructor TSubsumptionMatch.Create(keysrc : integer; urisrc, codesrc : String; keytgt : integer; uritgt, codetgt : String); begin inherited create; FKeysrc := keysrc; FUrisrc := urisrc; FCodesrc := codesrc; FKeytgt := keytgt; FUritgt := uritgt; FCodetgt := codetgt; end; end.
37.866667
236
0.693203
fcdea3fc2ddd1f05e06798f69ce8bd5d18dce42d
2,316
dfm
Pascal
delphi-projects/uni prog/hotel2/Unit1.dfm
zoghal/my-old-projects
0d505840a3b840af889395df669f91751f8a2d36
[ "MIT" ]
3
2017-09-18T15:20:15.000Z
2020-02-11T17:40:41.000Z
delphi-projects/uni prog/hotel2/Unit1.dfm
zoghal/my-old-projects
0d505840a3b840af889395df669f91751f8a2d36
[ "MIT" ]
null
null
null
delphi-projects/uni prog/hotel2/Unit1.dfm
zoghal/my-old-projects
0d505840a3b840af889395df669f91751f8a2d36
[ "MIT" ]
null
null
null
object MainForm: TMainForm Left = 296 Top = 120 Width = 870 Height = 500 BiDiMode = bdRightToLeft Caption = 'MainForm' Color = clBtnFace Font.Charset = ARABIC_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False ParentBiDiMode = False PixelsPerInch = 96 TextHeight = 13 object SpeedButton1: TSpeedButton Left = 656 Top = 24 Width = 185 Height = 57 Caption = #1607#1578#1604 OnClick = SpeedButton1Click end object SpeedButton2: TSpeedButton Left = 464 Top = 24 Width = 185 Height = 57 Caption = #1575#1578#1575#1602 OnClick = SpeedButton2Click end object SpeedButton3: TSpeedButton Left = 264 Top = 24 Width = 185 Height = 57 Caption = #1605#1587#1575#1601#1585'/ '#1585#1586#1585#1608 OnClick = SpeedButton3Click end object SpeedButton4: TSpeedButton Left = 64 Top = 24 Width = 185 Height = 57 Caption = #1605#1587#1575#1601#1585'/ '#1585#1586#1585#1608 OnClick = SpeedButton3Click end object SpeedButton5: TSpeedButton Left = 656 Top = 88 Width = 185 Height = 57 Caption = #1582#1583#1605#1575#1578 OnClick = SpeedButton5Click end object SpeedButton6: TSpeedButton Left = 464 Top = 88 Width = 185 Height = 57 Caption = #1578#1582#1601#1610#1601 OnClick = SpeedButton6Click end object SpeedButton7: TSpeedButton Left = 264 Top = 88 Width = 185 Height = 57 Caption = #1589#1608#1585#1578' '#1581#1587#1575#1576 OnClick = SpeedButton7Click end object SpeedButton8: TSpeedButton Left = 64 Top = 88 Width = 185 Height = 57 Caption = #1604#1610#1587#1578' '#1578#1582#1601#1610#1601#1575#1578' '#1576#1585' '#1575#1587#1575#1587' '#1585#1606#1580 OnClick = SpeedButton8Click end object ADOConnection1: TADOConnection Connected = True ConnectionString = 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security In' + 'fo=False;Initial Catalog=hotel;Data Source=SALEH' LoginPrompt = False Provider = 'SQLOLEDB.1' Left = 32 Top = 416 end object ADOCommand1: TADOCommand Connection = ADOConnection1 Parameters = <> Left = 72 Top = 416 end end
23.393939
126
0.657599
47f97f20929a265a0dfa6a4495f7cae7030d8b25
42,020
pas
Pascal
Components/FolderTreeView.pas
tony8077616/issrc
3b0cd1eff411bc3f3b85a89190f02e47a5d78991
[ "FSFAP" ]
null
null
null
Components/FolderTreeView.pas
tony8077616/issrc
3b0cd1eff411bc3f3b85a89190f02e47a5d78991
[ "FSFAP" ]
null
null
null
Components/FolderTreeView.pas
tony8077616/issrc
3b0cd1eff411bc3f3b85a89190f02e47a5d78991
[ "FSFAP" ]
1
2022-03-05T09:32:15.000Z
2022-03-05T09:32:15.000Z
unit FolderTreeView; { Inno Setup Copyright (C) 1997-2018 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. TFolderTreeView component } interface {$I VERSION.INC} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, CommCtrl; type TCustomFolderTreeView = class; TFolderRenameEvent = procedure(Sender: TCustomFolderTreeView; var NewName: String; var Accept: Boolean) of object; TCustomFolderTreeView = class(TWinControl) private FDestroyingHandle: Boolean; FDirectory: String; FFriendlyTree: Boolean; FItemExpanding: Boolean; FOnChange: TNotifyEvent; FOnRename: TFolderRenameEvent; procedure Change; procedure DeleteObsoleteNewItems(const ParentItem, ItemToKeep: HTREEITEM); function FindItem(const ParentItem: HTREEITEM; const AName: String): HTREEITEM; function FindOrCreateItem(const ParentItem: HTREEITEM; const AName: String): HTREEITEM; function GetItemFullPath(Item: HTREEITEM): String; virtual; function InsertItem(const ParentItem: HTREEITEM; const AName, ACustomDisplayName: String; const ANewItem: Boolean): HTREEITEM; procedure SelectItem(const Item: HTREEITEM); procedure SetItemHasChildren(const Item: HTREEITEM; const AHasChildren: Boolean); procedure SetDirectory(const Value: String); function TryExpandItem(const Item: HTREEITEM): Boolean; procedure CNKeyDown(var Message: TWMKeyDown); message CN_KEYDOWN; procedure CNNotify(var Message: TWMNotify); message CN_NOTIFY; procedure WMCtlColorEdit(var Message: TMessage); message WM_CTLCOLOREDIT; procedure WMDestroy(var Message: TWMDestroy); message WM_DESTROY; procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND; protected function ItemChildrenNeeded(const Item: HTREEITEM): Boolean; virtual; abstract; procedure CreateParams(var Params: TCreateParams); override; procedure CreateWnd; override; function GetItemImageIndex(const Item: HTREEITEM; const NewItem, SelectedImage: Boolean): Integer; virtual; abstract; function GetRootItem: HTREEITEM; virtual; function ItemHasChildren(const Item: HTREEITEM): Boolean; virtual; abstract; procedure KeyDown(var Key: Word; Shift: TShiftState); override; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnRename: TFolderRenameEvent read FOnRename write FOnRename; public constructor Create(AOwner: TComponent); override; procedure ChangeDirectory(const Value: String; const CreateNewItems: Boolean); procedure CreateNewDirectory(const ADefaultName: String); property Directory: String read FDirectory write SetDirectory; end; TFolderTreeView = class(TCustomFolderTreeView) private procedure RefreshDriveItem(const Item: HTREEITEM; const ANewDisplayName: String); protected function ItemChildrenNeeded(const Item: HTREEITEM): Boolean; override; function ItemHasChildren(const Item: HTREEITEM): Boolean; override; function GetItemFullPath(Item: HTREEITEM): String; override; function GetItemImageIndex(const Item: HTREEITEM; const NewItem, SelectedImage: Boolean): Integer; override; published property Anchors; property TabOrder; property TabStop default True; property Visible; property OnChange; property OnRename; end; TStartMenuFolderTreeView = class(TCustomFolderTreeView) private FUserPrograms, FCommonPrograms: String; FUserStartup, FCommonStartup: String; FImageIndexes: array[Boolean] of Integer; protected procedure CreateParams(var Params: TCreateParams); override; function GetRootItem: HTREEITEM; override; function ItemChildrenNeeded(const Item: HTREEITEM): Boolean; override; function ItemHasChildren(const Item: HTREEITEM): Boolean; override; function GetItemImageIndex(const Item: HTREEITEM; const NewItem, SelectedImage: Boolean): Integer; override; public procedure SetPaths(const AUserPrograms, ACommonPrograms, AUserStartup, ACommonStartup: String); published property Anchors; property TabOrder; property TabStop default True; property Visible; property OnChange; property OnRename; end; procedure Register; implementation { Notes: 1. Don't call TreeView_SelectItem without calling TreeView_Expand on the item's parents first. Otherwise infinite recursion can occur: a. TreeView_SelectItem will first set the selected item. It will then try to expand the parent node, causing a TVN_ITEMEXPANDING message to be sent. b. If the TVN_ITEMEXPANDING handler calls TreeView_SortChildren, TV_SortCB will call TV_EnsureVisible if the selected item was one of the items affected by the sorting (which will always be the case). c. TV_EnsureVisible will expand parent nodes if necessary. However, since we haven't yet returned from the original TVN_ITEMEXPANDING message handler, the parent node doesn't yet have the TVIS_EXPANDED state, thus it thinks the node still needs expanding. d. Another, nested TVN_ITEMEXPANDING message is sent, bringing us back to step b. (Reproducible on Windows 95 and 2000.) The recursion can be seen if you comment out the ExpandParents call in the SelectItem method, then click "New Folder" on a folder with no children. (Note, however, that because of the ChildrenAdded check in our TVN_ITEMEXPANDING handler, it can only recurse once. That won't cause a fatal stack overflow (like it did before the ChildrenAdded check was added), but it's still wrong to allow that to happen.) } uses PathFunc, ShellApi, UxThemeISX{$IFDEF IS_D12}, Types{$ENDIF}; const SHPPFW_NONE = $00000000; var SHPathPrepareForWriteFunc: function(hwnd: HWND; punkEnableModless: Pointer; pszPath: PChar; dwFlags: DWORD): HRESULT; stdcall; const TVM_SETEXTENDEDSTYLE = TV_FIRST + 44; TVS_EX_DOUBLEBUFFER = $0004; procedure Register; begin RegisterComponents('JR', [TFolderTreeView, TStartMenuFolderTreeView]); end; function IsListableDirectory(const FindData: TWin32FindData): Boolean; begin Result := (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY <> 0) and (FindData.dwFileAttributes and (FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_SYSTEM) <> (FILE_ATTRIBUTE_HIDDEN or FILE_ATTRIBUTE_SYSTEM)) and (StrComp(FindData.cFileName, '.') <> 0) and (StrComp(FindData.cFileName, '..') <> 0); end; function HasSubfolders(const Path: String): Boolean; var H: THandle; FindData: TWin32FindData; begin Result := False; H := FindFirstFile(PChar(AddBackslash(Path) + '*'), FindData); if H <> INVALID_HANDLE_VALUE then begin try repeat if IsListableDirectory(FindData) then begin Result := True; Break; end; until not FindNextFile(H, FindData); finally Windows.FindClose(H); end; end; end; function GetFileDisplayName(const Filename: String): String; var FileInfo: TSHFileInfo; begin if SHGetFileInfo(PChar(Filename), 0, FileInfo, SizeOf(FileInfo), SHGFI_DISPLAYNAME) <> 0 then Result := FileInfo.szDisplayName else Result := ''; end; function GetFileImageIndex(const Filename: String; const OpenIcon: Boolean): Integer; const OpenFlags: array[Boolean] of UINT = (0, SHGFI_OPENICON); var FileInfo: TSHFileInfo; begin if SHGetFileInfo(PChar(Filename), 0, FileInfo, SizeOf(FileInfo), SHGFI_SYSICONINDEX or SHGFI_SMALLICON or OpenFlags[OpenIcon]) <> 0 then Result := FileInfo.iIcon else Result := 0; end; function GetDefFolderImageIndex(const OpenIcon: Boolean): Integer; const OpenFlags: array[Boolean] of UINT = (0, SHGFI_OPENICON); var FileInfo: TSHFileInfo; begin if SHGetFileInfo('c:\directory', FILE_ATTRIBUTE_DIRECTORY, FileInfo, SizeOf(FileInfo), SHGFI_USEFILEATTRIBUTES or SHGFI_SYSICONINDEX or SHGFI_SMALLICON or OpenFlags[OpenIcon]) <> 0 then Result := FileInfo.iIcon else Result := 0; end; function IsNetworkDrive(const Drive: Char): Boolean; { Returns True if Drive is a network drive. Unlike GetLogicalDrives and GetDriveType, this will find the drive even if it's currently in an unavailable/disconnected state (i.e. showing a red "X" on the drive icon in Windows Explorer). } var LocalName: String; RemoteName: array[0..MAX_PATH-1] of Char; RemoteNameLen, ErrorCode: DWORD; begin LocalName := Drive + ':'; RemoteNameLen := SizeOf(RemoteName) div SizeOf(RemoteName[0]); ErrorCode := WNetGetConnection(PChar(LocalName), RemoteName, RemoteNameLen); Result := (ErrorCode = NO_ERROR) or (ErrorCode = ERROR_CONNECTION_UNAVAIL); end; function MoveAppWindowToActiveWindowMonitor(var OldRect: TRect): Boolean; { This moves the application window (Application.Handle) to the same monitor as the active window, so that a subsequent Windows dialog will display on the same monitor. Based on code from D4+'s TApplication.MessageBox. NOTE: This function was copied from CmnFunc.pas. } type HMONITOR = type THandle; TMonitorInfo = record cbSize: DWORD; rcMonitor: TRect; rcWork: TRect; dwFlags: DWORD; end; const MONITOR_DEFAULTTONEAREST = $00000002; var ActiveWindow: HWND; Module: HMODULE; MonitorFromWindow: function(hwnd: HWND; dwFlags: DWORD): HMONITOR; stdcall; GetMonitorInfo: function(hMonitor: HMONITOR; var lpmi: TMonitorInfo): BOOL; stdcall; MBMonitor, AppMonitor: HMONITOR; Info: TMonitorInfo; begin Result := False; ActiveWindow := GetActiveWindow; if ActiveWindow = 0 then Exit; Module := GetModuleHandle(user32); MonitorFromWindow := GetProcAddress(Module, 'MonitorFromWindow'); GetMonitorInfo := GetProcAddress(Module, 'GetMonitorInfoA'); if Assigned(MonitorFromWindow) and Assigned(GetMonitorInfo) then begin MBMonitor := MonitorFromWindow(ActiveWindow, MONITOR_DEFAULTTONEAREST); AppMonitor := MonitorFromWindow(Application.Handle, MONITOR_DEFAULTTONEAREST); if MBMonitor <> AppMonitor then begin Info.cbSize := SizeOf(Info); if GetMonitorInfo(MBMonitor, Info) then begin GetWindowRect(Application.Handle, OldRect); SetWindowPos(Application.Handle, 0, Info.rcMonitor.Left + ((Info.rcMonitor.Right - Info.rcMonitor.Left) div 2), Info.rcMonitor.Top + ((Info.rcMonitor.Bottom - Info.rcMonitor.Top) div 2), 0, 0, SWP_NOACTIVATE or SWP_NOREDRAW or SWP_NOSIZE or SWP_NOZORDER); Result := True; end; end; end; end; procedure MoveAppWindowBack(const OldRect: TRect); { Moves the application window back to its previous position after a successful call to MoveAppWindowToActiveWindowMonitor } begin SetWindowPos(Application.Handle, 0, OldRect.Left + ((OldRect.Right - OldRect.Left) div 2), OldRect.Top + ((OldRect.Bottom - OldRect.Top) div 2), 0, 0, SWP_NOACTIVATE or SWP_NOREDRAW or SWP_NOSIZE or SWP_NOZORDER); end; function EnsurePathIsAccessible(const Path: String): Boolean; { Calls SHPathPrepareForWrite which ensures the specified path is accessible by reconnecting network drives (important) and prompting for media on removable drives (not so important for our purposes). (Note that despite its name, the function does not test for write access.) } var ActiveWindow: HWND; DidMove: Boolean; OldRect: TRect; WindowList: Pointer; begin { SHPathPrepareForWrite only exists on Windows 2000, Me, and later. Do nothing on older versions of Windows. } if @SHPathPrepareForWriteFunc = nil then begin Result := True; Exit; end; { Note: The SHPathPrepareForWrite documentation claims that "user interface windows will not be created" when hwnd is NULL, however I found that on Windows 2000, it would still display message boxes for network errors. (To reproduce: Disable your Local Area Connection and try expanding a network drive.) So to avoid bugs from having unowned message boxes floating around, go ahead and pass a proper owner window. } ActiveWindow := GetActiveWindow; DidMove := MoveAppWindowToActiveWindowMonitor(OldRect); WindowList := DisableTaskWindows(0); try Result := SUCCEEDED(SHPathPrepareForWriteFunc(Application.Handle, nil, PChar(Path), SHPPFW_NONE)); finally if DidMove then MoveAppWindowBack(OldRect); EnableTaskWindows(WindowList); SetActiveWindow(ActiveWindow); end; end; function UseFriendlyTree: Boolean; { Returns True if running Windows XP or 2003 and the "Display simple folder view" option in Explorer is enabled (by default, it is). Note: Windows Vista also has this option, but regardless of how it is set, folders never expand with a single click in Explorer. So on Vista and later, False is always returned. } var Ver: Word; K: HKEY; Typ, Value, Size: DWORD; begin Ver := Word(GetVersion); if (Lo(Ver) = 5) and (Hi(Ver) >= 1) then begin Result := True; if RegOpenKeyEx(HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced', 0, KEY_QUERY_VALUE, K) = ERROR_SUCCESS then begin Size := SizeOf(Value); if (RegQueryValueEx(K, 'FriendlyTree', nil, @Typ, @Value, @Size) = ERROR_SUCCESS) and (Typ = REG_DWORD) and (Size = SizeOf(Value)) then Result := (Value <> 0); RegCloseKey(K); end; end else Result := False; end; { TCustomFolderTreeView } type PItemData = ^TItemData; TItemData = record Name: String; NewItem: Boolean; ChildrenAdded: Boolean; end; constructor TCustomFolderTreeView.Create(AOwner: TComponent); var LogFont: TLogFont; begin inherited; ControlStyle := ControlStyle - [csCaptureMouse]; Width := 121; Height := 97; ParentColor := False; TabStop := True; if Lo(GetVersion) < 6 then Cursor := crArrow; { prevent hand cursor from appearing in TVS_TRACKSELECT mode } if SystemParametersInfo(SPI_GETICONTITLELOGFONT, SizeOf(LogFont), @LogFont, 0) then Font.Handle := CreateFontIndirect(LogFont); end; procedure TCustomFolderTreeView.CreateParams(var Params: TCreateParams); const TVS_TRACKSELECT = $0200; TVS_SINGLEEXPAND = $0400; begin InitCommonControls; inherited; CreateSubClass(Params, WC_TREEVIEW); with Params do begin Style := Style or WS_CLIPCHILDREN or WS_CLIPSIBLINGS or TVS_LINESATROOT or TVS_HASBUTTONS or TVS_SHOWSELALWAYS or TVS_EDITLABELS; FFriendlyTree := UseFriendlyTree; if FFriendlyTree then Style := Style or TVS_TRACKSELECT or TVS_SINGLEEXPAND else begin if Lo(GetVersion) >= 6 then Style := Style or TVS_TRACKSELECT else Style := Style or TVS_HASLINES; end; ExStyle := ExStyle or WS_EX_CLIENTEDGE; WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW); end; end; procedure TCustomFolderTreeView.CreateWnd; var ImageList: HIMAGELIST; FileInfo: TSHFileInfo; SaveCursor: HCURSOR; begin FDestroyingHandle := False; inherited; FDirectory := ''; if csDesigning in ComponentState then Exit; { On Vista, enable the new Explorer-style look } if (Lo(GetVersion) >= 6) and Assigned(SetWindowTheme) then begin SetWindowTheme(Handle, 'Explorer', nil); { Like Explorer, enable double buffering to avoid flicker when the mouse is moved across the items } SendMessage(Handle, TVM_SETEXTENDEDSTYLE, TVS_EX_DOUBLEBUFFER, TVS_EX_DOUBLEBUFFER); end; { Initialize the image list } ImageList := SHGetFileInfo('', 0, FileInfo, SizeOf(FileInfo), SHGFI_USEFILEATTRIBUTES or SHGFI_SYSICONINDEX or SHGFI_SMALLICON); TreeView_SetImageList(Handle, ImageList, TVSIL_NORMAL); { Add the root items } SaveCursor := SetCursor(LoadCursor(0, IDC_WAIT)); try ItemChildrenNeeded(nil); finally SetCursor(SaveCursor); end; end; procedure TCustomFolderTreeView.WMDestroy(var Message: TWMDestroy); begin { Work around bug in pre-v6 COMCTL32: If we have the TVS_SINGLEEXPAND style and there is a selected item when the window is destroyed, we end up getting a bunch of TVN_SINGLEEXPAND messages because it keeps moving the selection as it's destroying items, resulting in a stream of "Please insert a disk in drive X:" message boxes as the selection moves across removable drives. Currently, however, this problem isn't seen in practice because we don't use TVS_SINGLEEXPAND on pre-XP Windows. } FDestroyingHandle := True; { disables our TVN_SELCHANGED handling } SelectItem(nil); inherited; end; procedure TCustomFolderTreeView.KeyDown(var Key: Word; Shift: TShiftState); var Item: HTREEITEM; begin inherited; if (Key = VK_F2) and (Shift * [ssShift, ssAlt, ssCtrl] = []) then begin Key := 0; Item := TreeView_GetSelection(Handle); if Assigned(Item) then TreeView_EditLabel(Handle, Item); end; end; procedure TCustomFolderTreeView.CNKeyDown(var Message: TWMKeyDown); var FocusWnd: HWND; begin { On Delphi 5+, if a non-VCL control is focused, TApplication.IsKeyMsg will send the CN_KEYDOWN message to the nearest VCL control. This means that when the edit control is focused, the tree view itself gets CN_KEYDOWN messages. Don't let the VCL handle Enter and Escape; if we're on a dialog, those keys will close the window. } FocusWnd := GetFocus; if (FocusWnd <> 0) and (TreeView_GetEditControl(Handle) = FocusWnd) then if (Message.CharCode = VK_RETURN) or (Message.CharCode = VK_ESCAPE) then Exit; inherited; end; procedure TCustomFolderTreeView.WMEraseBkgnd(var Message: TWMEraseBkgnd); begin { For TVS_EX_DOUBLEBUFFER to be truly flicker-free on Vista, we must use comctl32's default WM_ERASEBKGND handling, not the VCL's (which calls FillRect). } DefaultHandler(Message); end; procedure TCustomFolderTreeView.WMCtlColorEdit(var Message: TMessage); begin { We can't let TWinControl.DefaultHandler handle this message. It tries to send a CN_CTLCOLOREDIT message to the tree view's internally-created edit control, which it won't understand because it's not a VCL control. Without this special handling, the border is painted incorrectly on Windows XP with themes enabled. } Message.Result := DefWindowProc(Handle, Message.Msg, Message.WParam, Message.LParam); end; function TCustomFolderTreeView.GetItemFullPath(Item: HTREEITEM): String; var TVItem: TTVItem; begin Result := ''; while Assigned(Item) do begin TVItem.mask := TVIF_PARAM; TVItem.hItem := Item; if not TreeView_GetItem(Handle, TVItem) then begin Result := ''; Exit; end; if Result = '' then Result := PItemData(TVItem.lParam).Name else Insert(AddBackslash(PItemData(TVItem.lParam).Name), Result, 1); Item := TreeView_GetParent(Handle, Item); end; end; procedure TCustomFolderTreeView.Change; var Item: HTREEITEM; begin Item := TreeView_GetSelection(Handle); if Assigned(Item) then FDirectory := GetItemFullPath(Item) else FDirectory := ''; if Assigned(FOnChange) then FOnChange(Self); end; procedure TCustomFolderTreeView.CNNotify(var Message: TWMNotify); const TVN_SINGLEEXPAND = (TVN_FIRST-15); TVNRET_SKIPOLD = 1; TVNRET_SKIPNEW = 2; procedure HandleClick; var Item: HTREEITEM; HitTestInfo: TTVHitTestInfo; begin HitTestInfo.pt := ScreenToClient(SmallPointToPoint(TSmallPoint(GetMessagePos()))); Item := TreeView_HitTest(Handle, HitTestInfo); if Assigned(Item) then begin if HitTestInfo.flags and TVHT_ONITEMBUTTON <> 0 then TreeView_Expand(Handle, Item, TVE_TOGGLE) else begin if TreeView_GetSelection(Handle) <> Item then SelectItem(Item) else begin { In 'friendly tree' mode, if the item is already selected, ensure it's expanded. Note: We do this only if SelectItem wasn't called, since newly selected items are expanded automatically. If we were to call this unconditionally, any error message would be shown twice. } if FFriendlyTree and (HitTestInfo.flags and TVHT_ONITEM <> 0) then TreeView_Expand(Handle, Item, TVE_EXPAND); end; end; end; end; var Hdr: PNMTreeView; SaveCursor: HCURSOR; DispItem: PTVItem; TVItem: TTVItem; S: String; Accept: Boolean; begin inherited; case Message.NMHdr.code of TVN_DELETEITEM: begin Dispose(PItemData(PNMTreeView(Message.NMHdr).itemOld.lParam)); end; TVN_ITEMEXPANDING: begin { Sanity check: Make sure this message isn't sent recursively. (See top of source code for details.) } if FItemExpanding then raise Exception.Create('Internal error: Item already expanding'); FItemExpanding := True; try Hdr := PNMTreeView(Message.NMHdr); if (Hdr.action = TVE_EXPAND) and not PItemData(Hdr.itemNew.lParam).ChildrenAdded and not PItemData(Hdr.itemNew.lParam).NewItem then begin PItemData(Hdr.itemNew.lParam).ChildrenAdded := True; SaveCursor := SetCursor(LoadCursor(0, IDC_WAIT)); try if ItemChildrenNeeded(Hdr.itemNew.hItem) then begin { If no subfolders were found, and there are no 'new' items underneath the parent item, remove the '+' sign } if TreeView_GetChild(Handle, Hdr.itemNew.hItem) = nil then SetItemHasChildren(Hdr.itemNew.hItem, False); end else begin { A result of False means no children were added due to a temporary error and that it should try again next time } PItemData(Hdr.itemNew.lParam).ChildrenAdded := False; { Return 1 to cancel the expansion process (although it seems to do that anyway when it sees no children were added) } Message.Result := 1; end; finally SetCursor(SaveCursor); end; end; finally FItemExpanding := False; end; end; TVN_GETDISPINFO: begin DispItem := @PTVDispInfo(Message.NMHdr).item; if DispItem.mask and TVIF_IMAGE <> 0 then begin DispItem.iImage := GetItemImageIndex(DispItem.hItem, PItemData(DispItem.lParam).NewItem, False); end; if DispItem.mask and TVIF_SELECTEDIMAGE <> 0 then begin DispItem.iSelectedImage := GetItemImageIndex(DispItem.hItem, PItemData(DispItem.lParam).NewItem, True); end; if DispItem.mask and TVIF_CHILDREN <> 0 then begin DispItem.cChildren := Ord(Assigned(TreeView_GetChild(Handle, DispItem.hItem))); if (DispItem.cChildren = 0) and not PItemData(DispItem.lParam).NewItem then DispItem.cChildren := Ord(ItemHasChildren(DispItem.hItem)); end; { Store the values with the item so the callback isn't called again } DispItem.mask := DispItem.mask or TVIF_DI_SETITEM; end; TVN_SELCHANGED: begin if not FDestroyingHandle then Change; end; TVN_BEGINLABELEDIT: begin DispItem := @PTVDispInfo(Message.NMHdr).item; { Only 'new' items may be renamed } if not PItemData(DispItem.lParam).NewItem then Message.Result := 1; end; TVN_ENDLABELEDIT: begin DispItem := @PTVDispInfo(Message.NMHdr).item; { Only 'new' items may be renamed } if PItemData(DispItem.lParam).NewItem and Assigned(DispItem.pszText) then begin S := DispItem.pszText; Accept := True; if Assigned(FOnRename) then FOnRename(Self, S, Accept); if Accept then begin PItemData(DispItem.lParam).Name := S; { Instead of returning 1 to let the tree view update the text, set the text ourself. This will downconvert any Unicode characters to ANSI (if we're compiled as an ANSI app). } TVItem.mask := TVIF_TEXT; TVItem.hItem := DispItem.hItem; TVItem.pszText := PChar(S); TreeView_SetItem(Handle, TVItem); TreeView_SortChildren(Handle, TreeView_GetParent(Handle, DispItem.hItem), {$IFDEF IS_DXE2}False{$ELSE}0{$ENDIF}); Change; end; end; end; NM_CLICK: begin { Use custom click handler to work more like Windows XP Explorer: - Items can be selected by clicking anywhere on their respective rows, except for the button. - In 'friendly tree' mode, clicking an item's icon or caption causes the item to expand, but never to collapse. } HandleClick; Message.Result := 1; end; TVN_SINGLEEXPAND: begin Hdr := PNMTreeView(Message.NMHdr); { Trying to emulate Windows XP's Explorer here: Only collapse old item if it's at the same level as the new item. } if Assigned(Hdr.itemOld.hItem) and Assigned(Hdr.itemNew.hItem) and (TreeView_GetParent(Handle, Hdr.itemNew.hItem) <> TreeView_GetParent(Handle, Hdr.itemOld.hItem)) then Message.Result := Message.Result or TVNRET_SKIPOLD; { Selecting expanded items shouldn't collapse them } if Assigned(Hdr.itemNew.hItem) then begin TVItem.mask := TVIF_STATE; TVItem.hItem := Hdr.itemNew.hItem; TVItem.stateMask := TVIS_EXPANDED; if TreeView_GetItem(Handle, TVItem) and (TVItem.state and TVIS_EXPANDED <> 0) then Message.Result := Message.Result or TVNRET_SKIPNEW; end; end; end; end; procedure TCustomFolderTreeView.SetItemHasChildren(const Item: HTREEITEM; const AHasChildren: Boolean); var TVItem: TTVItem; begin TVItem.mask := TVIF_CHILDREN; TVItem.hItem := Item; TVItem.cChildren := Ord(AHasChildren); TreeView_SetItem(Handle, TVItem); end; procedure TCustomFolderTreeView.DeleteObsoleteNewItems(const ParentItem, ItemToKeep: HTREEITEM); { Destroys all 'new' items except for ItemToKeep and its parents. (ItemToKeep doesn't necessarily have to be a 'new' item.) Pass nil in the ParentItem parameter when calling this method. } function EqualsOrContains(const AParent: HTREEITEM; AChild: HTREEITEM): Boolean; begin Result := False; repeat if AChild = AParent then begin Result := True; Break; end; AChild := TreeView_GetParent(Handle, AChild); until AChild = nil; end; var Item, NextItem: HTREEITEM; TVItem: TTVItem; begin Item := TreeView_GetChild(Handle, ParentItem); while Assigned(Item) do begin { Determine the next item in advance since Item might get deleted } NextItem := TreeView_GetNextSibling(Handle, Item); TVItem.mask := TVIF_PARAM; TVItem.hItem := Item; if TreeView_GetItem(Handle, TVItem) then begin if PItemData(TVItem.lParam).NewItem and not EqualsOrContains(Item, ItemToKeep) then begin TreeView_DeleteItem(Handle, Item); { If there are no children left on the parent, remove its '+' sign } if TreeView_GetChild(Handle, ParentItem) = nil then SetItemHasChildren(ParentItem, False); end else DeleteObsoleteNewItems(Item, ItemToKeep); end; Item := NextItem; end; end; function TCustomFolderTreeView.InsertItem(const ParentItem: HTREEITEM; const AName, ACustomDisplayName: String; const ANewItem: Boolean): HTREEITEM; var InsertStruct: TTVInsertStruct; ItemData: PItemData; begin if ANewItem then DeleteObsoleteNewItems(nil, ParentItem); InsertStruct.hParent := ParentItem; if ANewItem then InsertStruct.hInsertAfter := TVI_SORT else InsertStruct.hInsertAfter := TVI_LAST; InsertStruct.item.mask := TVIF_TEXT or TVIF_IMAGE or TVIF_SELECTEDIMAGE or TVIF_CHILDREN or TVIF_PARAM; InsertStruct.item.hItem := nil; { not used } if ANewItem then begin InsertStruct.item.mask := InsertStruct.item.mask or TVIF_STATE; InsertStruct.item.stateMask := TVIS_CUT; InsertStruct.item.state := TVIS_CUT; end; { Note: There's no performance advantage in using a callback for the text. During a TreeView_InsertItem call, the tree view will try to read the new item's text in order to update the horizontal scroll bar range. (It doesn't wait until the item is painted.) In addition, the caller may sort newly-inserted subitems, which obviously requires reading their text. } if ACustomDisplayName = '' then InsertStruct.item.pszText := PChar(AName) else InsertStruct.item.pszText := PChar(ACustomDisplayName); InsertStruct.item.iImage := I_IMAGECALLBACK; InsertStruct.item.iSelectedImage := I_IMAGECALLBACK; if ANewItem then InsertStruct.item.cChildren := 0 else begin if ParentItem = nil then InsertStruct.item.cChildren := 1 else InsertStruct.item.cChildren := I_CHILDRENCALLBACK; end; InsertStruct.item.lParam := 0; New(ItemData); ItemData.Name := AName; ItemData.NewItem := ANewItem; ItemData.ChildrenAdded := False; Pointer(InsertStruct.item.lParam) := ItemData; Result := TreeView_InsertItem(Handle, InsertStruct); end; function TCustomFolderTreeView.FindItem(const ParentItem: HTREEITEM; const AName: String): HTREEITEM; var TVItem: TTVItem; begin Result := TreeView_GetChild(Handle, ParentItem); while Assigned(Result) do begin TVItem.mask := TVIF_PARAM; TVItem.hItem := Result; if TreeView_GetItem(Handle, TVItem) then if PathCompare(PItemData(TVItem.lParam).Name, AName) = 0 then Break; Result := TreeView_GetNextSibling(Handle, Result); end; end; function TCustomFolderTreeView.FindOrCreateItem(const ParentItem: HTREEITEM; const AName: String): HTREEITEM; begin Result := FindItem(ParentItem, AName); if Result = nil then begin if Assigned(ParentItem) then SetItemHasChildren(ParentItem, True); Result := InsertItem(ParentItem, AName, '', True); end; end; function TCustomFolderTreeView.GetRootItem: HTREEITEM; begin Result := nil; end; procedure TCustomFolderTreeView.SelectItem(const Item: HTREEITEM); procedure ExpandParents(Item: HTREEITEM); begin Item := TreeView_GetParent(Handle, Item); if Assigned(Item) then begin ExpandParents(Item); TreeView_Expand(Handle, Item, TVE_EXPAND); end; end; begin { Must manually expand parents prior to calling TreeView_SelectItem; see top of source code for details } if Assigned(Item) then ExpandParents(Item); TreeView_SelectItem(Handle, Item); end; function TCustomFolderTreeView.TryExpandItem(const Item: HTREEITEM): Boolean; { Tries to expand the specified item. Returns True if the item's children were initialized (if any), or False if the initialization failed due to a temporary error (i.e. ItemChildrenNeeded returned False). } var TVItem: TTVItem; begin TreeView_Expand(Handle, Item, TVE_EXPAND); TVItem.mask := TVIF_CHILDREN or TVIF_PARAM; TVItem.hItem := Item; Result := TreeView_GetItem(Handle, TVItem) and (PItemData(TVItem.lParam).ChildrenAdded or (TVItem.cChildren = 0)); end; procedure TCustomFolderTreeView.ChangeDirectory(const Value: String; const CreateNewItems: Boolean); { Changes to the specified directory. Value must begin with a drive letter (e.g. "C:\directory"); relative paths and UNC paths are not allowed. If CreateNewItems is True, new items will be created if one or more elements of the path do not exist. } var PStart, PEnd: PChar; S: String; ParentItem, Item: HTREEITEM; begin SelectItem(nil); ParentItem := GetRootItem; PStart := PChar(Value); while PStart^ <> #0 do begin if Assigned(ParentItem) then if not TryExpandItem(ParentItem) then Break; { Extract a single path component } PEnd := PStart; while (PEnd^ <> #0) and not PathCharIsSlash(PEnd^) do PEnd := PathStrNextChar(PEnd); SetString(S, PStart, PEnd - PStart); { Find that component under ParentItem } if CreateNewItems and Assigned(ParentItem) then Item := FindOrCreateItem(ParentItem, S) else Item := FindItem(ParentItem, S); if Item = nil then Break; ParentItem := Item; PStart := PEnd; while PathCharIsSlash(PStart^) do Inc(PStart); end; if Assigned(ParentItem) then SelectItem(ParentItem); end; procedure TCustomFolderTreeView.SetDirectory(const Value: String); begin ChangeDirectory(Value, False); end; procedure TCustomFolderTreeView.CreateNewDirectory(const ADefaultName: String); { Creates a new node named AName underneath the selected node. Does nothing if there is no selected node. } var ParentItem, Item: HTREEITEM; I: Integer; S: String; begin ParentItem := TreeView_GetSelection(Handle); if ParentItem = nil then Exit; DeleteObsoleteNewItems(nil, ParentItem); { Expand and find a unique name } if not TryExpandItem(ParentItem) then Exit; I := 0; repeat Inc(I); if I = 1 then S := ADefaultName else S := ADefaultName + Format(' (%d)', [I]); until FindItem(ParentItem, S) = nil; SetItemHasChildren(ParentItem, True); Item := InsertItem(ParentItem, S, '', True); SelectItem(Item); if CanFocus then SetFocus; TreeView_EditLabel(Handle, Item); end; { TFolderTreeView } function TFolderTreeView.ItemChildrenNeeded(const Item: HTREEITEM): Boolean; procedure AddDrives; var Drives: DWORD; Drive: Char; begin Drives := GetLogicalDrives; for Drive := 'A' to 'Z' do begin if (Drives and 1 <> 0) or IsNetworkDrive(Drive) then InsertItem(nil, Drive + ':', GetFileDisplayName(Drive + ':\'), False); Drives := Drives shr 1; end; end; function AddSubdirectories(const ParentItem: HTREEITEM; const Path: String): Boolean; var OldErrorMode: UINT; H: THandle; FindData: TWin32FindData; S: String; begin OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try { The path might be on a disconnected network drive. Ensure it's connected before attempting to enumerate subdirectories. } if Length(Path) = 3 then begin { ...only do this on the root } if not EnsurePathIsAccessible(Path) then begin Result := False; Exit; end; { Refresh the icon and text in case the drive was indeed reconnected } RefreshDriveItem(ParentItem, GetFileDisplayName(Path)); end; Result := True; H := FindFirstFile(PChar(AddBackslash(Path) + '*'), FindData); if H <> INVALID_HANDLE_VALUE then begin try repeat if IsListableDirectory(FindData) then begin S := FindData.cFileName; InsertItem(ParentItem, S, GetFileDisplayName(AddBackslash(Path) + S), False); end; until not FindNextFile(H, FindData); finally Windows.FindClose(H); end; end; finally SetErrorMode(OldErrorMode); end; end; begin if Item = nil then begin AddDrives; Result := True; end else begin Result := AddSubdirectories(Item, GetItemFullPath(Item)); if Result then begin { When a text callback is used, sorting after all items are inserted is exponentially faster than using hInsertAfter=TVI_SORT } TreeView_SortChildren(Handle, Item, {$IFDEF IS_DXE2}False{$ELSE}0{$ENDIF}); end; end; end; function TFolderTreeView.GetItemFullPath(Item: HTREEITEM): String; begin Result := inherited GetItemFullPath(Item); if (Length(Result) = 2) and (Result[2] = ':') then Result := Result + '\'; end; function TFolderTreeView.GetItemImageIndex(const Item: HTREEITEM; const NewItem, SelectedImage: Boolean): Integer; begin if NewItem then Result := GetDefFolderImageIndex(SelectedImage) else Result := GetFileImageIndex(GetItemFullPath(Item), SelectedImage); end; function TFolderTreeView.ItemHasChildren(const Item: HTREEITEM): Boolean; var Path: String; OldErrorMode: UINT; begin Path := GetItemFullPath(Item); OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try Result := (GetDriveType(PChar(AddBackslash(PathExtractDrive(Path)))) = DRIVE_REMOTE) or HasSubfolders(Path); finally SetErrorMode(OldErrorMode); end; end; procedure TFolderTreeView.RefreshDriveItem(const Item: HTREEITEM; const ANewDisplayName: String); var TVItem: TTVItem; begin TVItem.mask := TVIF_IMAGE or TVIF_SELECTEDIMAGE; TVItem.hItem := Item; TVItem.iImage := I_IMAGECALLBACK; TVItem.iSelectedImage := I_IMAGECALLBACK; if ANewDisplayName <> '' then begin TVItem.mask := TVItem.mask or TVIF_TEXT; TVItem.pszText := PChar(ANewDisplayName); end; TreeView_SetItem(Handle, TVItem); end; { TStartMenuFolderTreeView } procedure TStartMenuFolderTreeView.CreateParams(var Params: TCreateParams); begin inherited; Params.Style := Params.Style and not TVS_LINESATROOT; end; function TStartMenuFolderTreeView.GetItemImageIndex(const Item: HTREEITEM; const NewItem, SelectedImage: Boolean): Integer; begin Result := FImageIndexes[SelectedImage]; end; function TStartMenuFolderTreeView.GetRootItem: HTREEITEM; begin { The top item ('Programs') is considered the root } Result := TreeView_GetRoot(Handle); end; function TStartMenuFolderTreeView.ItemChildrenNeeded(const Item: HTREEITEM): Boolean; procedure AddSubfolders(const ParentItem: HTREEITEM; const Path, StartupPath: String); var StartupName: String; OldErrorMode: UINT; H: THandle; FindData: TWin32FindData; S: String; begin { Determine the name of the Startup folder so that we can hide it from the list } if StartupPath <> '' then if PathCompare(AddBackslash(Path), PathExtractPath(StartupPath)) = 0 then StartupName := PathExtractName(StartupPath); OldErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS); try H := FindFirstFile(PChar(AddBackslash(Path) + '*'), FindData); if H <> INVALID_HANDLE_VALUE then begin try repeat if IsListableDirectory(FindData) then begin S := FindData.cFileName; if PathCompare(S, StartupName) <> 0 then if FindItem(ParentItem, S) = nil then InsertItem(ParentItem, S, GetFileDisplayName(AddBackslash(Path) + S), False); end; until not FindNextFile(H, FindData); finally Windows.FindClose(H); end; end; finally SetErrorMode(OldErrorMode); end; end; var Root, S: String; NewItem: HTREEITEM; Path: String; begin Result := True; if Item = nil then begin Root := FUserPrograms; if Root = '' then begin { User programs folder doesn't exist for some reason? } Root := FCommonPrograms; if Root = '' then Exit; end; FImageIndexes[False] := GetFileImageIndex(Root, False); FImageIndexes[True] := FImageIndexes[False]; S := GetFileDisplayName(Root); if S = '' then S := PathExtractName(Root); NewItem := InsertItem(nil, '', S, False); TreeView_Expand(Handle, NewItem, TVE_EXPAND); end else begin Path := GetItemFullPath(Item); if FCommonPrograms <> '' then AddSubfolders(Item, AddBackslash(FCommonPrograms) + Path, FCommonStartup); if FUserPrograms <> '' then AddSubfolders(Item, AddBackslash(FUserPrograms) + Path, FUserStartup); TreeView_SortChildren(Handle, Item, {$IFDEF IS_DXE2}False{$ELSE}0{$ENDIF}); end; end; function TStartMenuFolderTreeView.ItemHasChildren(const Item: HTREEITEM): Boolean; var Path: String; begin Path := GetItemFullPath(Item); if (FCommonPrograms <> '') and HasSubfolders(AddBackslash(FCommonPrograms) + Path) then Result := True else if (FUserPrograms <> '') and HasSubfolders(AddBackslash(FUserPrograms) + Path) then Result := True else Result := False; end; procedure TStartMenuFolderTreeView.SetPaths(const AUserPrograms, ACommonPrograms, AUserStartup, ACommonStartup: String); begin FUserPrograms := AUserPrograms; FCommonPrograms := ACommonPrograms; FUserStartup := AUserStartup; FCommonStartup := ACommonStartup; RecreateWnd; end; function GetSystemDir: String; var Buf: array[0..MAX_PATH-1] of Char; begin GetSystemDirectory(Buf, SizeOf(Buf) div SizeOf(Buf[0])); Result := StrPas(Buf); end; initialization InitThemeLibrary; SHPathPrepareForWriteFunc := GetProcAddress(LoadLibrary(PChar(AddBackslash(GetSystemDir) + shell32)), {$IFDEF UNICODE}'SHPathPrepareForWriteW'{$ELSE}'SHPathPrepareForWriteA'{$ENDIF}); end.
34.669967
126
0.686435
f13de6f395804147d2fee39e89e58f28e45fe11e
7,106
pas
Pascal
service/uprocessexecute.pas
itfx3035/lazarus-freepascal-ims
b411f18490dbee0a7b37fe6bb74cb96ba523bae0
[ "MIT" ]
null
null
null
service/uprocessexecute.pas
itfx3035/lazarus-freepascal-ims
b411f18490dbee0a7b37fe6bb74cb96ba523bae0
[ "MIT" ]
null
null
null
service/uprocessexecute.pas
itfx3035/lazarus-freepascal-ims
b411f18490dbee0a7b37fe6bb74cb96ba523bae0
[ "MIT" ]
null
null
null
unit uProcessExecute; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Process, uStrUtils, uLog {$IFDEF WINDOWS} ,windows {$ENDIF}; type TBatchToExecute = record exec_param: string; exec_wait_finish: boolean; exec_timeout: string; exec_write_log: boolean; end; TThreadProcessExecuter = class(TThread) private { Private declarations } trParam: string; trSudoPwd: string; trTimeout: integer; trWriteResult: boolean; resSL: TStringList; trLogMsg: string; procedure WriteResToLog; procedure toReportMSG; procedure trWriteReportMSG(msg_str: string); protected { Protected declarations } procedure Execute; override; public constructor Create(param, sudo_pwd: string; timeout: integer; write_result: boolean); end; function ExecuteAndWaitOutput(param,sudo_pwd: string; timeout_sec: integer): TStringList; procedure ExecuteAndNoWait(param,sudo_pwd: string; timeout_sec: integer; write_result: boolean); function CheckAdminPrev(sudo_pwd:string):boolean; implementation function CheckAdminPrev(sudo_pwd:string):boolean; var w_path:array[0..1024] of char; fp:string; tf:textfile; begin {$IFDEF UNIX} fp:='/etc/tmp_adm_f_ch.tmp'; try ExecuteAndWaitOutput('dd if=/dev/zero of='+fp+' bs=1k count=1', sudo_pwd, 10); except end; if fileexists(fp) then begin result:=true; end else begin Result:=false; end; try ExecuteAndWaitOutput('rm -f '+fp, sudo_pwd, 10); except end; {$ENDIF} {$IFDEF WINDOWS} windows.GetSystemDirectory(w_path,1024); fp:=string(w_path)+'\tmp_adm_f_ch.txt'; try AssignFile(tf,fp); rewrite(tf); writeln(tf,fp); except end; try closefile(tf); except end; if FileExists(fp) then begin result:=true; end else begin Result:=false; end; try SysUtils.DeleteFile(fp); except end; {$ENDIF} end; constructor TThreadProcessExecuter.Create(param, sudo_pwd: string; timeout: integer; write_result: boolean); begin inherited Create(False); FreeOnTerminate := True; trParam := param; trSudoPwd:= sudo_pwd; trTimeout := timeout; trWriteResult := write_result; end; procedure TThreadProcessExecuter.Execute; var iserr: boolean; begin iserr := False; trWriteReportMSG('4 Thread ID: ' + IntToStr(Handle)+', executing ['+trParam+']'); try resSL := ExecuteAndWaitOutput(trParam, trSudoPwd, trTimeout); except iserr := True; end; if iserr then begin trWriteReportMSG('0 Thread ID: ' + IntToStr(Handle)+', error executing ['+trParam+']'); exit; end; if trWriteResult then begin //Synchronize(@WriteResToLog); WriteResToLog; end; trWriteReportMSG('4 Thread ID: ' + IntToStr(Handle) + ' execution finished.'); end; procedure TThreadProcessExecuter.trWriteReportMSG(msg_str: string); begin trLogMsg := msg_str; //Synchronize(@toReportMSG); toReportMSG; end; procedure TThreadProcessExecuter.toReportMSG; begin uLog.WriteReportMsg(trLogMsg); end; procedure TThreadProcessExecuter.WriteResToLog; var x: integer; begin for x := 1 to resSL.Count do begin uLog.WriteReportMsg('4 Thread ID ' + IntToStr(Handle) + ' - ' + resSL[x - 1]); end; end; procedure ExecuteAndNoWait(param,sudo_pwd: string; timeout_sec: integer; write_result: boolean); begin TThreadProcessExecuter.Create(param, sudo_pwd, timeout_sec, write_result); end; function ExecuteAndWaitOutput(param,sudo_pwd: string; timeout_sec: integer): TStringList; var MemStream: TMemoryStream; NumBytes: longint; BytesRead: longint; OurProcess: TProcess; begin_time: tdatetime; timeout_double: double; timeout_verb:string; term: boolean; SudoPassword:string; something_readed:boolean; BytesToRead:integer; begin MemStream := TMemoryStream.Create; BytesRead := 0; timeout_verb:='timeout '+inttostr(timeout_sec)+' '; if timeout_sec = 0 then begin timeout_sec := 999999999; timeout_verb:=''; end; timeout_double := timeout_sec / (24 * 3600); OurProcess := TProcess.Create(nil); {$IFDEF WINDOWS} OurProcess.CommandLine := param; {$ENDIF} // on linux we need to execute 'sudo' to get root, and set timeout // on windows our service must be executed under admin, so we don't need this {$IFDEF UNIX} if LeftStr(sudo_pwd,1)='1' then begin OurProcess.CommandLine := timeout_verb+'sudo -S '+param; end else begin OurProcess.CommandLine := timeout_verb+param; end; {$ENDIF} OurProcess.Options := [poUsePipes]; OurProcess.Execute; // input param sudo (pwd) writing after executing 'sudo' {$IFDEF UNIX} if LeftStr(sudo_pwd,1)='1' then begin SudoPassword:=''; SudoPassword := rightstr(sudo_pwd,length(sudo_pwd)-1) + LineEnding; OurProcess.Input.Write(SudoPassword[1], Length(SudoPassword)); SudoPassword:=''; end; {$ENDIF} begin_time := now; term := False; BytesToRead := 2048; while (OurProcess.Running) do begin something_readed:=false; // read stdout BytesToRead:=OurProcess.Output.NumBytesAvailable; if BytesToRead>0 then begin MemStream.SetSize(BytesRead + BytesToRead); NumBytes := OurProcess.Output.Read((MemStream.Memory + BytesRead)^, BytesToRead); if NumBytes > 0 then begin Inc(BytesRead, NumBytes); something_readed:=true; end; end; // read stderr BytesToRead:=OurProcess.Stderr.NumBytesAvailable; if BytesToRead>0 then begin MemStream.SetSize(BytesRead + BytesToRead); NumBytes := OurProcess.Stderr.Read((MemStream.Memory + BytesRead)^, BytesToRead); if NumBytes > 0 then begin Inc(BytesRead, NumBytes); something_readed:=true; end; end; // check time on windows, terminate our process if exceeded {$IFDEF WINDOWS} if (now - begin_time) > timeout_double then begin OurProcess.Terminate(1); end; {$ENDIF} if not something_readed then begin Sleep(100); // no output, waiting... end; end; // execution finished repeat MemStream.SetSize(BytesRead + 2048); NumBytes := OurProcess.Output.Read((MemStream.Memory + BytesRead)^, 2048); if NumBytes > 0 then begin Inc(BytesRead, NumBytes); end; until NumBytes <= 0; repeat MemStream.SetSize(BytesRead + 2048); NumBytes := OurProcess.Stderr.Read((MemStream.Memory + BytesRead)^, 2048); if NumBytes > 0 then begin Inc(BytesRead, NumBytes); end; until NumBytes <= 0; MemStream.SetSize(BytesRead); Result := TStringList.Create; Result.LoadFromStream(MemStream); OurProcess.Free; MemStream.Free; end; end.
23.529801
97
0.650155
c34a5eb0de13229cfb5d84bae9f8170089d92693
3,406
pas
Pascal
Web/SvHTTPClient.Mock.pas
godeargit/delphi-oop
bf1b63f60d4e34b3026f444f5f86c2590e51a346
[ "MIT" ]
3
2018-01-22T04:18:06.000Z
2020-01-09T16:46:18.000Z
Web/SvHTTPClient.Mock.pas
godeargit/delphi-oop
bf1b63f60d4e34b3026f444f5f86c2590e51a346
[ "MIT" ]
null
null
null
Web/SvHTTPClient.Mock.pas
godeargit/delphi-oop
bf1b63f60d4e34b3026f444f5f86c2590e51a346
[ "MIT" ]
1
2019-12-19T16:10:14.000Z
2019-12-19T16:10:14.000Z
unit SvHTTPClient.Mock; interface uses SvHTTPClient ,SvHTTPClientInterface ,Classes ; type TMockHttpClient = class(THTTPClient) private FConsumeMediaType: MEDIA_TYPE; FProduceMediaType: MEDIA_TYPE; protected procedure SetConsumeMediaType(const AMediaType: MEDIA_TYPE); override; function GetConsumeMediaType(): MEDIA_TYPE; override; function GetProduceMediaType: MEDIA_TYPE; override; procedure SetProduceMediaType(const Value: MEDIA_TYPE); override; public constructor Create(); override; destructor Destroy; override; procedure SetCustomRequestHeader(const AHeaderValue: string); override; procedure ClearCustomRequestHeaders(); override; function Delete(const AUrl: string): Integer; override; function Get(const AUrl: string; AResponse: TStream): Integer; override; function Post(const AUrl: string; AResponse: TStream; ASourceContent: TStream): Integer; override; function Put(const AUrl: string; AResponse: TStream; ASourceContent: TStream): Integer; override; function Head(const AUrl: string): Integer; override; function Options(const AUrl: string): Integer; override; procedure SetUpHttps(); override; function GetLastResponseCode(): Integer; override; function GetLastResponseText(): string; override; function GetLastResponseHeaders(): string; override; end; implementation uses SvHTTPClient.Factory ,SvWeb.Consts ; { TMockHttpClient } procedure TMockHttpClient.SetCustomRequestHeader(const AHeaderValue: string); begin inherited; end; procedure TMockHttpClient.ClearCustomRequestHeaders; begin inherited; end; constructor TMockHttpClient.Create; begin inherited; end; function TMockHttpClient.Delete(const AUrl: string): Integer; begin Result := 200; end; destructor TMockHttpClient.Destroy; begin inherited; end; function TMockHttpClient.Get(const AUrl: string; AResponse: TStream): Integer; begin Result := 200; end; function TMockHttpClient.GetConsumeMediaType: MEDIA_TYPE; begin Result := FConsumeMediaType; end; function TMockHttpClient.GetLastResponseCode: Integer; begin Result := 200; end; function TMockHttpClient.GetLastResponseHeaders: string; begin Result := ''; end; function TMockHttpClient.GetLastResponseText: string; begin Result := ''; end; function TMockHttpClient.GetProduceMediaType: MEDIA_TYPE; begin Result := FProduceMediaType; end; function TMockHttpClient.Head(const AUrl: string): Integer; begin Result := 200; end; function TMockHttpClient.Options(const AUrl: string): Integer; begin Result := 200; end; function TMockHttpClient.Post(const AUrl: string; AResponse, ASourceContent: TStream): Integer; begin Result := 200; end; function TMockHttpClient.Put(const AUrl: string; AResponse, ASourceContent: TStream): Integer; begin Result := 200; end; procedure TMockHttpClient.SetConsumeMediaType(const AMediaType: MEDIA_TYPE); begin FConsumeMediaType := AMediaType; end; procedure TMockHttpClient.SetProduceMediaType(const Value: MEDIA_TYPE); begin FProduceMediaType := Value; end; procedure TMockHttpClient.SetUpHttps; begin inherited; end; initialization TSvHTTPClientFactory.RegisterHTTPClient(HTTP_CLIENT_MOCK, TMockHttpClient); end.
22.556291
103
0.741926
fc62fe0bd77b896270d4758097521c40141b93f6
6,341
dfm
Pascal
Planer/Schiffsplaner.dfm
morrigan-dev/bbst
b9cacf3ec01af2b3e65064755d91b99aca25fb29
[ "Apache-2.0" ]
null
null
null
Planer/Schiffsplaner.dfm
morrigan-dev/bbst
b9cacf3ec01af2b3e65064755d91b99aca25fb29
[ "Apache-2.0" ]
null
null
null
Planer/Schiffsplaner.dfm
morrigan-dev/bbst
b9cacf3ec01af2b3e65064755d91b99aca25fb29
[ "Apache-2.0" ]
null
null
null
object frmPlaner: TfrmPlaner Left = 0 Top = 72 Width = 1211 Height = 657 Caption = 'Schiffsplaner' Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 8 Top = 560 Width = 32 Height = 13 Caption = 'Label1' end object Label2: TLabel Left = 192 Top = 56 Width = 32 Height = 13 Caption = 'Label2' end object Button1: TButton Left = 8 Top = 600 Width = 75 Height = 25 Caption = 'Button1' TabOrder = 0 OnClick = Button1Click end object maxModuls: TLabeledEdit Left = 8 Top = 16 Width = 65 Height = 21 EditLabel.Width = 60 EditLabel.Height = 13 EditLabel.Caption = 'max. Module' TabOrder = 1 Text = '20' end object techlevel: TLabeledEdit Left = 80 Top = 16 Width = 49 Height = 21 EditLabel.Width = 50 EditLabel.Height = 13 EditLabel.Caption = 'Techlevel:' TabOrder = 2 Text = '11' end object kommando: TLabeledEdit Left = 136 Top = 16 Width = 89 Height = 21 EditLabel.Width = 89 EditLabel.Height = 13 EditLabel.Caption = 'Kommandopunkte:' TabOrder = 3 Text = '60' end object angriffswert: TLabeledEdit Left = 232 Top = 16 Width = 57 Height = 21 EditLabel.Width = 58 EditLabel.Height = 13 EditLabel.Caption = 'Angriffswert:' TabOrder = 4 Text = '0' end object schilde: TLabeledEdit Left = 296 Top = 16 Width = 57 Height = 21 EditLabel.Width = 38 EditLabel.Height = 13 EditLabel.Caption = 'Schilde:' TabOrder = 5 Text = '0' end object panzer: TLabeledEdit Left = 360 Top = 16 Width = 57 Height = 21 EditLabel.Width = 54 EditLabel.Height = 13 EditLabel.Caption = 'Panzerung:' TabOrder = 6 Text = '0' end object struktur: TLabeledEdit Left = 424 Top = 16 Width = 57 Height = 21 EditLabel.Width = 40 EditLabel.Height = 13 EditLabel.Caption = 'Struktur:' TabOrder = 7 Text = '0' end object wendigkeit: TLabeledEdit Left = 488 Top = 16 Width = 57 Height = 21 EditLabel.Width = 57 EditLabel.Height = 13 EditLabel.Caption = 'Wendigkeit:' TabOrder = 8 Text = '0' end object ProgressBar1: TProgressBar Left = 8 Top = 576 Width = 953 Height = 16 Smooth = True TabOrder = 16 end object ListBox1: TListBox Left = 192 Top = 72 Width = 761 Height = 481 Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -9 Font.Name = 'MS Serif' Font.Style = [] ItemHeight = 11 ParentFont = False TabOrder = 17 OnClick = ListBox1Click end object ListBox2: TListBox Left = 960 Top = 72 Width = 233 Height = 481 ItemHeight = 13 TabOrder = 18 end object Button2: TButton Left = 88 Top = 600 Width = 75 Height = 25 Caption = 'Button2' TabOrder = 19 OnClick = Button2Click end object Reaktor: TLabeledEdit Left = 552 Top = 16 Width = 41 Height = 21 EditLabel.Width = 41 EditLabel.Height = 13 EditLabel.Caption = 'Reaktor:' TabOrder = 9 Text = '0' end object Laderaum: TLabeledEdit Left = 600 Top = 16 Width = 57 Height = 21 EditLabel.Width = 50 EditLabel.Height = 13 EditLabel.Caption = 'Laderaum:' TabOrder = 10 Text = '0' end object SektorSprung: TLabeledEdit Left = 752 Top = 16 Width = 65 Height = 21 EditLabel.Width = 68 EditLabel.Height = 13 EditLabel.Caption = 'SektorSprung:' TabOrder = 13 Text = '0' end object stop: TCheckBox Left = 176 Top = 600 Width = 97 Height = 17 Caption = 'Stop' TabOrder = 20 end object angriffszeit: TLabeledEdit Left = 824 Top = 16 Width = 57 Height = 21 EditLabel.Width = 54 EditLabel.Height = 13 EditLabel.Caption = 'Angriffszeit:' TabOrder = 14 Text = '0' end object Sprungzeit: TLabeledEdit Left = 888 Top = 16 Width = 57 Height = 21 EditLabel.Width = 53 EditLabel.Height = 13 EditLabel.Caption = 'Sprungzeit:' TabOrder = 15 Text = '0' end object Sensor: TLabeledEdit Left = 664 Top = 16 Width = 33 Height = 21 EditLabel.Width = 36 EditLabel.Height = 13 EditLabel.Caption = 'Sensor:' TabOrder = 11 Text = '0' end object Tarnung: TLabeledEdit Left = 704 Top = 16 Width = 41 Height = 21 EditLabel.Width = 43 EditLabel.Height = 13 EditLabel.Caption = 'Tarnung:' TabOrder = 12 Text = '0' end object Rumpf: TComboBox Left = 712 Top = 48 Width = 121 Height = 21 ItemHeight = 13 TabOrder = 21 OnChange = RumpfChange Items.Strings = ( 'Korvette' 'Fregatte' 'Frachtschiff' 'Tanker' 'Zerst'#246'rer' 'Versorgungsschiff' 'Waffenplattform' 'Kreuzer' '') end object Klasse: TComboBox Left = 840 Top = 48 Width = 113 Height = 21 ItemHeight = 13 TabOrder = 22 Text = 'Klasse' OnChange = KlasseChange end object Forschungen: TComboBox Left = 8 Top = 48 Width = 177 Height = 21 ItemHeight = 13 TabOrder = 23 Text = 'Forschungen' OnChange = ForschungenChange Items.Strings = ( 'alle' 'keine') end object Button3: TButton Left = 1008 Top = 556 Width = 147 Height = 14 Caption = 'save' TabOrder = 24 OnClick = Button3Click end object IsoKosten: TLabeledEdit Left = 952 Top = 16 Width = 33 Height = 21 EditLabel.Width = 22 EditLabel.Height = 13 EditLabel.Caption = 'Isos:' TabOrder = 25 Text = '0' end end
20.066456
42
0.560322
f1a85155964ce616183ca385fc08c93cec1626d9
512
pas
Pascal
app/src/main/assets/CodeSample/Graph/line.pas
tranleduy2000/pascalnide
c7f3f79ecf4cf6a81b32c7d389aad7f4034c8f01
[ "Apache-2.0" ]
81
2017-05-07T13:26:56.000Z
2022-03-03T19:39:15.000Z
app/src/main/assets/CodeSample/Graph/line.pas
tranleduy2000/pascalnide
c7f3f79ecf4cf6a81b32c7d389aad7f4034c8f01
[ "Apache-2.0" ]
52
2017-06-13T08:46:43.000Z
2021-06-09T09:50:07.000Z
app/src/main/assets/CodeSample/Graph/line.pas
tranleduy2000/pascalnide
c7f3f79ecf4cf6a81b32c7d389aad7f4034c8f01
[ "Apache-2.0" ]
28
2017-05-22T21:09:58.000Z
2021-09-07T13:05:27.000Z
Program draw_line; Uses Crt, Graph; Var graphicsDriver, graphicsMode, i, startX, startY, maxColor, color : Integer; Begin graphicsDriver := Detect; InitGraph(graphicsDriver, graphicsMode, ''); Randomize; startX := getMaxX(); startY := getMaxY(); maxColor := getMaxColor(); While (not keypressed) do Begin delay(50); color := random(maxColor) + 1; setColor(color); line(random(startX), random(startY), random(startX), random(startY)); end; ReadLn; CloseGraph; End.
18.962963
73
0.669922
c3b7fd574ea61ad46ad0f5ca39d3fd2fe0b1f46e
2,338
pas
Pascal
additional/bass/AnsiStringStream.pas
Tallefer/kspnew
57c69ac319c19e61ceb23e5a02759b98c9e4f8cd
[ "BSD-3-Clause" ]
1
2018-10-06T02:12:58.000Z
2018-10-06T02:12:58.000Z
additional/bass/AnsiStringStream.pas
Tallefer/kspnew
57c69ac319c19e61ceb23e5a02759b98c9e4f8cd
[ "BSD-3-Clause" ]
null
null
null
additional/bass/AnsiStringStream.pas
Tallefer/kspnew
57c69ac319c19e61ceb23e5a02759b98c9e4f8cd
[ "BSD-3-Clause" ]
1
2018-10-06T02:13:13.000Z
2018-10-06T02:13:13.000Z
unit AnsiStringStream; interface uses classes; type TAnsiStringStream = class(TStream) private FDataString: ansistring; FPosition: Integer; protected procedure SetSize(NewSize: Longint); override; public constructor Create(const AString: ansistring); function Read(var Buffer; Count: Longint): Longint; override; function ReadString(Count: Longint): ansistring; function Seek(Offset: Longint; Origin: Word): Longint; override; function Write(const Buffer; Count: Longint): Longint; override; procedure WriteString(const AString: ansistring); property DataString: ansistring read FDataString; end; implementation constructor TAnsiStringStream.Create(const AString: ansistring); begin inherited Create; FDataString := AString; end; function TAnsiStringStream.Read(var Buffer; Count: Longint): Longint; begin Result := Length(FDataString) - FPosition; if Result > Count then Result := Count; Move(PAnsiChar(@FDataString[FPosition + 1])^, Buffer, Result); Inc(FPosition, Result); end; function TAnsiStringStream.Write(const Buffer; Count: Longint): Longint; begin Result := Count; SetLength(FDataString, (FPosition + Result)); Move(Buffer, PAnsiChar(@FDataString[FPosition + 1])^, Result); Inc(FPosition, Result); end; function TAnsiStringStream.Seek(Offset: Longint; Origin: Word): Longint; begin case Origin of soFromBeginning: FPosition := Offset; soFromCurrent: FPosition := FPosition + Offset; soFromEnd: FPosition := Length(FDataString) - Offset; end; if FPosition > Length(FDataString) then FPosition := Length(FDataString) else if FPosition < 0 then FPosition := 0; Result := FPosition; end; function TAnsiStringStream.ReadString(Count: Longint): Ansistring; var Len: Integer; begin Len := Length(FDataString) - FPosition; if Len > Count then Len := Count; SetString(Result, PAnsiChar(@FDataString[FPosition + 1]), Len); Inc(FPosition, Len); end; procedure TAnsiStringStream.WriteString(const AString: Ansistring); begin Write(PAnsiChar(AString)^, Length(AString)); end; procedure TAnsiStringStream.SetSize(NewSize: Longint); begin SetLength(FDataString, NewSize); if FPosition > NewSize then FPosition := NewSize; end; end.
27.833333
73
0.715569
fcebe34388db5bbdf032a5526b45bdd3dbcd2ad2
25,361
pas
Pascal
src/Faker.pas
gaitolini/TFaker
fe242a29906d4d2194d26a45dabb15b0e7c5dcec
[ "MIT" ]
null
null
null
src/Faker.pas
gaitolini/TFaker
fe242a29906d4d2194d26a45dabb15b0e7c5dcec
[ "MIT" ]
null
null
null
src/Faker.pas
gaitolini/TFaker
fe242a29906d4d2194d26a45dabb15b0e7c5dcec
[ "MIT" ]
null
null
null
unit Faker; interface const /// <summary> /// Lorem Ipsum [...] /// </summary> LOREM_IPSUM = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.' + 'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.' + 'Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.' + 'Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'; /// <summary> /// Random Male/Female/Non-binary names /// </summary> NAMES: array [0 .. 266] of string = ('Mario Speedwagon', 'Petey Cruiser', 'Anna Sthesia', 'Paul Molive', 'Anna Mull', 'Gail Forcewind', 'Paige Turner', 'Bob Frapples', 'Walter Melon', 'Nick R. Bocker', 'Barb Ackue', 'Buck Kinnear', 'Greta Life', 'Ira Membrit', 'Shonda Leer', 'Brock Lee', 'Maya Didas', 'Rick O Shea', 'Pete Sariya', 'Monty Carlo', 'Sal Monella', 'Sue Vaneer', 'Cliff Hanger', 'Barb Dwyer', 'Terry Aki', 'Cory Ander', 'Robin Banks', 'Jimmy Changa', 'Barry Wine', 'Wilma Mumduya', 'Buster Hyman', 'Poppa Cherry', 'Zack Lee', 'Don Stairs', 'Saul T. Balls', 'Peter Pants', 'Hal Appeno ', 'Otto Matic', 'Moe Fugga', 'Graham Cracker', 'Tom Foolery', 'Al Dente', 'Bud Wiser', 'Polly Tech', 'Holly Graham', 'Frank N. Stein', 'Cam L. Toe', 'Pat Agonia', 'Tara Zona', 'Barry Cade', 'Phil Anthropist ', 'Marvin Gardens', 'Phil Harmonic ', 'Arty Ficial', 'Will Power', 'Donatella Nobatti', 'Juan Annatoo', 'Stew Gots', 'Anna Rexia', 'Bill Emia', 'Curt N. Call', 'Max Emum', 'Minnie Mum', 'Bill Yerds', 'Hap E. Birthday', 'Matt Innae', 'Polly Science', 'Tara Misu', 'Ed U. Cation', 'Gerry Atric', 'Kerry Oaky', 'Midge Itz', 'Gabe Lackmen', 'Mary Christmas', 'Dan Druff', 'Jim Nasium', 'Angie O. Plasty', 'Ella Vator', 'Sal Vidge', 'Bart Ender', 'Artie Choke', 'Hans Olo', 'Marge Arin', 'Hugh Briss', 'Gene Poole', 'Ty Tanic', 'Manuel Labor', 'Lynn Guini', 'Claire Voyant', 'Peg Leg', 'Jack E. Sack', 'Marty Graw', 'Ash Wednesday', 'Olive Yu', 'Gene Jacket', 'Tom Atoe', 'Doug Out', 'Sharon Needles', 'Beau Tie', 'Serj Protector', 'Marcus Down', 'Warren Peace', 'Bud Jet', 'Barney Cull', 'Marion Gaze', 'Eric Shun', 'Mal Practice', 'Ed Itorial', 'Rick Shaw', 'Paul Issy', 'Ben Effit', 'Kat E. Gory', 'Justin Case', 'Louie Z. Ana', 'Aaron Ottix', 'Ty Ballgame', 'Anne Fibbiyon', 'Barry Cuda', 'John Withawind', 'Joe Thyme', 'Mary Goround', 'Marge Arita', 'Frank Senbeans', 'Bill Dabear', 'Ray Zindaroof', 'Adam Zapple', 'Lewis N. Clark', 'Matt Schtick', 'Sue Shee', 'Chris P. Bacon', 'Doug Lee Duckling', 'Mason Protesters', 'Sil Antro', 'Cal Orie', 'Sara Bellum', 'Al Acart', 'Marv Ellis', 'Evan Shlee', 'Terry Bull', 'Mort Ission', 'Mark Ette', 'Ken Tucky', 'Louis Ville', 'Colin Oscopy', 'Fred Attchini', 'Al Fredo', 'Penny Tration', 'Reed Iculous', 'Chip Zinsalsa', 'Matt Uhrafact', 'Jack Dup', 'Mike Roscope', 'Lou Sinclark', 'Faye Daway', 'Javy Cado', 'Tom Ollie', 'Sam Buca', 'Phil Anderer', 'Sam Owen', 'Mary Achi', 'Ray Cyst', 'Curtis E. Flush', 'Holland Oats', 'Helen Highwater', 'Eddy Kitt', 'Al Toesacks', 'Sir Kim Scision', 'Elle Bowdrop', 'Anderson Gaitolini', 'Ellis Dee', 'Anna Lytics', 'Sara Bellum', 'Penny Trate', 'Phil Erup', 'Jenna Side', 'Mary Nara', 'Mick Donalds', 'Amber Alert', 'Vic Tory', 'Bobby Pin', 'Dom Inate', 'Hugh Miliation', 'Christian Mingle', 'Juan Soponatime', 'Dante Sinferno', 'Ed Zupp', 'Sarah Yevo', 'Jess Thetip', 'Arthur Itis', 'Faye Sbook', 'Carrie R. Pigeon', 'Rachel Slurs', 'Ty Pryder', 'Cole Slaw', 'Pat Ernity', 'Deb Utant', 'Luke Warm', 'Travis Tee', 'Clara Fication', 'Paul Itician', 'Deb Utant', 'Moe Thegrass', 'Carol Sell', 'Scott Schtape', 'Cody Pendant', 'Frank Furter', 'Barry Dalive', 'Mort Adella', 'Ray Diation', 'Mack Adamia', 'Farrah Moan', 'Theo Retical', 'Eda Torial', 'Mae O Nayse', 'Bella Ruse', 'Yuri thra', 'Tucker Doubt', 'Cara Larm', 'Abel Body', 'Sal Ami', 'Colin Derr', 'Cathy Derr', 'Colin O Scopy', 'Mel Anoma', 'Adam Up', 'Lou Zing', 'Mark Key', 'Sven Gineer', 'Mick Rib', 'Benny Ficial', 'Genie Inabottle', 'Gene Therapy', 'Reggie Stration', 'Lou Ow', 'Lance Dorporal', 'Lou Tenant', 'Nick Knack', 'Patty Whack', 'Reuben Sandwich', 'Hugo Slavia', 'Aaron Spacemuseum', 'Petey Atricks', 'Dan Delion', 'Terry Torial', 'Cal Q. Later', 'Jen Trification', 'Indy Nile', 'Ray Volver', 'Minnie Strone', 'Gustav Wind', 'Paul Samic', 'Vinny Gret', 'Joyce Tick', 'Cliff Diver', 'Earl E. Riser', 'Cooke Edoh', 'Jen Youfelct', 'Reanne Carnation', 'Paul Misunday', 'Chris P. Cream', 'Gio Metric', 'Caire Innet', 'Marsha Mello', 'Manny Petty', 'Val Adictorian', 'Lucy Tania', 'Jaques Amole'); /// <summary> /// Most used email domains /// </summary> EMAIL_DOMAINS: array [0 .. 99] of string = ('gmail.com', 'yahoo.com', 'hotmail.com', 'aol.com', 'hotmail.co.uk', 'hotmail.fr', 'msn.com', 'yahoo.fr', 'wanadoo.fr', 'orange.fr', 'comcast.net', 'yahoo.co.uk', 'yahoo.com.br', 'yahoo.co.in', 'live.com', 'rediffmail.com', 'free.fr', 'gmx.de', 'web.de', 'yandex.ru', 'ymail.com', 'libero.it', 'outlook.com', 'uol.com.br', 'bol.com.br', 'mail.ru', 'cox.net', 'hotmail.it', 'sbcglobal.net', 'sfr.fr', 'live.fr', 'verizon.net', 'live.co.uk', 'googlemail.com', 'yahoo.es', 'ig.com.br', 'live.nl', 'bigpond.com', 'terra.com.br', 'yahoo.it', 'neuf.fr', 'yahoo.de', 'alice.it', 'rocketmail.com', 'att.net', 'laposte.net', 'facebook.com', 'bellsouth.net', 'yahoo.in', 'hotmail.es', 'charter.net', 'yahoo.ca', 'yahoo.com.au', 'rambler.ru', 'hotmail.de', 'tiscali.it', 'shaw.ca', 'yahoo.co.jp', 'sky.com', 'earthlink.net', 'optonline.net', 'freenet.de', 't-online.de', 'aliceadsl.fr', 'virgilio.it', 'home.nl', 'qq.com', 'telenet.be', 'me.com', 'yahoo.com.ar', 'tiscali.co.uk', 'yahoo.com.mx', 'voila.fr', 'gmx.net', 'mail.com', 'planet.nl', 'tin.it', 'live.it', 'ntlworld.com', 'arcor.de', 'yahoo.co.id', 'frontiernet.net', 'hetnet.nl', 'live.com.au', 'yahoo.com.sg', 'zonnet.nl', 'club-internet.fr', 'juno.com', 'optusnet.com.au', 'blueyonder.co.uk', 'bluewin.ch', 'skynet.be', 'sympatico.ca', 'windstream.net', 'mac.com', 'centurytel.net', 'chello.nl', 'live.ca', 'aim.com', 'bigpond.net.au'); PASSWORDS: array [0 .. 99] of string = ('rU5FBfTtLCZ4tt', 'hZfmhCAbxaN9bQ', 'vvvkE8umrH55CF', 'UpmdMHeQQUWfak', 'RWhTznx23RQ2Qn', 'EvGWjLf33vm7TL', '6Ra99fBKvPgTWs', 'uuev44UXNPtZPq', '92yrNuRyPrEZGn', '4YzMNMbPhsTCNF', '5DFNn6Gk9mfbxP', 'zQUwxjWxSE4bmh', 'x8FRft5ymtFnKF', 'UJ4naDCMgrcRGz', 'k8RhAr2nvEZrT7', 'cd2FFYTPW9vLHy', '5prJnUSD4bKFNC', 'QZEmhZMRQxrhKg', '7qQ8DckhR9fPsc', 'bpyDXvgkQmtDvt', 'TQELgvkqLtHh2p', 'KxNEEPt9q4bUYJ', 'uvBS4De6byUAmX', 'ErYhejB9fa7Eyn', 'eFP2L9GtkRCfXg', 'YMe6759Vhr998Q', 'Z7E9f4jMVsHUTc', 'yvqQpRyEkywt3G', 'gqKa8pkytUBauQ', 'E27KCgfHaQdZcU', 'kqt5jeVCt99QmC', 'cFvmMuNSjfMXTX', 'gK9nP4rLNZ87pc', 'Pk9zZua9MSUyQ6', 'YKNQD82v2TX4bL', 'pVDGQWyzJeWkCs', 'fbsjTnRdmBVsr7', 'nbp3vg6xUpvH5A', 'tTKkKsETjw3Q7D', 'R7xWHCHQ2RdHFR', '9nGAkQ3PvGUTaB', 'CgWS8aK6Z24QYv', 'bg6QkjtfRS6sU5', 'rbyyvaSGnDCJBV', 'D5PRySPG9ShvNZ', 's2D2weNxVusCzL', 'NB5M9hyMHzjxyx', '4ZtBjUzuCRAL7f', 'Y9xpcY3tqdaxuB', 'bwgzvKpeZRqpQf', 'k9KjbDLydUnMAz', 'rbsKXCdMLmbhYT', 'KsjAZcNRruWetm', 'CeHSMpZMRMRR7c', 'g7DcLnRqFVD7YL', 'jEqDJ7ySHA4W8X', 'yQHVQnutFTvmCA', 'aMAmVgkLr6myYy', 'p3V3sRL56RsBPp', 'BJMYLATKjWKZLk', '6HMephVTAnTVxg', 'AryUEHayXxWV9Y', 'FNdcDCR6HwWGML', '8Q3zy9KR2nbtEn', 'WDuRucgrrewNbr', 'F69YYjYWKHBAGu', 'YG3EtbMxNMtwaA', 'r39WWUVjP43DEP', 'WVWZkRcWjtFMU4', 'cZDefZMXaxXZHV', '3KJgEjbsUYbB4a', 'YmMbSBrXsfrbhh', 'pk27dvJaGGWthj', 'a2BUqTaSJ2sXTf', 'huqQgJcqFBQ49E', 'EGjRYsYCEbhZrq', 'uC3DP924cZWCqf', 'tBRftq5WGtA4aK', 'S3E8CLjVPnZNdJ', 'QjBT8hwjZSttQs', 'd6f3fpvTHhBam2', 'Bqd6nVp5j67rKT', 'WqsNxNHQZSZetg', 'L64P7XXEhXWEHX', '7GE5AtwL96HsTu', 'WDkF3xeAGvpXm8', 'QP44Je5RknMb9T', 'ACULGJHgVmLawB', '8VUCKWn6VYYfBR', 'StDuWZwTEYaPQM', 'fGTe75jbPE8Wnj', 'uzxvVQaHa37Z8z', '9c3bCJNqPpMNNC', 'zgdKjwkQdDzRLy', 'FUt2LZumxS8RAS', 'qKQxxKBr5dq2bH', 'gLqd38F6ZVrTcN', 'asRpuUmFLZhKur', 'rzapBBaqVbjjjz', 'TKn3wWXt6xryJy'); /// <summary> /// Random things,objects,home stuffs and etc /// </summary> THINGS: array [0 .. 189] of string = ('plate', 'bread', 'lamp', 'wallet', 'stop sign', 'helmet', 'headphones', 'credit card', 'shawl', 'thermometer', 'balloon', 'mouse pad', 'toothbrush', 'lip gloss', 'doll', 'paper', 'greeting card', 'water bottle', 'flowers', 'desk', 'air freshener', 'glow stick', 'toe ring', 'pillow', 'television', 'brocolli', 'door', 'cat', 'apple', 'floor', 'bananas', 'eye liner', 'phone', 'fake flowers', 'perfume', 'bottle', 'pants', 'controller', 'ice cube tray', 'cup', 'piano', 'glasses', 'bottle cap', 'candy wrapper', 'lace', 'bow', 'sharpie', 'magnet', 'lotion', 'shoe lace', 'bookmark', 'spring', 'sailboat', 'ipod', 'truck', 'USB drive', 'house', 'soap', 'buckel', 'thread', 'food', 'slipper', 'box', 'sketch pad', 'picture frame', 'thermostat', 'clothes', 'drill press', 'coasters', 'speakers', 'cinder block', 'tomato', 'zipper', 'candle', 'chocolate', 'clock', 'packing peanuts', 'bowl', 'purse', 'twister', 'rubber duck', 'beef', 'tv', 'tooth picks', 'hanger', 'milk', 'cork', 'keyboard', 'outlet', 'drawer', 'washing machine', 'newspaper', 'CD', 'scotch tape', 'mp3 player', 'book', 'flag', 'clamp', 'bag', 'bracelet', 'screw', 'sidewalk', 'fridge', 'sticky note', 'toilet', 'couch', 'table', 'photo album', 'cell phone', 'soda can', 'chapter book', 'pen', 'remote', 'car', 'knife', 'pencil', 'plastic fork', 'playing card', 'mirror', 'leg warmers', 'nail clippers', 'white out', 'sofa', 'button', 'rusty nail', 'sandal', 'canvas', 'boom box', 'charger', 'street lights', 'ring', 'blanket', 'lamp shade', 'camera', 'vase', 'shoes', 'seat belt', 'blouse', 'computer', 'nail file', 'eraser', 'sponge', 'glass', 'watch', 'hair tie', 'tire swing', 'tree', 'soy sauce packet', 'teddies', 'socks', 'puddle', 'cookie jar', 'keys', 'conditioner', 'paint brush', 'towel', 'sand paper', 'shirt', 'hair brush', 'grid paper', 'money', 'model car', 'sun glasses', 'chalk', 'toothpaste', 'radio', 'mop', 'spoon', 'rubber band', 'face wash', 'checkbook', 'shampoo', 'needle', 'tissue box', 'carrots', 'chair', 'fork', 'wagon', 'stockings', 'twezzers', 'rug', 'key chain', 'clay pot', 'deodorant', 'monitor', 'video games', 'pool stick', 'shovel', 'window', 'bed'); OTAN_ALPHABET: array [0 .. 25] of string = ('Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf', 'Hotel', 'India', 'Juliet', 'Kilo', 'Lima', 'Mike', 'November', 'Oscar', 'Papa', 'Quebec', 'Romeo', 'Sierra', 'Tango', 'Uniform', 'Victor', 'Whiskey', 'Xray', 'Yankee', 'Zulu'); WORDS: array [0 .. 1000] of string = ('bite', 'mate', 'quill', 'back', 'church', 'pear', 'knit', 'bent', 'wrench', 'crack', 'heavenly', 'deceive', 'maddening', 'plain', 'writer', 'rapid', 'acidic', 'decide', 'hat', 'paint', 'cow', 'dysfunctional', 'pet', 'giraffe', 'connection', 'sour', 'voracious', 'cloudy', 'wry', 'curve', 'agree', 'eggnog', 'flaky', 'painstaking', 'warm', 'silk', 'icy', 'hellish', 'toy', 'milky', 'skirt', 'test', 'daffy', 'questionable', 'gamy', 'aware', 'berry', 'throne', 'oven', 'subtract', 'cool', 'care', 'charge', 'smash', 'curve', 'comfortable', 'narrow', 'merciful', 'material', 'fear', 'exercise', 'skinny', 'fire', 'rainstorm', 'tail', 'nondescript', 'calculating', 'pack', 'steel', 'marvelous', 'baseball', 'furtive', 'stitch', 'abiding', 'empty', 'bushes', 'painful', 'tense', 'verse', 'unwritten', 'reproduce', 'receptive', 'bottle', 'silky', 'alleged', 'stingy', 'irritate', 'expand', 'cap', 'unsuitable', 'gigantic', 'exist', 'damp', 'scrub', 'disgusted', 'sun', 'ink', 'detailed', 'defeated', 'economic', 'chunky', 'stop', 'overflow', 'numerous', 'joyous', 'wipe', 'drink', 'error', 'branch', 'male', 'proud', 'soggy', 'ship', 'excite', 'industry', 'wistful', 'man', 'vacation', 'doctor', 'naughty', 'plane', 'ignore', 'open', 'act', 'earthquake', 'inconclusive', 'reflect', 'force', 'funny', 'wonder', 'magenta', 'near', 'dam', 'windy', 'maid', 'wacky', 'release', 'birthday', 'statement', 'psychotic', 'quicksand', 'things', 'planes', 'boundary', 'nod', 'touch', 'argue', 'sin', 'train', 'adhoc', 'needle', 'regret', 'stroke', 'strengthen', 'bruise', 'mine', 'rod', 'tax', 'twig', 'advise', 'stamp', 'rhyme', 'obnoxious', 'few', 'inform', 'fixed', 'mailbox', 'bells', 'grade', 'machine', 'yarn', 'lighten', 'tub', 'guiltless', 'hot', 'misty', 'van', 'flap', 'nosy', 'neighborly', 'crime', 'nifty', 'uninterested', 'noisy', 'oafish', 'squeal', 'page', 'wet', 'embarrassed', 'long-term', 'closed', 'language', 'argument', 'elite', 'ban', 'trip', 'tour', 'wine', 'profit', 'envious', 'love', 'back', 'bite-sized', 'magical', 'snatch', 'elated', 'sniff', 'far', 'shy', 'deeply', 'zoom', 'invent', 'downtown', 'heartbreaking', 'angry', 'can', 'bucket', 'important', 'fetch', 'shoe', 'self', 'x-ray', 'abhorrent', 'lumpy', 'fertile', 'nest', 'pick', 'history', 'offbeat', 'interrupt', 'yell', 'grain', 'scintillating', 'alluring', 'wren', 'form', 'attack', 'foregoing', 'suspect', 'daughter', 'moldy', 'signal', 'placid', 'quirky', 'itchy', 'butter', 'ordinary', 'imaginary', 'list', 'known', 'servant', 'slow', 'apparel', 'meeting', 'lovely', 'bat', 'insurance', 'waste', 'aromatic', 'foot', 'breakable', 'theory', 'stiff', 'cream', 'train', 'ground', 'fuel', 'wary', 'store', 'wonderful', 'corn', 'zippy', 'dashing', 'risk', 'prose', 'try', 'green', 'bead', 'recess', 'chop', 'stain', 'faded', 'heat', 'camera', 'panicky', 'depressed', 'wooden', 'clumsy', 'gullible', 'railway', 'guide', 'current', 'giants', 'enter', 'talented', 'bustling', 'square', 'jewel', 'bee', 'jelly', 'utopian', 'heal', 'anger', 'balance', 'tick', 'turn', 'unique', 'lively', 'wrist', 'fade', 'tender', 'outgoing', 'own', 'sigh', 'jobless', 'boiling', 'parallel', 'vest', 'leather', 'spark', 'suck', 'knot', 'circle', 'square', 'supply', 'tank', 'fax', 'spotless', 'habitual', 'feeling', 'watch', 'cattle', 'end', 'true', 'zonked', 'poison', 'man', 'pedal', 'boorish', 'moaning', 'mindless', 'bone', 'spot', 'chubby', 'numberless', 'eye', 'bright', 'sweet', 'fanatical', 'oranges', 'calm', 'squash', 'tooth', 'petite', 'design', 'one', 'bump', 'aberrant', 'mine', 'fit', 'rub', 'optimal', 'ugly', 'lyrical', 'borrow', 'queue', 'alert', 'normal', 'wrathful', 'truculent', 'level', 'hollow', 'disillusioned', 'kick', 'weather', 'mighty', 'upbeat', 'troubled', 'snotty', 'many', 'warn', 'thank', 'trains', 'plan', 'choke', 'activity', 'attend', 'walk', 'thought', 'gabby', 'actor', 'prickly', 'smell', 'dangerous', 'observation', 'action', 'steady', 'hypnotic', 'second-hand', 'zip', 'mundane', 'sand', 'sneaky', 'harm', 'pancake', 'guarantee', 'empty', 'bulb', 'burn', 'reject', 'decorate', 'obese', 'crowd', 'clap', 'flat', 'available', 'hop', 'untidy', 'wreck', 'fasten', 'waves', 'dinosaurs', 'dreary', 'fearful', 'answer', 'parched', 'tight', 'animated', 'desk', 'jaded', 'wax', 'silver', 'scream', 'puzzling', 'unbiased', 'unite', 'branch', 'quack', 'writing', 'tease', 'mint', 'full', 'plate', 'gusty', 'bear', 'bell', 'sparkling', 'absurd', 'past', 'earsplitting', 'seemly', 'unadvised', 'paper', 'battle', 'friend', 'control', 'rich', 'regret', 'used', 'scattered', 'redundant', 'slave', 'languid', 'didactic', 'fairies', 'sofa', 'spiteful', 'reply', 'division', 'engine', 'suppose', 'homeless', 'pinch', 'ray', 'channel', 'repeat', 'smoke', 'concentrate', 'handy', 'committee', 'songs', 'madly', 'itch', 'hands', 'clean', 'addition', 'majestic', 'careful', 'fallacious', 'guarded', 'last', 'time', 'tumble', 'plastic', 'force', 'guess', 'grape', 'loving', 'hand', 'remain', 'vigorous', 'wash', 'cars', 'same', 'provide', 'shelf', 'yam', 'onerous', 'claim', 'tramp', 'glistening', 'innocent', 'lock', 'close', 'absorbing', 'daily', 'amuck', 'manage', 'energetic', 'absent', 'fantastic', 'flippant', 'unnatural', 'amount', 'luxuriant', 'clover', 'alert', 'wheel', 'cellar', 'agonizing', 'card', 'memorise', 'meal', 'suspend', 'concerned', 'uneven', 'deranged', 'spiritual', 'arch', 'dare', 'hammer', 'tug', 'jump', 'vase', 'plant', 'color', 'worm', 'grab', 'frame', 'taste', 'incandescent', 'little', 'rule', 'confused', 'roomy', 'gorgeous', 'heat', 'whole', 'cracker', 'water', 'flimsy', 'high-pitched', 'grandfather', 'spooky', 'natural', 'grease', 'noiseless', 'superficial', 'gaze', 'finger', 'afford', 'racial', 'tiresome', 'tremendous', 'zealous', 'slip', 'position', 'mountainous', 'shelter', 'calculator', 'tacky', 'whip', 'mountain', 'clear', 'thin', 'smell', 'ants', 'yellow', 'cross', 'employ', 'trouble', 'dazzling', 'enchanting', 'groovy', 'measure', 'disapprove', 'elastic', 'sparkle', 'cub', 'foolish', 'discussion', 'stormy', 'pies', 'absorbed', 'trashy', 'mammoth', 'low', 'subdued', 'badge', 'letter', 'previous', 'challenge', 'tart', 'cute', 'suit', 'condition', 'pricey', 'rule', 'wrong', 'bomb', 'wiry', 'swim', 'crack', 'disgusting', 'gather', 'half', 'sturdy', 'probable', 'stream', 'trick', 'silly', 'sulky', 'nail', 'rotten', 'stir', 'sneeze', 'even', 'adamant', 'cluttered', 'object', 'battle', 'petite', 'wait', 'instinctive', 'donkey', 'squeamish', 'rainy', 'craven', 'acceptable', 'husky', 'pollution', 'judicious', 'distribution', 'neck', 'left', 'collect', 'thankful', 'describe', 'complex', 'transport', 'horses', 'hope', 'chemical', 'dress', 'idea', 'extend', 'laugh', 'event', 'route', 'hose', 'abundant', 'insect', 'spectacular', 'whistle', 'home', 'vast', 'massive', 'grey', 'sail', 'lavish', 'word', 'coach', 'repair', 'squeak', 'curious', 'beam', 'middle', 'obscene', 'efficacious', 'supreme', 'torpid', 'jazzy', 'linen', 'cause', 'synonymous', 'book', 'brave', 'staking', 'weak', 'show', 'birds', 'barbarous', 'hilarious', 'injure', 'walk', 'screeching', 'frequent', 'wide', 'kiss', 'lonely', 'quarrelsome', 'arm', 'flowers', 'surround', 'level', 'enjoy', 'calculate', 'reach', 'brother', 'grandiose', 'clammy', 'thunder', 'pen', 'rake', 'whirl', 'sharp', 'fence', 'scissors', 'polish', 'recondite', 'brief', 'pig', 'ten', 'spell', 'coal', 'sidewalk', 'straight', 'melted', 'ring', 'deadpan', 'nine', 'wound', 'use', 'switch', 'watch', 'meat', 'governor', 'lively', 'neat', 'dapper', 'gate', 'rose', 'wealthy', 'psychedelic', 'slap', 'note', 'request', 'match', 'abashed', 'snail', 'tray', 'pump', 'disappear', 'vegetable', 'wool', 'abstracted', 'impulse', 'fork', 'brake', 'shiny', 'team', 'coherent', 'dust', 'relieved', 'long', 'broad', 'shop', 'innate', 'milk', 'mother', 'screw', 'cushion', 'listen', 'spot', 'willing', 'legs', 'clever', 'obsolete', 'coil', 'smoke', 'call', 'men', 'purpose', 'bumpy', 'receipt', 'soothe', 'thinkable', 'launch', 'kittens', 'oceanic', 'dolls', 'jagged', 'fine', 'start', 'muddled', 'want', 'develop', 'skillful', 'real', 'sisters', 'cooperative', 'retire', 'scarecrow', 'caring', 'chance', 'search', 'visitor', 'stem', 'rabid', 'seed', 'endurable', 'cloistered', 'knife', 'cast', 'trouble', 'cold', 'brainy', 'admit', 'base', 'multiply', 'escape', 'bike', 'frighten', 'large', 'pull', 'observant', 'stereotyped', 'dirty', 'tin', 'vague', 'celery', 'hungry', 'best', 'difficult', 'burly', 'horse', 'flawless', 'fresh', 'inquisitive', 'illegal', 'omniscient', 'simplistic', 'selfish', 'clean', 'hospital', 'encouraging', 'incompetent', 'right', 'learn', 'relation', 'spoil', 'amused', 'ruthless', 'squalid', 'aftermath', 'increase', 'greasy', 'futuristic', 'shut', 'friendly', 'steep', 'range', 'faint', 'jail', 'wide-eyed', 'uptight', 'erratic', 'eyes', 'cure', 'overwrought', 'muddle', 'bedroom', 'scale', 'rub', 'conscious', 'snake', 'box', 'command', 'slippery', 'handsome', 'spy', 'tongue', 'unbecoming', 'magnificent', 'gold', 'resolute', 'face', 'childlike', 'approval', 'meaty', 'frog', 'abrasive', 'rat', 'peel', 'office', 'panoramic', 'explode', 'selective', 'ahead', 'thaw', 'mean', 'odd', 'hate', 'window', 'somber', 'guard', 'riddle', 'judge', 'flock', 'black', 'amusement', 'bikes', 'milk', 'sock', 'historical', 'tawdry', 'bare', 'mitten', 'harsh', 'street', 'unequal', 'five', 'zinc', 'faulty', 'messy', 'thoughtful', 'spicy', 'oval', 'telephone', 'decisive', 'teeny', 'fix', 'outstanding', 'excuse', 'abject', 'print', 'receive', 'jump', 'knock', 'ubiquitous', 'anxious', 'fill', 'shrug', 'ossified', 'penitent', 'dry', 'abaft', 'uncle', 'voiceless', 'spray', 'town', 'aspiring', 'testy', 'bed', 'likeable', 'breezy', 'jumpy', 'talk', 'powerful', 'various', 'crawl', 'lacking', 'lethal', 'baby', 'sore', 'mourn', 'behave', 'pass', 'mark', 'summer', 'cause', 'destruction', 'stale', 'basin', 'embarrass', 'rob', 'income', 'overjoyed', 'aback', 'spark', 'air', 'worthless', 'hospitable', 'dynamic', 'push', 'nervous', 'dark', 'chin', 'shock', 'frame', 'dojo'); type /// <summary>This Type provides fake/random data.</summary> TFaker = class private class function randVal(aArray: array of String): string; class function replace(aFullString, aSubString: string; aReplaceWith: string = ''): string; overload; class function replace(aFullString: string; aSubStringArray: array of string; aReplaceWith: string = ''): string; overload; public class function firstName: string; class function lastName: string; class function fullName: string; class function userName: string; class function email(aCustomDomain: string = ''): string; class function password: string; /// <summary> /// Return a birth date at where age is less than or equal to 100 /// </summary> class function birthDate: TDateTime; class function thing: string; class function otan: string; class function word: string; class function text(wordsNumber: Integer = 0): string; class function loremIpsum(): string; end; implementation uses SysUtils, Math, dateutils, types, classes; { TFaker helper methods } class function TFaker.randVal(aArray: array of String): string; begin result := aArray[Random(Length(aArray))]; end; class function TFaker.replace(aFullString, aSubString, aReplaceWith: string): string; begin result := StringReplace(aFullString, aSubString, aReplaceWith, [rfReplaceAll]); end; class function TFaker.replace(aFullString: string; aSubStringArray: array of string; aReplaceWith: string): string; var s: string; I: Integer; begin result := aFullString; {$IFDEF VER150} for I := 0 to Length(aSubStringArray)-1 do begin Result := replace(result,s, aReplaceWith); end; {$ELSE} for s in aSubStringArray do result := replace(result, s, aReplaceWith); {$ENDIF} end; { TFaker data provider } class function TFaker.fullName: string; begin result := randVal(NAMES); end; class function TFaker.firstName: string; begin result := TFaker.fullName; result := Copy(result, 0, Pos(' ', result) - 1); end; class function TFaker.lastName: string; begin result := TFaker.fullName; result := Copy(result, Pos(' ', result) + 1, Length(result)); end; class function TFaker.otan: string; begin result := randVal(OTAN_ALPHABET); end; class function TFaker.password: string; function p: string; begin result := Copy(randVal(PASSWORDS), 0, Random(Length(PASSWORDS))); end; begin // Why 3? result := p + p + p; end; class function TFaker.birthDate: TDateTime; begin result := EncodeDate(RandomRange(yearof(date) - 100, yearof(date)), RandomRange(1, 12), RandomRange(1, 31)); end; class function TFaker.userName: string; begin result := LowerCase(replace(TFaker.fullName, ['.'])); result := replace(result, ' ', randVal(['.', '_', IntToStr(Random(999999))])); end; class function TFaker.email(aCustomDomain: string = ''): string; begin if aCustomDomain <> '' then result := TFaker.userName + '@' + aCustomDomain else result := TFaker.userName + '@' + randVal(EMAIL_DOMAINS); end; class function TFaker.thing: string; begin result := randVal(THINGS); end; class function TFaker.word: string; begin result := randVal(WORDS); end; class function TFaker.text(wordsNumber: Integer): string; var countWords, index: Integer; _words: TStringList; begin countWords := wordsNumber; if countWords = 0 then countWords := RandomRange(1, Length(WORDS)); _words := TStringList.Create; while _words.Count <> countWords do _words.Add(randVal(WORDS) + ' '); _words.Delete(countWords - 1); result := _words.text; end; class function TFaker.loremIpsum: string; begin result := LOREM_IPSUM; end; end.
74.154971
140
0.619061
f168b5ec324fa0a62b5a17ce29b631c733fbf99b
1,359
pas
Pascal
src/ListView.EmptyMessage.pas
yypbd/filecombine
0a57febbcd5f7dfab56aef89e5e25e806438e9b7
[ "MIT" ]
2
2017-02-22T02:35:51.000Z
2019-03-06T17:11:30.000Z
src/ListView.EmptyMessage.pas
yypbd/filecombine
0a57febbcd5f7dfab56aef89e5e25e806438e9b7
[ "MIT" ]
null
null
null
src/ListView.EmptyMessage.pas
yypbd/filecombine
0a57febbcd5f7dfab56aef89e5e25e806438e9b7
[ "MIT" ]
3
2018-06-12T21:47:37.000Z
2020-02-02T11:35:47.000Z
unit ListView.EmptyMessage; interface uses Winapi.Windows, Winapi.Messages, System.Classes, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Graphics; type TListView = class( Vcl.ComCtrls.TListView ) private FEmptyMessage: string; procedure SetEmptyMessage(const Value: string); procedure DrawEmptyMessage; procedure WMPaint(var Message: TWMPaint); message WM_PAINT; public property EmptyMessage: string read FEmptyMessage write SetEmptyMessage; end; implementation uses CommCtrl; { TListView } procedure TListView.DrawEmptyMessage; var Text: string; TextWidth, TextHeight, TextLeft, TextTop: Integer; StringList: TStringList; begin StringList := TStringList.Create; try StringList.Text := FEmptyMessage; TextTop := 80; for Text in StringList do begin TextWidth := Canvas.TextWidth( Text ); TextLeft := ( Width - TextWidth ) div 2; Canvas.TextOut( TextLeft, TextTop, Text ); TextHeight := Canvas.TextHeight( Text ); TextTop := TextTop + TextHeight + 5; end; finally StringList.Free; end; end; procedure TListView.SetEmptyMessage(const Value: string); begin FEmptyMessage := Value; end; procedure TListView.WMPaint(var Message: TWMPaint); begin inherited; if (Items.Count = 0) and (FEmptyMessage <> '') then begin DrawEmptyMessage; end; end; end.
19.695652
92
0.711553
fcf4ce9a0a77af2540b897ab0a71232401765e1d
2,813
pas
Pascal
Chapter03/Prototype/PrototypeRecordMain.pas
PacktPublishing/Hands-On-Design-Patterns-with-Delphi
30f6ab51e61d583f822be4918f4b088e2255cd82
[ "MIT" ]
38
2019-02-28T06:22:52.000Z
2022-03-16T12:30:43.000Z
Chapter03/Prototype/PrototypeRecordMain.pas
alefragnani/Hands-On-Design-Patterns-with-Delphi
3d29e5b2ce9e99e809a6a9a178c3f5e549a8a03d
[ "MIT" ]
null
null
null
Chapter03/Prototype/PrototypeRecordMain.pas
alefragnani/Hands-On-Design-Patterns-with-Delphi
3d29e5b2ce9e99e809a6a9a178c3f5e549a8a03d
[ "MIT" ]
18
2019-03-29T08:36:14.000Z
2022-03-30T00:31:28.000Z
unit PrototypeRecordMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Prototype.Rec; type TfrmPrototypeRecord = class(TForm) btnCloneRecord: TButton; lbLog: TListBox; procedure btnCloneRecordClick(Sender: TObject); private FMasterCharacter: TCharacter; function CreateRecord: TCloneableRec; procedure LogRecord(const name: string; const rec: TCloneableRec); public end; var frmPrototypeRecord: TfrmPrototypeRecord; implementation {$R *.dfm} function GetRefCount(const intf: IInterface): integer; begin Result := intf._AddRef - 1; intf._Release; end; { TfrmPrototypeRecord } procedure TfrmPrototypeRecord.btnCloneRecordClick(Sender: TObject); var source: TCloneableRec; clone: TCloneableRec; begin FMasterCharacter := TCharacter.Create; try FMasterCharacter.Value := '*'; source := CreateRecord; LogRecord('Original', source); clone := source; LogRecord('Clone', clone); source.Str := 'Changed'; source.Intf.Value := source.Intf.Value * 2; source.ArrS[Low(source.ArrS)] := 9999; source.ArrD[Low(source.ArrD)] := 9999; source.Obj.Value := '+'; LogRecord('Clone', clone); finally FreeAndNil(FMasterCharacter); end; end; function TfrmPrototypeRecord.CreateRecord: TCloneableRec; var i: integer; begin Result.Str := 'Cloneable record'; Result.Int := 21; Result.Intf := TInteger.Create; Result.Intf.Value := 1234; for i := Low(Result.ArrS) to High(Result.ArrS) do Result.ArrS[i] := i; SetLength(Result.ArrD, 5); for i := Low(Result.ArrD) to High(Result.ArrD) do Result.ArrD[i] := 10*i; Result.Rec.ValueI := 9999; Result.Rec.ValueS := '----'; Result.Obj := FMasterCharacter; end; procedure TfrmPrototypeRecord.LogRecord(const name: string; const rec: TCloneableRec); function ToString(const intArr: array of integer): string; var strArr: TArray<string>; i: integer; j: integer; begin SetLength(strArr, Length(intArr)); j := Low(strArr); for i := Low(intArr) to High(intArr) do begin strArr[j] := IntToStr(intArr[i]); Inc(j); end; Result := string.Join(', ', strArr); end; begin lbLog.Items.Add(name); lbLog.Items.Add(Format('Str: %s', [rec.Str])); lbLog.Items.Add(Format('Int: %d', [rec.Int])); lbLog.Items.Add(Format('Intf: %d [%d]', [rec.Intf.Value, GetRefCount(rec.Intf)])); lbLog.Items.Add(Format('ArrS: %s', [ToString(rec.ArrS)])); lbLog.Items.Add(Format('ArrD: %s', [ToString(rec.ArrD)])); lbLog.Items.Add(Format('Rec: %d, %s', [rec.Rec.ValueI, rec.Rec.ValueS])); lbLog.Items.Add(Format('Obj: %s [%p]', [rec.Obj.Value, pointer(rec.Obj)])); lbLog.Items.Add(''); end; end.
25.116071
98
0.677568
f1f356b686242f782df85ce633f08881e274fdbc
15,816
dfm
Pascal
preferform.dfm
CyberShadow/ProSnooper
081fe3b1d79124f802054f2310638c2eb751e284
[ "EFL-2.0" ]
2
2016-04-15T16:51:11.000Z
2016-12-03T21:20:26.000Z
preferform.dfm
CyberShadow/ProSnooper
081fe3b1d79124f802054f2310638c2eb751e284
[ "EFL-2.0" ]
1
2016-03-06T12:09:29.000Z
2016-09-04T15:06:42.000Z
preferform.dfm
CyberShadow/ProSnooper
081fe3b1d79124f802054f2310638c2eb751e284
[ "EFL-2.0" ]
null
null
null
object frmSettings: TfrmSettings Left = 498 Top = 150 BorderStyle = bsDialog Caption = 'ProSnooper - Settings' ClientHeight = 424 ClientWidth = 303 Color = clBtnFace Font.Charset = ANSI_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False Position = poScreenCenter OnShow = FormShow PixelsPerInch = 96 TextHeight = 13 object Bevel1: TBevel Left = -8 Top = 384 Width = 321 Height = 9 Shape = bsTopLine end object Button1: TButton Left = 216 Top = 392 Width = 81 Height = 25 Caption = 'OK' TabOrder = 1 OnClick = Button1Click end object PageControl1: TPageControl Left = 8 Top = 8 Width = 289 Height = 361 ActivePage = TabSheet1 MultiLine = True TabOrder = 0 object TabSheet1: TTabSheet Caption = 'Colors' object Label9: TLabel Left = 16 Top = 48 Width = 31 Height = 13 Caption = 'Text 1' end object Label6: TLabel Left = 16 Top = 240 Width = 25 Height = 13 Caption = 'Quits' end object Label5: TLabel Left = 16 Top = 208 Width = 25 Height = 13 Caption = 'Parts' end object Label4: TLabel Left = 16 Top = 176 Width = 24 Height = 13 Caption = 'Joins' end object Label3: TLabel Left = 16 Top = 144 Width = 35 Height = 13 Caption = 'Actions' end object Label2: TLabel Left = 16 Top = 112 Width = 84 Height = 13 Caption = 'Private messages' end object Label10: TLabel Left = 16 Top = 80 Width = 31 Height = 13 Caption = 'Text 2' end object Label1: TLabel Left = 16 Top = 16 Width = 56 Height = 13 Caption = 'Background' end object colText2: TColorBox Left = 120 Top = 80 Width = 145 Height = 22 Selected = 7703700 Style = [cbStandardColors, cbExtendedColors, cbCustomColor, cbPrettyNames] ItemHeight = 16 TabOrder = 2 end object colText1: TColorBox Left = 120 Top = 48 Width = 145 Height = 22 Selected = 14074262 Style = [cbStandardColors, cbExtendedColors, cbCustomColor, cbPrettyNames] ItemHeight = 16 TabOrder = 1 end object colQuits: TColorBox Left = 120 Top = 240 Width = 145 Height = 22 Selected = 11523313 Style = [cbStandardColors, cbExtendedColors, cbCustomColor, cbPrettyNames] ItemHeight = 16 TabOrder = 7 end object colPrivate: TColorBox Left = 120 Top = 112 Width = 145 Height = 22 Selected = 7335633 Style = [cbStandardColors, cbExtendedColors, cbCustomColor, cbPrettyNames] ItemHeight = 16 TabOrder = 3 end object colParts: TColorBox Left = 120 Top = 208 Width = 145 Height = 22 Selected = 14475461 Style = [cbStandardColors, cbExtendedColors, cbCustomColor, cbPrettyNames] ItemHeight = 16 TabOrder = 6 end object colJoins: TColorBox Left = 120 Top = 176 Width = 145 Height = 22 Selected = 13559276 Style = [cbStandardColors, cbExtendedColors, cbCustomColor, cbPrettyNames] ItemHeight = 16 TabOrder = 5 end object colBackground: TColorBox Left = 120 Top = 16 Width = 145 Height = 22 Style = [cbStandardColors, cbExtendedColors, cbCustomColor, cbPrettyNames] ItemHeight = 16 TabOrder = 0 end object colActions: TColorBox Left = 120 Top = 144 Width = 145 Height = 22 Selected = 10794749 Style = [cbStandardColors, cbExtendedColors, cbCustomColor, cbPrettyNames] ItemHeight = 16 TabOrder = 4 end end object TabSheet6: TTabSheet Caption = 'Buddies' ImageIndex = 5 object lbBuddies: TListBox Left = 8 Top = 8 Width = 185 Height = 313 ItemHeight = 13 TabOrder = 0 end object Button8: TButton Left = 200 Top = 43 Width = 73 Height = 25 Caption = 'Delete' TabOrder = 1 OnClick = Button8Click end object Button9: TButton Left = 200 Top = 11 Width = 73 Height = 25 Caption = 'Add' TabOrder = 2 OnClick = Button9Click end end object TabSheet2: TTabSheet Caption = 'Display' ImageIndex = 1 object Bevel3: TBevel Left = 72 Top = 24 Width = 193 Height = 9 Shape = bsTopLine end object Bevel2: TBevel Left = 96 Top = 104 Width = 169 Height = 9 Shape = bsTopLine end object Label7: TLabel Left = 32 Top = 64 Width = 38 Height = 13 Caption = 'Format:' end object Label8: TLabel Left = 16 Top = 96 Width = 77 Height = 13 Caption = 'Channel Actions' end object Label11: TLabel Left = 16 Top = 16 Width = 51 Height = 13 Caption = 'Timestamp' end object Bevel10: TBevel Left = 40 Top = 208 Width = 225 Height = 9 Shape = bsTopLine end object Label16: TLabel Left = 16 Top = 200 Width = 23 Height = 13 Caption = 'Chat' end object Label19: TLabel Left = 24 Top = 224 Width = 50 Height = 13 Caption = 'Font size: ' end object edTimeStamp: TEdit Left = 80 Top = 64 Width = 57 Height = 21 TabOrder = 1 Text = 'hh:nn:ss' end object cbTimeStamps: TCheckBox Left = 24 Top = 40 Width = 77 Height = 17 Caption = 'Timestamps' Checked = True State = cbChecked TabOrder = 0 end object cbQuits: TCheckBox Left = 24 Top = 168 Width = 97 Height = 17 Caption = 'Show quits' Checked = True State = cbChecked TabOrder = 4 end object cbParts: TCheckBox Left = 24 Top = 144 Width = 97 Height = 17 Caption = 'Show parts' Checked = True State = cbChecked TabOrder = 3 end object cbJoins: TCheckBox Left = 24 Top = 120 Width = 97 Height = 17 Caption = 'Show joins' Checked = True State = cbChecked TabOrder = 2 end object edFntSize: TComboBox Left = 80 Top = 224 Width = 57 Height = 21 ItemHeight = 13 TabOrder = 5 Text = '8' Items.Strings = ( '8' '9' '10' '11' '12' '14' '18' '24' '36' '48' '72') end object cbBlink: TCheckBox Left = 24 Top = 256 Width = 241 Height = 17 Caption = 'Blink tray icon' TabOrder = 6 end object cbDisableScroll: TCheckBox Left = 24 Top = 280 Width = 105 Height = 17 Caption = 'Disable autoscroll' TabOrder = 7 end end object TabSheet3: TTabSheet Caption = 'Sounds' ImageIndex = 2 object Bevel6: TBevel Left = 136 Top = 152 Width = 129 Height = 9 Shape = bsTopLine end object Bevel5: TBevel Left = 141 Top = 88 Width = 124 Height = 9 Shape = bsTopLine end object Bevel4: TBevel Left = 152 Top = 24 Width = 113 Height = 9 Shape = bsTopLine end object Label12: TLabel Left = 16 Top = 16 Width = 134 Height = 13 Caption = 'When a buddy comes online' end object Label13: TLabel Left = 16 Top = 80 Width = 123 Height = 13 Caption = 'When you are highlighted' end object Label14: TLabel Left = 16 Top = 144 Width = 119 Height = 13 Caption = 'When you are messaged' end object edsndBuddy: TEdit Left = 24 Top = 40 Width = 161 Height = 21 TabOrder = 0 end object Button2: TButton Left = 192 Top = 40 Width = 25 Height = 21 Caption = '>' TabOrder = 1 OnClick = Button2Click end object edsndHiLite: TEdit Left = 24 Top = 104 Width = 161 Height = 21 TabOrder = 3 end object Button3: TButton Left = 224 Top = 104 Width = 25 Height = 21 Caption = '...' TabOrder = 5 OnClick = Button3Click end object edsndMsg: TEdit Left = 24 Top = 168 Width = 161 Height = 21 TabOrder = 6 end object Button4: TButton Left = 224 Top = 168 Width = 25 Height = 21 Caption = '...' TabOrder = 8 OnClick = Button4Click end object Button5: TButton Left = 224 Top = 40 Width = 25 Height = 21 Caption = '...' TabOrder = 2 OnClick = Button5Click end object Button6: TButton Left = 192 Top = 104 Width = 25 Height = 21 Caption = '>' TabOrder = 4 OnClick = Button6Click end object Button7: TButton Left = 192 Top = 168 Width = 25 Height = 21 Caption = '>' TabOrder = 7 OnClick = Button7Click end object Button10: TButton Left = 192 Top = 216 Width = 73 Height = 25 Caption = 'Stop sounds' TabOrder = 9 Visible = False OnClick = Button10Click end end object TabSheet4: TTabSheet Caption = 'Games' ImageIndex = 3 object Bevel7: TBevel Left = 124 Top = 24 Width = 141 Height = 9 Shape = bsTopLine end object Label15: TLabel Left = 16 Top = 16 Width = 104 Height = 13 Caption = 'When hosting a game' end object Label17: TLabel Left = 56 Top = 88 Width = 55 Height = 13 Caption = 'Away-text:' end object Label20: TLabel Left = 56 Top = 216 Width = 55 Height = 13 Caption = 'Away-text:' end object Label18: TLabel Left = 16 Top = 168 Width = 100 Height = 13 Caption = 'When joining a game' end object Bevel8: TBevel Left = 120 Top = 176 Width = 145 Height = 9 Shape = bsTopLine end object Label22: TLabel Left = 16 Top = 272 Width = 137 Height = 13 Caption = 'Use W:A exe to open games' end object Bevel11: TBevel Left = 160 Top = 280 Width = 105 Height = 9 Shape = bsTopLine end object cbHostGameAnn: TCheckBox Left = 32 Top = 40 Width = 185 Height = 17 Caption = 'Announce' Checked = True State = cbChecked TabOrder = 0 end object cbHostGameAway: TCheckBox Left = 32 Top = 64 Width = 97 Height = 17 Caption = 'Go away' TabOrder = 1 end object edHostGameAway: TEdit Left = 56 Top = 104 Width = 185 Height = 21 TabOrder = 2 end object cbGetIP: TCheckBox Left = 32 Top = 136 Width = 217 Height = 17 Caption = 'Get IP and port from W:A' Checked = True State = cbChecked TabOrder = 3 end object cbJoinGameAway: TCheckBox Left = 32 Top = 192 Width = 97 Height = 17 Caption = 'Go away' TabOrder = 4 end object edJoinGameAway: TEdit Left = 56 Top = 232 Width = 185 Height = 21 TabOrder = 5 end object edExe: TEdit Left = 56 Top = 296 Width = 153 Height = 21 TabOrder = 6 end object Button11: TButton Left = 216 Top = 296 Width = 25 Height = 21 Caption = '...' TabOrder = 7 OnClick = Button11Click end end object TabSheet5: TTabSheet Caption = 'Away' ImageIndex = 4 object Bevel9: TBevel Left = 48 Top = 24 Width = 217 Height = 9 Shape = bsTopLine end object Label21: TLabel Left = 16 Top = 16 Width = 27 Height = 13 Caption = 'Away' end object cbAwayAnnounce: TCheckBox Left = 32 Top = 40 Width = 233 Height = 17 Caption = 'Announce when going away' TabOrder = 0 end object cbResumeAnnounce: TCheckBox Left = 32 Top = 64 Width = 217 Height = 17 Caption = 'Announce when resuming from away' TabOrder = 1 end object cbSendAwayPriv: TCheckBox Left = 32 Top = 88 Width = 233 Height = 17 Caption = 'Send away reason on private message' TabOrder = 2 end object cbSendAwayHiLite: TCheckBox Left = 32 Top = 112 Width = 233 Height = 17 Hint = 'Send the away-reason to anyone who mentions your nickname.' Caption = 'Send away reason on highlight' ParentShowHint = False ShowHint = True TabOrder = 3 end end end object mp: TMediaPlayer Left = 40 Top = 392 Width = 29 Height = 28 VisibleButtons = [btPlay] Visible = False TabOrder = 2 OnNotify = mpNotify end object OpenDialog1: TOpenDialog Filter = 'Wave files (*.wav)|*.wav|Windows Media Audio (*.wma)|*.wma|MP3 a' + 'udio (*.mp3)|*.mp3|All files (*.*)|*.*' Left = 8 Top = 392 end object OpenDialog2: TOpenDialog Filter = 'WA.exe, WormKit.exe|wa.exe;wormkit.exe|Executable files (*.exe)|' + '*.exe' Left = 72 Top = 392 end end
22.855491
83
0.469335
fc2b72f47f59c460ca4f07806ab9f848b971fdc6
1,984
pas
Pascal
examples/Delphi/Compound/Locking/Server/PServerDM.pas
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
121
2020-09-22T10:46:20.000Z
2021-11-17T12:33:35.000Z
examples/Delphi/Compound/Locking/Server/PServerDM.pas
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
8
2020-09-23T12:32:23.000Z
2021-07-28T07:01:26.000Z
examples/Delphi/Compound/Locking/Server/PServerDM.pas
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
42
2020-09-22T14:37:20.000Z
2021-10-04T10:24:12.000Z
unit PServerDM; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, BoldPersistenceHandlePassthrough, BoldSnooperHandle, BoldPersistenceHandle, BoldPersistenceHandleDB, BoldComServerHandles, BoldSubscription, BoldHandle, BoldServerHandles, BoldSOAPServerPersistenceHandles, ModelDM, BoldAbstractPropagatorHandle, BoldPropagatorHandleCOM, BoldClientHandles, BoldComClientHandles, BoldAbstractLockManagerHandle, BoldLockManagerHandleCom, DB, IBDatabase, BoldAbstractDatabaseAdapter, BoldDatabaseAdapterIB, BoldAbstractPersistenceHandleDB, BoldPersistenceHandlePTWithModel; type TdmPServer = class(TDataModule) BoldSOAPServerPersistenceHandle1: TBoldSOAPServerPersistenceHandle; BoldComServerHandle1: TBoldComServerHandle; BoldSnooperHandle1: TBoldSnooperHandle; BoldPropagatorHandleCOM1: TBoldPropagatorHandleCOM; BoldLockManagerHandleCom1: TBoldLockManagerHandleCom; BoldComConnectionHandle1: TBoldComConnectionHandle; BoldPersistenceHandleDB1: TBoldPersistenceHandleDB; BoldDatabaseAdapterIB1: TBoldDatabaseAdapterIB; IBDatabase1: TIBDatabase; procedure IBDatabase1BeforeConnect(Sender: TObject); private { Private declarations } protected procedure Loaded; override; public { Public declarations } end; var dmPServer: TdmPServer; implementation {$R *.DFM} procedure TdmPServer.Loaded; begin inherited; // Due to timing-problems, it is better to activate the persistencehandles here in Loaded instead of Datamodulecreate. // The first client to connect might try to retrieve the com-interface to the persistencehandle before DataModuleCreate. BoldPersistenceHandleDB1.Active := True; BoldSOAPServerPersistenceHandle1.Active := True; end; procedure TdmPServer.IBDatabase1BeforeConnect(Sender: TObject); begin IBDatabase1.DatabaseName := 'localhost:' + ExtractFilePath(Application.ExeName) + ExtractFileName(IBDatabase1.DatabaseName); end; end.
34.206897
126
0.821069