text stringlengths 14 6.51M |
|---|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Data.SqlConst;
interface
const
DRIVERS_KEY = 'Installed Drivers'; //TDBXPropertyNames.InstalledDrivers; { Do not localize }
CONNECTIONS_KEY = 'Installed Connections'; { Do not localize }
DRIVERNAME_KEY = 'DriverName'; { Do not localize }
HOSTNAME_KEY = 'HostName'; { Do not localize }
ROLENAME_KEY = 'RoleName'; { Do not localize }
DATABASENAME_KEY = 'Database'; //TDBXPropertyNames.Database; { Do not localize }
MAXBLOBSIZE_KEY = 'BlobSize'; { Do not localize }
VENDORLIB_KEY = 'VendorLib'; //TDBXPropertyNames.VendorLib; { Do not localize }
DLLLIB_KEY = 'LibraryName'; //TDBXPropertyNames.LibraryName; { Do not localize }
GETDRIVERFUNC_KEY = 'GetDriverFunc'; //TDBXPropertyNames.GetDriverFunc;{ Do not localize }
AUTOCOMMIT_KEY = 'AutoCommit'; { Do not localize }
BLOCKINGMODE_KEY = 'BlockingMode'; { Do not localize }
WAITONLOCKS_KEY= 'WaitOnLocks'; { Do not localize }
COMMITRETAIN_KEY = 'CommitRetain'; { Do not localize }
TRANSISOLATION_KEY = '%s TransIsolation'; { Do not localize }
SQLDIALECT_KEY = 'SqlDialect'; { Do not localize }
SQLLOCALE_CODE_KEY = 'LocaleCode'; { Do not localize }
ERROR_RESOURCE_KEY = 'ErrorResourceFile'; { Do not localize }
SQLSERVER_CHARSET_KEY = 'ServerCharSet'; { Do not localize }
CONNECTION_STRING = 'ConnectionString'; { Do not localize }
SREADCOMMITTED = 'readcommitted'; { Do not localize }
SREPEATREAD = 'repeatableread'; { Do not localize }
SDIRTYREAD = 'dirtyread'; { Do not localize }
{$EXTERNALSYM szUSERNAME}
szUSERNAME = 'USER_NAME'; { Do not localize }
szPASSWORD = 'PASSWORD'; { Do not localize }
SLocaleCode = 'LCID'; { Do not localize }
ROWSETSIZE_KEY = 'RowsetSize'; { Do not localize }
OSAUTHENTICATION = 'OS Authentication'; { Do not localize }
SERVERPORT = 'Server Port'; { Do not localize }
MULTITRANSENABLED = 'Multiple Transaction'; { Do not localize }
TRIMCHAR = 'Trim Char'; { Do not localize }
CUSTOM_INFO = 'Custom String'; { Do not localize }
CONN_TIMEOUT = 'Connection Timeout'; { Do not localize }
TDSPACKETSIZE = 'TDS Packet Size'; { Do not localize }
CLIENTHOSTNAME = 'Client HostName'; { Do not localize }
CLIENTAPPNAME = 'Client AppName'; { Do not localize }
COMPRESSED = 'Compressed'; { Do not localize }
ENCRYPTED = 'Encrypted'; { Do not localize }
PREPARESQL = 'Prepare SQL'; { Do not localize }
// DECIMALSEPARATOR = 'Decimal Separator'; { Do not localize }
resourcestring
SLoginError = 'Cannot connect to database ''%s''';
SMonitorActive = 'Cannot change connection on Active Monitor';
SMissingConnection = 'Missing SQLConnection property';
SDatabaseOpen = 'Cannot perform this operation on an open connection';
SDatabaseClosed = 'Cannot perform this operation on a closed connection';
SMissingSQLConnection = 'SQLConnection property required for this operation';
SConnectionNameMissing = 'Connection name missing';
SEmptySQLStatement = 'No SQL statement available';
SNoParameterValue = 'No value for parameter ''%s''';
SNoParameterType = 'No parameter type for parameter ''%s''';
SParameterTypes = ';Input;Output;Input/Output;Result';
SDataTypes = ';String;SmallInt;Integer;Word;Boolean;Float;Currency;BCD;Date;Time;DateTime;;;;Blob;Memo;Graphic;;;;;Cursor;';
SResultName = 'Result';
SNoTableName = 'Missing TableName property';
SNoSqlStatement = 'Missing query, table name or procedure name';
SNoDataSetField = 'Missing DataSetField property';
SNoCachedUpdates = 'Not in cached update mode';
SMissingDataBaseName = 'Missing Database property';
SMissingDataSet = 'Missing DataSet property';
SMissingDriverName = 'Missing DriverName property';
SPrepareError = 'Unable to execute Query';
SObjectNameError = 'Table/Procedure not found';
SSQLDataSetOpen = 'Unable to determine field names for %s';
SNoActiveTrans = 'There is no active transaction';
SActiveTrans = 'A transaction is already active';
SDllLoadError = 'Unable to Load %s';
SDllProcLoadError = 'Unable to Find Procedure %s';
SConnectionEditor = '&Edit Connection Properties';
SAddConnectionString = '&Add ConnectionString Param';
SRefreshConnectionString = 'R&efresh ConnectionString Param';
SRemoveConnectionString = '&Remove ConnectionString Param';
SCommandTextEditor = '&Edit CommandText';
SMissingDLLName = 'DLL/Shared Library Name not Set';
SMissingDriverRegFile = 'Driver/Connection Registry File ''%s'' not found';
STableNameNotFound = 'Cannot find TableName in CommandText';
SNoCursor = 'Cursor not returned from Query';
SMetaDataOpenError = 'Unable to Open Metadata';
SErrorMappingError = 'SQL Error: Error mapping failed';
SStoredProcsNotSupported = 'Stored Procedures not supported by ''%s'' Server';
SPackagesNotSupported = 'Packages are not supported by ''%s'' Server';
STooManyActualParam = '%s: Actual number of parameters (%d) exceeds the current number of stored procedure parameters (%d). Either uncheck the ParamCheck component property or review the parameter list content';
SDBXUNKNOWNERROR = 'dbExpress Error: Unknown Error Code ''%s''';
// SDBXNOCONNECTION = 'dbExpress Error: Connection not found, error message cannot be retrieved';
// SDBXNOMETAOBJECT = 'dbExpress Error: MetadataObject not found, error message cannot be retrieved';
// SDBXNOCOMMAND = 'dbExpress Error: Command not found, error message cannot be retrieved';
// SDBXNOCURSOR = 'dbExpress Error: Cursor not found, error message cannot be retrieved';
// #define DBXERR_NONE 0x0000
SNOERROR = '';
// #define DBXERR_WARNING 0x0001
SWARNING = '[0x0001]: Warning';
//#define DBXERR_NOMEMORY 0x0002
SNOMEMORY = '[0x0002]: Insufficient Memory for Operation';
//#define DBXERR_INVALIDFLDTYPE 0x0003
SINVALIDFLDTYPE = '[0x0003]: Invalid Field Type';
//#define DBXERR_INVALIDHNDL 0x0004
SINVALIDHNDL = '[0x0004]: Invalid Handle';
//#define DBXERR_NOTSUPPORTED 0x0005
SNOTSUPPORTED = '[0x0005]: Operation Not Supported';
//#define DBXERR_INVALIDTIME 0x0006
SINVALIDTIME = '[0x0006]: Invalid Time';
//#define DBXERR_INVALIDXLATION 0x0007
SINVALIDXLATION = '[0x0007]: Invalid Data Translation';
//#define DBXERR_OUTOFRANGE 0x0008
SOUTOFRANGE = '[0x0008]: Parameter/Column out of Range';
//#define DBXERR_INVALIDPARAM 0x0009
SINVALIDPARAM = '[0x0009]: Invalid Parameter';
//#define DBXERR_EOF 0x000A
SEOF = '[0x000A]: Result set at EOF';
//#define DBXERR_SQLPARAMNOTSET 0x000B
SSQLPARAMNOTSET = 'dbExpress Error [0x000B]: Parameter Not Set';
//#define DBXERR_INVALIDUSRPASS 0x000C
SINVALIDUSRPASS = '[0x000C] Invalid Username/Password';
//#define DBXERR_INVALIDPRECISION 0x000D
SINVALIDPRECISION = '[0x000D]: Invalid Precision';
//#define DBXERR_INVALIDLEN 0x000E
SINVALIDLEN = '[0x000E]: Invalid Length';
//#define DBXERR_INVALIDTXNISOLEVEL 0x000F
SINVALIDXISOLEVEL = '[0x000F]: Invalid Transaction Isolation Level';
//#define DBXERR_INVALIDTXNID 0x0010
SINVALIDTXNID = '[0x0010]: Invalid Transaction ID';
//#define DBXERR_DUPLICATETXNID 0x0011
SDUPLICATETXNID = '[0x0011]: Duplicate Transaction ID';
//#define DBXERR_DRIVERRESTRICTED 0x0012
SDRIVERRESTRICTED = '[0x0012]: Application is not licensed to use this feature';
//#define DBXERR_LOCALTRANSACTIVE 0x0013
SLOCALTRANSACTIVE = '[0x0013]: Local Transaction already active';
//#define DBXERR_MULTIPLETRANSNOTENABLED 0x0014
SMULTIPLETRANSNOTENABLED = '[0x0014]: Multiple Transactions not Enabled';
//#define DBXERR_CONNECTIONFAILED 0x0015
SCONNECTIONFAILED = '[0x0015]: Connection failed';
//#define DBXERR_DRIVERINITFAILED 0x0016
SDRIVERINITFAILED ='[0x0016]: Driver initialization failed';
//#define DBXERR_OPTLOCKFAILED 0x0017
SOPTLOCKFAILED = '[0x0017]: Optimistic Locking failed';
//#define DBXERR_INVALIDREF 0x0018
SINVALIDREF = '[0x0018]: Invalid REF';
//#define DBXERR_NOTABLE 0x0019
SNOTABLE = '[0x0019]: No table found';
//#define DBXERR_MISSINGPARAMINSQL 0x001A
SMISSINGPARAMINSQL = '[0x001A] Missing parameter marker in SQL';
//#define DBXERR_NOTIMPLEMENT 0x001B
SNOTIMPLEMENTED = '[0x001B] Not implemented';
//#define DBXERR_DRIVERINCOMPATIBLE 0x001cC
SDRIVERINCOMPATIBLE = '[0x001C] Incompatible driver';
//#define DBXERR_NODATA 0x0064
SNODATA = '[0x0064]: No more data';
//#define DBXERR_SQLERROR 0x0065
SSQLERROR = '[0x0065]: SQL Error';
SDBXError = 'dbExpress Error: %s';
SSQLServerError = 'Database Server Error: %s';
SConfFileMoveError = 'Unable to move %s to %s';
SMissingConfFile = 'Configuration file %s not found';
SObjectViewNotTrue = 'ObjectView must be True for Table with Object fields';
SObjectTypenameRequired = 'Object type name required as parameter value';
SCannotCreateFile = 'Cannot create file %s';
// used in SqlReg.pas
SDlgOpenCaption = 'Open trace log file';
SDlgFilterTxt = 'Text files (*.txt)|*.txt|All files (*.*)|*.*';
SLogFileFilter = 'Log files (*.log)';
SCircularProvider = 'Circular provider references not allowed.';
SUnknownDataType = 'Unknown data type: %s for %s parameter';
SSaveConnectionParams = 'Save connection parameters';
SReloadConnectionParams = 'Reload connection parameters';
SGenerateClientClasses = 'Generate DataSnap client classes';
implementation
end.
|
unit NtUtils.Svc.Security;
interface
uses
Winapi.WinNt, Winapi.Svc, NtUtils.Exceptions, NtUtils.Security.Acl,
NtUtils.Security.Sid;
type
TAce = NtUtils.Security.Acl.TAce;
IAcl = NtUtils.Security.Acl.IAcl;
TAcl = NtUtils.Security.Acl.TAcl;
ISid = NtUtils.Security.Sid.ISid;
{ Query security }
// Security descriptor
function ScmxQuerySecurityObject(ScmHandle: TScmHandle; SecurityInformation:
TSecurityInformation; out SecDesc: PSecurityDescriptor): TNtxStatus;
// Owner
function ScmxQueryOwnerObject(ScmHandle: TScmHandle; out Owner: ISid):
TNtxStatus;
// Primary group
function ScmxQueryPrimaryGroupObject(ScmHandle: TScmHandle;
out PrimaryGroup: ISid): TNtxStatus;
// DACL
function ScmxQueryDaclObject(ScmHandle: TScmHandle; out Dacl: IAcl): TNtxStatus;
// SACL
function ScmxQuerySaclObject(ScmHandle: TScmHandle; out Sacl: IAcl): TNtxStatus;
// Mandatory label
function ScmxQueryLabelObject(ScmHandle: TScmHandle; out Sacl: IAcl):
TNtxStatus;
{ Set security }
// Security descriptor
function ScmxSetSecurityObject(ScmHandle: TScmHandle; SecInfo:
TSecurityInformation; const SecDesc: TSecurityDescriptor): TNtxStatus;
// Owner
function ScmxSetOwnerObject(ScmHandle: TScmHandle; Owner: ISid): TNtxStatus;
// Primary group
function ScmxSetPrimaryGroupObject(ScmHandle: TScmHandle; Group: ISid):
TNtxStatus;
// DACL
function ScmxSetDaclObject(ScmHandle: TScmHandle; Dacl: IAcl): TNtxStatus;
// SACL
function ScmxSetSaclObject(ScmHandle: TScmHandle; Sacl: IAcl): TNtxStatus;
// Mandatory label
function ScmxSetLabelObject(ScmHandle: TScmHandle; Sacl: IAcl): TNtxStatus;
implementation
uses
Ntapi.ntrtl;
// Security descriptor
function ScmxQuerySecurityObject(ScmHandle: TScmHandle; SecurityInformation:
TSecurityInformation; out SecDesc: PSecurityDescriptor): TNtxStatus;
var
BufferSize, Required: Cardinal;
begin
Result.Location := 'QueryServiceObjectSecurity';
Result.LastCall.Expects(RtlxComputeReadAccess(SecurityInformation),
@NonSpecificAccessType);
BufferSize := 0;
repeat
SecDesc := AllocMem(BufferSize);
Required := 0;
Result.Win32Result := QueryServiceObjectSecurity(ScmHandle,
SecurityInformation, SecDesc, BufferSize, Required);
if not Result.IsSuccess then
begin
FreeMem(SecDesc);
SecDesc := nil;
end;
until not NtxExpandBuffer(Result, BufferSize, Required);
end;
// Owner
function ScmxQueryOwnerObject(ScmHandle: TScmHandle; out Owner: ISid):
TNtxStatus;
var
pSD: PSecurityDescriptor;
begin
Result := ScmxQuerySecurityObject(ScmHandle, OWNER_SECURITY_INFORMATION, pSD);
if not Result.IsSuccess then
Exit;
Result := RtlxGetOwnerSD(pSD, Owner);
FreeMem(pSD);
end;
// Primary group
function ScmxQueryPrimaryGroupObject(ScmHandle: TScmHandle;
out PrimaryGroup: ISid): TNtxStatus;
var
pSD: PSecurityDescriptor;
begin
Result := ScmxQuerySecurityObject(ScmHandle, GROUP_SECURITY_INFORMATION, pSD);
if not Result.IsSuccess then
Exit;
Result := RtlxGetPrimaryGroupSD(pSD, PrimaryGroup);
FreeMem(pSD);
end;
// DACL
function ScmxQueryDaclObject(ScmHandle: TScmHandle; out Dacl: IAcl): TNtxStatus;
var
pSD: PSecurityDescriptor;
begin
Result := ScmxQuerySecurityObject(ScmHandle, DACL_SECURITY_INFORMATION, pSD);
if not Result.IsSuccess then
Exit;
Result := RtlxGetDaclSD(pSD, Dacl);
FreeMem(pSD);
end;
// SACL
function ScmxQuerySaclObject(ScmHandle: TScmHandle; out Sacl: IAcl): TNtxStatus;
var
pSD: PSecurityDescriptor;
begin
Result := ScmxQuerySecurityObject(ScmHandle, SACL_SECURITY_INFORMATION, pSD);
if not Result.IsSuccess then
Exit;
Result := RtlxGetSaclSD(pSD, Sacl);
FreeMem(pSD);
end;
// Mandatory label
function ScmxQueryLabelObject(ScmHandle: TScmHandle; out Sacl: IAcl):
TNtxStatus;
var
pSD: PSecurityDescriptor;
begin
Result := ScmxQuerySecurityObject(ScmHandle, LABEL_SECURITY_INFORMATION, pSD);
if not Result.IsSuccess then
Exit;
Result := RtlxGetSaclSD(pSD, Sacl);
FreeMem(pSD);
end;
{ Set security }
// Security descriptor
function ScmxSetSecurityObject(ScmHandle: TScmHandle; SecInfo:
TSecurityInformation; const SecDesc: TSecurityDescriptor): TNtxStatus;
begin
Result.Location := 'SetServiceObjectSecurity';
Result.LastCall.Expects(RtlxComputeWriteAccess(SecInfo),
@NonSpecificAccessType);
Result.Win32Result := SetServiceObjectSecurity(ScmHandle, SecInfo, SecDesc);
end;
// Owner
function ScmxSetOwnerObject(ScmHandle: TScmHandle; Owner: ISid): TNtxStatus;
var
SD: TSecurityDescriptor;
begin
Result := RtlxPrepareOwnerSD(SD, Owner);
if Result.IsSuccess then
Result := ScmxSetSecurityObject(ScmHandle, OWNER_SECURITY_INFORMATION, SD);
end;
// Primary group
function ScmxSetPrimaryGroupObject(ScmHandle: TScmHandle; Group: ISid):
TNtxStatus;
var
SD: TSecurityDescriptor;
begin
Result := RtlxPreparePrimaryGroupSD(SD, Group);
if Result.IsSuccess then
Result := ScmxSetSecurityObject(ScmHandle, GROUP_SECURITY_INFORMATION, SD);
end;
// DACL
function ScmxSetDaclObject(ScmHandle: TScmHandle; Dacl: IAcl): TNtxStatus;
var
SD: TSecurityDescriptor;
begin
Result := RtlxPrepareDaclSD(SD, Dacl);
if Result.IsSuccess then
Result := ScmxSetSecurityObject(ScmHandle, DACL_SECURITY_INFORMATION, SD);
end;
// SACL
function ScmxSetSaclObject(ScmHandle: TScmHandle; Sacl: IAcl): TNtxStatus;
var
SD: TSecurityDescriptor;
begin
Result := RtlxPrepareSaclSD(SD, Sacl);
if Result.IsSuccess then
Result := ScmxSetSecurityObject(ScmHandle, SACL_SECURITY_INFORMATION, SD);
end;
// Mandatory label
function ScmxSetLabelObject(ScmHandle: TScmHandle; Sacl: IAcl): TNtxStatus;
var
SD: TSecurityDescriptor;
begin
Result := RtlxPrepareSaclSD(SD, Sacl);
if Result.IsSuccess then
Result := ScmxSetSecurityObject(ScmHandle, LABEL_SECURITY_INFORMATION, SD);
end;
end.
|
unit uTestMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls,
JD.Weather.ApiSvr, Data.DB, Data.Win.ADODB;
type
TForm1 = class(TForm)
pTop: TPanel;
btnStop: TBitBtn;
btnStart: TBitBtn;
Log: TMemo;
DB: TADOConnection;
procedure btnStartClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
FSvr: TJDWeatherApiSvrThread;
procedure ThreadLog(Sender: TObject; const Timestamp: TDateTime;
const Msg: String);
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnStartClick(Sender: TObject);
begin
btnStart.Enabled:= False;
btnStop.Enabled:= True;
FSvr:= TJDWeatherApiSvrThread.Create;
FSvr.ConnStr:= 'Provider=SQLOLEDB.1;Persist Security Info=True;Data Source=LocalHost\JD;Initial Catalog=JDWeather;User ID=sa;Password=';
FSvr.OnLog:= ThreadLog;
FSvr.Start;
end;
procedure TForm1.btnStopClick(Sender: TObject);
begin
btnStart.Enabled:= True;
btnStop.Enabled:= False;
if Assigned(FSvr) then begin
FSvr.Terminate;
FSvr.WaitFor;
FreeAndNil(FSvr);
end;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Assigned(FSvr) then begin
FSvr.Terminate;
FSvr.WaitFor;
FreeAndNil(FSvr);
end;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
btnStart.Click;
end;
procedure TForm1.ThreadLog(Sender: TObject; const Timestamp: TDateTime;
const Msg: String);
begin
Log.Lines.Append(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Timestamp)+' - '+Msg);
end;
end.
|
program BridgeCrossing;
uses SwinGame, sgTypes;
const
SIDEWIDTH = 37;
SIDEHEIGHT = 288;
type
Alphabet = (A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z);
CharacterData = record
StretchSpeed,length,x,y : Integer;
bmp: Bitmap;
//types : CharacterType;
end;
GameData = record
character : CharacterData;
key : KeyCode;
charBmp: Bitmap;
x,y: Integer;
time : Timer;
end;
function GameKey(alphabet: Alphabet): GameData;
begin
// Return the bitmap that matches the kind of fruit asked for
case alphabet of
A:
begin
result.key := vk_a;
result.charBmp := BitmapNamed('a');
end;
B:
begin
result.key := vk_b;
result.charBmp := BitmapNamed('b');
end;
C:
begin
result.key := vk_c;
result.charBmp := BitmapNamed('c');
end;
D:
begin
result.key := vk_d;
result.charBmp := BitmapNamed('d');
end;
E:
begin
result.key := vk_e;
result.charBmp := BitmapNamed('e');
end;
F:
begin
result.key := vk_f;
result.charBmp := BitmapNamed('f');
end;
G:
begin
result.key := vk_g;
result.charBmp := BitmapNamed('g');
end;
H:
begin
result.key := vk_h;
result.charBmp := BitmapNamed('h');
end;
I:
begin
result.key := vk_i;
result.charBmp := BitmapNamed('i');
end;
J:
begin
result.key := vk_j;
result.charBmp := BitmapNamed('j');
end;
K:
begin
result.key := vk_k;
result.charBmp := BitmapNamed('k');
end;
L:
begin
result.key := vk_l;
result.charBmp := BitmapNamed('l');
end;
M:
begin
result.key := vk_m;
result.charBmp := BitmapNamed('m');
end;
N:
begin
result.key := vk_n;
result.charBmp := BitmapNamed('n');
end;
O:
begin
result.key := vk_o;
result.charBmp := BitmapNamed('o');
end;
P:
begin
result.key := vk_p;
result.charBmp := BitmapNamed('p');
end;
Q:
begin
result.key := vk_q;
result.charBmp := BitmapNamed('q');
end;
R:
begin
result.key := vk_r;
result.charBmp := BitmapNamed('r');
end;
S:
begin
result.key := vk_s;
result.charBmp := BitmapNamed('s');
end;
T:
begin
result.key := vk_t;
result.charBmp := BitmapNamed('t');
end;
U:
begin
result.key := vk_u;
result.charBmp := BitmapNamed('u');
end;
V:
begin
result.key := vk_v;
result.charBmp := BitmapNamed('v');
end;
W:
begin
result.key := vk_w;
result.charBmp := BitmapNamed('w');
end;
X:
begin
result.key := vk_x;
result.charBmp := BitmapNamed('x');
end;
Y:
begin
result.key := vk_y;
result.charBmp := BitmapNamed('y');
end;
Z:
begin
result.key := vk_z;
result.charBmp := BitmapNamed('z');
end;
else
result.key := vk_a;
result.charBmp := BitmapNamed('a'); // return nil if not match any alphabet
end;
end;
function RandomAlphabet() : GameData;
begin
// Randomly pick one of the 26 alphabet
result := GameKey(Alphabet(Rnd(26)));
end;
procedure DrawGame(mainGameData : GameData;x,y,bridgeX: Integer;characterMoving: Sprite);
begin
DrawBitMap('cloud',0,0);
DrawSprite(characterMoving );
UpdateSprite(characterMoving );
DrawBitMap('side',0,200);
DrawBitMap('side',ScreenWidth()-SIDEWIDTH,200);
//DrawBitMap('bridge',bridgeX+16,200);
//DrawBitMap('bridge',bridgeX+32,200);
//DrawBitMap('bridge',bridgeX,200);
DrawBitMap(mainGameData.charBmp,mainGameData.x,mainGameData.y);
DrawBitMapPart(BitmapNamed('bridge1'),80,0,bridgeX,16,SIDEWIDTH,200);
SpriteSetX(characterMoving ,x);
SpriteSetY(characterMoving ,y);
RefreshScreen(40);
end;
procedure UpdateGame(var x,y,bridgeX,gamespeed: Integer);
var
playSound: Integer;
begin
if (x < ScreenWidth() - 65) then
begin
x := x + gamespeed;
end;
if KeyTyped(vk_UP) then
begin
end;
playSound := 0;
if(x > bridgeX) then
begin
if(playSound = 0) then
y := y + gamespeed*5;
if(y > ScreenHeight()) then
begin
x := 0;
y := 165;
bridgeX := SIDEWIDTH;
end;
end;
end;
procedure HandleInput(var mainGameData :GameData;var x,bridgeX:Integer;var gameWin: Boolean);
begin
if KeyTyped(mainGameData.key) and (x < bridgeX) then
begin
PlaySoundEffect('Type');
mainGameData := RandomAlphabet();
mainGameData.x := (Rnd(ScreenWidth() - BitmapWidth(mainGameData.charBmp)));
mainGameData.y := (Rnd(100));
//DrawBitMapPart(BitmapNamed('bridge1'),100,100,100,100,bridgeX,200);
if (bridgeX < ScreenWidth() - 2*SIDEWIDTH) then
begin
bridgeX := bridgeX + 32;
end
else
begin
gameWin := true;
end;
end;
end;
procedure LevelSelect();
begin
DrawBitMap('cloud',0,0);
DrawText ('Please Choose The Difficulty For the Game',ColorBlack,'gamefont',200,100);
DrawText ('1. Easy',ColorBlack,'gamefont',250,120);
DrawText ('2. Medium',ColorBlack,'gamefont',250,140);
DrawText ('3. Hard',ColorBlack,'gamefont',250,160);
end;
procedure Main();
var
characterMoving : Sprite;
bridgeX,x,y,gamespeed: Integer;
mainGameData: GameData;
gameBegin,gameWin: boolean;
begin
OpenAudio();
gameBegin := false;
OpenGraphicsWindow('Bridge', 705, 344);
LoadMusicNamed('music','HarvestMoonBackToNature.mp3');
LoadSoundEffectNamed('Fall', 'fall.wav');
LoadSoundEffectNamed('Type', '3.wav');
PlayMusic('music',-1);
SetMusicVolume(0.5);
LoadDefaultColors();
// LoadResources();
LoadResourceBundle('character.txt' );
characterMoving := CreateSprite(BitmapNamed('sprite') ,AnimationScriptNamed('Moving' ) );
SpriteStartAnimation(characterMoving,'Moving');
mainGameData := RandomAlphabet();
mainGameData.x := (Rnd(ScreenWidth()));
mainGameData.y := (Rnd(100));
x := 0;
y := 165;
bridgeX := SIDEWIDTH;
SpriteSetX(characterMoving ,x);
SpriteSetY(characterMoving ,y);
//loop the game
repeat
ProcessEvents();
//Level Choice
repeat
ProcessEvents();
ClearScreen(ColorWhite);
//Level select interface
LevelSelect();
RefreshScreen(60);
//Event handle for difficulty
if (KeyTyped(vk_1)) then
begin
gamespeed := 1;
gameBegin := true;
end;
if (KeyTyped(vk_2)) then
begin
gamespeed := 2;
gameBegin := true;
end;
if (KeyTyped(vk_3)) then
begin
gamespeed := 3;
gameBegin := true;
end;
until (WindowCloseRequested() or gameBegin);
gameWin := false;
//real game begin
repeat
ProcessEvents();
UpdateGame(x,y,bridgeX,gamespeed);
HandleInput(mainGameData,x,bridgeX,gameWin);
DrawGame(mainGameData,x,y,bridgeX,characterMoving);
until (WindowCloseRequested() or gameWin );
//reset the value
gameBegin := false;
x := 0;
y := 165;
bridgeX := SIDEWIDTH;
until(WindowCloseRequested());
ReleaseAllResources();
end;
begin
Main();
end.
|
unit pos_func;
interface
implementation
function Pos(const SubStr, Str: string): Int32;
var
I, LIterCnt, L, J: Int32;
begin
L := Length(SubStr);
LIterCnt := Length(Str) - L;
if (LIterCnt >= 0) and (L > 0) then
begin
for I := 0 to LIterCnt do
begin
J := 0;
while (J >= 0) and (J < L) do
begin
if Str[I + J] = SubStr[J] then
Inc(J)
else
J := -1;
end;
if J >= L then
Exit(I);
end;
end;
Result := -1;
end;
procedure Test;
var
p: Int32;
begin
p := Pos('PAD', 'PADDING');
Assert(p = 0);
p := Pos('AD', 'PADDING');
Assert(p = 1);
p := Pos('D', 'PADDING');
Assert(p = 2);
p := Pos('ING', 'PADDING');
Assert(p = 4);
p := Pos('NG', 'PADDING');
Assert(p = 5);
p := Pos('G', 'PADDING');
Assert(p = 6);
p := Pos('X', 'PADDING');
Assert(p = -1);
end;
initialization
Test();
finalization
end. |
unit u_xpl_xhcp;
{$ifdef fpc}
{$mode objfpc}{$H+}
{$endif}
interface
uses Classes
, SysUtils
, IdTelnetServer
, IdTelnet;
type
TXHCPDataAvailEvent = procedure (const ansType : integer; const Buffer: TStringList) of object;
{ TXHCPServer ============================================================}
TXHCPServer = class(TIdTelnetServer)
public
constructor Create(const aOwner : TComponent);
end;
{ TXHCPClient }
TXHCPClient = class(TIdTelnet) // Connexion used to listen XHCP messages
private
fOnAnswerAvailable : TXHCPDataAvailEvent;
BigBuff : TStringList;
ResponsePending : boolean;
protected
procedure DataAvailable(Sender: TIdTelnet; const Buffer: String);
public
constructor Create(const aOwner : TComponent);
destructor Destroy; override;
procedure Connect; override;
procedure Send(const aString : string);
property OnAnswerAvailable : TXHCPDataAvailEvent read fOnAnswerAvailable write fOnAnswerAvailable;
end;
implementation
uses u_xpl_common
, StrUtils;
// TXHCPServer ===============================================================
constructor TXHCPServer.Create(const aOwner: TComponent);
begin
inherited Create(aOwner);
DefaultPort := XPL_UDP_BASE_PORT;
LoginMessage := '';
Active := True;
end;
{ TXHCPClient }
constructor TXHCPClient.Create(const aOwner: TComponent);
begin
inherited Create(aOwner);
Port := XPL_UDP_BASE_PORT;
OnDataAvailable := @DataAvailable;
ResponsePending := false;
BigBuff := TStringList.Create;
BigBuff.Delimiter:=#13;
BigBuff.StrictDelimiter:=true;
end;
destructor TXHCPClient.Destroy;
begin
BigBuff.Free;
inherited Destroy;
end;
procedure TXHCPClient.DataAvailable(Sender: TIdTelnet; const Buffer: String);
var newbuff : string;
response_code : string;
response_start: integer;
iresponse : integer = -1;
begin
NewBuff := AnsiReplaceStr(Buffer,#10,'');
if not ResponsePending then begin
BigBuff.DelimitedText := NewBuff;
ResponsePending := (AnsiPos('follows',BigBuff[0]) <> 0);
end else
BigBuff.DelimitedText := BigBuff.DelimitedText + #13 + NewBuff;
if BigBuff[BigBuff.Count-1] = '' then BigBuff.Delete(BigBuff.Count-1);
if BigBuff[BigBuff.Count-1] = '.' then ResponsePending := false;
if not ResponsePending then begin
iResponse := StrToIntDef(AnsiLeftStr(BigBuff[0],3),-1);
BigBuff[0] := AnsiRightStr(BigBuff[0], length(BigBuff[0])-4);
if AnsiPos('follows',BigBuff[0])<>0 then BigBuff.Delete(0);
if BigBuff[BigBuff.Count-1]='.' then BigBuff.Delete(BigBuff.Count-1);
OnAnswerAvailable(iResponse, bigbuff);
end;
end;
procedure TXHCPClient.Connect;
begin
if Connected then Disconnect;
inherited Connect;
end;
procedure TXHCPClient.Send(const aString: string);
var ch : char;
begin
for ch in aString do SendCh(ch);
SendCh(#13);
end;
end.
|
unit Demo.Framework;
interface
uses
W3C.DOM4, W3C.HTML5, W3C.Canvas2DContext, W3C.CSSOM, W3C.SVG2;
type
TVector2i = record
X: Integer;
Y: Integer;
class function Create(const X, Y: Integer): TVector2i; static;
end;
TVector2f = record
X: Float;
Y: Float;
class function Create(const X, Y: Float): TVector2f; static;
end;
IHtmlElementOwner = interface
function GetHtmlElement: JHTMLElement;
property HtmlElement: JHTMLElement read GetHtmlElement;
end;
THtmlElement = class;
THtmlElementClass = class of THtmlElement;
THtmlElement = class(IHtmlElementOwner)
private
function GetVisible: Boolean;
procedure SetName(Value: String);
procedure SetVisible(Value: Boolean);
protected
FOwner: IHtmlElementOwner;
FName: String;
FElement: JHTMLElement;
class var Counter: Integer;
function GetHtmlElement: JHTMLElement;
class function ElementName: String; virtual; abstract;
procedure NameChanged; virtual;
procedure AfterConstructor; virtual; empty;
property Element: JHTMLElement read FElement;
public
constructor Create(Owner: IHtmlElementOwner); overload; virtual;
constructor Create(Element: JHTMLElement); overload; virtual;
destructor Destroy; override;
procedure Resize; virtual; empty;
property Name: String read FName write SetName;
property Visible: Boolean read GetVisible write SetVisible;
property Style: JCSS2Properties read (JCSS2Properties(Element.Style));
property Owner: IHtmlElementOwner read FOwner;
end;
TDivElement = class(THtmlElement)
protected
class function ElementName: String; override;
public
property DivElement: JHTMLDivElement read (JHTMLDivElement(Element));
end;
TButtonElement = class(THtmlElement)
protected
FTextNode: JText;
class function ElementName: String; override;
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
property ButtonElement: JHTMLButtonElement read (JHTMLButtonElement(Element));
property Text: string read (FTextNode.Data) write (FTextNode.Data);
end;
TParagraphElement = class(THtmlElement)
private
FTextNode: JText;
protected
class function ElementName: String; override;
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
property ParagraphElement: JHTMLParagraphElement read (JHTMLParagraphElement(Element));
property Text: string read (FTextNode.Data) write (FTextNode.Data);
end;
TLinkElement = class(THtmlElement)
private
FTextNode: JText;
protected
class function ElementName: String; override;
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
property LinkElement: JHTMLLinkElement read (JHTMLLinkElement(Element));
property Text: string read (FTextNode.Data) write (FTextNode.Data);
end;
TCustomHeadingElement = class(THtmlElement)
private
FTextNode: JText;
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
property HeadingElement: JHTMLHeadingElement read (JHTMLHeadingElement(Element));
property Text: string read (FTextNode.Data) write (FTextNode.Data);
end;
TH1Element = class(TCustomHeadingElement)
protected
class function ElementName: String; override;
end;
TH2Element = class(TCustomHeadingElement)
protected
class function ElementName: String; override;
end;
TH3Element = class(TCustomHeadingElement)
protected
class function ElementName: String; override;
end;
TH4Element = class(TCustomHeadingElement)
protected
class function ElementName: String; override;
end;
TH5Element = class(TCustomHeadingElement)
protected
class function ElementName: String; override;
end;
TH6Element = class(TCustomHeadingElement)
protected
class function ElementName: String; override;
end;
TImageElement = class(THtmlElement)
protected
class function ElementName: String; override;
public
property ImageElement: JHTMLImageElement read (JHTMLImageElement(Element));
end;
TInputElement = class(THtmlElement)
protected
class function ElementName: String; override;
public
property InputElement: JHTMLInputElement read (JHTMLInputElement(Element));
property Value: string read (InputElement.Value) write (InputElement.Value);
end;
TInputTextElement = class(TInputElement)
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
property Placeholder: String read (InputElement.Placeholder) write (InputElement.Placeholder);
end;
TInputPasswordElement = class(TInputElement)
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
property Placeholder: String read (InputElement.Placeholder) write (InputElement.Placeholder);
end;
TInputRadioElement = class(TInputElement)
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
end;
TInputCheckBoxElement = class(TInputElement)
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
end;
TInputRangeElement = class(TInputElement)
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
end;
TInputFileElement = class(TInputElement)
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
end;
TFieldSetElement = class(THtmlElement)
protected
class function ElementName: String; override;
end;
TTextAreaElement = class(THtmlElement)
protected
class function ElementName: String; override;
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
property TextAreaElement: JHTMLTextAreaElement read (JHTMLTextAreaElement(Element));
property Value: string read (TextAreaElement.Value) write (TextAreaElement.Value);
end;
TLabelElement = class(THtmlElement)
private
FTextNode: JText;
protected
class function ElementName: String; override;
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
property LabelElement: JHTMLLabelElement read (JHTMLLabelElement(Element));
property Text: string read (FTextNode.Data) write (FTextNode.Data);
end;
TCanvasElement = class(THtmlElement)
protected
class function ElementName: String; override;
public
property CanvasElement: JHTMLCanvasElement read (JHTMLCanvasElement(Element));
end;
TCanvas2DElement = class(TCanvasElement)
private
FContext: JCanvasRenderingContext2D;
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
property Context: JCanvasRenderingContext2D read FContext;
end;
TSvgElement = class(THtmlElement)
protected
class function ElementName: String; override;
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
property SvgElement: JSvgSvgElement read (JSvgSvgElement(Element));
end;
TOptionElement = class(THtmlElement)
private
FTextNode: JText;
protected
class function ElementName: String; override;
public
constructor Create(Owner: IHtmlElementOwner); overload; override;
property OptionElement: JHTMLOptionElement read (JHTMLOptionElement(Element));
property Text: string read (FTextNode.Data) write (FTextNode.Data);
end;
TSelectElement = class(THtmlElement)
private
FItems: array of TOptionElement;
protected
class function ElementName: String; override;
public
procedure AddItem(Text: String); overload;
procedure AddItem(Text, ID: String); overload;
procedure Clear;
property SelectElement: JHTMLSelectElement read (JHTMLSelectElement(Element));
end;
TApplication = class(IHtmlElementOwner)
private
FPixelRatio: Float;
FElements: array of THtmlElement;
function GetHtmlElement: JHTMLElement;
public
constructor Create;
destructor Destroy; override;
procedure DeviceReady; virtual;
procedure Pause; virtual; empty;
procedure Resume; virtual; empty;
function CreateElement(HtmlElementClass: THtmlElementClass): THtmlElement;
procedure Run; empty;
property PixelRatio: Float read FPixelRatio;
end;
var
Application: TApplication;
CordovaAvailable: Boolean;
implementation
uses
WHATWG.Console, W3C.CSSOM, Cordova.StatusBar;
{ TVector2i }
class function TVector2i.Create(const X, Y: Integer): TVector2i;
begin
Result.X := X;
Result.Y := Y;
end;
{ TVector2f }
class function TVector2f.Create(const X, Y: Float): TVector2f;
begin
Result.X := X;
Result.Y := Y;
end;
{ THtmlElement }
constructor THtmlElement.Create(Owner: IHtmlElementOwner);
var
Classes: String;
begin
FOwner := Owner;
FElement := JHTMLElement(Document.createElement(ElementName));
Owner.HtmlElement.appendChild(FElement);
Classes := ClassName;
var ParentClass := ClassParent;
while Assigned(ParentClass) do
begin
if ParentClass.ClassName = 'TObject' then
break;
Classes += ' ' + ParentClass.ClassName;
ParentClass := ParentClass.ClassParent;
end;
// specify element class
FElement.setAttribute('class', Classes);
Inc(Counter);
FName := ElementName + IntToStr(Counter);
// call after constructor
AfterConstructor;
end;
constructor THtmlElement.Create(Element: JHTMLElement);
begin
FOwner := nil;
FElement := Element;
Inc(Counter);
FName := ElementName + IntToStr(Counter);
// call after constructor
AfterConstructor;
end;
destructor THtmlElement.Destroy;
begin
//BeforeDestructor;
FOwner.HtmlElement.removeChild(FElement);
inherited;
end;
function THtmlElement.GetHtmlElement: JHTMLElement;
begin
Result := FElement;
end;
function THtmlElement.GetVisible: Boolean;
begin
Result := Element.style.getPropertyValue('visibility') = 'visible';
end;
procedure THtmlElement.SetName(Value: String);
begin
if Name <> Value then
begin
FName := Value;
NameChanged;
end;
end;
procedure THtmlElement.SetVisible(Value: Boolean);
begin
Element.style.setProperty('visibility', if Value then 'visible' else 'hidden');
end;
procedure THtmlElement.NameChanged;
begin
FElement.id := Name;
end;
{ TDivElement }
class function TDivElement.ElementName: String;
begin
Result := 'div';
end;
{ TButtonElement }
constructor TButtonElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
FTextNode := Document.createTextNode('');
Element.appendChild(FTextNode);
end;
class function TButtonElement.ElementName: String;
begin
Result := 'button';
end;
{ TParagraphElement }
constructor TParagraphElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
FTextNode := Document.createTextNode('');
Element.appendChild(FTextNode);
end;
class function TParagraphElement.ElementName: String;
begin
Result := 'p';
end;
{ TLinkElement }
constructor TLinkElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
FTextNode := Document.createTextNode('');
Element.appendChild(FTextNode);
end;
class function TLinkElement.ElementName: String;
begin
Result := 'a';
end;
{ TCustomHeadingElement }
constructor TCustomHeadingElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
FTextNode := Document.createTextNode('');
Element.appendChild(FTextNode);
end;
{ TH1Element }
class function TH1Element.ElementName: String;
begin
Result := 'H1';
end;
{ TH2Element }
class function TH2Element.ElementName: String;
begin
Result := 'H2';
end;
{ TH3Element }
class function TH3Element.ElementName: String;
begin
Result := 'H3';
end;
{ TH4Element }
class function TH4Element.ElementName: String;
begin
Result := 'H4';
end;
{ TH5Element }
class function TH5Element.ElementName: String;
begin
Result := 'H5';
end;
{ TH6Element }
class function TH6Element.ElementName: String;
begin
Result := 'H6';
end;
{ TImageElement }
class function TImageElement.ElementName: String;
begin
Result := 'img';
end;
{ TInputElement }
class function TInputElement.ElementName: String;
begin
Result := 'input';
end;
{ TInputTextElement }
constructor TInputTextElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
InputElement.type := THTMLInputElementType.Text;
end;
{ TInputPasswordElement }
constructor TInputPasswordElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
InputElement.type := THTMLInputElementType.Password;
end;
{ TInputRadioElement }
constructor TInputRadioElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
InputElement.type := THTMLInputElementType.Radio;
end;
{ TInputCheckBoxElement }
constructor TInputCheckBoxElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
InputElement.type := THTMLInputElementType.CheckBox;
end;
{ TInputRangeElement }
constructor TInputRangeElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
InputElement.type := THTMLInputElementType.Range;
end;
{ TInputFileElement }
constructor TInputFileElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
InputElement.type := 'file';
end;
{ TTextAreaElement }
constructor TTextAreaElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
end;
class function TTextAreaElement.ElementName: String;
begin
Result := 'textarea';
end;
{ TFieldSetElement }
class function TFieldSetElement.ElementName: String;
begin
Result := 'fieldset';
end;
{ TLabelElement }
constructor TLabelElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
FTextNode := Document.createTextNode('');
Element.appendChild(FTextNode);
end;
class function TLabelElement.ElementName: String;
begin
Result := 'label';
end;
{ TCanvasElement }
class function TCanvasElement.ElementName: String;
begin
Result := 'canvas';
end;
{ TCanvas2DElement }
constructor TCanvas2DElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
FContext := JCanvasRenderingContext2D(CanvasElement.getContext('2d'));
end;
{ TSvgElement }
constructor TSvgElement.Create(Owner: IHtmlElementOwner);
var
Classes: String;
begin
FOwner := Owner;
FElement := JHTMLElement(Document.createElementNS('http://www.w3.org/2000/svg', ElementName));
Owner.HtmlElement.appendChild(FElement);
Classes := ClassName;
var ParentClass := ClassParent;
while Assigned(ParentClass) do
begin
if ParentClass.ClassName = 'TObject' then
break;
Classes += ' ' + ParentClass.ClassName;
ParentClass := ParentClass.ClassParent;
end;
// specify element class
FElement.setAttribute('class', Classes);
Inc(Counter);
FName := ElementName + IntToStr(Counter);
// call after constructor
AfterConstructor;
end;
class function TSvgElement.ElementName: String;
begin
Result := 'svg';
end;
{ TOptionElement }
constructor TOptionElement.Create(Owner: IHtmlElementOwner);
begin
inherited Create(Owner);
FTextNode := Document.createTextNode('');
Element.appendChild(FTextNode);
end;
class function TOptionElement.ElementName: String;
begin
Result := 'option';
end;
{ TSelectElement }
class function TSelectElement.ElementName: String;
begin
Result := 'select';
end;
procedure TSelectElement.Clear;
begin
while FItems.Count > 0 do
begin
FItems[0].Free;
FItems.Delete(0);
end;
end;
procedure TSelectElement.AddItem(Text: String);
begin
var Item := TOptionElement.Create(Self as IHtmlElementOwner);
Item.Text := Text;
FItems.Add(Item);
end;
procedure TSelectElement.AddItem(Text, ID: String);
begin
var Item := TOptionElement.Create(Self as IHtmlElementOwner);
Item.Text := Text;
Item.OptionElement.id := ID;
FItems.Add(Item);
end;
{ TApplication }
constructor TApplication.Create;
begin
// add cordova events
Document.addEventListener('deviceready', @DeviceReady);
// determine pixel ratio
FPixelRatio := 1;
asm
@FPixelRatio = window.devicePixelRatio || 1;
end;
end;
destructor TApplication.Destroy;
begin
inherited;
end;
function TApplication.GetHtmlElement: JHTMLElement;
begin
Result := Document.Body;
end;
function TApplication.CreateElement(HtmlElementClass: THtmlElementClass): THtmlElement;
begin
Result := HtmlElementClass.Create(Self as IHtmlElementOwner);
FElements.Add(Result);
end;
procedure TApplication.DeviceReady;
begin
{$IFDEF DEBUG} Console.Log('Cordova is ready!'); {$ENDIF}
// add cordova events
Document.addEventListener('pause', @Pause);
Document.addEventListener('resume', @Resume);
{$IFDEF iOS}
// try to hide status bar
if Assigned(StatusBar) then
StatusBar.hide;
{$ENDIF}
CordovaAvailable := True;
end;
initialization
Application := TApplication.Create;
end. |
{
GMGeoCode unit
ES: Contiene las classes necesarias para la geocodificación.
EN: Includes the necessary classes to geocoding.
=========================================================================
MODO DE USO/HOW TO USE
ES: poner el componente en el formulario, unirlo a un TGMMap y ejecutar el
método Geocode. Si queremos mostrar los marcadores, linkarlo a un TGMMarker.
EN: put the component into a form, link it to a TGMMap and execute Geocode
method. If you want to show markers, link it to a TGMMarker.
=========================================================================
History:
ver 1.5.2
ES:
error: TGMGeoCode -> TGeoResult.Geometry.LocationType siempre devolvía gltNothing (GC: issue 46)
EN:
bug: TGMGeoCode -> TGeoResult.Geometry.LocationType is always gltNothing (GC: issue 46)
ver 1.2.0
ES:
error: TAddressComponentsList -> corregido Memory leak en el método Destroy (gracias Mike) (GC: issue 13).
EN:
bug: TAddressComponentsList -> fixed Memory leak on Destroy method (thanks Mike) (GC: issue 13).
ver 1.0.1
ES:
error: JavaScript -> corregido error en función GeocoderToXMLData cuando la
geocodificación no devolvía resultados.
EN:
bug: JavaScript -> bug fixed on GeocoderToXMLData function when geocoding not
retrun results.
ver 1.0.0
ES:
nuevo: documentación.
nuevo: se hace compatible con FireMonkey.
cambio: recodificación del componente para no usar WebService.
cambio: la clase TGeometry pasa a llamarse TGeocodeGeometry para evitar confusiones.
cambio: se suprime la clase TGoogleBusiness porque no puede usarse en la
geocodificación mediante clases.
cambio: TGMGeoCode ahora desciende de TGMObjects.
error: corregido error en el método TGMGeoCode.DoMarkers (gracias Herwig).
error: corregido error en el método TGMGeoCode.ParseData (gracias Herwig).
EN:
new: documentation.
new: now compatible with FireMonkey.
change: recodification of component to avoid use Web Service.
change: TGeometry class is renamed to TGeocodeGeometry to avoid confusions.
change: TGoogleBusiness is removed because cannot be used in geocoding with classes.
change: TGMGeoCode now descends from TGMObjects.
bug: bug fixed in TGMGeoCode.DoMarkers method (thanks Herwig).
bug: bug fixed in TGMGeoCode.ParseData (thanks Herwig).
ver 0.1.7
ES:
cambio: TGMGeoCode-> añadida propiedad booleana PaintMarkerFound. A true se
generarán automáticamente los marcadores (si hay un TGMMarker asociado)
(por Luis Joaquin Sencion)
cambio: TGMGeoCode-> en DoMarkers se codifica la URL generada en UTF8 para
evitar problemas con carácteres especiales (ñ, acentos, ....)
EN:
change: TGMGeoCode-> added boolean property PaintMarkerFound. To true, all
markers are automatically generated (if a TGMMarker is linked) (by Luis
Joaquin Sencion)
change: TGMGeoCode-> generated URL is encoded in UTF8 to avoid problems
with special characters (ñ, accents, ....)
ver 0.1.6
ES:
nuevo: TAddressComponent -> añadido método Assign
nuevo: TAddressComponentsList -> añadido método Assign
nuevo: TGeocodeGeometry -> añadido método Assign
nuevo: TGeoResult -> añadido método Assign
nuevo: TGoogleBusiness -> añadido método Assign
nuevo: TGMGeoCode -> se sobreescribe el método Notification para controlar
la propiedad Marker
cambio: TGMGeoCode -> se trasladan los métodos xxToStr y StrToxxx a la clase
TTransform de la unidad GMFunctions
nuevo: TGMGeoCode -> añadido método Assign
EN:
new: TAddressComponent -> added Assign method
new: TAddressComponentsList -> added Assign method
new: TGeocodeGeometry -> added Assign method
new: TGeoResult -> added Assign method
new: TGoogleBusiness -> added Assign method
new: TGMGeoCode -> overrided Notification method to control Marker property
change: TGMGeoCode -> xxToStr and StrToxxx moved to the TTransform class
into the GMFunctions unit
new: TGMGeoCode -> added Assign method
ver 0.1.5
ES: primera versión
EN: first version
=========================================================================
ATENCION!!! LIMITES DE USO SEGUN Google
- 2.500 geolocalizaciones por día
- la geolocalización debe usarse con un mapa de Google Maps
- para más información visitar https://developers.google.com/maps/documentation/geocoding/index#Limits
WARNING!!! USAGE LIMITS BY Google
- 2,500 geolocation requests per day
- the geolocation should be used with Google Maps
- for more information visit https://developers.google.com/maps/documentation/geocoding/index#Limits
=========================================================================
URL de interés
URL of Interest
- https://developers.google.com/maps/documentation/javascript/services
- http://stackoverflow.com/questions/5782611/how-do-i-use-google-maps-geocoder-getlatlng-and-store-its-result-in-a-database
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2012, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
{*------------------------------------------------------------------------------
Includes the necessary classes to geocoding.
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Contiene las classes necesarias para la geocodificación.
@author Xavier Martinez (cadetill)
@version 1.5.3
-------------------------------------------------------------------------------}
unit GMGeoCode;
{$I ..\gmlib.inc}
interface
uses
{$IFDEF DELPHIXE2}
System.Classes, System.Contnrs,
{$ELSE}
Classes, Contnrs,
{$ENDIF}
GMMap, GMClasses, GMMarker, GMConstants;
type
{*------------------------------------------------------------------------------
A single address component within a GeocoderResult.
A full address may consist of multiple address components.
More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#GeocoderAddressComponent
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Un componente de la dirección único dentro de un GeocoderResult.
Una dirección completa puede constar de múltiples componentes de dirección.
Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#GeocoderAddressComponent
-------------------------------------------------------------------------------}
TAddressComponent = class
private
{*------------------------------------------------------------------------------
The abbreviated, short text of the given address component.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Abreviación o texto corto del componente de la dirección dado.
-------------------------------------------------------------------------------}
FShortName: string;
{*------------------------------------------------------------------------------
List of strings denoting the type of this address component.
See possibles types at https://developers.google.com/maps/documentation/geocoding/#Types
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Lista de cadenas que representan el tipo de este componente de la dirección.
Ver posibles tipos en https://developers.google.com/maps/documentation/geocoding/#Types
-------------------------------------------------------------------------------}
FAddrCompTypeList: TStringList;
{*------------------------------------------------------------------------------
The full text of the address component.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Texto completo del componente de la dirección.
-------------------------------------------------------------------------------}
FLongName: string;
public
{*------------------------------------------------------------------------------
Constructor class.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase.
-------------------------------------------------------------------------------}
constructor Create; virtual;
{*------------------------------------------------------------------------------
Destructor class.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Destructor de la clase.
-------------------------------------------------------------------------------}
destructor Destroy; override;
{*------------------------------------------------------------------------------
Assign method copies the contents of another similar object.
@param Source Object to copy content.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método Assign copia el contenido de un objeto similar.
@param Source Objeto a copiar el contenido.
-------------------------------------------------------------------------------}
procedure Assign(Source: TObject); virtual;
property ShortName: string read FShortName;
property LongName: string read FLongName;
property AddrCompTypeList: TStringList read FAddrCompTypeList;
end;
{*------------------------------------------------------------------------------
Internal class to manage the address components list.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Clase interna para gestionar la lista de componentes de la dirección.
-------------------------------------------------------------------------------}
TAddressComponentsList = class
private
FAddrComponents: TObjectList;
function GetItem(Index: Integer): TAddressComponent;
function GetCount: Integer;
public
{*------------------------------------------------------------------------------
Constructor class.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase.
-------------------------------------------------------------------------------}
constructor Create; virtual;
{*------------------------------------------------------------------------------
Destructor class.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Destructor de la clase.
-------------------------------------------------------------------------------}
destructor Destroy; override;
{*------------------------------------------------------------------------------
Assign method copies the contents of another similar object.
@param Source Object to copy content.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método Assign copia el contenido de un objeto similar.
@param Source Objeto a copiar el contenido.
-------------------------------------------------------------------------------}
procedure Assign(Source: TObject); virtual;
{*------------------------------------------------------------------------------
Adds a new element to the list.
@param AddrComp Element to add.
@return Position it has been added.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Añade un nuevo elemento a la lista.
@param AddrComp Elemento a añadir.
@return Posición en la que se ha añadido.
-------------------------------------------------------------------------------}
function Add(AddrComp: TAddressComponent): Integer;
{*------------------------------------------------------------------------------
Number of items in the list.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Cantidad de elementos en la lista.
-------------------------------------------------------------------------------}
property Count: Integer read GetCount;
{*------------------------------------------------------------------------------
Lists of items.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Lista de elementos.
-------------------------------------------------------------------------------}
property Items[Index: Integer]: TAddressComponent read GetItem; default;
end;
{*------------------------------------------------------------------------------
Geometry information about this GeocoderResult.
More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#GeocoderGeometry
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Información geométrica del GeocoderResult.
Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#GeocoderGeometry
-------------------------------------------------------------------------------}
TGeocodeGeometry = class
private
{*------------------------------------------------------------------------------
The coordinates of this result.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Las coordenadas de éste resultado.
-------------------------------------------------------------------------------}
FLocation: TLatLng;
{*------------------------------------------------------------------------------
The type of location returned in location.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Tipo de ubicación devuelta en la localización.
-------------------------------------------------------------------------------}
FLocationType: TGeocoderLocationType;
{*------------------------------------------------------------------------------
The bounds of the recommended viewport for displaying this GeocodeResult.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Los límites de la ventana recomendada para mostrar este GeocodeResult.
-------------------------------------------------------------------------------}
FViewport: TLatLngBounds;
{*------------------------------------------------------------------------------
The precise bounds of this GeocodeResult, if applicable.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Límites precisos de este GeocodeResult, si aplica.
-------------------------------------------------------------------------------}
FBounds: TLatLngBounds;
public
{*------------------------------------------------------------------------------
Constructor class.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase.
-------------------------------------------------------------------------------}
constructor Create; virtual;
{*------------------------------------------------------------------------------
Destructor class.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Destructor de la clase.
-------------------------------------------------------------------------------}
destructor Destroy; override;
{*------------------------------------------------------------------------------
Assign method copies the contents of another similar object.
@param Source Object to copy content.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método Assign copia el contenido de un objeto similar.
@param Source Objeto a copiar el contenido.
-------------------------------------------------------------------------------}
procedure Assign(Source: TObject); virtual;
property Location: TLatLng read FLocation;
property LocationType: TGeocoderLocationType read FLocationType;
property Viewport: TLatLngBounds read FViewport;
property Bounds: TLatLngBounds read FBounds;
end;
{*------------------------------------------------------------------------------
A single geocoder result retrieved from the geocode server.
A geocode request may return multiple result objects.
More information at https://developers.google.com/maps/documentation/javascript/reference?hl=en#GeocoderResult
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Un único resultado de la geocodificación devuelto por el servidor de geocodificación.
Una consulta de geocodificación puede devolver varios resultados.
Más información en https://developers.google.com/maps/documentation/javascript/reference?hl=en#GeocoderResult
-------------------------------------------------------------------------------}
TGeoResult = class
private
{*------------------------------------------------------------------------------
List of strings denoting the type of the returned geocoded element.
See possibles types at https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingAddressTypes
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Lista de cadenas que representan el tipo de elemento devuelto por la geocodificación.
Ver posibles tipos en https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingAddressTypes
-------------------------------------------------------------------------------}
FTypeList: TStringList;
{*------------------------------------------------------------------------------
A string containing the human-readable address of this location.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Cadena que contiene la dirección interpretable por humanos de la localización.
-------------------------------------------------------------------------------}
FFormatedAddr: string;
{*------------------------------------------------------------------------------
List of GeocoderAddressComponents.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Lista de GeocoderAddressComponents.
-------------------------------------------------------------------------------}
FAddrCompList: TAddressComponentsList;
{*------------------------------------------------------------------------------
Geometry information about this GeocoderResult.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Información geométrica del GeocoderResult.
-------------------------------------------------------------------------------}
FGeometry: TGeocodeGeometry;
public
{*------------------------------------------------------------------------------
Constructor class.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Constructor de la clase.
-------------------------------------------------------------------------------}
constructor Create; virtual;
{*------------------------------------------------------------------------------
Destructor class.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Destructor de la clase.
-------------------------------------------------------------------------------}
destructor Destroy; override;
{*------------------------------------------------------------------------------
Assign method copies the contents of another similar object.
@param Source Object to copy content.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El método Assign copia el contenido de un objeto similar.
@param Source Objeto a copiar el contenido.
-------------------------------------------------------------------------------}
procedure Assign(Source: TObject); virtual;
property TypeList: TStringList read FTypeList;
property FormatedAddr: string read FFormatedAddr;
property AddrCompList: TAddressComponentsList read FAddrCompList;
property Geometry: TGeocodeGeometry read FGeometry;
end;
{*------------------------------------------------------------------------------
TParseData event is fired in each row of the XML file.
@param Sender Owner object of the collection item.
@param ActualNode Actual XML node.
@param CountNodes Number of nodes to process.
@param Continue If we like to continue the process.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
El evento TParseData se dispara en cada iteración de la lectura del archivo XML.
@param Sender Objecto propietario del elemento de la colección.
@param ActualNode Nodo XML actual.
@param CountNodes Cantidad de nodos a procesar.
@param Continue Si queremos continuar con el proceso.
-------------------------------------------------------------------------------}
TParseData = procedure(Sender: TObject; ActualNode, CountNodes: Integer; var Continue: Boolean) of object;
{*------------------------------------------------------------------------------
A service for converting between an address and a LatLng.
More information at
- https://developers.google.com/maps/documentation/javascript/reference?hl=en#Geocoder
- https://developers.google.com/maps/documentation/javascript/geocoding
- https://developers.google.com/maps/documentation/geocoding/index
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Servicio para convertir entre dirección y LatLng.
Más información en
- https://developers.google.com/maps/documentation/javascript/reference?hl=en#Geocoder
- https://developers.google.com/maps/documentation/javascript/geocoding
- https://developers.google.com/maps/documentation/geocoding/index
-------------------------------------------------------------------------------}
TGMGeoCode = class(TGMObjects)
private
{*------------------------------------------------------------------------------
Associated GMMarker in which will create the results.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
GMMarker asociado en el que se crearán los resultados.
-------------------------------------------------------------------------------}
FMarker: TCustomGMMarker;
{*------------------------------------------------------------------------------
Resulting XML geocoding.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
XML resultante de la geocodificación.
-------------------------------------------------------------------------------}
FXMLData: TStringList;
{*------------------------------------------------------------------------------
Event fired after get data.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Evento disparado después de conseguir los datos.
-------------------------------------------------------------------------------}
FAfterGetData: TNotifyEvent;
{*------------------------------------------------------------------------------
Event fired before data parsing.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Evento disparado antes de analizar los datos.
-------------------------------------------------------------------------------}
FBeforeParseData: TNotifyEvent;
{*------------------------------------------------------------------------------
Event fired after data parsing.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Evento disparado después de analizar los datos.
-------------------------------------------------------------------------------}
FAfterParseData: TNotifyEvent;
{*------------------------------------------------------------------------------
Geolocation status.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Estado de la geolocalización.
-------------------------------------------------------------------------------}
FGeoStatus: TGeoCoderStatus;
{*------------------------------------------------------------------------------
Event fired during data parsing.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Evento disparado durante el análisis de los datos.
-------------------------------------------------------------------------------}
FOnParseData: TParseData;
{*------------------------------------------------------------------------------
Geolocation results.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Resultados de la geolocalización.
-------------------------------------------------------------------------------}
FGeoResults: TObjectList;
{*------------------------------------------------------------------------------
Icon to show the results.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Icono para mostrar los resultados.
-------------------------------------------------------------------------------}
FIcon: string;
{*------------------------------------------------------------------------------
LatLngBounds within which to search.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
LatLngBounds dentro de la que buscar.
-------------------------------------------------------------------------------}
FBounds: TLatLngBounds;
{*------------------------------------------------------------------------------
Country code used to bias the search.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Código de pais utilizado para centrar la búsqueda.
-------------------------------------------------------------------------------}
FRegion: TRegion;
{*------------------------------------------------------------------------------
Language used in the result.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Idioma usado en el resultado.
-------------------------------------------------------------------------------}
FLangCode: TLangCode;
{*------------------------------------------------------------------------------
If true, will be created the markers into the GMMarker associated.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Si se establece a true, se crearán los marcadores en el GMMarker asociado.
-------------------------------------------------------------------------------}
FPaintMarkerFound: Boolean;
procedure GeocodeData(Data: string);
procedure ParseData;
function GetGeoResult(Index: Integer): TGeoResult;
function GetCount: Integer;
protected
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetAPIUrl: string; override;
procedure DeleteMapObjects; override;
procedure ShowElements; override;
procedure EventFired(EventType: TEventType; Params: array of const); override;
{*------------------------------------------------------------------------------
Returns the TGeocoderLocationType represented by the string GeocoderLocationType.
@param GeocoderLocationType string to convert to TGeocoderLocationType
@return TGeocoderLocationType that represents the string
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Devuelve el TGeocoderLocationType representado por la cadena GeocoderLocationType.
@param GeocoderLocationType Cadena a convertir a TGeocoderLocationType
@return TGeocoderLocationType que representa la cadena
-------------------------------------------------------------------------------}
function StrToGeocoderLocationType(GeocoderLocationType: string): TGeocoderLocationType;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
{*------------------------------------------------------------------------------
Geocodes the address passed by parameter.
@param Address Address to geocoder.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Geolocaliza la dirección pasada por parámetro.
@param Address Dirección a geolocalizar.
-------------------------------------------------------------------------------}
procedure Geocode(Address: string); overload;
{*------------------------------------------------------------------------------
Geocodes the LatLng passed by parameter.
@param LatLng TLatLng to geocoder.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Geolocaliza la LatLng pasada por parámetro.
@param LatLng TLatLng a geolocalizar.
-------------------------------------------------------------------------------}
procedure Geocode(LatLng: TLatLng); overload;
{*------------------------------------------------------------------------------
Geocodes the Lat/Lng passed by parameter.
@param Lat Latitude to geocoder.
@param Lng Longitude to geocoder.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Geolocaliza la Lat/Lng pasada por parámetro.
@param Lat Latitud a geolocalizar.
@param Lng Longitud a geolocalizar.
-------------------------------------------------------------------------------}
procedure Geocode(Lat, Lng: Real); overload;
{*------------------------------------------------------------------------------
Create the markers resulting of geocoder into the linked GMMarker.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Crea los marcadores resultantes de la geocodificación en el GMMarker asociado.
-------------------------------------------------------------------------------}
procedure DoMarkers;
{*------------------------------------------------------------------------------
Number of results.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Cantidad de resultados.
-------------------------------------------------------------------------------}
property Count: Integer read GetCount;
{*------------------------------------------------------------------------------
Array of results.
-------------------------------------------------------------------------------}
{=------------------------------------------------------------------------------
Array de resultados.
-------------------------------------------------------------------------------}
property GeoResult[Index: Integer]: TGeoResult read GetGeoResult; default;
property XMLData: TStringList read FXMLData write FXMLData;
property GeoStatus: TGeocoderStatus read FGeoStatus;
published
property Marker: TCustomGMMarker read FMarker write FMarker;
property Icon: string read FIcon write FIcon;
property Bounds: TLatLngBounds read FBounds write FBounds;
property Region: TRegion read FRegion write FRegion default r_NO_REGION;
property LangCode: TLangCode read FLangCode write FLangCode default lcENGLISH;
property PaintMarkerFound: Boolean read FPaintMarkerFound write FPaintMarkerFound default False;
// eventos
// events
property AfterGetData: TNotifyEvent read FAfterGetData write FAfterGetData;
property BeforeParseData: TNotifyEvent read FBeforeParseData write FBeforeParseData;
property AfterParseData: TNotifyEvent read FAfterParseData write FAfterParseData;
property OnParseData: TParseData read FOnParseData write FOnParseData;
end;
implementation
uses
{$IFDEF DELPHIXE2}
System.SysUtils, Xml.XMLIntf, Xml.XMLDoc, System.StrUtils,
{$ELSE}
SysUtils, XMLIntf, XMLDoc, StrUtils, Controls,
{$ENDIF}
GMFunctions, Lang;
{ TGMGeoCode }
procedure TGMGeoCode.Geocode(Address: string);
var
Tmp: string;
begin
Tmp := QuotedStr(Trim(GetConvertedString(Address))) + ',-1, -1';
GeocodeData(Tmp);
end;
function TGMGeoCode.GetCount: Integer;
begin
Result := FGeoResults.Count;
end;
procedure TGMGeoCode.Assign(Source: TPersistent);
begin
if Source is TGMGeoCode then
begin
Marker := TGMGeoCode(Source).Marker;
Icon := TGMGeoCode(Source).Icon;
Bounds.Assign(TGMGeoCode(Source).Bounds);
Region := TGMGeoCode(Source).Region;
LangCode := TGMGeoCode(Source).LangCode;
end
else
inherited Assign(Source);
end;
constructor TGMGeoCode.Create(aOwner: TComponent);
begin
inherited;
FXMLData := TStringList.Create;
FGeoResults := TObjectList.Create;
FBounds := TLatLngBounds.Create;
FRegion := r_NO_REGION;
FLangCode := lcENGLISH;
FGeoStatus := gsWithoutState;
end;
procedure TGMGeoCode.DeleteMapObjects;
begin
inherited;
end;
destructor TGMGeoCode.Destroy;
begin
if Assigned(FXMLData) then FreeAndNil(FXMLData);
if Assigned(FGeoResults) then FreeAndNil(FGeoResults);
if Assigned(FBounds) then FreeAndNil(FBounds);
inherited;
end;
procedure TGMGeoCode.DoMarkers;
var
i: Integer;
Marker: TCustomMarker;
begin
if not Assigned(FMarker) or not FPaintMarkerFound then Exit;
for i := 0 to FGeoResults.Count - 1 do
begin
Marker := FMarker.Add(TGeoResult(FGeoResults[i]).Geometry.Location.Lat,
TGeoResult(FGeoResults[i]).Geometry.Location.Lng,
TGeoResult(FGeoResults[i]).FormatedAddr);
Marker.Icon := Icon;
end;
end;
procedure TGMGeoCode.EventFired(EventType: TEventType; Params: array of const);
begin
inherited;
end;
procedure TGMGeoCode.Geocode(LatLng: TLatLng);
var
Tmp: string;
begin
Tmp := QuotedStr('') + ',' + LatLng.LatToStr(0) + ',' + LatLng.LngToStr(0);
GeocodeData(Tmp);
end;
procedure TGMGeoCode.GeocodeData(Data: string);
var
Tmp: string;
begin
if not Assigned(Map) then
raise Exception.Create(GetTranslateText('Mapa no asignado', Language));
Tmp := Data + ',' + QuotedStr(TCustomTransform.RegionToStr(FRegion));
if (Bounds.NE.Lat <> 0) or (Bounds.NE.Lng <> 0) or
(Bounds.SW.Lat <> 0) or (Bounds.SW.Lng <> 0) then
Tmp := Tmp + ',' + Bounds.SW.ToUrlValue(0) + ',' + Bounds.NE.ToUrlValue(0)
else
Tmp := Tmp + ',-1,-1,-1,-1';
Tmp := Tmp + ',' + QuotedStr(TCustomTransform.LangCodeToStr(FLangCode));
ExecuteScript('GetGeocoder', Tmp);
repeat
TGMGenFunc.ProcessMessages;
until (GetIntegerField(GeocoderForm, GeocoderFormResponse) = 1);
FXMLData.Text := GetStringField(GeocoderForm, GeocoderFormXML);
if Assigned(FAfterGetData) then FAfterGetData(Self);
ParseData;
end;
function TGMGeoCode.GetAPIUrl: string;
begin
Result := 'https://developers.google.com/maps/documentation/geocoding/index';
end;
function TGMGeoCode.GetGeoResult(Index: Integer): TGeoResult;
begin
Result := nil;
if Assigned(FGeoResults[Index]) then Result := TGeoResult(FGeoResults[Index]);
end;
procedure TGMGeoCode.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent <> nil) and (AComponent = FMarker) then
FMarker := nil;
end;
procedure TGMGeoCode.ParseData;
var
XML: IXMLDocument;
procedure ParseNodes(Node: IXMLNode);
function ParseResultNode(Node: IXMLNode): TGeoResult;
function ParseAddrComponent(Node: IXMLNode): TAddressComponent;
begin
Result := TAddressComponent.Create;
while Assigned(Node) do
begin
// ES: etiqueta "long_name" (sólo una) // EN: "long_name" tag (only one)
if SameText(Node.NodeName, LBL_LONG_NAME) then
Result.FLongName := Node.NodeValue;
// ES: etiqueta "short_name" (sólo una) // EN: "short_name" tag (only one)
if SameText(Node.NodeName, LBL_SHORT_NAME) then
Result.FShortName := Node.NodeValue;
// ES: etiqueta "type" (una o más) // EN: "type" tag (one or more)
if SameText(Node.NodeName, LBL_TYPE) then
Result.AddrCompTypeList.Add(Node.NodeValue);
Node := Node.NextSibling;
end;
end;
procedure ParseGeometry(GeoResult: TGeoResult; Node: IXMLNode);
procedure GetLatLng(LatLng: TLatLng; Node: IXMLNode);
begin
while Assigned(Node) do
begin
if SameText(Node.NodeName, LBL_LAT) then
LatLng.Lat := LatLng.StringToReal(Node.NodeValue);
if SameText(Node.NodeName, LBL_LNG) then
LatLng.Lng := LatLng.StringToReal(Node.NodeValue);
Node := Node.NextSibling;
end;
end;
procedure GetLatLngBounds(LatLngBounds: TLatLngBounds; Node: IXMLNode);
begin
while Assigned(Node) do
begin
if SameText(Node.NodeName, LBL_SOUTHWEST) and (Node.ChildNodes.Count = 2) then
GetLatLng(LatLngBounds.SW, Node.ChildNodes.First);
if SameText(Node.NodeName, LBL_NORTHEAST) and (Node.ChildNodes.Count = 2) then
GetLatLng(LatLngBounds.NE, Node.ChildNodes.First);
Node := Node.NextSibling;
end;
end;
begin
while Assigned(Node) do
begin
// ES: etiqueta "location" (sólo una) // EN: "location" tag (only one)
if SameText(Node.NodeName, LBL_LOCATION) and (Node.ChildNodes.Count = 2) then
GetLatLng(Result.Geometry.Location, Node.ChildNodes.First);
// ES: etiqueta "location_type" (sólo una) // EN: "location_type" tag (only one)
if SameText(Node.NodeName, LBL_LOCATION_TYPE) then
Result.Geometry.FLocationType := StrToGeocoderLocationType(Node.NodeValue);
// ES: etiqueta "viewport" (sólo una) // EN: "viewport" tag (only one)
if SameText(Node.NodeName, LBL_VIEWPORT) and (Node.ChildNodes.Count = 2) then
GetLatLngBounds(Result.Geometry.Viewport, Node.ChildNodes.First);
// ES: etiqueta "bounds" (sólo una) // EN: "bounds" tag (only one)
if SameText(Node.NodeName, LBL_BOUNDS) and (Node.ChildNodes.Count = 2) then
GetLatLngBounds(Result.Geometry.Bounds, Node.ChildNodes.First);
Node := Node.NextSibling;
end;
end;
begin
Result := TGeoResult.Create;
while Assigned(Node) do
begin
// ES: etiqueta "type" (una o varias, normalmente sólo una)
// EN: "type" tag (one or more, normally only one)
if SameText(Node.NodeName, LBL_TYPE) then
Result.TypeList.Add(Node.NodeValue);
// ES: etiqueta "formatted_address" (sólo una) // EN: "formatted_address" tag (only one)
if SameText(Node.NodeName, LBL_FORMATTED_ADDRESS) then
Result.FFormatedAddr := Node.NodeValue;
// ES: etiqueta "address_component" (una o varias) // EN: "address_component" tag (one or more)
if SameText(Node.NodeName, LBL_ADDRCOMPONENT) and (Node.ChildNodes.Count > 0) then
Result.AddrCompList.Add(ParseAddrComponent(Node.ChildNodes.First));
// ES: etiqueta "geometry" (sólo una) // EN: "geometry" tag (only one)
if SameText(Node.NodeName, LBL_GEOMETRY) and (Node.ChildNodes.Count > 0) then
ParseGeometry(Result, Node.ChildNodes.First);
Node := Node.NextSibling;
end;
end;
var
ActualNode: Integer;
CountNodes: Integer;
Continue: Boolean;
begin
// ES: nos posicionamos en "GeocodeResponse" // EN: go to "GeocodeResponse" tag
while Assigned(Node) and not SameText(Node.NodeName, LBL_GEOCODERESPONSE) do
Node := Node.NextSibling;
if not Assigned(Node) or (Node.ChildNodes.Count = 0) then Exit;
CountNodes := Node.ChildNodes.Count;
Node := Node.ChildNodes.First;
Continue := True;
ActualNode := 1;
while Assigned(Node) and Continue do
begin
if Assigned(FOnParseData) then FOnParseData(Self, ActualNode, CountNodes, Continue);
Inc(ActualNode);
// ES: etiqueta "status" (sólo una) // EN: "status" tag (only one)
if SameText(Node.NodeName, LBL_STATUS) then
FGeoStatus := TCustomTransform.StrToGeocoderStatus(Node.NodeValue);
// ES: etiqueta "result" (ninguna, una o varias) // EN: "result" (none, one or more)
if SameText(Node.NodeName, LBL_RESULT) and (Node.ChildNodes.Count > 0) then
FGeoResults.Add(ParseResultNode(Node.ChildNodes.First));
Node := Node.NextSibling;
end;
end;
begin
if Assigned(FBeforeParseData) then FBeforeParseData(Self);
if FXMLData.Text <> '' then
begin
if Assigned(FMarker) and FPaintMarkerFound then FMarker.Clear;
FGeoResults.Clear;
{$IFDEF DELPHI2010}
XML := LoadXMLData(FXMLData.Text);
{$ELSE}
XML := LoadXMLData(AnsiToUtf8(FXMLData.Text));
{$ENDIF}
try
XML.Active := True;
ParseNodes(XML.ChildNodes.First);
finally
XML := nil;
end;
DoMarkers;
end;
if Assigned(AfterParseData) then AfterParseData(Self);
end;
procedure TGMGeoCode.ShowElements;
begin
inherited;
end;
function TGMGeoCode.StrToGeocoderLocationType(
GeocoderLocationType: string): TGeocoderLocationType;
begin
case AnsiIndexStr(UpperCase(GeocoderLocationType), ['GLTAPPROXIMATE', 'GLTGEOMETRIC_CENTER',
'GLTRANGE_INTERPOLATED', 'GLTROOFTOP', 'GLTNOTHING']) of
0: Result := gltAPPROXIMATE;
1: Result := gltGEOMETRIC_CENTER;
2: Result := gltRANGE_INTERPOLATED;
3: Result := gltROOFTOP;
else Result := gltNOTHING;
end;
end;
procedure TGMGeoCode.Geocode(Lat, Lng: Real);
var
Tmp: TLatLng;
begin
Tmp := TLatLng.Create(Lat, Lng);
try
Geocode(Tmp);
finally
FreeAndNil(Tmp);
end;
end;
{ TGeoResult }
procedure TGeoResult.Assign(Source: TObject);
begin
if Source is TGeoResult then
begin
FFormatedAddr := TGeoResult(Source).FormatedAddr;
FTypeList.Assign(TGeoResult(Source).TypeList);
FAddrCompList.Assign(TGeoResult(Source).AddrCompList);
FGeometry.Assign(TGeoResult(Source).Geometry);
end;
end;
constructor TGeoResult.Create;
begin
FTypeList := TStringList.Create;
FAddrCompList := TAddressComponentsList.Create;
FGeometry := TGeocodeGeometry.Create;
end;
destructor TGeoResult.Destroy;
begin
if Assigned(FTypeList) then FreeAndNil(FTypeList);
if Assigned(FAddrCompList) then FreeAndNil(FAddrCompList);
if Assigned(FGeometry) then FreeAndNil(FGeometry);
inherited;
end;
{ TGeocodeGeometry }
procedure TGeocodeGeometry.Assign(Source: TObject);
begin
if Source is TGeocodeGeometry then
begin
FLocationType := TGeocodeGeometry(Source).LocationType;
FLocation.Assign(TGeocodeGeometry(Source).Location);
FViewport.Assign(TGeocodeGeometry(Source).Viewport);
FBounds.Assign(TGeocodeGeometry(Source).Bounds);
end;
end;
constructor TGeocodeGeometry.Create;
begin
FLocation := TLatLng.Create;
FLocationType := gltNOTHING;
FViewport := TLatLngBounds.Create;
FBounds := TLatLngBounds.Create;
end;
destructor TGeocodeGeometry.Destroy;
begin
if Assigned(FLocation) then FreeAndNil(FLocation);
if Assigned(FViewport) then FreeAndNil(FViewport);
if Assigned(FBounds) then FreeAndNil(FBounds);
inherited;
end;
{ TAddressComponentsList }
function TAddressComponentsList.Add(AddrComp: TAddressComponent): Integer;
begin
Result := FAddrComponents.Add(AddrComp);
end;
procedure TAddressComponentsList.Assign(Source: TObject);
begin
if Source is TAddressComponentsList then
begin
FAddrComponents.Assign(TAddressComponentsList(Source).FAddrComponents);
end;
end;
constructor TAddressComponentsList.Create;
begin
FAddrComponents := TObjectList.Create;
end;
destructor TAddressComponentsList.Destroy;
begin
if Assigned(FAddrComponents) then FreeAndNil(FAddrComponents);
inherited;
end;
function TAddressComponentsList.GetCount: Integer;
begin
Result := FAddrComponents.Count;
end;
function TAddressComponentsList.GetItem(Index: Integer): TAddressComponent;
begin
Result := nil;
if Assigned(FAddrComponents[Index]) then
Result := TAddressComponent(FAddrComponents[Index]);
end;
{ TAddressComponent }
procedure TAddressComponent.Assign(Source: TObject);
begin
if Source is TAddressComponent then
begin
FShortName := TAddressComponent(Source).ShortName;
FLongName := TAddressComponent(Source).LongName;
FAddrCompTypeList.Assign(TAddressComponent(Source).AddrCompTypeList);
end;
end;
constructor TAddressComponent.Create;
begin
FAddrCompTypeList := TStringList.Create;
end;
destructor TAddressComponent.Destroy;
begin
if Assigned(FAddrCompTypeList) then FreeAndNil(FAddrCompTypeList);
inherited;
end;
end.
|
unit uStringUtils;
interface
function DurationToStr(Miliseconds: Int64): string;
implementation
uses SysUtils;
function DurationToStr(Miliseconds: Int64): string;
const
AproxDaysPerMonth = 30;
MonthsPerYear = 12;
var
Y, Mo, D, H, M, S, Ms: Int64;
YSt, MoSt, DSt, HSt, MSt, SSt: string;
begin
Ms := Miliseconds;
if Ms >= MSecsPerSec then
begin
S := Ms div MSecsPerSec;
SSt := 'second';
if (S > 1) or (S = 0) then
SSt := SSt + 's';
end else
begin
SSt := 'millisecond';
if (Ms > 1) or (Ms = 0) then
SSt := SSt + 's';
Result := Format('%d %s', [Ms, SSt]);
Exit;
end;
if S >= SecsPerMin then
begin
M := S div SecsPerMin;
S := S mod SecsPerMin;
MSt := 'minute';
if (M > 1) or (M = 0) then
MSt := MSt + 's';
end else
begin
Result := Format('%d %s', [S, SSt]);
Exit;
end;
if M >= MinsPerHour then
begin
H := M div MinsPerHour;
M := M mod MinsPerHour;
HSt := 'hour';
if (H > 1) or (H = 0) then
HSt := HSt + 's';
end else
begin
Result := Format('%d %s, %d %s', [M, MSt, S, SSt]);
Exit;
end;
if H >= HoursPerDay then
begin
D := H div HoursPerDay;
H := H mod HoursPerDay;
Dst := 'day';
if (D > 1) or (D = 0) then
Dst := Dst + 's';
end else
begin
Result := Format('%d %s, %d %s, %d %s', [H, HSt, M, MSt, S, SSt]);
Exit;
end;
if D >= AproxDaysPerMonth then
begin
Mo := D div AproxDaysPerMonth;
D := D mod AproxDaysPerMonth;
MoSt := 'month';
if (Mo > 1) or (Mo = 0) then
MoSt := MoSt + 's';
end else
begin
Result := Format('%d %s, %d %s, %d %s, %d %s', [D, Dst, H, HSt, M, MSt, S, SSt]);
Exit;
end;
if Mo >= MonthsPerYear then
begin
Y := Mo div MonthsPerYear;
Mo := Mo mod MonthsPerYear;
Yst := 'year';
if (Y > 1) or (Y = 0) then
Yst := Yst + 's';
end else
begin
Result := Format('%d %s, %d %s, %d %s, %d %s, %d %s',
[Mo, MoSt, D, Dst, H, HSt, M, MSt, S, SSt]);
Exit;
end;
Result := Format('%d %s, %d %s, %d %s, %d %s, %d %s, %d %s', [Y, Yst, Mo, MoSt, D, Dst, H, HSt, M, MSt, S, SSt]);
end;
end.
|
unit exweb_import;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
exweb_type,UExWebType, DB, DBClient;
type
TExweb_import = class(TObject)
private
dll: THandle;
fDllFileName: string;
fParam: TStringList;
fTimeStart: Double;
hGetParam: TProcGetParam;
hPrepare: TProcPrepare;
hQuery: TProcQuery;
hRecv: TProcRecv;
hSend: TProcSend;
hSetParam: TProcSetParam;
function getConnected: Boolean;
function getTimeSec: Double;
procedure reConnectAuto;
public
constructor Create(const aDllFileName: string = '');
destructor Destroy; override;
//1 Загрузка библиотеки
function Connect(const aDllFileName: string): Boolean;
procedure Disconnect;
//1 Получить параметры exweb
function getParam(name:string): string;
//1 Выполнить запрос к базе.
{:
sql - запрос ( не только select )
base - алиас базы к которой выполняется запрос
outDS - ClientDataSet - с результатом запроса ( или nil)
coding - кодировка результат
}
function query(const sql, base: string; outDS: TClientDataSet; const
coding: string = ''): Boolean;
//1 Полное переподключение библиотеки
function reConnect: Boolean;
{:
Прием данных с сервера.
}
function recv(var str:string;data:TStream;prevState:TExWebState):
TExWebState;
{:
Отправка данных на сервер.
data можно указать nil.
!!! Возвращаемый результат TExWebResult необходимо в том же виде
передавать в следующий вызов send, не зависимо от того прошла
или нет передача
}
function send(const str: string; data: TStream; prevState:
TExWebState): TExWebState;
//1 Устанавливает параметр обмена
{:
Доступны следующие параметры
SCRIPT or URL - адрес скрипта exweb
KEY - ключ авторизации ( на сервере прописан в ws_conf.php)
PROXYPASSWORD
PROXYPORT
PROXYSERVER
PROXYUSERNAME
MAXDATASETFIELDLEN - максимальная длина поля данных
}
procedure setParam(name:string;value:string);
//1 Признак есть или нет подключение
property Connected: Boolean read getConnected;
end;
implementation
var
ptPrecInit:boolean = false;
ptPrecRate:double;
{
******************************** TExweb_import *********************************
}
constructor TExweb_import.Create(const aDllFileName: string = '');
begin
inherited Create;
dll:=0;
fParam:=TStringList.Create();
if (aDllFileName<>'') then
Connect(aDllFileName);
end;
destructor TExweb_import.Destroy;
begin
Disconnect();
fParam.Free();
inherited Destroy;
end;
function TExweb_import.Connect(const aDllFileName: string): Boolean;
var
cStr: string;
begin
if Connected then
Disconnect;
if (not FileExists(aDllFileName)) then begin
result:=false;
exit;
end;
try
fDllFileName:=aDllFileName;
fTimeStart:=getTimeSec();
dll := LoadLibrary(PChar(aDllFileName));
hSend:=GetProcAddress(dll,strProcSend);
hRecv:=GetProcAddress(dll,strProcRecv);
hQuery:=GetProcAddress(dll,strProcQuery);
hSetParam:=GetProcAddress(dll,strProcSetParam);
hGetParam:=GetProcAddress(dll,strProcGetParam);
hPrepare:=GetProcAddress(dll,strProcPrepare);
result:=true;
if (Application<>nil) then begin
cStr:=ExtractFileDir(Application.ExeName)+'\exweb_error.log';
setParam('LOGFILENAME',cStr);
setParam('ENABLELOG','1');
end;
except
result:=false;
Disconnect();
end;
end;
procedure TExweb_import.Disconnect;
begin
if (dll<>0) then begin
FreeLibrary(dll);
dll:=0;
end;
end;
function TExweb_import.getConnected: Boolean;
begin
result:= (dll<>0);
end;
function TExweb_import.getParam(name:string): string;
begin
result:=hGetParam(name);
end;
function TExweb_import.getTimeSec: Double;
var
ET: TLargeInteger;
l: LARGE_INTEGER;
begin
if not ptPrecInit then
begin
ptPrecInit:=true;
QueryPerformanceFrequency(ET);
l:=LARGE_INTEGER(ET);
ptPrecRate:=L.QuadPart;
end;
QueryPerformanceCounter(ET);
l:=LARGE_INTEGER(ET);
Result := (l.QuadPart)/ptPrecRate;
end;
function TExweb_import.query(const sql, base: string; outDS: TClientDataSet;
const coding: string = ''): Boolean;
var
cLen: Integer;
cName: string;
cNameIndex: Integer;
data: TStringList;
i: Integer;
len: Integer;
cNames: TStringList;
begin
reConnectAuto();
if outDS<>nil then begin
data:=TstringList.Create();
cNames:=TStringList.Create;
end else
data:=nil;
try
try
result:=hQuery(sql, base,data,coding);
if (not result) then
raise Exception.Create('query result=false');
if data = nil then
exit;
outDS.Active:=false;
outDS.FieldDefs.Clear;
outDS.Fields.Clear;
len:=StrToInt(data.Strings[0]);
for i:=0 to len-1 do begin
cLen:=StrToInt(data[1+i*2]);
cName:=data[1+i*2+1];
cNames.Add(cName);
outDS.FieldDefs.Add(cName,ftString,cLen);
end;
outDS.CreateDataSet;
cNameIndex:=0;
for i:=1+len*2 to data.Count-1 do begin
if (cNameIndex = 0) then
outDS.Append;
cName:=cNames[cNameIndex];
outDS.FieldByName(cName).AsString:=data[i];
cNameIndex:=cNameIndex+1;
if cNameIndex>=len then begin
outDS.Post;
cNameIndex:=0;
end
end;
except
on e:Exception do
begin
result:=false;
end;
end;
finally
if (data<>nil) then begin
cNames.Free;
data.Free;
end;
end;
end;
function TExweb_import.reConnect: Boolean;
var
cName: string;
cValue: string;
i: Integer;
begin
if (not Connected) then begin
result:=false;
exit;
end;
Disconnect();
if (Connect(fDllFileName)) then begin
// заново выставляем параметры
for i:=0 to fParam.Count - 1 do begin
cName:=fParam.Names[i];
cValue:=fParam.Values[cName];
setParam(cName,cValue);
end;
end;
end;
procedure TExweb_import.reConnectAuto;
begin
if (Connected) and (getTimeSec()-fTimeStart>3600) then
reConnect();
end;
function TExweb_import.recv(var str:string;data:TStream;prevState:TExWebState):
TExWebState;
begin
reConnectAuto();
result:=hRecv(str,data,prevState);
end;
function TExweb_import.send(const str: string; data: TStream; prevState:
TExWebState): TExWebState;
begin
reConnectAuto();
result:=hSend(str,data,prevState);
end;
procedure TExweb_import.setParam(name:string;value:string);
begin
// сохраняем параметры ( для reConnect)
fParam.Values[name]:=value;
hSetParam(name,value);
end;
end.
|
unit NtUtils.Registry.HKCU;
interface
uses
Winapi.WinNt, NtUtils.Exceptions, NtUtils.Objects, NtUtils.Registry;
// Get current user's hive path
function RtlxFormatCurrentUserKeyPath(out Path: String): TNtxStatus;
// Open a handle to the HKCU part of the registry
function RtlxOpenCurrentUserKey(out hxKey: IHandle; DesiredAccess: TAccessMask;
OpenOptions: Cardinal = 0; Attributes: Cardinal = 0) : TNtxStatus;
implementation
uses
Ntapi.ntseapi, Ntapi.ntpsapi, Ntapi.ntstatus, Ntapi.ntregapi,
NtUtils.Tokens.Query, NtUtils.Lsa.Sid, NtUtils.Security.Sid;
function RtlxFormatCurrentUserKeyPath(out Path: String): TNtxStatus;
var
User: TGroup;
UserName: String;
begin
// Query our effective SID of and convert it to string
Result := NtxQueryGroupToken(NtCurrentEffectiveToken, TokenUser, User);
if Result.IsSuccess then
Path := User.SecurityIdentifier.SDDL
else
begin
// Ask LSA for help since we can't open our token
if LsaxGetUserName(UserName).IsSuccess then
if LsaxLookupName(UserName, User.SecurityIdentifier).IsSuccess then
begin
Path := User.SecurityIdentifier.SDDL;
Result.Status := STATUS_SUCCESS;
end;
end;
if Result.IsSuccess then
Path := REG_PATH_USER + '\' + Path;
end;
function RtlxOpenCurrentUserKey(out hxKey: IHandle; DesiredAccess: TAccessMask;
OpenOptions: Cardinal; Attributes: Cardinal) : TNtxStatus;
var
HKCU: String;
begin
Result := RtlxFormatCurrentUserKeyPath(HKCU);
if not Result.IsSuccess then
Exit;
Result := NtxOpenKey(hxKey, HKCU, DesiredAccess, 0, OpenOptions, Attributes);
// Redirect to HKU\.Default if the user's profile is not loaded
if Result.Status = STATUS_OBJECT_NAME_NOT_FOUND then
Result := NtxOpenKey(hxKey, REG_PATH_USER_DEFAULT, DesiredAccess, 0,
OpenOptions, Attributes);
end;
end.
|
UNIT Lists;
interface
CONST
MaxItems = 10;
TYPE
Item = ARRAY[1..MaxItems] OF REAL;
NodeRecPtr = ^NodeRec;
NodeRec = RECORD
Data : Item;
Next : NodeRecPtr;
END;
List = OBJECT
Node,
CurrNode,
TailNode : NodeRecPtr;
constructor Init;
destructor Done;
procedure AddItem(Data : Item);
procedure ChangeCurrItem(Data : Item);
function GetNext(VAR Data : Item) : BOOLEAN;
{return false at end of list }
function SearchList(VAR Data : Item) : BOOLEAN;
{return TRUE IF FOUND }
END;
implementation
{ =============================================== }
constructor List.Init;
BEGIN
Node := NIL;
TailNode := NIL;
CurrNode := NIL;
END;
{ =============================================== }
destructor List.Done;
BEGIN
WHILE Node <> NIL DO
BEGIN
CurrNode := Node^.next;
Dispose(Node);
Node := CurrNode;
END;
TailNode := NIL;
END {Done};
{ =============================================== }
procedure List.AddItem(Data : Item);
{ Push items on a FIFO Stack }
VAR
n : NodeRecPtr;
BEGIN
New(n);
{clear memory}
FillChar(n^.Data,SizeOf(n^.Data),#0);
IF Node = NIL THEN
Node := n
ELSE
TailNode^.next := n; {chain forward }
n^.Data := Data;
n^.Next := NIL;
TailNode := n;
END {AddItem};
{ =============================================== }
procedure List.ChangeCurrItem(Data : Item);
BEGIN
CurrNode^.Data := Data;
END {ChangeCurrItem};
{ =============================================== }
function List.GetNext(VAR Data : Item) : BOOLEAN;
{return false at end of list }
BEGIN
{Check if initial access or at end of list }
IF (CurrNode = NIL) THEN
CurrNode := Node
ELSE
CurrNode := CurrNode^.next;
IF (CurrNode = NIL) THEN {At end of list}
GetNext := FALSE
ELSE BEGIN
Data := CurrNode^.Data;
GetNext := TRUE;
END;
END {GetNext};
function SearchList(VAR Data : Item) : BOOLEAN;
{return TRUE IF FOUND }
END. |
{ *********************************************************************** }
{ }
{ Delphi / Kylix Cross-Platform Runtime Library }
{ System Unit }
{ }
{ Copyright (c) 1988-2001 Borland Software Corporation }
{ }
{ *********************************************************************** }
unit System; { Predefined constants, types, procedures, }
{ and functions (such as True, Integer, or }
{ Writeln) do not have actual declarations.}
{ Instead they are built into the compiler }
{ and are treated as if they were declared }
{ at the beginning of the System unit. }
{$H+,I-,R-,O+,W-}
{$WARN SYMBOL_PLATFORM OFF}
{ L- should never be specified.
The IDE needs to find DebugHook (through the C++
compiler sometimes) for integrated debugging to
function properly.
ILINK will generate debug info for DebugHook if
the object module has not been compiled with debug info.
ILINK will not generate debug info for DebugHook if
the object module has been compiled with debug info.
Thus, the Pascal compiler must be responsible for
generating the debug information for that symbol
when a debug-enabled object file is produced.
}
interface
(* You can use RTLVersion in $IF expressions to test the runtime library
version level independently of the compiler version level.
Example: {$IF RTLVersion >= 16.2} ... {$IFEND} *)
const
RTLVersion = 14.1;
{$EXTERNALSYM CompilerVersion}
(*
const
CompilerVersion = 0.0;
CompilerVersion is assigned a value by the compiler when
the system unit is compiled. It indicates the revision level of the
compiler features / language syntax, which may advance independently of
the RTLVersion. CompilerVersion can be tested in $IF expressions and
should be used instead of testing for the VERxxx conditional define.
Always test for greater than or less than a known revision level.
It's a bad idea to test for a specific revision level.
*)
{$IFDEF DECLARE_GPL}
(* The existence of the GPL symbol indicates that the System unit
and the rest of the Delphi runtime library were compiled for use
and distribution under the terms of the GNU General Public License (GPL).
Under the terms of the GPL, all applications compiled with the
GPL version of the Delphi runtime library must also be distributed
under the terms of the GPL.
For more information about the GNU GPL, see
http://www.gnu.org/copyleft/gpl.html
The GPL symbol does not exist in the Delphi runtime library
purchased for commercial/proprietary software development.
If your source code needs to know which licensing model it is being
compiled into, you can use {$IF DECLARED(GPL)}...{$IFEND} to
test for the existence of the GPL symbol. The value of the
symbol itself is not significant. *)
const
GPL = True;
{$ENDIF}
{ Variant type codes (wtypes.h) }
varEmpty = $0000; { vt_empty }
varNull = $0001; { vt_null }
varSmallint = $0002; { vt_i2 }
varInteger = $0003; { vt_i4 }
varSingle = $0004; { vt_r4 }
varDouble = $0005; { vt_r8 }
varCurrency = $0006; { vt_cy }
varDate = $0007; { vt_date }
varOleStr = $0008; { vt_bstr }
varDispatch = $0009; { vt_dispatch }
varError = $000A; { vt_error }
varBoolean = $000B; { vt_bool }
varVariant = $000C; { vt_variant }
varUnknown = $000D; { vt_unknown }
//varDecimal = $000E; { vt_decimal } {UNSUPPORTED}
{ undefined $0f } {UNSUPPORTED}
varShortInt = $0010; { vt_i1 }
varByte = $0011; { vt_ui1 }
varWord = $0012; { vt_ui2 }
varLongWord = $0013; { vt_ui4 }
varInt64 = $0014; { vt_i8 }
//varWord64 = $0015; { vt_ui8 } {UNSUPPORTED}
{ if adding new items, update Variants' varLast, BaseTypeMap and OpTypeMap }
varStrArg = $0048; { vt_clsid }
varString = $0100; { Pascal string; not OLE compatible }
varAny = $0101; { Corba any }
varTypeMask = $0FFF;
varArray = $2000;
varByRef = $4000;
{ TVarRec.VType values }
vtInteger = 0;
vtBoolean = 1;
vtChar = 2;
vtExtended = 3;
vtString = 4;
vtPointer = 5;
vtPChar = 6;
vtObject = 7;
vtClass = 8;
vtWideChar = 9;
vtPWideChar = 10;
vtAnsiString = 11;
vtCurrency = 12;
vtVariant = 13;
vtInterface = 14;
vtWideString = 15;
vtInt64 = 16;
{ Virtual method table entries }
vmtSelfPtr = -76;
vmtIntfTable = -72;
vmtAutoTable = -68;
vmtInitTable = -64;
vmtTypeInfo = -60;
vmtFieldTable = -56;
vmtMethodTable = -52;
vmtDynamicTable = -48;
vmtClassName = -44;
vmtInstanceSize = -40;
vmtParent = -36;
vmtSafeCallException = -32;
vmtAfterConstruction = -28;
vmtBeforeDestruction = -24;
vmtDispatch = -20;
vmtDefaultHandler = -16;
vmtNewInstance = -12;
vmtFreeInstance = -8;
vmtDestroy = -4;
vmtQueryInterface = 0;
vmtAddRef = 4;
vmtRelease = 8;
vmtCreateObject = 12;
type
TObject = class;
TClass = class of TObject;
HRESULT = type Longint; { from WTYPES.H }
{$EXTERNALSYM HRESULT}
PGUID = ^TGUID;
TGUID = packed record
D1: LongWord;
D2: Word;
D3: Word;
D4: array[0..7] of Byte;
end;
PInterfaceEntry = ^TInterfaceEntry;
TInterfaceEntry = packed record
IID: TGUID;
VTable: Pointer;
IOffset: Integer;
ImplGetter: Integer;
end;
PInterfaceTable = ^TInterfaceTable;
TInterfaceTable = packed record
EntryCount: Integer;
Entries: array[0..9999] of TInterfaceEntry;
end;
TMethod = record
Code, Data: Pointer;
end;
{ TObject.Dispatch accepts any data type as its Message parameter. The
first 2 bytes of the data are taken as the message id to search for
in the object's message methods. TDispatchMessage is an example of
such a structure with a word field for the message id.
}
TDispatchMessage = record
MsgID: Word;
end;
TObject = class
constructor Create;
procedure Free;
class function InitInstance(Instance: Pointer): TObject;
procedure CleanupInstance;
function ClassType: TClass;
class function ClassName: ShortString;
class function ClassNameIs(const Name: string): Boolean;
class function ClassParent: TClass;
class function ClassInfo: Pointer;
class function InstanceSize: Longint;
class function InheritsFrom(AClass: TClass): Boolean;
class function MethodAddress(const Name: ShortString): Pointer;
class function MethodName(Address: Pointer): ShortString;
function FieldAddress(const Name: ShortString): Pointer;
function GetInterface(const IID: TGUID; out Obj): Boolean;
class function GetInterfaceEntry(const IID: TGUID): PInterfaceEntry;
class function GetInterfaceTable: PInterfaceTable;
function SafeCallException(ExceptObject: TObject;
ExceptAddr: Pointer): HResult; virtual;
procedure AfterConstruction; virtual;
procedure BeforeDestruction; virtual;
procedure Dispatch(var Message); virtual;
procedure DefaultHandler(var Message); virtual;
class function NewInstance: TObject; virtual;
procedure FreeInstance; virtual;
destructor Destroy; virtual;
end;
const
S_OK = 0; {$EXTERNALSYM S_OK}
S_FALSE = $00000001; {$EXTERNALSYM S_FALSE}
E_NOINTERFACE = HRESULT($80004002); {$EXTERNALSYM E_NOINTERFACE}
E_UNEXPECTED = HRESULT($8000FFFF); {$EXTERNALSYM E_UNEXPECTED}
E_NOTIMPL = HRESULT($80004001); {$EXTERNALSYM E_NOTIMPL}
type
IInterface = interface
['{00000000-0000-0000-C000-000000000046}']
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
(*$HPPEMIT '#define IInterface IUnknown' *)
IUnknown = IInterface;
{$M+}
IInvokable = interface(IInterface)
end;
{$M-}
IDispatch = interface(IUnknown)
['{00020400-0000-0000-C000-000000000046}']
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;
end;
{$EXTERNALSYM IUnknown}
{$EXTERNALSYM IDispatch}
{ TInterfacedObject provides a threadsafe default implementation
of IInterface. You should use TInterfaceObject as the base class
of objects implementing interfaces. }
TInterfacedObject = class(TObject, IInterface)
protected
FRefCount: Integer;
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
class function NewInstance: TObject; override;
property RefCount: Integer read FRefCount;
end;
TInterfacedClass = class of TInterfacedObject;
{ TAggregatedObject and TContainedObject are suitable base
classes for interfaced objects intended to be aggregated
or contained in an outer controlling object. When using
the "implements" syntax on an interface property in
an outer object class declaration, use these types
to implement the inner object.
Interfaces implemented by aggregated objects on behalf of
the controller should not be distinguishable from other
interfaces provided by the controller. Aggregated objects
must not maintain their own reference count - they must
have the same lifetime as their controller. To achieve this,
aggregated objects reflect the reference count methods
to the controller.
TAggregatedObject simply reflects QueryInterface calls to
its controller. From such an aggregated object, one can
obtain any interface that the controller supports, and
only interfaces that the controller supports. This is
useful for implementing a controller class that uses one
or more internal objects to implement the interfaces declared
on the controller class. Aggregation promotes implementation
sharing across the object hierarchy.
TAggregatedObject is what most aggregate objects should
inherit from, especially when used in conjunction with
the "implements" syntax. }
TAggregatedObject = class(TObject)
private
FController: Pointer; // weak reference to controller
function GetController: IInterface;
protected
{ IInterface }
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
constructor Create(const Controller: IInterface);
property Controller: IInterface read GetController;
end;
{ TContainedObject is an aggregated object that isolates
QueryInterface on the aggregate from the controller.
TContainedObject will return only interfaces that the
contained object itself implements, not interfaces
that the controller implements. This is useful for
implementing nodes that are attached to a controller and
have the same lifetime as the controller, but whose
interface identity is separate from the controller.
You might do this if you don't want the consumers of
an aggregated interface to have access to other interfaces
implemented by the controller - forced encapsulation.
This is a less common case than TAggregatedObject. }
TContainedObject = class(TAggregatedObject, IInterface)
protected
{ IInterface }
function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
end;
PShortString = ^ShortString;
PAnsiString = ^AnsiString;
PWideString = ^WideString;
PString = PAnsiString;
UCS2Char = WideChar;
PUCS2Char = PWideChar;
UCS4Char = type LongWord;
{$NODEFINE UCS4CHAR}
PUCS4Char = ^UCS4Char;
{$NODEFINE PUCS4CHAR}
TUCS4CharArray = array [0..$effffff] of UCS4Char;
PUCS4CharArray = ^TUCS4CharArray;
UCS4String = array of UCS4Char;
{$NODEFINE UCS4String}
UTF8String = type string;
PUTF8String = ^UTF8String;
{$NODEFINE UTF8String}
{$NODEFINE PUTF8String}
IntegerArray = array[0..$effffff] of Integer;
PIntegerArray = ^IntegerArray;
PointerArray = array [0..512*1024*1024 - 2] of Pointer;
PPointerArray = ^PointerArray;
TBoundArray = array of Integer;
TPCharArray = packed array[0..(MaxLongint div SizeOf(PChar))-1] of PChar;
PPCharArray = ^TPCharArray;
(*$HPPEMIT 'namespace System' *)
(*$HPPEMIT '{' *)
(*$HPPEMIT ' typedef int *PLongint;' *)
(*$HPPEMIT ' typedef bool *PBoolean;' *)
(*$HPPEMIT ' typedef PChar *PPChar;' *)
(*$HPPEMIT ' typedef double *PDouble;' *)
(*$HPPEMIT ' typedef wchar_t UCS4Char;' *)
(*$HPPEMIT ' typedef wchar_t *PUCS4Char;' *)
(*$HPPEMIT ' typedef DynamicArray<UCS4Char> UCS4String;' *)
(*$HPPEMIT '}' *)
PLongint = ^Longint;
{$EXTERNALSYM PLongint}
PInteger = ^Integer;
PCardinal = ^Cardinal;
PWord = ^Word;
PSmallInt = ^SmallInt;
PByte = ^Byte;
PShortInt = ^ShortInt;
PInt64 = ^Int64;
PLongWord = ^LongWord;
PSingle = ^Single;
PDouble = ^Double;
PDate = ^Double;
PDispatch = ^IDispatch;
PPDispatch = ^PDispatch;
PError = ^LongWord;
PWordBool = ^WordBool;
PUnknown = ^IUnknown;
PPUnknown = ^PUnknown;
{$NODEFINE PByte}
PPWideChar = ^PWideChar;
PPChar = ^PChar;
PPAnsiChar = PPChar;
PExtended = ^Extended;
PComp = ^Comp;
PCurrency = ^Currency;
PVariant = ^Variant;
POleVariant = ^OleVariant;
PPointer = ^Pointer;
PBoolean = ^Boolean;
TDateTime = type Double;
PDateTime = ^TDateTime;
THandle = LongWord;
TVarArrayBound = packed record
ElementCount: Integer;
LowBound: Integer;
end;
TVarArrayBoundArray = array [0..0] of TVarArrayBound;
PVarArrayBoundArray = ^TVarArrayBoundArray;
TVarArrayCoorArray = array [0..0] of Integer;
PVarArrayCoorArray = ^TVarArrayCoorArray;
PVarArray = ^TVarArray;
TVarArray = packed record
DimCount: Word;
Flags: Word;
ElementSize: Integer;
LockCount: Integer;
Data: Pointer;
Bounds: TVarArrayBoundArray;
end;
TVarType = Word;
PVarData = ^TVarData;
{$EXTERNALSYM PVarData}
TVarData = packed record
VType: TVarType;
case Integer of
0: (Reserved1: Word;
case Integer of
0: (Reserved2, Reserved3: Word;
case Integer of
varSmallInt: (VSmallInt: SmallInt);
varInteger: (VInteger: Integer);
varSingle: (VSingle: Single);
varDouble: (VDouble: Double);
varCurrency: (VCurrency: Currency);
varDate: (VDate: TDateTime);
varOleStr: (VOleStr: PWideChar);
varDispatch: (VDispatch: Pointer);
varError: (VError: LongWord);
varBoolean: (VBoolean: WordBool);
varUnknown: (VUnknown: Pointer);
varShortInt: (VShortInt: ShortInt);
varByte: (VByte: Byte);
varWord: (VWord: Word);
varLongWord: (VLongWord: LongWord);
varInt64: (VInt64: Int64);
varString: (VString: Pointer);
varAny: (VAny: Pointer);
varArray: (VArray: PVarArray);
varByRef: (VPointer: Pointer);
);
1: (VLongs: array[0..2] of LongInt);
);
2: (VWords: array [0..6] of Word);
3: (VBytes: array [0..13] of Byte);
end;
{$EXTERNALSYM TVarData}
type
TVarOp = Integer;
const
opAdd = 0;
opSubtract = 1;
opMultiply = 2;
opDivide = 3;
opIntDivide = 4;
opModulus = 5;
opShiftLeft = 6;
opShiftRight = 7;
opAnd = 8;
opOr = 9;
opXor = 10;
opCompare = 11;
opNegate = 12;
opNot = 13;
opCmpEQ = 14;
opCmpNE = 15;
opCmpLT = 16;
opCmpLE = 17;
opCmpGT = 18;
opCmpGE = 19;
type
{ Dispatch call descriptor }
PCallDesc = ^TCallDesc;
TCallDesc = packed record
CallType: Byte;
ArgCount: Byte;
NamedArgCount: Byte;
ArgTypes: array[0..255] of Byte;
end;
PDispDesc = ^TDispDesc;
TDispDesc = packed record
DispID: Integer;
ResType: Byte;
CallDesc: TCallDesc;
end;
PVariantManager = ^TVariantManager;
{$EXTERNALSYM PVariantManager}
TVariantManager = record
VarClear: procedure(var V : Variant);
VarCopy: procedure(var Dest: Variant; const Source: Variant);
VarCopyNoInd: procedure; // ARGS PLEASE!
VarCast: procedure(var Dest: Variant; const Source: Variant; VarType: Integer);
VarCastOle: procedure(var Dest: Variant; const Source: Variant; VarType: Integer);
VarToInt: function(const V: Variant): Integer;
VarToInt64: function(const V: Variant): Int64;
VarToBool: function(const V: Variant): Boolean;
VarToReal: function(const V: Variant): Extended;
VarToCurr: function(const V: Variant): Currency;
VarToPStr: procedure(var S; const V: Variant);
VarToLStr: procedure(var S: string; const V: Variant);
VarToWStr: procedure(var S: WideString; const V: Variant);
VarToIntf: procedure(var Unknown: IInterface; const V: Variant);
VarToDisp: procedure(var Dispatch: IDispatch; const V: Variant);
VarToDynArray: procedure(var DynArray: Pointer; const V: Variant; TypeInfo: Pointer);
VarFromInt: procedure(var V: Variant; const Value, Range: Integer);
VarFromInt64: procedure(var V: Variant; const Value: Int64);
VarFromBool: procedure(var V: Variant; const Value: Boolean);
VarFromReal: procedure; // var V: Variant; const Value: Real
VarFromTDateTime: procedure; // var V: Variant; const Value: TDateTime
VarFromCurr: procedure; // var V: Variant; const Value: Currency
VarFromPStr: procedure(var V: Variant; const Value: ShortString);
VarFromLStr: procedure(var V: Variant; const Value: string);
VarFromWStr: procedure(var V: Variant; const Value: WideString);
VarFromIntf: procedure(var V: Variant; const Value: IInterface);
VarFromDisp: procedure(var V: Variant; const Value: IDispatch);
VarFromDynArray: procedure(var V: Variant; const DynArray: Pointer; TypeInfo: Pointer);
OleVarFromPStr: procedure(var V: OleVariant; const Value: ShortString);
OleVarFromLStr: procedure(var V: OleVariant; const Value: string);
OleVarFromVar: procedure(var V: OleVariant; const Value: Variant);
OleVarFromInt: procedure(var V: OleVariant; const Value, Range: Integer);
VarOp: procedure(var Left: Variant; const Right: Variant; OpCode: TVarOp);
VarCmp: procedure(const Left, Right: TVarData; const OpCode: TVarOp); { result is set in the flags }
VarNeg: procedure(var V: Variant);
VarNot: procedure(var V: Variant);
DispInvoke: procedure(Dest: PVarData; const Source: TVarData;
CallDesc: PCallDesc; Params: Pointer); cdecl;
VarAddRef: procedure(var V: Variant);
VarArrayRedim: procedure(var A : Variant; HighBound: Integer);
VarArrayGet: function(var A: Variant; IndexCount: Integer;
Indices: Integer): Variant; cdecl;
VarArrayPut: procedure(var A: Variant; const Value: Variant;
IndexCount: Integer; Indices: Integer); cdecl;
WriteVariant: function(var T: Text; const V: Variant; Width: Integer): Pointer;
Write0Variant: function(var T: Text; const V: Variant): Pointer;
end;
{$EXTERNALSYM TVariantManager}
{ Dynamic array support }
PDynArrayTypeInfo = ^TDynArrayTypeInfo;
{$EXTERNALSYM PDynArrayTypeInfo}
TDynArrayTypeInfo = packed record
kind: Byte;
name: string[0];
elSize: Longint;
elType: ^PDynArrayTypeInfo;
varType: Integer;
end;
{$EXTERNALSYM TDynArrayTypeInfo}
PVarRec = ^TVarRec;
TVarRec = record { do not pack this record; it is compiler-generated }
case Byte of
vtInteger: (VInteger: Integer; VType: Byte);
vtBoolean: (VBoolean: Boolean);
vtChar: (VChar: Char);
vtExtended: (VExtended: PExtended);
vtString: (VString: PShortString);
vtPointer: (VPointer: Pointer);
vtPChar: (VPChar: PChar);
vtObject: (VObject: TObject);
vtClass: (VClass: TClass);
vtWideChar: (VWideChar: WideChar);
vtPWideChar: (VPWideChar: PWideChar);
vtAnsiString: (VAnsiString: Pointer);
vtCurrency: (VCurrency: PCurrency);
vtVariant: (VVariant: PVariant);
vtInterface: (VInterface: Pointer);
vtWideString: (VWideString: Pointer);
vtInt64: (VInt64: PInt64);
end;
PMemoryManager = ^TMemoryManager;
TMemoryManager = record
GetMem: function(Size: Integer): Pointer;
FreeMem: function(P: Pointer): Integer;
ReallocMem: function(P: Pointer; Size: Integer): Pointer;
end;
THeapStatus = record
TotalAddrSpace: Cardinal;
TotalUncommitted: Cardinal;
TotalCommitted: Cardinal;
TotalAllocated: Cardinal;
TotalFree: Cardinal;
FreeSmall: Cardinal;
FreeBig: Cardinal;
Unused: Cardinal;
Overhead: Cardinal;
HeapErrorCode: Cardinal;
end;
{$IFDEF PC_MAPPED_EXCEPTIONS}
PUnwinder = ^TUnwinder;
TUnwinder = record
RaiseException: function(Exc: Pointer): LongBool; cdecl;
RegisterIPLookup: function(fn: Pointer; StartAddr, EndAddr: LongInt; Context: Pointer; GOT: LongInt): LongBool; cdecl;
UnregisterIPLookup: procedure(StartAddr: LongInt) cdecl;
DelphiLookup: function(Addr: LongInt; Context: Pointer): Pointer; cdecl;
ClosestHandler: function(Context: Pointer): LongWord; cdecl;
end;
{$ENDIF PC_MAPPED_EXCEPTIONS}
PackageUnitEntry = packed record
Init, FInit : Pointer;
end;
{ Compiler generated table to be processed sequentially to init & finit all package units }
{ Init: 0..Max-1; Final: Last Initialized..0 }
UnitEntryTable = array [0..9999999] of PackageUnitEntry;
PUnitEntryTable = ^UnitEntryTable;
PackageInfoTable = packed record
UnitCount : Integer; { number of entries in UnitInfo array; always > 0 }
UnitInfo : PUnitEntryTable;
end;
PackageInfo = ^PackageInfoTable;
{ Each package exports a '@GetPackageInfoTable' which can be used to retrieve }
{ the table which contains compiler generated information about the package DLL }
GetPackageInfoTable = function : PackageInfo;
{$IFDEF DEBUG_FUNCTIONS}
{ Inspector Query; implementation in GETMEM.INC; no need to conditionalize that }
THeapBlock = record
Start: Pointer;
Size: Cardinal;
end;
THeapBlockArray = array of THeapBlock;
TObjectArray = array of TObject;
function GetHeapBlocks: THeapBlockArray;
function FindObjects(AClass: TClass; FindDerived: Boolean): TObjectArray;
{ Inspector Query }
{$ENDIF}
{
When an exception is thrown, the exception object that is thrown is destroyed
automatically when the except clause which handles the exception is exited.
There are some cases in which an application may wish to acquire the thrown
object and keep it alive after the except clause is exited. For this purpose,
we have added the AcquireExceptionObject and ReleaseExceptionObject functions.
These functions maintain a reference count on the most current exception object,
allowing applications to legitimately obtain references. If the reference count
for an exception that is being thrown is positive when the except clause is exited,
then the thrown object is not destroyed by the RTL, but assumed to be in control
of the application. It is then the application's responsibility to destroy the
thrown object. If the reference count is zero, then the RTL will destroy the
thrown object when the except clause is exited.
}
function AcquireExceptionObject: Pointer;
procedure ReleaseExceptionObject;
{$IFDEF PC_MAPPED_EXCEPTIONS}
procedure GetUnwinder(var Dest: TUnwinder);
procedure SetUnwinder(const NewUnwinder: TUnwinder);
function IsUnwinderSet: Boolean;
//function SysRegisterIPLookup(ModuleHandle, StartAddr, EndAddr: LongInt; Context: Pointer; GOT: LongInt): LongBool;
{
Do NOT call these functions. They are for internal use only:
SysRegisterIPLookup
SysUnregisterIPLookup
BlockOSExceptions
UnblockOSExceptions
AreOSExceptionsBlocked
}
function SysRegisterIPLookup(StartAddr, EndAddr: LongInt; Context: Pointer; GOT: LongInt): LongBool;
procedure SysUnregisterIPLookup(StartAddr: LongInt);
//function SysAddressIsInPCMap(Addr: LongInt): Boolean;
function SysClosestDelphiHandler(Context: Pointer): LongWord;
procedure BlockOSExceptions;
procedure UnblockOSExceptions;
function AreOSExceptionsBlocked: Boolean;
{$ELSE}
// These functions are not portable. Use AcquireExceptionObject above instead
function RaiseList: Pointer; deprecated; { Stack of current exception objects }
function SetRaiseList(NewPtr: Pointer): Pointer; deprecated; { returns previous value }
{$ENDIF}
function ExceptObject: TObject;
function ExceptAddr: Pointer;
procedure SetInOutRes(NewValue: Integer);
type
TAssertErrorProc = procedure (const Message, Filename: string;
LineNumber: Integer; ErrorAddr: Pointer);
TSafeCallErrorProc = procedure (ErrorCode: HResult; ErrorAddr: Pointer);
{$IFDEF DEBUG}
{
This variable is just for debugging the exception handling system. See
_DbgExcNotify for the usage.
}
var
ExcNotificationProc : procedure ( NotificationKind: Integer;
ExceptionObject: Pointer;
ExceptionName: PShortString;
ExceptionLocation: Pointer;
HandlerAddr: Pointer) = nil;
{$ENDIF}
var
DispCallByIDProc: Pointer;
ExceptProc: Pointer; { Unhandled exception handler }
ErrorProc: procedure (ErrorCode: Byte; ErrorAddr: Pointer); { Error handler procedure }
{$IFDEF MSWINDOWS}
ExceptClsProc: Pointer; { Map an OS Exception to a Delphi class reference }
ExceptObjProc: Pointer; { Map an OS Exception to a Delphi class instance }
RaiseExceptionProc: Pointer;
RTLUnwindProc: Pointer;
{$ENDIF}
ExceptionClass: TClass; { Exception base class (must be Exception) }
SafeCallErrorProc: TSafeCallErrorProc; { Safecall error handler }
AssertErrorProc: TAssertErrorProc; { Assertion error handler }
ExitProcessProc: procedure; { Hook to be called just before the process actually exits }
AbstractErrorProc: procedure; { Abstract method error handler }
HPrevInst: LongWord deprecated; { Handle of previous instance - HPrevInst cannot be tested for multiple instances in Win32}
MainInstance: LongWord; { Handle of the main(.EXE) HInstance }
MainThreadID: LongWord; { ThreadID of thread that module was initialized in }
IsLibrary: Boolean; { True if module is a DLL }
CmdShow: Integer platform; { CmdShow parameter for CreateWindow }
CmdLine: PChar platform; { Command line pointer }
InitProc: Pointer; { Last installed initialization procedure }
ExitCode: Integer = 0; { Program result }
ExitProc: Pointer; { Last installed exit procedure }
ErrorAddr: Pointer = nil; { Address of run-time error }
RandSeed: Longint = 0; { Base for random number generator }
IsConsole: Boolean; { True if compiled as console app }
IsMultiThread: Boolean; { True if more than one thread }
FileMode: Byte = 2; { Standard mode for opening files }
{$IFDEF LINUX}
FileAccessRights: Integer platform; { Default access rights for opening files }
ArgCount: Integer platform;
ArgValues: PPChar platform;
{$ENDIF}
Test8086: Byte; { CPU family (minus one) See consts below }
Test8087: Byte = 3; { assume 80387 FPU or OS supplied FPU emulation }
TestFDIV: Shortint; { -1: Flawed Pentium, 0: Not determined, 1: Ok }
Input: Text; { Standard input }
Output: Text; { Standard output }
ErrOutput: Text; { Standard error output }
envp: PPChar platform;
const
CPUi386 = 2;
CPUi486 = 3;
CPUPentium = 4;
var
Default8087CW: Word = $1332;{ Default 8087 control word. FPU control
register is set to this value.
CAUTION: Setting this to an invalid value
could cause unpredictable behavior. }
HeapAllocFlags: Word platform = 2; { Heap allocation flags, gmem_Moveable }
DebugHook: Byte platform = 0; { 1 to notify debugger of non-Delphi exceptions
>1 to notify debugger of exception unwinding }
JITEnable: Byte platform = 0; { 1 to call UnhandledExceptionFilter if the exception
is not a Pascal exception.
>1 to call UnhandledExceptionFilter for all exceptions }
NoErrMsg: Boolean platform = False; { True causes the base RTL to not display the message box
when a run-time error occurs }
{$IFDEF LINUX}
{ CoreDumpEnabled = True will cause unhandled
exceptions and runtime errors to raise a
SIGABRT signal, which will cause the OS to
coredump the process address space. This can
be useful for postmortem debugging. }
CoreDumpEnabled: Boolean platform = False;
{$ENDIF}
type
(*$NODEFINE TTextLineBreakStyle*)
TTextLineBreakStyle = (tlbsLF, tlbsCRLF);
var { Text output line break handling. Default value for all text files }
DefaultTextLineBreakStyle: TTextLineBreakStyle = {$IFDEF LINUX} tlbsLF {$ENDIF}
{$IFDEF MSWINDOWS} tlbsCRLF {$ENDIF};
const
sLineBreak = {$IFDEF LINUX} #10 {$ENDIF} {$IFDEF MSWINDOWS} #13#10 {$ENDIF};
type
HRSRC = THandle;
TResourceHandle = HRSRC; // make an opaque handle type
HINST = THandle;
HMODULE = HINST;
HGLOBAL = THandle;
{$IFDEF ELF}
{ ELF resources }
function FindResource(ModuleHandle: HMODULE; ResourceName, ResourceType: PChar): TResourceHandle;
function LoadResource(ModuleHandle: HMODULE; ResHandle: TResourceHandle): HGLOBAL;
function SizeofResource(ModuleHandle: HMODULE; ResHandle: TResourceHandle): Integer;
function LockResource(ResData: HGLOBAL): Pointer;
function UnlockResource(ResData: HGLOBAL): LongBool;
function FreeResource(ResData: HGLOBAL): LongBool;
{$ENDIF}
{ Memory manager support }
procedure GetMemoryManager(var MemMgr: TMemoryManager);
procedure SetMemoryManager(const MemMgr: TMemoryManager);
function IsMemoryManagerSet: Boolean;
function SysGetMem(Size: Integer): Pointer;
function SysFreeMem(P: Pointer): Integer;
function SysReallocMem(P: Pointer; Size: Integer): Pointer;
var
AllocMemCount: Integer; { Number of allocated memory blocks }
AllocMemSize: Integer; { Total size of allocated memory blocks }
{$IFDEF MSWINDOWS}
function GetHeapStatus: THeapStatus; platform;
{$ENDIF}
{ Thread support }
type
TThreadFunc = function(Parameter: Pointer): Integer;
{$IFDEF LINUX}
TSize_T = Cardinal;
TSchedParam = record
sched_priority: Integer;
end;
pthread_attr_t = record
__detachstate,
__schedpolicy: Integer;
__schedparam: TSchedParam;
__inheritsched,
__scope: Integer;
__guardsize: TSize_T;
__stackaddr_set: Integer;
__stackaddr: Pointer;
__stacksize: TSize_T;
end;
{$EXTERNALSYM pthread_attr_t}
TThreadAttr = pthread_attr_t;
PThreadAttr = ^TThreadAttr;
TBeginThreadProc = function (Attribute: PThreadAttr;
ThreadFunc: TThreadFunc; Parameter: Pointer;
var ThreadId: Cardinal): Integer;
TEndThreadProc = procedure(ExitCode: Integer);
var
BeginThreadProc: TBeginThreadProc = nil;
EndThreadProc: TEndThreadProc = nil;
{$ENDIF}
{$IFDEF MSWINDOWS}
function BeginThread(SecurityAttributes: Pointer; StackSize: LongWord;
ThreadFunc: TThreadFunc; Parameter: Pointer; CreationFlags: LongWord;
var ThreadId: LongWord): Integer;
{$ENDIF}
{$IFDEF LINUX}
function BeginThread(Attribute: PThreadAttr; ThreadFunc: TThreadFunc;
Parameter: Pointer; var ThreadId: Cardinal): Integer;
{$ENDIF}
procedure EndThread(ExitCode: Integer);
{ Standard procedures and functions }
const
{ File mode magic numbers }
fmClosed = $D7B0;
fmInput = $D7B1;
fmOutput = $D7B2;
fmInOut = $D7B3;
{ Text file flags }
tfCRLF = $1; // Dos compatibility flag, for CR+LF line breaks and EOF checks
type
{ Typed-file and untyped-file record }
TFileRec = packed record (* must match the size the compiler generates: 332 bytes *)
Handle: Integer;
Mode: Word;
Flags: Word;
case Byte of
0: (RecSize: Cardinal); // files of record
1: (BufSize: Cardinal; // text files
BufPos: Cardinal;
BufEnd: Cardinal;
BufPtr: PChar;
OpenFunc: Pointer;
InOutFunc: Pointer;
FlushFunc: Pointer;
CloseFunc: Pointer;
UserData: array[1..32] of Byte;
Name: array[0..259] of Char; );
end;
{ Text file record structure used for Text files }
PTextBuf = ^TTextBuf;
TTextBuf = array[0..127] of Char;
TTextRec = packed record (* must match the size the compiler generates: 460 bytes *)
Handle: Integer; (* must overlay with TFileRec *)
Mode: Word;
Flags: Word;
BufSize: Cardinal;
BufPos: Cardinal;
BufEnd: Cardinal;
BufPtr: PChar;
OpenFunc: Pointer;
InOutFunc: Pointer;
FlushFunc: Pointer;
CloseFunc: Pointer;
UserData: array[1..32] of Byte;
Name: array[0..259] of Char;
Buffer: TTextBuf;
end;
TTextIOFunc = function (var F: TTextRec): Integer;
TFileIOFunc = function (var F: TFileRec): Integer;
procedure SetLineBreakStyle(var T: Text; Style: TTextLineBreakStyle);
procedure ChDir(const S: string); overload;
procedure ChDir(P: PChar); overload;
function Flush(var t: Text): Integer;
procedure _LGetDir(D: Byte; var S: string);
procedure _SGetDir(D: Byte; var S: ShortString);
function IOResult: Integer;
procedure MkDir(const S: string); overload;
procedure MkDir(P: PChar); overload;
procedure Move(const Source; var Dest; Count: Integer);
function ParamCount: Integer;
function ParamStr(Index: Integer): string;
procedure Randomize;
procedure RmDir(const S: string); overload;
procedure RmDir(P: PChar); overload;
function UpCase(Ch: Char): Char;
{ Control 8087 control word }
procedure Set8087CW(NewCW: Word);
function Get8087CW: Word;
{ Wide character support procedures and functions for C++ }
{ These functions should not be used in Delphi code!
(conversion is implicit in Delphi code) }
function WideCharToString(Source: PWideChar): string;
function WideCharLenToString(Source: PWideChar; SourceLen: Integer): string;
procedure WideCharToStrVar(Source: PWideChar; var Dest: string);
procedure WideCharLenToStrVar(Source: PWideChar; SourceLen: Integer;
var Dest: string);
function StringToWideChar(const Source: string; Dest: PWideChar;
DestSize: Integer): PWideChar;
{ PUCS4Chars returns a pointer to the UCS4 char data in the
UCS4String array, or a pointer to a null char if UCS4String is empty }
function PUCS4Chars(const S: UCS4String): PUCS4Char;
{ Widestring <-> UCS4 conversion }
function WideStringToUCS4String(const S: WideString): UCS4String;
function UCS4StringToWideString(const S: UCS4String): WideString;
{ PChar/PWideChar Unicode <-> UTF8 conversion }
// UnicodeToUTF8(3):
// UTF8ToUnicode(3):
// Scans the source data to find the null terminator, up to MaxBytes
// Dest must have MaxBytes available in Dest.
// MaxDestBytes includes the null terminator (last char in the buffer will be set to null)
// Function result includes the null terminator.
function UnicodeToUtf8(Dest: PChar; Source: PWideChar; MaxBytes: Integer): Integer; overload; deprecated;
function Utf8ToUnicode(Dest: PWideChar; Source: PChar; MaxChars: Integer): Integer; overload; deprecated;
// UnicodeToUtf8(4):
// UTF8ToUnicode(4):
// MaxDestBytes includes the null terminator (last char in the buffer will be set to null)
// Function result includes the null terminator.
// Nulls in the source data are not considered terminators - SourceChars must be accurate
function UnicodeToUtf8(Dest: PChar; MaxDestBytes: Cardinal; Source: PWideChar; SourceChars: Cardinal): Cardinal; overload;
function Utf8ToUnicode(Dest: PWideChar; MaxDestChars: Cardinal; Source: PChar; SourceBytes: Cardinal): Cardinal; overload;
{ WideString <-> UTF8 conversion }
function UTF8Encode(const WS: WideString): UTF8String;
function UTF8Decode(const S: UTF8String): WideString;
{ Ansi <-> UTF8 conversion }
function AnsiToUtf8(const S: string): UTF8String;
function Utf8ToAnsi(const S: UTF8String): string;
{ OLE string support procedures and functions }
function OleStrToString(Source: PWideChar): string;
procedure OleStrToStrVar(Source: PWideChar; var Dest: string);
function StringToOleStr(const Source: string): PWideChar;
{ Variant manager support procedures and functions }
procedure GetVariantManager(var VarMgr: TVariantManager);
procedure SetVariantManager(const VarMgr: TVariantManager);
function IsVariantManagerSet: Boolean;
{ Variant support procedures and functions }
procedure _VarClear(var V: Variant);
procedure _VarCopy(var Dest: Variant; const Source: Variant);
procedure _VarCopyNoInd;
procedure _VarCast(var Dest: Variant; const Source: Variant; VarType: Integer);
procedure _VarCastOle(var Dest: Variant; const Source: Variant; VarType: Integer);
procedure _VarClr(var V: Variant);
{ Variant text streaming support }
function _WriteVariant(var T: Text; const V: Variant; Width: Integer): Pointer;
function _Write0Variant(var T: Text; const V: Variant): Pointer;
{ Variant math and conversion support }
function _VarToInt(const V: Variant): Integer;
function _VarToInt64(const V: Variant): Int64;
function _VarToBool(const V: Variant): Boolean;
function _VarToReal(const V: Variant): Extended;
function _VarToCurr(const V: Variant): Currency;
procedure _VarToPStr(var S; const V: Variant);
procedure _VarToLStr(var S: string; const V: Variant);
procedure _VarToWStr(var S: WideString; const V: Variant);
procedure _VarToIntf(var Unknown: IInterface; const V: Variant);
procedure _VarToDisp(var Dispatch: IDispatch; const V: Variant);
procedure _VarToDynArray(var DynArray: Pointer; const V: Variant; TypeInfo: Pointer);
procedure _VarFromInt(var V: Variant; const Value, Range: Integer);
procedure _VarFromInt64(var V: Variant; const Value: Int64);
procedure _VarFromBool(var V: Variant; const Value: Boolean);
procedure _VarFromReal; // var V: Variant; const Value: Real
procedure _VarFromTDateTime; // var V: Variant; const Value: TDateTime
procedure _VarFromCurr; // var V: Variant; const Value: Currency
procedure _VarFromPStr(var V: Variant; const Value: ShortString);
procedure _VarFromLStr(var V: Variant; const Value: string);
procedure _VarFromWStr(var V: Variant; const Value: WideString);
procedure _VarFromIntf(var V: Variant; const Value: IInterface);
procedure _VarFromDisp(var V: Variant; const Value: IDispatch);
procedure _VarFromDynArray(var V: Variant; const DynArray: Pointer; TypeInfo: Pointer);
procedure _OleVarFromPStr(var V: OleVariant; const Value: ShortString);
procedure _OleVarFromLStr(var V: OleVariant; const Value: string);
procedure _OleVarFromVar(var V: OleVariant; const Value: Variant);
procedure _OleVarFromInt(var V: OleVariant; const Value, Range: Integer);
procedure _VarAdd(var Left: Variant; const Right: Variant);
procedure _VarSub(var Left: Variant; const Right: Variant);
procedure _VarMul(var Left: Variant; const Right: Variant);
procedure _VarDiv(var Left: Variant; const Right: Variant);
procedure _VarMod(var Left: Variant; const Right: Variant);
procedure _VarAnd(var Left: Variant; const Right: Variant);
procedure _VarOr(var Left: Variant; const Right: Variant);
procedure _VarXor(var Left: Variant; const Right: Variant);
procedure _VarShl(var Left: Variant; const Right: Variant);
procedure _VarShr(var Left: Variant; const Right: Variant);
procedure _VarRDiv(var Left: Variant; const Right: Variant);
procedure _VarCmpEQ(const Left, Right: Variant); // result is set in the flags
procedure _VarCmpNE(const Left, Right: Variant); // result is set in the flags
procedure _VarCmpLT(const Left, Right: Variant); // result is set in the flags
procedure _VarCmpLE(const Left, Right: Variant); // result is set in the flags
procedure _VarCmpGT(const Left, Right: Variant); // result is set in the flags
procedure _VarCmpGE(const Left, Right: Variant); // result is set in the flags
procedure _VarNeg(var V: Variant);
procedure _VarNot(var V: Variant);
{ Variant dispatch and reference support }
procedure _DispInvoke; cdecl; // Dest: PVarData; const Source: TVarData;
// CallDesc: PCallDesc; Params: Pointer
procedure _IntfDispCall; cdecl; // ARGS PLEASE!
procedure _IntfVarCall; cdecl; // ARGS PLEASE!
procedure _VarAddRef(var V: Variant);
{ Variant array support procedures and functions }
procedure _VarArrayRedim(var A : Variant; HighBound: Integer);
function _VarArrayGet(var A: Variant; IndexCount: Integer;
Indices: Integer): Variant; cdecl;
procedure _VarArrayPut(var A: Variant; const Value: Variant;
IndexCount: Integer; Indices: Integer); cdecl;
{ Package/Module registration and unregistration }
type
PLibModule = ^TLibModule;
TLibModule = record
Next: PLibModule;
Instance: LongWord;
CodeInstance: LongWord;
DataInstance: LongWord;
ResInstance: LongWord;
Reserved: Integer;
{$IFDEF LINUX}
InstanceVar: Pointer platform;
GOT: LongWord platform;
CodeSegStart: LongWord platform;
CodeSegEnd: LongWord platform;
InitTable: Pointer platform;
{$ENDIF}
end;
TEnumModuleFunc = function (HInstance: Integer; Data: Pointer): Boolean;
{$EXTERNALSYM TEnumModuleFunc}
TEnumModuleFuncLW = function (HInstance: LongWord; Data: Pointer): Boolean;
{$EXTERNALSYM TEnumModuleFuncLW}
TModuleUnloadProc = procedure (HInstance: Integer);
{$EXTERNALSYM TModuleUnloadProc}
TModuleUnloadProcLW = procedure (HInstance: LongWord);
{$EXTERNALSYM TModuleUnloadProcLW}
PModuleUnloadRec = ^TModuleUnloadRec;
TModuleUnloadRec = record
Next: PModuleUnloadRec;
Proc: TModuleUnloadProcLW;
end;
var
LibModuleList: PLibModule = nil;
ModuleUnloadList: PModuleUnloadRec = nil;
procedure RegisterModule(LibModule: PLibModule);
procedure UnregisterModule(LibModule: PLibModule);
function FindHInstance(Address: Pointer): LongWord;
function FindClassHInstance(ClassType: TClass): LongWord;
function FindResourceHInstance(Instance: LongWord): LongWord;
function LoadResourceModule(ModuleName: PChar; CheckOwner: Boolean = True): LongWord;
procedure EnumModules(Func: TEnumModuleFunc; Data: Pointer); overload;
procedure EnumResourceModules(Func: TEnumModuleFunc; Data: Pointer); overload;
procedure EnumModules(Func: TEnumModuleFuncLW; Data: Pointer); overload;
procedure EnumResourceModules(Func: TEnumModuleFuncLW; Data: Pointer); overload;
procedure AddModuleUnloadProc(Proc: TModuleUnloadProc); overload;
procedure RemoveModuleUnloadProc(Proc: TModuleUnloadProc); overload;
procedure AddModuleUnloadProc(Proc: TModuleUnloadProcLW); overload;
procedure RemoveModuleUnloadProc(Proc: TModuleUnloadProcLW); overload;
{$IFDEF LINUX}
{ Given an HMODULE, this function will return its fully qualified name. There is
no direct equivalent in Linux so this function provides that capability. }
function GetModuleFileName(Module: HMODULE; Buffer: PChar; BufLen: Integer): Integer;
{$ENDIF}
{ ResString support function/record }
type
PResStringRec = ^TResStringRec;
TResStringRec = packed record
Module: ^Cardinal;
Identifier: Integer;
end;
function LoadResString(ResStringRec: PResStringRec): string;
{ Procedures and functions that need compiler magic }
procedure _COS;
procedure _EXP;
procedure _INT;
procedure _SIN;
procedure _FRAC;
procedure _ROUND;
procedure _TRUNC;
procedure _AbstractError;
procedure _Assert(const Message, Filename: AnsiString; LineNumber: Integer);
function _Append(var t: TTextRec): Integer;
function _Assign(var t: TTextRec; const S: String): Integer;
function _BlockRead(var f: TFileRec; buffer: Pointer; recCnt: Longint; var recsRead: Longint): Longint;
function _BlockWrite(var f: TFileRec; buffer: Pointer; recCnt: Longint; var recsWritten: Longint): Longint;
function _Close(var t: TTextRec): Integer;
procedure _PStrCat;
procedure _PStrNCat;
procedure _PStrCpy(Dest: PShortString; Source: PShortString);
procedure _PStrNCpy(Dest: PShortString; Source: PShortString; MaxLen: Byte);
function _EofFile(var f: TFileRec): Boolean;
function _EofText(var t: TTextRec): Boolean;
function _Eoln(var t: TTextRec): Boolean;
procedure _Erase(var f: TFileRec);
function _FilePos(var f: TFileRec): Longint;
function _FileSize(var f: TFileRec): Longint;
procedure _FillChar(var Dest; count: Integer; Value: Char);
function _FreeMem(P: Pointer): Integer;
function _GetMem(Size: Integer): Pointer;
function _ReallocMem(var P: Pointer; NewSize: Integer): Pointer;
procedure _Halt(Code: Integer);
procedure _Halt0;
procedure Mark; deprecated;
procedure _PStrCmp;
procedure _AStrCmp;
procedure _RandInt;
procedure _RandExt;
function _ReadRec(var f: TFileRec; Buffer: Pointer): Integer;
function _ReadChar(var t: TTextRec): Char;
function _ReadLong(var t: TTextRec): Longint;
procedure _ReadString(var t: TTextRec; s: PShortString; maxLen: Longint);
procedure _ReadCString(var t: TTextRec; s: PChar; maxLen: Longint);
procedure _ReadLString(var t: TTextRec; var s: AnsiString);
procedure _ReadWString(var t: TTextRec; var s: WideString);
procedure _ReadWCString(var t: TTextRec; s: PWideChar; maxBytes: Longint);
function _ReadWChar(var t: TTextRec): WideChar;
function _ReadExt(var t: TTextRec): Extended;
procedure _ReadLn(var t: TTextRec);
procedure _Rename(var f: TFileRec; newName: PChar);
procedure Release; deprecated;
function _ResetText(var t: TTextRec): Integer;
function _ResetFile(var f: TFileRec; recSize: Longint): Integer;
function _RewritText(var t: TTextRec): Integer;
function _RewritFile(var f: TFileRec; recSize: Longint): Integer;
procedure _RunError(errorCode: Byte);
procedure _Run0Error;
procedure _Seek(var f: TFileRec; recNum: Cardinal);
function _SeekEof(var t: TTextRec): Boolean;
function _SeekEoln(var t: TTextRec): Boolean;
procedure _SetTextBuf(var t: TTextRec; p: Pointer; size: Longint);
procedure _StrLong(val, width: Longint; s: PShortString);
procedure _Str0Long(val: Longint; s: PShortString);
procedure _Truncate(var f: TFileRec);
function _ValLong(const s: String; var code: Integer): Longint;
{$IFDEF LINUX}
procedure _UnhandledException;
{$ENDIF}
function _WriteRec(var f: TFileRec; buffer: Pointer): Pointer;
function _WriteChar(var t: TTextRec; c: Char; width: Integer): Pointer;
function _Write0Char(var t: TTextRec; c: Char): Pointer;
function _WriteBool(var t: TTextRec; val: Boolean; width: Longint): Pointer;
function _Write0Bool(var t: TTextRec; val: Boolean): Pointer;
function _WriteLong(var t: TTextRec; val, width: Longint): Pointer;
function _Write0Long(var t: TTextRec; val: Longint): Pointer;
function _WriteString(var t: TTextRec; const s: ShortString; width: Longint): Pointer;
function _Write0String(var t: TTextRec; const s: ShortString): Pointer;
function _WriteCString(var t: TTextRec; s: PChar; width: Longint): Pointer;
function _Write0CString(var t: TTextRec; s: PChar): Pointer;
function _Write0LString(var t: TTextRec; const s: AnsiString): Pointer;
function _WriteLString(var t: TTextRec; const s: AnsiString; width: Longint): Pointer;
function _Write0WString(var t: TTextRec; const s: WideString): Pointer;
function _WriteWString(var t: TTextRec; const s: WideString; width: Longint): Pointer;
function _WriteWCString(var t: TTextRec; s: PWideChar; width: Longint): Pointer;
function _Write0WCString(var t: TTextRec; s: PWideChar): Pointer;
function _WriteWChar(var t: TTextRec; c: WideChar; width: Integer): Pointer;
function _Write0WChar(var t: TTextRec; c: WideChar): Pointer;
procedure _Write2Ext;
procedure _Write1Ext;
procedure _Write0Ext;
function _WriteLn(var t: TTextRec): Pointer;
procedure __CToPasStr(Dest: PShortString; const Source: PChar);
procedure __CLenToPasStr(Dest: PShortString; const Source: PChar; MaxLen: Integer);
procedure __ArrayToPasStr(Dest: PShortString; const Source: PChar; Len: Integer);
procedure __PasToCStr(const Source: PShortString; const Dest: PChar);
procedure __IOTest;
function _Flush(var t: TTextRec): Integer;
procedure _SetElem;
procedure _SetRange;
procedure _SetEq;
procedure _SetLe;
procedure _SetIntersect;
procedure _SetIntersect3; { BEG only }
procedure _SetUnion;
procedure _SetUnion3; { BEG only }
procedure _SetSub;
procedure _SetSub3; { BEG only }
procedure _SetExpand;
procedure _Str2Ext;
procedure _Str0Ext;
procedure _Str1Ext;
procedure _ValExt;
procedure _Pow10;
procedure _Real2Ext;
procedure _Ext2Real;
procedure _ObjSetup;
procedure _ObjCopy;
procedure _Fail;
procedure _BoundErr;
procedure _IntOver;
{ Module initialization context. For internal use only. }
type
PInitContext = ^TInitContext;
TInitContext = record
OuterContext: PInitContext; { saved InitContext }
{$IFNDEF PC_MAPPED_EXCEPTIONS}
ExcFrame: Pointer; { bottom exc handler }
{$ENDIF}
InitTable: PackageInfo; { unit init info }
InitCount: Integer; { how far we got }
Module: PLibModule; { ptr to module desc }
DLLSaveEBP: Pointer; { saved regs for DLLs }
DLLSaveEBX: Pointer; { saved regs for DLLs }
DLLSaveESI: Pointer; { saved regs for DLLs }
DLLSaveEDI: Pointer; { saved regs for DLLs }
{$IFDEF MSWINDOWS}
ExitProcessTLS: procedure; { Shutdown for TLS }
{$ENDIF}
DLLInitState: Byte; { 0 = package, 1 = DLL shutdown, 2 = DLL startup }
end platform;
type
TDLLProc = procedure (Reason: Integer);
// TDLLProcEx provides the reserved param returned by WinNT
TDLLProcEx = procedure (Reason: Integer; Reserved: Integer);
{$IFDEF LINUX}
procedure _StartExe(InitTable: PackageInfo; Module: PLibModule; Argc: Integer; Argv: Pointer);
procedure _StartLib(Context: PInitContext; Module: PLibModule; DLLProc: TDLLProcEx);
{$ENDIF}
{$IFDEF MSWINDOWS}
procedure _StartExe(InitTable: PackageInfo; Module: PLibModule);
procedure _StartLib;
{$ENDIF}
procedure _PackageLoad(const Table : PackageInfo; Module: PLibModule);
procedure _PackageUnload(const Table : PackageInfo; Module: PLibModule);
procedure _InitResStrings;
procedure _InitResStringImports;
procedure _InitImports;
{$IFDEF MSWINDOWS}
procedure _InitWideStrings;
{$ENDIF}
function _ClassCreate(AClass: TClass; Alloc: Boolean): TObject;
procedure _ClassDestroy(Instance: TObject);
function _AfterConstruction(Instance: TObject): TObject;
function _BeforeDestruction(Instance: TObject; OuterMost: ShortInt): TObject;
function _IsClass(Child: TObject; Parent: TClass): Boolean;
function _AsClass(Child: TObject; Parent: TClass): TObject;
{$IFDEF PC_MAPPED_EXCEPTIONS}
procedure _RaiseAtExcept;
//procedure _DestroyException(Exc: PRaisedException);
procedure _DestroyException;
{$ENDIF}
procedure _RaiseExcept;
procedure _RaiseAgain;
procedure _DoneExcept;
{$IFNDEF PC_MAPPED_EXCEPTIONS}
procedure _TryFinallyExit;
{$ENDIF}
procedure _HandleAnyException;
procedure _HandleFinally;
procedure _HandleOnException;
{$IFDEF PC_MAPPED_EXCEPTIONS}
procedure _HandleOnExceptionPIC;
{$ENDIF}
procedure _HandleAutoException;
{$IFDEF PC_MAPPED_EXCEPTIONS}
procedure _ClassHandleException;
{$ENDIF}
procedure _CallDynaInst;
procedure _CallDynaClass;
procedure _FindDynaInst;
procedure _FindDynaClass;
procedure _LStrClr(var S);
procedure _LStrArrayClr(var StrArray; cnt: longint);
procedure _LStrAsg(var dest; const source);
procedure _LStrLAsg(var dest; const source);
procedure _LStrFromPCharLen(var Dest: AnsiString; Source: PAnsiChar; Length: Integer);
procedure _LStrFromPWCharLen(var Dest: AnsiString; Source: PWideChar; Length: Integer);
procedure _LStrFromChar(var Dest: AnsiString; Source: AnsiChar);
procedure _LStrFromWChar(var Dest: AnsiString; Source: WideChar);
procedure _LStrFromPChar(var Dest: AnsiString; Source: PAnsiChar);
procedure _LStrFromPWChar(var Dest: AnsiString; Source: PWideChar);
procedure _LStrFromString(var Dest: AnsiString; const Source: ShortString);
procedure _LStrFromArray(var Dest: AnsiString; Source: PAnsiChar; Length: Integer);
procedure _LStrFromWArray(var Dest: AnsiString; Source: PWideChar; Length: Integer);
procedure _LStrFromWStr(var Dest: AnsiString; const Source: WideString);
procedure _LStrToString{(var Dest: ShortString; const Source: AnsiString; MaxLen: Integer)};
function _LStrLen(const s: AnsiString): Longint;
procedure _LStrCat{var dest: AnsiString; source: AnsiString};
procedure _LStrCat3{var dest:AnsiString; source1: AnsiString; source2: AnsiString};
procedure _LStrCatN{var dest:AnsiString; argCnt: Integer; ...};
procedure _LStrCmp{left: AnsiString; right: AnsiString};
function _LStrAddRef(var str): Pointer;
function _LStrToPChar(const s: AnsiString): PChar;
procedure _Copy{ s : ShortString; index, count : Integer ) : ShortString};
procedure _Delete{ var s : openstring; index, count : Integer };
procedure _Insert{ source : ShortString; var s : openstring; index : Integer };
procedure _Pos{ substr : ShortString; s : ShortString ) : Integer};
procedure _SetLength(s: PShortString; newLength: Byte);
procedure _SetString(s: PShortString; buffer: PChar; len: Byte);
procedure UniqueString(var str: AnsiString); overload;
procedure UniqueString(var str: WideString); overload;
procedure _UniqueStringA(var str: AnsiString);
procedure _UniqueStringW(var str: WideString);
procedure _LStrCopy { const s : AnsiString; index, count : Integer) : AnsiString};
procedure _LStrDelete{ var s : AnsiString; index, count : Integer };
procedure _LStrInsert{ const source : AnsiString; var s : AnsiString; index : Integer };
procedure _LStrPos{ const substr : AnsiString; const s : AnsiString ) : Integer};
procedure _LStrSetLength{ var str: AnsiString; newLength: Integer};
procedure _LStrOfChar{ c: Char; count: Integer): AnsiString };
function _NewAnsiString(length: Longint): Pointer; { for debugger purposes only }
function _NewWideString(CharLength: Longint): Pointer;
procedure _WStrClr(var S);
procedure _WStrArrayClr(var StrArray; Count: Integer);
procedure _WStrAsg(var Dest: WideString; const Source: WideString);
procedure _WStrLAsg(var Dest: WideString; const Source: WideString);
function _WStrToPWChar(const S: WideString): PWideChar;
function _WStrLen(const S: WideString): Integer;
procedure _WStrFromPCharLen(var Dest: WideString; Source: PAnsiChar; Length: Integer);
procedure _WStrFromPWCharLen(var Dest: WideString; Source: PWideChar; CharLength: Integer);
procedure _WStrFromChar(var Dest: WideString; Source: AnsiChar);
procedure _WStrFromWChar(var Dest: WideString; Source: WideChar);
procedure _WStrFromPChar(var Dest: WideString; Source: PAnsiChar);
procedure _WStrFromPWChar(var Dest: WideString; Source: PWideChar);
procedure _WStrFromString(var Dest: WideString; const Source: ShortString);
procedure _WStrFromArray(var Dest: WideString; Source: PAnsiChar; Length: Integer);
procedure _WStrFromWArray(var Dest: WideString; Source: PWideChar; Length: Integer);
procedure _WStrFromLStr(var Dest: WideString; const Source: AnsiString);
procedure _WStrToString(Dest: PShortString; const Source: WideString; MaxLen: Integer);
procedure _WStrCat(var Dest: WideString; const Source: WideString);
procedure _WStrCat3(var Dest: WideString; const Source1, Source2: WideString);
procedure _WStrCatN{var dest:WideString; argCnt: Integer; ...};
procedure _WStrCmp{left: WideString; right: WideString};
function _WStrCopy(const S: WideString; Index, Count: Integer): WideString;
procedure _WStrDelete(var S: WideString; Index, Count: Integer);
procedure _WStrInsert(const Source: WideString; var Dest: WideString; Index: Integer);
procedure _WStrPos{ const substr : WideString; const s : WideString ) : Integer};
procedure _WStrSetLength(var S: WideString; NewLength: Integer);
function _WStrOfWChar(Ch: WideChar; Count: Integer): WideString;
function _WStrAddRef(var str: WideString): Pointer;
procedure _Initialize(p: Pointer; typeInfo: Pointer);
procedure _InitializeArray(p: Pointer; typeInfo: Pointer; elemCount: Cardinal);
procedure _InitializeRecord(p: Pointer; typeInfo: Pointer);
procedure _Finalize(p: Pointer; typeInfo: Pointer);
procedure _FinalizeArray(p: Pointer; typeInfo: Pointer; elemCount: Cardinal);
procedure _FinalizeRecord(P: Pointer; typeInfo: Pointer);
procedure _AddRef;
procedure _AddRefArray;
procedure _AddRefRecord;
procedure _CopyArray;
procedure _CopyRecord;
procedure _CopyObject;
function _New(size: Longint; typeInfo: Pointer): Pointer;
procedure _Dispose(p: Pointer; typeInfo: Pointer);
{ 64-bit Integer helper routines }
procedure __llmul;
procedure __lldiv;
procedure __lludiv;
procedure __llmod;
procedure __llmulo;
procedure __lldivo;
procedure __llmodo;
procedure __llumod;
procedure __llshl;
procedure __llushr;
procedure _WriteInt64;
procedure _Write0Int64;
procedure _ReadInt64;
function _StrInt64(val: Int64; width: Integer): ShortString;
function _Str0Int64(val: Int64): ShortString;
function _ValInt64(const s: AnsiString; var code: Integer): Int64;
{ Dynamic array helper functions }
procedure _DynArrayHigh;
procedure _DynArrayClear(var a: Pointer; typeInfo: Pointer);
procedure _DynArrayLength;
procedure _DynArraySetLength;
procedure _DynArrayCopy(a: Pointer; typeInfo: Pointer; var Result: Pointer);
procedure _DynArrayCopyRange(a: Pointer; typeInfo: Pointer; index, count : Integer; var Result: Pointer);
procedure _DynArrayAsg;
procedure _DynArrayAddRef;
procedure DynArrayClear(var a: Pointer; typeInfo: Pointer);
procedure DynArraySetLength(var a: Pointer; typeInfo: Pointer; dimCnt: Longint; lengthVec: PLongint);
function DynArrayDim(typeInfo: PDynArrayTypeInfo): Integer;
{$NODEFINE DynArrayDim}
function _IntfClear(var Dest: IInterface): Pointer;
procedure _IntfCopy(var Dest: IInterface; const Source: IInterface);
procedure _IntfCast(var Dest: IInterface; const Source: IInterface; const IID: TGUID);
procedure _IntfAddRef(const Dest: IInterface);
{$IFDEF MSWINDOWS}
procedure _FSafeDivide;
procedure _FSafeDivideR;
{$ENDIF}
function _CheckAutoResult(ResultCode: HResult): HResult;
procedure FPower10;
procedure TextStart; deprecated;
// Conversion utility routines for C++ convenience. Not for Delphi code.
function CompToDouble(Value: Comp): Double; cdecl;
procedure DoubleToComp(Value: Double; var Result: Comp); cdecl;
function CompToCurrency(Value: Comp): Currency; cdecl;
procedure CurrencyToComp(Value: Currency; var Result: Comp); cdecl;
function GetMemory(Size: Integer): Pointer; cdecl;
function FreeMemory(P: Pointer): Integer; cdecl;
function ReallocMemory(P: Pointer; Size: Integer): Pointer; cdecl;
{ Internal runtime error codes }
type
TRuntimeError = (reNone, reOutOfMemory, reInvalidPtr, reDivByZero,
reRangeError, reIntOverflow, reInvalidOp, reZeroDivide, reOverflow,
reUnderflow, reInvalidCast, reAccessViolation, rePrivInstruction,
reControlBreak, reStackOverflow,
{ reVar* used in Variants.pas }
reVarTypeCast, reVarInvalidOp,
reVarDispatch, reVarArrayCreate, reVarNotArray, reVarArrayBounds,
reAssertionFailed,
reExternalException, { not used here; in SysUtils }
reIntfCastError, reSafeCallError);
{$NODEFINE TRuntimeError}
procedure Error(errorCode: TRuntimeError);
{$NODEFINE Error}
{ GetLastError returns the last error reported by an OS API call. Calling
this function usually resets the OS error state.
}
function GetLastError: Integer; {$IFDEF MSWINDOWS} stdcall; {$ENDIF}
{$EXTERNALSYM GetLastError}
{ SetLastError writes to the thread local storage area read by GetLastError. }
procedure SetLastError(ErrorCode: Integer); {$IFDEF MSWINDOWS} stdcall; {$ENDIF}
{$IFDEF LINUX}
{ To improve performance, some RTL routines cache module handles and data
derived from modules. If an application dynamically loads and unloads
shared object libraries, packages, or resource packages, it is possible for
the handle of the newly loaded module to match the handle of a recently
unloaded module. The resource caches have no way to detect when this happens.
To address this issue, the RTL maintains an internal counter that is
incremented every time a module is loaded or unloaded using RTL functions
(like LoadPackage). This provides a cache version level signature that
can detect when modules have been cycled but have the same handle.
If you load or unload modules "by hand" using dlopen or dlclose, you must call
InvalidateModuleCache after each load or unload so that the RTL module handle
caches will refresh themselves properly the next time they are used. This is
especially important if you manually tinker with the LibModuleList list of
loaded modules, or manually add or remove resource modules in the nodes
of that list.
ModuleCacheID returns the "current generation" or version number kept by
the RTL. You can use this to implement your own refresh-on-next-use
(passive) module handle caches as the RTL does. The value changes each
time InvalidateModuleCache is called.
}
function ModuleCacheID: Cardinal;
procedure InvalidateModuleCache;
{$ENDIF}
{$IFDEF LINUX}
{ When a process that is being debugged is stopped while it has the mouse
pointer grabbed, there is no way for the debugger to release the grab on
behalf of the process. The process needs to do it itself. To accomplish this,
the debugger causes DbgUnlockX to execute whenever it detects the process
might have the mouse grabbed. This method will call through DbgUnlockXProc
which should be assigned by any library using X and locks the X pointer. This
method should be chained, by storing of the previous instance and calling it
when you are called, since there might be more than one display that needs
to be unlocked. This method should call XUngrabPointer on the display that
has the pointer grabbed.
}
var
DbgUnlockXProc: procedure;
procedure DbgUnlockX;
{$ENDIF}
(* =================================================================== *)
implementation
uses
SysInit;
{ This procedure should be at the very beginning of the }
{ text segment. It used to be used by _RunError to find }
{ start address of the text segment, but is not used anymore. }
procedure TextStart;
begin
end;
{$IFDEF PIC}
function GetGOT: LongWord; export;
begin
asm
MOV Result,EBX
end;
end;
{$ENDIF}
{$IFDEF PC_MAPPED_EXCEPTIONS}
const
UNWINDFI_TOPOFSTACK = $BE00EF00;
const
{$IFDEF MSWINDOWS}
unwind = 'unwind.dll';
type
UNWINDPROC = Pointer;
function UnwindRegisterIPLookup(fn: UNWINDPROC; StartAddr, EndAddr: LongInt; Context: Pointer; GOT: LongInt): LongBool; cdecl;
external unwind name '__BorUnwind_RegisterIPLookup';
function UnwindDelphiLookup(Addr: LongInt; Context: Pointer): UNWINDPROC; cdecl;
external unwind name '__BorUnwind_DelphiLookup';
function UnwindRaiseException(Exc: Pointer): LongBool; cdecl;
external unwind name '__BorUnwind_RaiseException';
function UnwindClosestHandler(Context: Pointer): LongWord; cdecl;
external unwind name '__BorUnwind_ClosestDelphiHandler';
{$ENDIF}
{$IFDEF LINUX}
unwind = 'libborunwind.so.6';
type
UNWINDPROC = Pointer;
{$DEFINE STATIC_UNWIND}
{$IFDEF STATIC_UNWIND}
function _BorUnwind_RegisterIPLookup(fn: UNWINDPROC; StartAddr, EndAddr: LongInt; Context: Pointer; GOT: LongInt): LongBool; cdecl;
external;
procedure _BorUnwind_UnregisterIPLookup(StartAddr: LongInt); cdecl; external;
function _BorUnwind_DelphiLookup(Addr: LongInt; Context: Pointer): UNWINDPROC; cdecl; external;
function _BorUnwind_RaiseException(Exc: Pointer): LongBool; cdecl; external;
//function _BorUnwind_AddressIsInPCMap(Addr: LongInt): LongBool; cdecl; external;
function _BorUnwind_ClosestDelphiHandler(Context: Pointer): LongWord; cdecl; external;
{$ELSE}
function _BorUnwind_RegisterIPLookup(fn: UNWINDPROC; StartAddr, EndAddr: LongInt; Context: Pointer; GOT: LongInt): LongBool; cdecl;
external unwind name '_BorUnwind_RegisterIPLookup';
procedure _BorUnwind_UnregisterIPLookup(StartAddr: LongInt); cdecl;
external unwind name '_BorUnwind_UnregisterIPLookup';
function _BorUnwind_DelphiLookup(Addr: LongInt; Context: Pointer): UNWINDPROC; cdecl;
external unwind name '_BorUnwind_DelphiLookup';
function _BorUnwind_RaiseException(Exc: Pointer): LongBool; cdecl;
external unwind name '_BorUnwind_RaiseException';
function _BorUnwind_ClosestDelphiHandler(Context: Pointer): LongWord; cdecl;
external unwind name '_BorUnwind_ClosestDelphiHandler';
{$ENDIF}
{$ENDIF}
{$ENDIF}
const { copied from xx.h }
cContinuable = 0;
cNonContinuable = 1;
cUnwinding = 2;
cUnwindingForExit = 4;
cUnwindInProgress = cUnwinding or cUnwindingForExit;
cDelphiException = $0EEDFADE;
cDelphiReRaise = $0EEDFADF;
cDelphiExcept = $0EEDFAE0;
cDelphiFinally = $0EEDFAE1;
cDelphiTerminate = $0EEDFAE2;
cDelphiUnhandled = $0EEDFAE3;
cNonDelphiException = $0EEDFAE4;
cDelphiExitFinally = $0EEDFAE5;
cCppException = $0EEFFACE; { used by BCB }
EXCEPTION_CONTINUE_SEARCH = 0;
EXCEPTION_EXECUTE_HANDLER = 1;
EXCEPTION_CONTINUE_EXECUTION = -1;
{$IFDEF PC_MAPPED_EXCEPTIONS}
const
excIsBeingHandled = $00000001;
excIsBeingReRaised = $00000002;
{$ENDIF}
type
JmpInstruction =
packed record
opCode: Byte;
distance: Longint;
end;
TExcDescEntry =
record
vTable: Pointer;
handler: Pointer;
end;
PExcDesc = ^TExcDesc;
TExcDesc =
packed record
{$IFNDEF PC_MAPPED_EXCEPTIONS}
jmp: JmpInstruction;
{$ENDIF}
case Integer of
0: (instructions: array [0..0] of Byte);
1{...}: (cnt: Integer; excTab: array [0..0{cnt-1}] of TExcDescEntry);
end;
{$IFNDEF PC_MAPPED_EXCEPTIONS}
PExcFrame = ^TExcFrame;
TExcFrame = record
next: PExcFrame;
desc: PExcDesc;
hEBP: Pointer;
case Integer of
0: ( );
1: ( ConstructedObject: Pointer );
2: ( SelfOfMethod: Pointer );
end;
PExceptionRecord = ^TExceptionRecord;
TExceptionRecord =
record
ExceptionCode : LongWord;
ExceptionFlags : LongWord;
OuterException : PExceptionRecord;
ExceptionAddress : Pointer;
NumberParameters : Longint;
case {IsOsException:} Boolean of
True: (ExceptionInformation : array [0..14] of Longint);
False: (ExceptAddr: Pointer; ExceptObject: Pointer);
end;
{$ENDIF}
{$IFDEF PC_MAPPED_EXCEPTIONS}
PRaisedException = ^TRaisedException;
TRaisedException = packed record
RefCount: Integer;
ExceptObject: TObject;
ExceptionAddr: Pointer;
HandlerEBP: LongWord;
Flags: LongWord;
end;
{$ELSE}
PRaiseFrame = ^TRaiseFrame;
TRaiseFrame = packed record
NextRaise: PRaiseFrame;
ExceptAddr: Pointer;
ExceptObject: TObject;
ExceptionRecord: PExceptionRecord;
end;
{$ENDIF}
const
cCR = $0D;
cLF = $0A;
cEOF = $1A;
{$IFDEF LINUX}
const
libc = 'libc.so.6';
libdl = 'libdl.so.2';
libpthread = 'libpthread.so.0';
O_RDONLY = $0000;
O_WRONLY = $0001;
O_RDWR = $0002;
O_CREAT = $0040;
O_EXCL = $0080;
O_NOCTTY = $0100;
O_TRUNC = $0200;
O_APPEND = $0400;
// protection flags
S_IREAD = $0100; // Read by owner.
S_IWRITE = $0080; // Write by owner.
S_IEXEC = $0040; // Execute by owner.
S_IRUSR = S_IREAD;
S_IWUSR = S_IWRITE;
S_IXUSR = S_IEXEC;
S_IRWXU = S_IRUSR or S_IWUSR or S_IXUSR;
S_IRGRP = S_IRUSR shr 3; // Read by group.
S_IWGRP = S_IWUSR shr 3; // Write by group.
S_IXGRP = S_IXUSR shr 3; // Execute by group.
S_IRWXG = S_IRWXU shr 3; // Read, write, and execute by group.
S_IROTH = S_IRGRP shr 3; // Read by others.
S_IWOTH = S_IWGRP shr 3; // Write by others.
S_IXOTH = S_IXGRP shr 3; // Execute by others.
S_IRWXO = S_IRWXG shr 3; // Read, write, and execute by others.
STDIN_FILENO = 0;
STDOUT_FILENO = 1;
STDERR_FILENO = 2;
SEEK_SET = 0;
SEEK_CUR = 1;
SEEK_END = 2;
LC_CTYPE = 0;
_NL_CTYPE_CODESET_NAME = LC_CTYPE shl 16 + 14;
MAX_PATH = 4095;
function __open(PathName: PChar; Flags: Integer; Mode: Integer): Integer; cdecl;
external libc name 'open';
function __close(Handle: Integer): Integer; cdecl;
external libc name 'close';
function __read(Handle: Integer; Buffer: Pointer; Count: Cardinal): Cardinal; cdecl;
external libc name 'read';
function __write(Handle: Integer; Buffer: Pointer; Count: Cardinal): Cardinal; cdecl;
external libc name 'write';
function __mkdir(PathName: PChar; Mode: Integer): Integer; cdecl;
external libc name 'mkdir';
function __getcwd(Buffer: PChar; BufSize: Integer): PChar; cdecl;
external libc name 'getcwd';
function __getenv(Name: PChar): PChar; cdecl;
external libc name 'getenv';
function __chdir(PathName: PChar): Integer; cdecl;
external libc name 'chdir';
function __rmdir(PathName: PChar): Integer; cdecl;
external libc name 'rmdir';
function __remove(PathName: PChar): Integer; cdecl;
external libc name 'remove';
function __rename(OldPath, NewPath: PChar): Integer; cdecl;
external libc name 'rename';
{$IFDEF EFENCE}
function __malloc(Size: Integer): Pointer; cdecl;
external 'libefence.so' name 'malloc';
procedure __free(P: Pointer); cdecl;
external 'libefence.so' name 'free';
function __realloc(P: Pointer; Size: Integer): Pointer; cdecl;
external 'libefence.so' name 'realloc';
{$ELSE}
function __malloc(Size: Integer): Pointer; cdecl;
external libc name 'malloc';
procedure __free(P: Pointer); cdecl;
external libc name 'free';
function __realloc(P: Pointer; Size: Integer): Pointer; cdecl;
external libc name 'realloc';
{$ENDIF}
procedure ExitProcess(status: Integer); cdecl;
external libc name 'exit';
function _time(P: Pointer): Integer; cdecl;
external libc name 'time';
function _lseek(Handle, Offset, Direction: Integer): Integer; cdecl;
external libc name 'lseek';
function _ftruncate(Handle: Integer; Filesize: Integer): Integer; cdecl;
external libc name 'ftruncate';
function strcasecmp(s1, s2: PChar): Integer; cdecl;
external libc name 'strcasecmp';
function __errno_location: PInteger; cdecl;
external libc name '__errno_location';
function nl_langinfo(item: integer): pchar; cdecl;
external libc name 'nl_langinfo';
function iconv_open(ToCode: PChar; FromCode: PChar): Integer; cdecl;
external libc name 'iconv_open';
function iconv(cd: Integer; var InBuf; var InBytesLeft: Integer; var OutBuf; var OutBytesLeft: Integer): Integer; cdecl;
external libc name 'iconv';
function iconv_close(cd: Integer): Integer; cdecl;
external libc name 'iconv_close';
function mblen(const S: PChar; N: LongWord): Integer; cdecl;
external libc name 'mblen';
function mmap(start: Pointer; length: Cardinal; prot, flags, fd, offset: Integer): Pointer; cdecl;
external libc name 'mmap';
function munmap(start: Pointer; length: Cardinal): Integer; cdecl;
external libc name 'munmap';
const
SIGABRT = 6;
function __raise(SigNum: Integer): Integer; cdecl;
external libc name 'raise';
type
TStatStruct = record
st_dev: Int64; // device
__pad1: Word;
st_ino: Cardinal; // inode
st_mode: Cardinal; // protection
st_nlink: Cardinal; // number of hard links
st_uid: Cardinal; // user ID of owner
st_gid: Cardinal; // group ID of owner
st_rdev: Int64; // device type (if inode device)
__pad2: Word;
st_size: Cardinal; // total size, in bytes
st_blksize: Cardinal; // blocksize for filesystem I/O
st_blocks: Cardinal; // number of blocks allocated
st_atime: Integer; // time of last access
__unused1: Cardinal;
st_mtime: Integer; // time of last modification
__unused2: Cardinal;
st_ctime: Integer; // time of last change
__unused3: Cardinal;
__unused4: Cardinal;
__unused5: Cardinal;
end;
const
STAT_VER_LINUX = 3;
function _fxstat(Version: Integer; Handle: Integer; var Stat: TStatStruct): Integer; cdecl;
external libc name '__fxstat';
function __xstat(Ver: Integer; FileName: PChar; var StatBuffer: TStatStruct): Integer; cdecl;
external libc name '__xstat';
function _strlen(P: PChar): Integer; cdecl;
external libc name 'strlen';
function _readlink(PathName: PChar; Buf: PChar; Len: Integer): Integer; cdecl;
external libc name 'readlink';
type
TDLInfo = record
FileName: PChar;
BaseAddress: Pointer;
NearestSymbolName: PChar;
SymbolAddress: Pointer;
end;
const
RTLD_LAZY = 1;
RTLD_NOW = 2;
function dladdr(Address: Pointer; var Info: TDLInfo): Integer; cdecl;
external libdl name 'dladdr';
function dlopen(Filename: PChar; Flag: Integer): LongWord; cdecl;
external libdl name 'dlopen';
function dlclose(Handle: LongWord): Integer; cdecl;
external libdl name 'dlclose';
function FreeLibrary(Handle: LongWord): Integer; cdecl;
external libdl name 'dlclose';
function dlsym(Handle: LongWord; Symbol: PChar): Pointer; cdecl;
external libdl name 'dlsym';
function dlerror: PChar; cdecl;
external libdl name 'dlerror';
type
TPthread_fastlock = record
__status: LongInt;
__spinlock: Integer;
end;
TRTLCriticalSection = record
__m_reserved,
__m_count: Integer;
__m_owner: Pointer;
__m_kind: Integer; // __m_kind := 0 fastlock, __m_kind := 1 recursive lock
__m_lock: TPthread_fastlock;
end;
function _pthread_mutex_lock(var Mutex: TRTLCriticalSection): Integer; cdecl;
external libpthread name 'pthread_mutex_lock';
function _pthread_mutex_unlock(var Mutex: TRTLCriticalSection): Integer; cdecl;
external libpthread name 'pthread_mutex_unlock';
function _pthread_create(var ThreadID: Cardinal; Attr: PThreadAttr;
TFunc: TThreadFunc; Arg: Pointer): Integer; cdecl;
external libpthread name 'pthread_create';
function _pthread_exit(var RetVal: Integer): Integer; cdecl;
external libpthread name 'pthread_exit';
function GetCurrentThreadID: LongWord; cdecl;
external libpthread name 'pthread_self';
function _pthread_detach(ThreadID: Cardinal): Integer; cdecl;
external libpthread name 'pthread_detach'
function GetLastError: Integer;
begin
Result := __errno_location^;
end;
procedure SetLastError(ErrorCode: Integer);
begin
__errno_location^ := ErrorCode;
end;
function InterlockedIncrement(var I: Integer): Integer;
asm
MOV EDX,1
XCHG EAX,EDX
LOCK XADD [EDX],EAX
INC EAX
end;
function InterlockedDecrement(var I: Integer): Integer;
asm
MOV EDX,-1
XCHG EAX,EDX
LOCK XADD [EDX],EAX
DEC EAX
end;
var
ModuleCacheVersion: Cardinal = 0;
function ModuleCacheID: Cardinal;
begin
Result := ModuleCacheVersion;
end;
procedure InvalidateModuleCache;
begin
InterlockedIncrement(Integer(ModuleCacheVersion));
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
type
PMemInfo = ^TMemInfo;
TMemInfo = packed record
BaseAddress: Pointer;
AllocationBase: Pointer;
AllocationProtect: Longint;
RegionSize: Longint;
State: Longint;
Protect: Longint;
Type_9 : Longint;
end;
PStartupInfo = ^TStartupInfo;
TStartupInfo = record
cb: Longint;
lpReserved: Pointer;
lpDesktop: Pointer;
lpTitle: Pointer;
dwX: Longint;
dwY: Longint;
dwXSize: Longint;
dwYSize: Longint;
dwXCountChars: Longint;
dwYCountChars: Longint;
dwFillAttribute: Longint;
dwFlags: Longint;
wShowWindow: Word;
cbReserved2: Word;
lpReserved2: ^Byte;
hStdInput: Integer;
hStdOutput: Integer;
hStdError: Integer;
end;
TWin32FindData = packed record
dwFileAttributes: Integer;
ftCreationTime: Int64;
ftLastAccessTime: Int64;
ftLastWriteTime: Int64;
nFileSizeHigh: Integer;
nFileSizeLow: Integer;
dwReserved0: Integer;
dwReserved1: Integer;
cFileName: array[0..259] of Char;
cAlternateFileName: array[0..13] of Char;
end;
const
advapi32 = 'advapi32.dll';
kernel = 'kernel32.dll';
user = 'user32.dll';
oleaut = 'oleaut32.dll';
GENERIC_READ = Integer($80000000);
GENERIC_WRITE = $40000000;
FILE_SHARE_READ = $00000001;
FILE_SHARE_WRITE = $00000002;
FILE_ATTRIBUTE_NORMAL = $00000080;
CREATE_NEW = 1;
CREATE_ALWAYS = 2;
OPEN_EXISTING = 3;
FILE_BEGIN = 0;
FILE_CURRENT = 1;
FILE_END = 2;
STD_INPUT_HANDLE = Integer(-10);
STD_OUTPUT_HANDLE = Integer(-11);
STD_ERROR_HANDLE = Integer(-12);
MAX_PATH = 260;
function CloseHandle(Handle: Integer): Integer; stdcall;
external kernel name 'CloseHandle';
function CreateFileA(lpFileName: PChar; dwDesiredAccess, dwShareMode: Integer;
lpSecurityAttributes: Pointer; dwCreationDisposition, dwFlagsAndAttributes: Integer;
hTemplateFile: Integer): Integer; stdcall;
external kernel name 'CreateFileA';
function DeleteFileA(Filename: PChar): LongBool; stdcall;
external kernel name 'DeleteFileA';
function GetFileType(hFile: Integer): Integer; stdcall;
external kernel name 'GetFileType';
procedure GetSystemTime; stdcall; external kernel name 'GetSystemTime';
function GetFileSize(Handle: Integer; x: Integer): Integer; stdcall;
external kernel name 'GetFileSize';
function GetStdHandle(nStdHandle: Integer): Integer; stdcall;
external kernel name 'GetStdHandle';
function MoveFileA(OldName, NewName: PChar): LongBool; stdcall;
external kernel name 'MoveFileA';
procedure RaiseException; stdcall; external kernel name 'RaiseException';
function ReadFile(hFile: Integer; var Buffer; nNumberOfBytesToRead: Cardinal;
var lpNumberOfBytesRead: Cardinal; lpOverlapped: Pointer): Integer; stdcall;
external kernel name 'ReadFile';
procedure RtlUnwind; stdcall; external kernel name 'RtlUnwind';
function SetEndOfFile(Handle: Integer): LongBool; stdcall;
external kernel name 'SetEndOfFile';
function SetFilePointer(Handle, Distance: Integer; DistanceHigh: Pointer;
MoveMethod: Integer): Integer; stdcall;
external kernel name 'SetFilePointer';
procedure UnhandledExceptionFilter; stdcall;
external kernel name 'UnhandledExceptionFilter';
function WriteFile(hFile: Integer; const Buffer; nNumberOfBytesToWrite: Cardinal;
var lpNumberOfBytesWritten: Cardinal; lpOverlapped: Pointer): Integer; stdcall;
external kernel name 'WriteFile';
function CharNext(lpsz: PChar): PChar; stdcall;
external user name 'CharNextA';
function CreateThread(SecurityAttributes: Pointer; StackSize: LongWord;
ThreadFunc: TThreadFunc; Parameter: Pointer;
CreationFlags: LongWord; var ThreadId: LongWord): Integer; stdcall;
external kernel name 'CreateThread';
procedure ExitThread(ExitCode: Integer); stdcall;
external kernel name 'ExitThread';
procedure ExitProcess(ExitCode: Integer); stdcall;
external kernel name 'ExitProcess';
procedure MessageBox(Wnd: Integer; Text: PChar; Caption: PChar; Typ: Integer); stdcall;
external user name 'MessageBoxA';
function CreateDirectory(PathName: PChar; Attr: Integer): WordBool; stdcall;
external kernel name 'CreateDirectoryA';
function FindClose(FindFile: Integer): LongBool; stdcall;
external kernel name 'FindClose';
function FindFirstFile(FileName: PChar; var FindFileData: TWIN32FindData): Integer; stdcall;
external kernel name 'FindFirstFileA';
function FreeLibrary(ModuleHandle: Longint): LongBool; stdcall;
external kernel name 'FreeLibrary';
function GetCommandLine: PChar; stdcall;
external kernel name 'GetCommandLineA';
function GetCurrentDirectory(BufSize: Integer; Buffer: PChar): Integer; stdcall;
external kernel name 'GetCurrentDirectoryA';
function GetLastError: Integer; stdcall;
external kernel name 'GetLastError';
procedure SetLastError(ErrorCode: Integer); stdcall;
external kernel name 'SetLastError';
function GetLocaleInfo(Locale: Longint; LCType: Longint; lpLCData: PChar; cchData: Integer): Integer; stdcall;
external kernel name 'GetLocaleInfoA';
function GetModuleFileName(Module: Integer; Filename: PChar;
Size: Integer): Integer; stdcall;
external kernel name 'GetModuleFileNameA';
function GetModuleHandle(ModuleName: PChar): Integer; stdcall;
external kernel name 'GetModuleHandleA';
function GetProcAddress(Module: Integer; ProcName: PChar): Pointer; stdcall;
external kernel name 'GetProcAddress';
procedure GetStartupInfo(var lpStartupInfo: TStartupInfo); stdcall;
external kernel name 'GetStartupInfoA';
function GetThreadLocale: Longint; stdcall;
external kernel name 'GetThreadLocale';
function LoadLibraryEx(LibName: PChar; hFile: Longint; Flags: Longint): Longint; stdcall;
external kernel name 'LoadLibraryExA';
function LoadString(Instance: Longint; IDent: Integer; Buffer: PChar;
Size: Integer): Integer; stdcall;
external user name 'LoadStringA';
{function lstrcat(lpString1, lpString2: PChar): PChar; stdcall;
external kernel name 'lstrcatA';}
function lstrcpy(lpString1, lpString2: PChar): PChar; stdcall;
external kernel name 'lstrcpyA';
function lstrcpyn(lpString1, lpString2: PChar;
iMaxLength: Integer): PChar; stdcall;
external kernel name 'lstrcpynA';
function _strlen(lpString: PChar): Integer; stdcall;
external kernel name 'lstrlenA';
function MultiByteToWideChar(CodePage, Flags: Integer; MBStr: PChar;
MBCount: Integer; WCStr: PWideChar; WCCount: Integer): Integer; stdcall;
external kernel name 'MultiByteToWideChar';
function RegCloseKey(hKey: Integer): Longint; stdcall;
external advapi32 name 'RegCloseKey';
function RegOpenKeyEx(hKey: LongWord; lpSubKey: PChar; ulOptions,
samDesired: LongWord; var phkResult: LongWord): Longint; stdcall;
external advapi32 name 'RegOpenKeyExA';
function RegQueryValueEx(hKey: LongWord; lpValueName: PChar;
lpReserved: Pointer; lpType: Pointer; lpData: PChar; lpcbData: Pointer): Integer; stdcall;
external advapi32 name 'RegQueryValueExA';
function RemoveDirectory(PathName: PChar): WordBool; stdcall;
external kernel name 'RemoveDirectoryA';
function SetCurrentDirectory(PathName: PChar): WordBool; stdcall;
external kernel name 'SetCurrentDirectoryA';
function WideCharToMultiByte(CodePage, Flags: Integer; WCStr: PWideChar;
WCCount: Integer; MBStr: PChar; MBCount: Integer; DefaultChar: PChar;
UsedDefaultChar: Pointer): Integer; stdcall;
external kernel name 'WideCharToMultiByte';
function VirtualQuery(lpAddress: Pointer;
var lpBuffer: TMemInfo; dwLength: Longint): Longint; stdcall;
external kernel name 'VirtualQuery';
//function SysAllocString(P: PWideChar): PWideChar; stdcall;
// external oleaut name 'SysAllocString';
function SysAllocStringLen(P: PWideChar; Len: Integer): PWideChar; stdcall;
external oleaut name 'SysAllocStringLen';
function SysReAllocStringLen(var S: WideString; P: PWideChar;
Len: Integer): LongBool; stdcall;
external oleaut name 'SysReAllocStringLen';
procedure SysFreeString(const S: WideString); stdcall;
external oleaut name 'SysFreeString';
function SysStringLen(const S: WideString): Integer; stdcall;
external oleaut name 'SysStringLen';
function InterlockedIncrement(var Addend: Integer): Integer; stdcall;
external kernel name 'InterlockedIncrement';
function InterlockedDecrement(var Addend: Integer): Integer; stdcall;
external kernel name 'InterlockedDecrement';
function GetCurrentThreadId: LongWord; stdcall;
external kernel name 'GetCurrentThreadId';
function GetCmdShow: Integer;
var
SI: TStartupInfo;
begin
Result := 10; { SW_SHOWDEFAULT }
GetStartupInfo(SI);
if SI.dwFlags and 1 <> 0 then { STARTF_USESHOWWINDOW }
Result := SI.wShowWindow;
end;
{$ENDIF} // MSWindows
function WCharFromChar(WCharDest: PWideChar; DestChars: Integer; const CharSource: PChar; SrcBytes: Integer): Integer; forward;
function CharFromWChar(CharDest: PChar; DestBytes: Integer; const WCharSource: PWideChar; SrcChars: Integer): Integer; forward;
{ ----------------------------------------------------- }
{ Memory manager }
{ ----------------------------------------------------- }
{$IFDEF MSWINDOWS}
{$I GETMEM.INC }
{$ENDIF}
{$IFDEF LINUX}
function SysGetMem(Size: Integer): Pointer;
begin
Result := __malloc(size);
end;
function SysFreeMem(P: Pointer): Integer;
begin
__free(P);
Result := 0;
end;
function SysReallocMem(P: Pointer; Size: Integer): Pointer;
begin
Result := __realloc(P, Size);
end;
{$ENDIF}
var
MemoryManager: TMemoryManager = (
GetMem: SysGetMem;
FreeMem: SysFreeMem;
ReallocMem: SysReallocMem);
{$IFDEF PC_MAPPED_EXCEPTIONS}
var
// Unwinder: TUnwinder = (
// RaiseException: UnwindRaiseException;
// RegisterIPLookup: UnwindRegisterIPLookup;
// UnregisterIPLookup: UnwindUnregisterIPLookup;
// DelphiLookup: UnwindDelphiLookup);
Unwinder: TUnwinder;
{$IFDEF STATIC_UNWIND}
{$IFDEF PIC}
{$L 'objs/arith.pic.o'}
{$L 'objs/diag.pic.o'}
{$L 'objs/delphiuw.pic.o'}
{$L 'objs/unwind.pic.o'}
{$ELSE}
{$L 'objs/arith.o'}
{$L 'objs/diag.o'}
{$L 'objs/delphiuw.o'}
{$L 'objs/unwind.o'}
{$ENDIF}
procedure Arith_RdUnsigned; external;
procedure Arith_RdSigned; external;
procedure __assert_fail; cdecl; external libc name '__assert_fail';
procedure malloc; cdecl; external libc name 'malloc';
procedure memset; cdecl; external libc name 'memset';
procedure strchr; cdecl; external libc name 'strchr';
procedure strncpy; cdecl; external libc name 'strncpy';
procedure strcpy; cdecl; external libc name 'strcpy';
procedure strcmp; cdecl; external libc name 'strcmp';
procedure printf; cdecl; external libc name 'printf';
procedure free; cdecl; external libc name 'free';
procedure getenv; cdecl; external libc name 'getenv';
procedure strtok; cdecl; external libc name 'strtok';
procedure strdup; cdecl; external libc name 'strdup';
procedure __strdup; cdecl; external libc name '__strdup';
procedure fopen; cdecl; external libc name 'fopen';
procedure fdopen; cdecl; external libc name 'fdopen';
procedure time; cdecl; external libc name 'time';
procedure ctime; cdecl; external libc name 'ctime';
procedure fclose; cdecl; external libc name 'fclose';
procedure fprintf; cdecl; external libc name 'fprintf';
procedure vfprintf; cdecl; external libc name 'vfprintf';
procedure fflush; cdecl; external libc name 'fflush';
procedure debug_init; external;
procedure debug_print; external;
procedure debug_class_enabled; external;
procedure debug_continue; external;
{$ENDIF}
{$ENDIF}
function _GetMem(Size: Integer): Pointer;
{$IF Defined(DEBUG) and Defined(LINUX)}
var
Signature: PLongInt;
{$IFEND}
begin
if Size > 0 then
begin
{$IF Defined(DEBUG) and Defined(LINUX)}
Signature := PLongInt(MemoryManager.GetMem(Size + 4));
if Signature = nil then
Error(reOutOfMemory);
Signature^ := 0;
Result := Pointer(LongInt(Signature) + 4);
{$ELSE}
Result := MemoryManager.GetMem(Size);
if Result = nil then
Error(reOutOfMemory);
{$IFEND}
end
else
Result := nil;
end;
const
FreeMemorySignature = Longint($FBEEFBEE);
function _FreeMem(P: Pointer): Integer;
{$IF Defined(DEBUG) and Defined(LINUX)}
var
Signature: PLongInt;
{$IFEND}
begin
if P <> nil then
begin
{$IF Defined(DEBUG) and Defined(LINUX)}
Signature := PLongInt(LongInt(P) - 4);
if Signature^ <> 0 then
Error(reInvalidPtr);
Signature^ := FreeMemorySignature;
Result := MemoryManager.Freemem(Pointer(Signature));
{$ELSE}
Result := MemoryManager.FreeMem(P);
{$IFEND}
if Result <> 0 then
Error(reInvalidPtr);
end
else
Result := 0;
end;
{$IFDEF LINUX}
function _ReallocMem(var P: Pointer; NewSize: Integer): Pointer;
{$IFDEF DEBUG}
var
Temp: Pointer;
{$ENDIF}
begin
if P <> nil then
begin
{$IFDEF DEBUG}
Temp := Pointer(LongInt(P) - 4);
if NewSize > 0 then
begin
Temp := MemoryManager.ReallocMem(Temp, NewSize + 4);
Result := Pointer(LongInt(Temp) + 4);
end
else
begin
MemoryManager.FreeMem(Temp);
Result := nil;
end;
{$ELSE}
if NewSize > 0 then
begin
Result := MemoryManager.ReallocMem(P, NewSize);
end
else
begin
MemoryManager.FreeMem(P);
Result := nil;
end;
{$ENDIF}
P := Result;
end else
begin
Result := _GetMem(NewSize);
P := Result;
end;
end;
{$ELSEIF Defined(MSWINDOWS)}
function _ReallocMem(var P: Pointer; NewSize: Integer): Pointer;
asm
MOV ECX,[EAX]
TEST ECX,ECX
JE @@alloc
TEST EDX,EDX
JE @@free
@@resize:
PUSH EAX
MOV EAX,ECX
CALL MemoryManager.ReallocMem
POP ECX
OR EAX,EAX
JE @@allocError
MOV [ECX],EAX
RET
@@freeError:
MOV AL,reInvalidPtr
JMP Error
@@free:
MOV [EAX],EDX
MOV EAX,ECX
CALL MemoryManager.FreeMem
OR EAX,EAX
JNE @@freeError
RET
@@allocError:
MOV AL,reOutOfMemory
JMP Error
@@alloc:
TEST EDX,EDX
JE @@exit
PUSH EAX
MOV EAX,EDX
CALL MemoryManager.GetMem
POP ECX
OR EAX,EAX
JE @@allocError
MOV [ECX],EAX
@@exit:
end;
{$IFEND}
procedure GetMemoryManager(var MemMgr: TMemoryManager);
begin
MemMgr := MemoryManager;
end;
procedure SetMemoryManager(const MemMgr: TMemoryManager);
begin
MemoryManager := MemMgr;
end;
function IsMemoryManagerSet: Boolean;
begin
with MemoryManager do
Result := (@GetMem <> @SysGetMem) or (@FreeMem <> @SysFreeMem) or
(@ReallocMem <> @SysReallocMem);
end;
{$IFDEF PC_MAPPED_EXCEPTIONS}
procedure GetUnwinder(var Dest: TUnwinder);
begin
Dest := Unwinder;
end;
procedure SetUnwinder(const NewUnwinder: TUnwinder);
begin
Unwinder := NewUnwinder;
end;
function IsUnwinderSet: Boolean;
begin
with Unwinder do
Result := (@RaiseException <> @_BorUnwind_RaiseException) or
(@RegisterIPLookup <> @_BorUnwind_RegisterIPLookup) or
(@UnregisterIPLookup <> @_BorUnwind_UnregisterIPLookup) or
(@DelphiLookup <> @_BorUnwind_DelphiLookup);
end;
procedure InitUnwinder;
var
Addr: Pointer;
begin
{
We look to see if we can find a dynamic version of the unwinder. This will
be the case if the application used Unwind.pas. If it is present, then we
fire it up. Otherwise, we use our static copy.
}
Addr := dlsym(0, '_BorUnwind_RegisterIPLookup');
if Addr <> nil then
begin
Unwinder.RegisterIPLookup := Addr;
Addr := dlsym(0, '_BorUnwind_UnregisterIPLookup');
Unwinder.UnregisterIPLookup := Addr;
Addr := dlsym(0, '_BorUnwind_RaiseException');
Unwinder.RaiseException := Addr;
Addr := dlsym(0, '_BorUnwind_DelphiLookup');
Unwinder.DelphiLookup := Addr;
Addr := dlsym(0, '_BorUnwind_ClosestHandler');
Unwinder.ClosestHandler := Addr;
end
else
begin
dlerror; // clear error state; dlsym doesn't
Unwinder.RegisterIPLookup := _BorUnwind_RegisterIPLookup;
Unwinder.DelphiLookup := _BorUnwind_DelphiLookup;
Unwinder.UnregisterIPLookup := _BorUnwind_UnregisterIPLookup;
Unwinder.RaiseException := _BorUnwind_RaiseException;
Unwinder.ClosestHandler := _BorUnwind_ClosestDelphiHandler;
end;
end;
function SysClosestDelphiHandler(Context: Pointer): LongWord;
begin
if not Assigned(Unwinder.ClosestHandler) then
InitUnwinder;
Result := Unwinder.ClosestHandler(Context);
end;
function SysRegisterIPLookup(StartAddr, EndAddr: LongInt; Context: Pointer; GOT: LongInt): LongBool;
begin
// xxx
if not Assigned(Unwinder.RegisterIPLookup) then
begin
InitUnwinder;
// Unwinder.RegisterIPLookup := UnwindRegisterIPLookup;
// Unwinder.DelphiLookup := UnwindDelphiLookup;
end;
Result := Unwinder.RegisterIPLookup(@Unwinder.DelphiLookup, StartAddr, EndAddr, Context, GOT);
end;
procedure SysUnregisterIPLookup(StartAddr: LongInt);
begin
// if not Assigned(Unwinder.UnregisterIPLookup) then
// Unwinder.UnregisterIPLookup := UnwindUnregisterIPLookup;
Unwinder.UnregisterIPLookup(StartAddr);
end;
function SysRaiseException(Exc: Pointer): LongBool; export;
begin
// if not Assigned(Unwinder.RaiseException) then
// Unwinder.RaiseException := UnwindRaiseException;
Result := Unwinder.RaiseException(Exc);
end;
const
MAX_NESTED_EXCEPTIONS = 16;
{$ENDIF}
threadvar
{$IFDEF PC_MAPPED_EXCEPTIONS}
ExceptionObjects: array[0..MAX_NESTED_EXCEPTIONS-1] of TRaisedException;
ExceptionObjectCount: Integer;
OSExceptionsBlocked: Integer;
{$ELSE}
RaiseListPtr: pointer;
{$ENDIF}
InOutRes: Integer;
{$IFDEF PUREPASCAL}
var
notimpl: array [0..15] of Char = 'not implemented'#10;
procedure NotImplemented;
begin
__write (2, @notimpl, 16);
Halt;
end;
{$ENDIF}
{$IFDEF PC_MAPPED_EXCEPTIONS}
procedure BlockOSExceptions;
asm
PUSH EAX
PUSH EDX
CALL SysInit.@GetTLS
MOV [EAX].OSExceptionsBlocked, 1
POP EDX
POP EAX
end;
procedure UnblockOSExceptions;
asm
PUSH EAX
CALL SysInit.@GetTLS
MOV [EAX].OSExceptionsBlocked, 0
POP EAX
end;
function AreOSExceptionsBlocked: Boolean;
asm
CALL SysInit.@GetTLS
MOV EAX, [EAX].OSExceptionsBlocked
end;
const
TRAISEDEXCEPTION_SIZE = SizeOf(TRaisedException);
function CurrentException: PRaisedException;
asm
CALL SysInit.@GetTLS
LEA EDX, [EAX].ExceptionObjects
MOV EAX, [EAX].ExceptionObjectCount
OR EAX, EAX
JE @@Done
DEC EAX
IMUL EAX, TRAISEDEXCEPTION_SIZE
ADD EAX, EDX
@@Done:
end;
function AllocateException(Exception: Pointer; ExceptionAddr: Pointer): PRaisedException;
asm
PUSH EAX
PUSH EDX
CALL SysInit.@GetTLS
CMP [EAX].ExceptionObjectCount, MAX_NESTED_EXCEPTIONS-1
JE @@TooManyNestedExceptions
INC [EAX].ExceptionObjectCount
CALL CurrentException
POP EDX
POP ECX
MOV [EAX].TRaisedException.ExceptObject, ECX
MOV [EAX].TRaisedException.ExceptionAddr, EDX
MOV [EAX].TRaisedException.RefCount, 0
MOV [EAX].TRaisedException.HandlerEBP, $FFFFFFFF
MOV [EAX].TRaisedException.Flags, 0
RET
@@TooManyNestedExceptions:
MOV EAX, 231
JMP _RunError
end;
{
In the interests of code size here, this function is slightly overloaded.
It is responsible for freeing up the current exception record on the
exception stack, and it conditionally returns the thrown object to the
caller. If the object has been acquired through AcquireExceptionObject,
we don't return the thrown object.
}
function FreeException: Pointer;
asm
CALL CurrentException
OR EAX, EAX
JE @@Error
{ EAX -> the TRaisedException }
XOR ECX, ECX
{ If the exception object has been referenced, we don't return it. }
CMP [EAX].TRaisedException.RefCount, 0
JA @@GotObject
MOV ECX, [EAX].TRaisedException.ExceptObject
@@GotObject:
PUSH ECX
CALL SysInit.@GetTLS
POP ECX
DEC [EAX].ExceptionObjectCount
MOV EAX, ECX
RET
@@Error:
{ Some kind of internal error }
JMP _Run0Error
end;
function AcquireExceptionObject: Pointer;
asm
CALL CurrentException
OR EAX, EAX
JE @@Error
INC [EAX].TRaisedException.RefCount
MOV EAX, [EAX].TRaisedException.ExceptObject
RET
@@Error:
{ This happens if there is no exception pending }
JMP _Run0Error
end;
procedure ReleaseExceptionObject;
asm
CALL CurrentException
OR EAX, EAX
JE @@Error
CMP [EAX].TRaisedException.RefCount, 0
JE @@Error
DEC [EAX].TRaisedException.RefCount
RET
@@Error:
{
This happens if there is no exception pending, or
if the reference count on a pending exception is
zero.
}
JMP _Run0Error
end;
function ExceptObject: TObject;
var
Exc: PRaisedException;
begin
Exc := CurrentException;
if Exc <> nil then
Result := TObject(Exc^.ExceptObject)
else
Result := nil;
end;
{ Return current exception address }
function ExceptAddr: Pointer;
var
Exc: PRaisedException;
begin
Exc := CurrentException;
if Exc <> nil then
Result := Exc^.ExceptionAddr
else
Result := nil;
end;
{$ELSE} {not PC_MAPPED_EXCEPTIONS}
function ExceptObject: TObject;
begin
if RaiseListPtr <> nil then
Result := PRaiseFrame(RaiseListPtr)^.ExceptObject
else
Result := nil;
end;
{ Return current exception address }
function ExceptAddr: Pointer;
begin
if RaiseListPtr <> nil then
Result := PRaiseFrame(RaiseListPtr)^.ExceptAddr
else
Result := nil;
end;
function AcquireExceptionObject: Pointer;
begin
if RaiseListPtr <> nil then
begin
Result := PRaiseFrame(RaiseListPtr)^.ExceptObject;
PRaiseFrame(RaiseListPtr)^.ExceptObject := nil;
end
else
Result := nil;
end;
procedure ReleaseExceptionObject;
begin
end;
function RaiseList: Pointer;
begin
Result := RaiseListPtr;
end;
function SetRaiseList(NewPtr: Pointer): Pointer;
asm
PUSH EAX
CALL SysInit.@GetTLS
MOV EDX, [EAX].RaiseListPtr
POP [EAX].RaiseListPtr
MOV EAX, EDX
end;
{$ENDIF}
{ ----------------------------------------------------- }
{ local functions & procedures of the system unit }
{ ----------------------------------------------------- }
procedure RunErrorAt(ErrCode: Integer; ErrorAtAddr: Pointer);
begin
ErrorAddr := ErrorAtAddr;
_Halt(ErrCode);
end;
procedure ErrorAt(ErrorCode: Byte; ErrorAddr: Pointer);
const
reMap: array [TRunTimeError] of Byte = (
0,
203, { reOutOfMemory }
204, { reInvalidPtr }
200, { reDivByZero }
201, { reRangeError }
{ 210 abstract error }
215, { reIntOverflow }
207, { reInvalidOp }
200, { reZeroDivide }
205, { reOverflow }
206, { reUnderflow }
219, { reInvalidCast }
216, { Access violation }
202, { Stack overflow }
217, { Control-C }
218, { Privileged instruction }
220, { Invalid variant type cast }
221, { Invalid variant operation }
222, { No variant method call dispatcher }
223, { Cannot create variant array }
224, { Variant does not contain an array }
225, { Variant array bounds error }
{ 226 thread init failure }
227, { reAssertionFailed }
0, { reExternalException not used here; in SysUtils }
228, { reIntfCastError }
229 { reSafeCallError }
{ 230 Reserved by the compiler for unhandled exceptions }
{ 231 Too many nested exceptions }
{ 232 Fatal signal raised on a non-Delphi thread });
begin
errorCode := errorCode and 127;
if Assigned(ErrorProc) then
ErrorProc(errorCode, ErrorAddr);
if errorCode = 0 then
errorCode := InOutRes
else if errorCode <= Byte(High(TRuntimeError)) then
errorCode := reMap[TRunTimeError(errorCode)];
RunErrorAt(errorCode, ErrorAddr);
end;
procedure Error(errorCode: TRuntimeError);
asm
AND EAX,127
MOV EDX,[ESP]
JMP ErrorAt
end;
procedure __IOTest;
asm
PUSH EAX
PUSH EDX
PUSH ECX
CALL SysInit.@GetTLS
CMP [EAX].InOutRes,0
POP ECX
POP EDX
POP EAX
JNE @error
RET
@error:
XOR EAX,EAX
JMP Error
end;
procedure SetInOutRes(NewValue: Integer);
begin
InOutRes := NewValue;
end;
procedure InOutError;
begin
SetInOutRes(GetLastError);
end;
procedure ChDir(const S: string);
begin
ChDir(PChar(S));
end;
procedure ChDir(P: PChar);
begin
{$IFDEF MSWINDOWS}
if not SetCurrentDirectory(P) then
{$ENDIF}
{$IFDEF LINUX}
if __chdir(P) <> 0 then
{$ENDIF}
InOutError;
end;
procedure _Copy{ s : ShortString; index, count : Integer ) : ShortString};
asm
{ ->EAX Source string }
{ EDX index }
{ ECX count }
{ [ESP+4] Pointer to result string }
PUSH ESI
PUSH EDI
MOV ESI,EAX
MOV EDI,[ESP+8+4]
XOR EAX,EAX
OR AL,[ESI]
JZ @@srcEmpty
{ limit index to satisfy 1 <= index <= Length(src) }
TEST EDX,EDX
JLE @@smallInx
CMP EDX,EAX
JG @@bigInx
@@cont1:
{ limit count to satisfy 0 <= count <= Length(src) - index + 1 }
SUB EAX,EDX { calculate Length(src) - index + 1 }
INC EAX
TEST ECX,ECX
JL @@smallCount
CMP ECX,EAX
JG @@bigCount
@@cont2:
ADD ESI,EDX
MOV [EDI],CL
INC EDI
REP MOVSB
JMP @@exit
@@smallInx:
MOV EDX,1
JMP @@cont1
@@bigInx:
{ MOV EDX,EAX
JMP @@cont1 }
@@smallCount:
XOR ECX,ECX
JMP @@cont2
@@bigCount:
MOV ECX,EAX
JMP @@cont2
@@srcEmpty:
MOV [EDI],AL
@@exit:
POP EDI
POP ESI
RET 4
end;
procedure _Delete{ var s : openstring; index, count : Integer };
asm
{ ->EAX Pointer to s }
{ EDX index }
{ ECX count }
PUSH ESI
PUSH EDI
MOV EDI,EAX
XOR EAX,EAX
MOV AL,[EDI]
{ if index not in [1 .. Length(s)] do nothing }
TEST EDX,EDX
JLE @@exit
CMP EDX,EAX
JG @@exit
{ limit count to [0 .. Length(s) - index + 1] }
TEST ECX,ECX
JLE @@exit
SUB EAX,EDX { calculate Length(s) - index + 1 }
INC EAX
CMP ECX,EAX
JLE @@1
MOV ECX,EAX
@@1:
SUB [EDI],CL { reduce Length(s) by count }
ADD EDI,EDX { point EDI to first char to be deleted }
LEA ESI,[EDI+ECX] { point ESI to first char to be preserved }
SUB EAX,ECX { #chars = Length(s) - index + 1 - count }
MOV ECX,EAX
REP MOVSB
@@exit:
POP EDI
POP ESI
end;
procedure _LGetDir(D: Byte; var S: string);
{$IFDEF MSWINDOWS}
var
Drive: array[0..3] of Char;
DirBuf, SaveBuf: array[0..MAX_PATH] of Char;
begin
if D <> 0 then
begin
Drive[0] := Chr(D + Ord('A') - 1);
Drive[1] := ':';
Drive[2] := #0;
GetCurrentDirectory(SizeOf(SaveBuf), SaveBuf);
SetCurrentDirectory(Drive);
end;
GetCurrentDirectory(SizeOf(DirBuf), DirBuf);
if D <> 0 then SetCurrentDirectory(SaveBuf);
S := DirBuf;
{$ENDIF}
{$IFDEF LINUX}
var
DirBuf: array[0..MAX_PATH] of Char;
begin
__getcwd(DirBuf, sizeof(DirBuf));
S := string(DirBuf);
{$ENDIF}
end;
procedure _SGetDir(D: Byte; var S: ShortString);
var
L: string;
begin
_LGetDir(D, L);
S := L;
end;
procedure _Insert{ source : ShortString; var s : openstring; index : Integer };
asm
{ ->EAX Pointer to source string }
{ EDX Pointer to destination string }
{ ECX Length of destination string }
{ [ESP+4] Index }
PUSH EBX
PUSH ESI
PUSH EDI
PUSH ECX
MOV ECX,[ESP+16+4]
SUB ESP,512 { VAR buf: ARRAY [0..511] of Char }
MOV EBX,EDX { save pointer to s for later }
MOV ESI,EDX
XOR EDX,EDX
MOV DL,[ESI]
INC ESI
{ limit index to [1 .. Length(s)+1] }
INC EDX
TEST ECX,ECX
JLE @@smallInx
CMP ECX,EDX
JG @@bigInx
@@cont1:
DEC EDX { EDX = Length(s) }
{ EAX = Pointer to src }
{ ESI = EBX = Pointer to s }
{ ECX = Index }
{ copy index-1 chars from s to buf }
MOV EDI,ESP
DEC ECX
SUB EDX,ECX { EDX = remaining length of s }
REP MOVSB
{ copy Length(src) chars from src to buf }
XCHG EAX,ESI { save pointer into s, point ESI to src }
MOV CL,[ESI] { ECX = Length(src) (ECX was zero after rep) }
INC ESI
REP MOVSB
{ copy remaining chars of s to buf }
MOV ESI,EAX { restore pointer into s }
MOV ECX,EDX { copy remaining bytes of s }
REP MOVSB
{ calculate total chars in buf }
SUB EDI,ESP { length = bufPtr - buf }
MOV ECX,[ESP+512] { ECX = Min(length, destLength) }
{ MOV ECX,[EBP-16] }{ ECX = Min(length, destLength) }
CMP ECX,EDI
JB @@1
MOV ECX,EDI
@@1:
MOV EDI,EBX { Point EDI to s }
MOV ESI,ESP { Point ESI to buf }
MOV [EDI],CL { Store length in s }
INC EDI
REP MOVSB { Copy length chars to s }
JMP @@exit
@@smallInx:
MOV ECX,1
JMP @@cont1
@@bigInx:
MOV ECX,EDX
JMP @@cont1
@@exit:
ADD ESP,512+4
POP EDI
POP ESI
POP EBX
RET 4
end;
function IOResult: Integer;
begin
Result := InOutRes;
InOutRes := 0;
end;
procedure MkDir(const S: string);
begin
MkDir(PChar(s));
end;
procedure MkDir(P: PChar);
begin
{$IFDEF MSWINDOWS}
if not CreateDirectory(P, 0) then
{$ENDIF}
{$IFDEF LINUX}
if __mkdir(P, -1) <> 0 then
{$ENDIF}
InOutError;
end;
procedure Move( const Source; var Dest; count : Integer );
{$IFDEF PUREPASCAL}
var
S, D: PChar;
I: Integer;
begin
S := PChar(@Source);
D := PChar(@Dest);
if S = D then Exit;
if Cardinal(D) > Cardinal(S) then
for I := count-1 downto 0 do
D[I] := S[I]
else
for I := 0 to count-1 do
D[I] := S[I];
end;
{$ELSE}
asm
{ ->EAX Pointer to source }
{ EDX Pointer to destination }
{ ECX Count }
PUSH ESI
PUSH EDI
MOV ESI,EAX
MOV EDI,EDX
MOV EAX,ECX
CMP EDI,ESI
JA @@down
JE @@exit
SAR ECX,2 { copy count DIV 4 dwords }
JS @@exit
REP MOVSD
MOV ECX,EAX
AND ECX,03H
REP MOVSB { copy count MOD 4 bytes }
JMP @@exit
@@down:
LEA ESI,[ESI+ECX-4] { point ESI to last dword of source }
LEA EDI,[EDI+ECX-4] { point EDI to last dword of dest }
SAR ECX,2 { copy count DIV 4 dwords }
JS @@exit
STD
REP MOVSD
MOV ECX,EAX
AND ECX,03H { copy count MOD 4 bytes }
ADD ESI,4-1 { point to last byte of rest }
ADD EDI,4-1
REP MOVSB
CLD
@@exit:
POP EDI
POP ESI
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
function GetParamStr(P: PChar; var Param: string): PChar;
var
i, Len: Integer;
Start, S, Q: PChar;
begin
while True do
begin
while (P[0] <> #0) and (P[0] <= ' ') do
P := CharNext(P);
if (P[0] = '"') and (P[1] = '"') then Inc(P, 2) else Break;
end;
Len := 0;
Start := P;
while P[0] > ' ' do
begin
if P[0] = '"' then
begin
P := CharNext(P);
while (P[0] <> #0) and (P[0] <> '"') do
begin
Q := CharNext(P);
Inc(Len, Q - P);
P := Q;
end;
if P[0] <> #0 then
P := CharNext(P);
end
else
begin
Q := CharNext(P);
Inc(Len, Q - P);
P := Q;
end;
end;
SetLength(Param, Len);
P := Start;
S := Pointer(Param);
i := 0;
while P[0] > ' ' do
begin
if P[0] = '"' then
begin
P := CharNext(P);
while (P[0] <> #0) and (P[0] <> '"') do
begin
Q := CharNext(P);
while P < Q do
begin
S[i] := P^;
Inc(P);
Inc(i);
end;
end;
if P[0] <> #0 then P := CharNext(P);
end
else
begin
Q := CharNext(P);
while P < Q do
begin
S[i] := P^;
Inc(P);
Inc(i);
end;
end;
end;
Result := P;
end;
{$ENDIF}
function ParamCount: Integer;
{$IFDEF MSWINDOWS}
var
P: PChar;
S: string;
begin
Result := 0;
P := GetParamStr(GetCommandLine, S);
while True do
begin
P := GetParamStr(P, S);
if S = '' then Break;
Inc(Result);
end;
{$ENDIF}
{$IFDEF LINUX}
begin
if ArgCount > 1 then
Result := ArgCount - 1
else Result := 0;
{$ENDIF}
end;
type
PCharArray = array[0..0] of PChar;
function ParamStr(Index: Integer): string;
{$IFDEF MSWINDOWS}
var
P: PChar;
Buffer: array[0..260] of Char;
begin
Result := '';
if Index = 0 then
SetString(Result, Buffer, GetModuleFileName(0, Buffer, SizeOf(Buffer)))
else
begin
P := GetCommandLine;
while True do
begin
P := GetParamStr(P, Result);
if (Index = 0) or (Result = '') then Break;
Dec(Index);
end;
end;
{$ENDIF}
{$IFDEF LINUX}
begin
if Index < ArgCount then
Result := PCharArray(ArgValues^)[Index]
else
Result := '';
{$ENDIF}
end;
procedure _Pos{ substr : ShortString; s : ShortString ) : Integer};
asm
{ ->EAX Pointer to substr }
{ EDX Pointer to string }
{ <-EAX Position of substr in s or 0 }
PUSH EBX
PUSH ESI
PUSH EDI
MOV ESI,EAX { Point ESI to substr }
MOV EDI,EDX { Point EDI to s }
XOR ECX,ECX { ECX = Length(s) }
MOV CL,[EDI]
INC EDI { Point EDI to first char of s }
PUSH EDI { remember s position to calculate index }
XOR EDX,EDX { EDX = Length(substr) }
MOV DL,[ESI]
INC ESI { Point ESI to first char of substr }
DEC EDX { EDX = Length(substr) - 1 }
JS @@fail { < 0 ? return 0 }
MOV AL,[ESI] { AL = first char of substr }
INC ESI { Point ESI to 2'nd char of substr }
SUB ECX,EDX { #positions in s to look at }
{ = Length(s) - Length(substr) + 1 }
JLE @@fail
@@loop:
REPNE SCASB
JNE @@fail
MOV EBX,ECX { save outer loop counter }
PUSH ESI { save outer loop substr pointer }
PUSH EDI { save outer loop s pointer }
MOV ECX,EDX
REPE CMPSB
POP EDI { restore outer loop s pointer }
POP ESI { restore outer loop substr pointer }
JE @@found
MOV ECX,EBX { restore outer loop counter }
JMP @@loop
@@fail:
POP EDX { get rid of saved s pointer }
XOR EAX,EAX
JMP @@exit
@@found:
POP EDX { restore pointer to first char of s }
MOV EAX,EDI { EDI points of char after match }
SUB EAX,EDX { the difference is the correct index }
@@exit:
POP EDI
POP ESI
POP EBX
end;
// Don't use var param here - var ShortString is an open string param, which passes
// the ptr in EAX and the string's declared buffer length in EDX. Compiler codegen
// expects only two params for this call - ptr and newlength
procedure _SetLength(s: PShortString; newLength: Byte);
begin
Byte(s^[0]) := newLength; // should also fill new space
end;
procedure _SetString(s: PShortString; buffer: PChar; len: Byte);
begin
Byte(s^[0]) := len;
if buffer <> nil then
Move(buffer^, s^[1], len);
end;
procedure Randomize;
{$IFDEF LINUX}
begin
RandSeed := _time(nil);
{$ENDIF}
{$IFDEF MSWINDOWS}
var
systemTime :
record
wYear : Word;
wMonth : Word;
wDayOfWeek : Word;
wDay : Word;
wHour : Word;
wMinute : Word;
wSecond : Word;
wMilliSeconds: Word;
reserved : array [0..7] of char;
end;
asm
LEA EAX,systemTime
PUSH EAX
CALL GetSystemTime
MOVZX EAX,systemTime.wHour
IMUL EAX,60
ADD AX,systemTime.wMinute { sum = hours * 60 + minutes }
IMUL EAX,60
XOR EDX,EDX
MOV DX,systemTime.wSecond
ADD EAX,EDX { sum = sum * 60 + seconds }
IMUL EAX,1000
MOV DX,systemTime.wMilliSeconds
ADD EAX,EDX { sum = sum * 1000 + milliseconds }
MOV RandSeed,EAX
{$ENDIF}
end;
procedure RmDir(const S: string);
begin
RmDir(PChar(s));
end;
procedure RmDir(P: PChar);
begin
{$IFDEF MSWINDOWS}
if not RemoveDirectory(P) then
{$ENDIF}
{$IFDEF LINUX}
if __rmdir(P) <> 0 then
{$ENDIF}
InOutError;
end;
function UpCase( ch : Char ) : Char;
{$IFDEF PUREPASCAL}
begin
Result := ch;
case Result of
'a'..'z': Dec(Result, Ord('a') - Ord('A'));
end;
end;
{$ELSE}
asm
{ -> AL Character }
{ <- AL Result }
CMP AL,'a'
JB @@exit
CMP AL,'z'
JA @@exit
SUB AL,'a' - 'A'
@@exit:
end;
{$ENDIF}
procedure Set8087CW(NewCW: Word);
begin
Default8087CW := NewCW;
asm
FNCLEX // don't raise pending exceptions enabled by the new flags
{$IFDEF PIC}
MOV EAX,[EBX].OFFSET Default8087CW
FLDCW [EAX]
{$ELSE}
FLDCW Default8087CW
{$ENDIF}
end;
end;
function Get8087CW: Word;
asm
PUSH 0
FNSTCW [ESP].Word
POP EAX
end;
{ ----------------------------------------------------- }
{ functions & procedures that need compiler magic }
{ ----------------------------------------------------- }
procedure _COS;
asm
FCOS
FNSTSW AX
SAHF
JP @@outOfRange
RET
@@outOfRange:
FSTP st(0) { for now, return 0. result would }
FLDZ { have little significance anyway }
end;
procedure _EXP;
asm
{ e**x = 2**(x*log2(e)) }
FLDL2E { y := x*log2e; }
FMUL
FLD ST(0) { i := round(y); }
FRNDINT
FSUB ST(1), ST { f := y - i; }
FXCH ST(1) { z := 2**f }
F2XM1
FLD1
FADD
FSCALE { result := z * 2**i }
FSTP ST(1)
end;
procedure _INT;
asm
SUB ESP,4
FNSTCW [ESP].Word // save
FNSTCW [ESP+2].Word // scratch
FWAIT
OR [ESP+2].Word, $0F00 // trunc toward zero, full precision
FLDCW [ESP+2].Word
FRNDINT
FWAIT
FLDCW [ESP].Word
ADD ESP,4
end;
procedure _SIN;
asm
FSIN
FNSTSW AX
SAHF
JP @@outOfRange
RET
@@outOfRange:
FSTP st(0) { for now, return 0. result would }
FLDZ { have little significance anyway }
end;
procedure _FRAC;
asm
FLD ST(0)
SUB ESP,4
FNSTCW [ESP].Word // save
FNSTCW [ESP+2].Word // scratch
FWAIT
OR [ESP+2].Word, $0F00 // trunc toward zero, full precision
FLDCW [ESP+2].Word
FRNDINT
FWAIT
FLDCW [ESP].Word
ADD ESP,4
FSUB
end;
procedure _ROUND;
asm
{ -> FST(0) Extended argument }
{ <- EDX:EAX Result }
SUB ESP,8
FISTP qword ptr [ESP]
FWAIT
POP EAX
POP EDX
end;
procedure _TRUNC;
asm
{ -> FST(0) Extended argument }
{ <- EDX:EAX Result }
SUB ESP,12
FNSTCW [ESP].Word // save
FNSTCW [ESP+2].Word // scratch
FWAIT
OR [ESP+2].Word, $0F00 // trunc toward zero, full precision
FLDCW [ESP+2].Word
FISTP qword ptr [ESP+4]
FWAIT
FLDCW [ESP].Word
POP ECX
POP EAX
POP EDX
end;
procedure _AbstractError;
{$IFDEF PC_MAPPED_EXCEPTIONS}
asm
MOV EAX,210
JMP _RunError
end;
{$ELSE}
{$IFDEF PIC}
begin
if Assigned(AbstractErrorProc) then
AbstractErrorProc;
_RunError(210); // loses return address
end;
{$ELSE}
asm
CMP AbstractErrorProc, 0
JE @@NoAbstErrProc
CALL AbstractErrorProc
@@NoAbstErrProc:
MOV EAX,210
JMP _RunError
end;
{$ENDIF}
{$ENDIF}
function TextOpen(var t: TTextRec): Integer; forward;
function OpenText(var t: TTextRec; Mode: Word): Integer;
begin
if (t.Mode < fmClosed) or (t.Mode > fmInOut) then
Result := 102
else
begin
if t.Mode <> fmClosed then _Close(t);
t.Mode := Mode;
if (t.Name[0] = #0) and (t.OpenFunc = nil) then // stdio
t.OpenFunc := @TextOpen;
Result := TTextIOFunc(t.OpenFunc)(t);
end;
if Result <> 0 then SetInOutRes(Result);
end;
function _ResetText(var t: TTextRec): Integer;
begin
Result := OpenText(t, fmInput);
end;
function _RewritText(var t: TTextRec): Integer;
begin
Result := OpenText(t, fmOutput);
end;
function _Append(var t: TTextRec): Integer;
begin
Result := OpenText(t, fmInOut);
end;
function TextIn(var t: TTextRec): Integer;
begin
t.BufEnd := 0;
t.BufPos := 0;
{$IFDEF LINUX}
t.BufEnd := __read(t.Handle, t.BufPtr, t.BufSize);
if Integer(t.BufEnd) = -1 then
begin
t.BufEnd := 0;
Result := GetLastError;
end
else
Result := 0;
{$ENDIF}
{$IFDEF MSWINDOWS}
if ReadFile(t.Handle, t.BufPtr^, t.BufSize, t.BufEnd, nil) = 0 then
begin
Result := GetLastError;
if Result = 109 then
Result := 0; // NT quirk: got "broken pipe"? it's really eof
end
else
Result := 0;
{$ENDIF}
end;
function FileNOPProc(var t): Integer;
begin
Result := 0;
end;
function TextOut(var t: TTextRec): Integer;
{$IFDEF MSWINDOWS}
var
Dummy: Cardinal;
{$ENDIF}
begin
if t.BufPos = 0 then
Result := 0
else
begin
{$IFDEF LINUX}
if __write(t.Handle, t.BufPtr, t.BufPos) = Cardinal(-1) then
{$ENDIF}
{$IFDEF MSWINDOWS}
if WriteFile(t.Handle, t.BufPtr^, t.BufPos, Dummy, nil) = 0 then
{$ENDIF}
Result := GetLastError
else
Result := 0;
t.BufPos := 0;
end;
end;
function InternalClose(Handle: Integer): Boolean;
begin
{$IFDEF LINUX}
Result := __close(Handle) = 0;
{$ENDIF}
{$IFDEF MSWINDOWS}
Result := CloseHandle(Handle) = 1;
{$ENDIF}
end;
function TextClose(var t: TTextRec): Integer;
begin
t.Mode := fmClosed;
if not InternalClose(t.Handle) then
Result := GetLastError
else
Result := 0;
end;
function TextOpenCleanup(var t: TTextRec): Integer;
begin
InternalClose(t.Handle);
t.Mode := fmClosed;
Result := GetLastError;
end;
function TextOpen(var t: TTextRec): Integer;
{$IFDEF LINUX}
var
Flags: Integer;
Temp, I: Integer;
BytesRead: Integer;
begin
Result := 0;
t.BufPos := 0;
t.BufEnd := 0;
case t.Mode of
fmInput: // called by Reset
begin
Flags := O_RDONLY;
t.InOutFunc := @TextIn;
end;
fmOutput: // called by Rewrite
begin
Flags := O_CREAT or O_TRUNC or O_WRONLY;
t.InOutFunc := @TextOut;
end;
fmInOut: // called by Append
begin
Flags := O_APPEND or O_RDWR;
t.InOutFunc := @TextOut;
end;
else
Exit;
Flags := 0;
end;
t.FlushFunc := @FileNOPProc;
if t.Name[0] = #0 then // stdin or stdout
begin
t.BufPtr := @t.Buffer;
t.BufSize := sizeof(t.Buffer);
t.CloseFunc := @FileNOPProc;
if t.Mode = fmOutput then
begin
if @t = @ErrOutput then
t.Handle := STDERR_FILENO
else
t.Handle := STDOUT_FILENO;
t.FlushFunc := @TextOut;
end
else
t.Handle := STDIN_FILENO;
end
else
begin
t.CloseFunc := @TextClose;
Temp := __open(t.Name, Flags, FileAccessRights);
if Temp = -1 then
begin
Result := TextOpenCleanup(t);
Exit;
end;
t.Handle := Temp;
if t.Mode = fmInOut then // Append mode
begin
t.Mode := fmOutput;
if (t.flags and tfCRLF) <> 0 then // DOS mode, EOF significant
begin // scan for EOF char in last 128 byte sector.
Temp := _lseek(t.Handle, 0, SEEK_END);
if Temp = -1 then
begin
Result := TextOpenCleanup(t);
Exit;
end;
Dec(Temp, 128);
if Temp < 0 then Temp := 0;
if _lseek(t.Handle, Temp, SEEK_SET) = -1 then
begin
Result := TextOpenCleanup(t);
Exit;
end;
BytesRead := __read(t.Handle, t.BufPtr, 128);
if BytesRead = -1 then
begin
Result := TextOpenCleanup(t);
Exit;
end;
for I := 0 to BytesRead - 1 do
begin
if t.Buffer[I] = Char(cEOF) then
begin // truncate the file here
if _ftruncate(t.Handle, _lseek(t.Handle, I - BytesRead, SEEK_END)) = -1 then
begin
Result := TextOpenCleanup(t);
Exit;
end;
Break;
end;
end;
end;
end;
end;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
(*
var
OpenMode: Integer;
Flags, Std: ShortInt;
Temp: Integer;
I, BytesRead: Cardinal;
Mode: Byte;
begin
Result := 0;
if (t.Mode - fmInput) > (fmInOut - fmInput) then Exit;
Mode := t.Mode and 3;
t.BufPos := 0;
t.BufEnd := 0;
t.FlushFunc := @FileNOPProc;
if t.Name[0] = #0 then // stdin or stdout
begin
t.BufPtr := @t.Buffer;
t.BufSize := sizeof(t.Buffer);
t.CloseFunc := @FileNOPProc;
if Mode = (fmOutput and 3) then
begin
t.InOutFunc := @TextOut;
if @t = @ErrOutput then
Std := STD_ERROR_HANDLE
else
Std := STD_OUTPUT_HANDLE;
end
else
begin
t.InOutFunc := @TextIn;
Std := STD_INPUT_HANDLE;
end;
t.Handle := GetStdHandle(Std);
end
else
begin
t.CloseFunc := @TextClose;
Flags := OPEN_EXISTING;
if Mode = (fmInput and 3) then
begin // called by Reset
t.InOutFunc := @TextIn;
OpenMode := GENERIC_READ; // open for read
end
else
begin
t.InOutFunc := @TextOut;
if Mode = (fmInOut and 3) then // called by Append
OpenMode := GENERIC_READ OR GENERIC_WRITE // open for read/write
else
begin // called by Rewrite
OpenMode := GENERIC_WRITE; // open for write
Flags := CREATE_ALWAYS;
end;
end;
Temp := CreateFileA(t.Name, OpenMode, FILE_SHARE_READ, nil, Flags, FILE_ATTRIBUTE_NORMAL, 0);
if Temp = -1 then
begin
Result := TextOpenCleanup(t);
Exit;
end;
t.Handle := Temp;
if Mode = (fmInOut and 3) then
begin
Dec(t.Mode); // fmInOut -> fmOutput
{; ??? we really have to look for the first eof byte in the
; ??? last record and truncate the file there.
; Not very nice and clean...
;
; lastRecPos = Max( GetFileSize(...) - 128, 0);
}
Temp := GetFileSize(t.Handle, 0);
if Temp = -1 then
begin
Result := TextOpenCleanup(t);
Exit;
end;
Dec(Temp, 128);
if Temp < 0 then Temp := 0;
if (SetFilePointer(t.Handle, Temp, nil, FILE_BEGIN) = -1) or
(ReadFile(t.Handle, t.Buffer, 128, BytesRead, nil) = 0) then
begin
Result := TextOpenCleanup(t);
Exit;
end;
for I := 0 to BytesRead do
begin
if t.Buffer[I] = Char(cEOF) then
begin // truncate the file here
if (SetFilePointer(t.Handle, I - BytesRead, nil, FILE_END) = -1) or
(not SetEndOfFile(t.Handle)) then
begin
Result := TextOpenCleanup(t);
Exit;
end;
Break;
end;
end;
end;
if Mode <> (fmInput and 3) then
begin
case GetFileType(t.Handle) of
0: begin // bad file type
TextOpenCleanup(t);
Result := 105;
Exit;
end;
2: t.FlushFunc := @TextOut;
end;
end;
end;
end;
*)
asm
// -> EAX Pointer to text record
PUSH ESI
MOV ESI,EAX
XOR EAX,EAX
MOV [ESI].TTextRec.BufPos,EAX
MOV [ESI].TTextRec.BufEnd,EAX
MOV AX,[ESI].TTextRec.Mode
SUB EAX,fmInput
JE @@calledByReset
DEC EAX
JE @@calledByRewrite
DEC EAX
JE @@calledByAppend
JMP @@exit
@@calledByReset:
MOV EAX,GENERIC_READ // open for read
MOV EDX,FILE_SHARE_READ
MOV ECX,OPEN_EXISTING
MOV [ESI].TTextRec.InOutFunc,offset TextIn
JMP @@common
@@calledByRewrite:
MOV EAX,GENERIC_WRITE // open for write
MOV EDX,FILE_SHARE_READ
MOV ECX,CREATE_ALWAYS
JMP @@commonOut
@@calledByAppend:
MOV EAX,GENERIC_READ OR GENERIC_WRITE // open for read/write
MOV EDX,FILE_SHARE_READ
MOV ECX,OPEN_EXISTING
@@commonOut:
MOV [ESI].TTextRec.InOutFunc,offset TextOut
@@common:
MOV [ESI].TTextRec.CloseFunc,offset TextClose
MOV [ESI].TTextRec.FlushFunc,offset FileNOPProc
CMP byte ptr [ESI].TTextRec.Name,0
JE @@isCon
// CreateFile(t.Name, EAX, EDX, Nil, ECX, FILE_ATTRIBUTE_NORMAL, 0);
PUSH 0
PUSH FILE_ATTRIBUTE_NORMAL
PUSH ECX
PUSH 0
PUSH EDX
PUSH EAX
LEA EAX,[ESI].TTextRec.Name
PUSH EAX
CALL CreateFileA
CMP EAX,-1
JZ @@error
MOV [ESI].TTextRec.Handle,EAX
CMP [ESI].TTextRec.Mode,fmInOut
JNE @@success
DEC [ESI].TTextRec.Mode // fmInOut -> fmOutput
{; ??? we really have to look for the first eof byte in the
; ??? last record and truncate the file there.
; Not very nice and clean...
;
; lastRecPos = Max( GetFileSize(...) - 128, 0);
}
PUSH 0
PUSH [ESI].TTextRec.Handle
CALL GetFileSize
INC EAX
JZ @@error
SUB EAX,129
JNC @@3
XOR EAX,EAX
@@3:
// lseek(f.Handle, SEEK_SET, lastRecPos);
PUSH FILE_BEGIN
PUSH 0
PUSH EAX
PUSH [ESI].TTextRec.Handle
CALL SetFilePointer
INC EAX
JE @@error
// bytesRead = read(f.Handle, f.Buffer, 128);
PUSH 0
MOV EDX,ESP
PUSH 0
PUSH EDX
PUSH 128
LEA EDX,[ESI].TTextRec.Buffer
PUSH EDX
PUSH [ESI].TTextRec.Handle
CALL ReadFile
POP EDX
DEC EAX
JNZ @@error
// for (i = 0; i < bytesRead; i++)
XOR EAX,EAX
@@loop:
CMP EAX,EDX
JAE @@success
// if (f.Buffer[i] == eof)
CMP byte ptr [ESI].TTextRec.Buffer[EAX],eof
JE @@truncate
INC EAX
JMP @@loop
@@truncate:
// lseek( f.Handle, SEEK_END, i - bytesRead );
PUSH FILE_END
PUSH 0
SUB EAX,EDX
PUSH EAX
PUSH [ESI].TTextRec.Handle
CALL SetFilePointer
INC EAX
JE @@error
// SetEndOfFile( f.Handle );
PUSH [ESI].TTextRec.Handle
CALL SetEndOfFile
DEC EAX
JNE @@error
JMP @@success
@@isCon:
LEA EAX,[ESI].TTextRec.Buffer
MOV [ESI].TTextRec.BufSize, TYPE TTextRec.Buffer
MOV [ESI].TTextRec.CloseFunc,offset FileNOPProc
MOV [ESI].TTextRec.BufPtr,EAX
CMP [ESI].TTextRec.Mode,fmOutput
JE @@output
PUSH STD_INPUT_HANDLE
JMP @@1
@@output:
CMP ESI,offset ErrOutput
JNE @@stdout
PUSH STD_ERROR_HANDLE
JMP @@1
@@stdout:
PUSH STD_OUTPUT_HANDLE
@@1:
CALL GetStdHandle
CMP EAX,-1
JE @@error
MOV [ESI].TTextRec.Handle,EAX
@@success:
CMP [ESI].TTextRec.Mode,fmInput
JE @@2
PUSH [ESI].TTextRec.Handle
CALL GetFileType
TEST EAX,EAX
JE @@badFileType
CMP EAX,2
JNE @@2
MOV [ESI].TTextRec.FlushFunc,offset TextOut
@@2:
XOR EAX,EAX
@@exit:
POP ESI
RET
@@badFileType:
PUSH [ESI].TTextRec.Handle
CALL CloseHandle
MOV [ESI].TTextRec.Mode,fmClosed
MOV EAX,105
JMP @@exit
@@error:
MOV [ESI].TTextRec.Mode,fmClosed
CALL GetLastError
JMP @@exit
end;
{$ENDIF}
const
fNameLen = 260;
function _Assign(var t: TTextRec; const s: String): Integer;
begin
FillChar(t, sizeof(TFileRec), 0);
t.BufPtr := @t.Buffer;
t.Mode := fmClosed;
t.Flags := tfCRLF * Byte(DefaultTextLineBreakStyle);
t.BufSize := sizeof(t.Buffer);
t.OpenFunc := @TextOpen;
Move(S[1], t.Name, Length(s));
t.Name[Length(s)] := #0;
Result := 0;
end;
function InternalFlush(var t: TTextRec; Func: TTextIOFunc): Integer;
begin
case t.Mode of
fmOutput,
fmInOut : Result := Func(t);
fmInput : Result := 0;
else
if (@t = @Output) or (@t = @ErrOutput) then
Result := 0
else
Result := 103;
end;
if Result <> 0 then SetInOutRes(Result);
end;
function Flush(var t: Text): Integer;
begin
Result := InternalFlush(TTextRec(t), TTextRec(t).InOutFunc);
end;
function _Flush(var t: TTextRec): Integer;
begin
Result := InternalFlush(t, t.FlushFunc);
end;
type
{$IFDEF MSWINDOWS}
TIOProc = function (hFile: Integer; Buffer: Pointer; nNumberOfBytesToWrite: Cardinal;
var lpNumberOfBytesWritten: Cardinal; lpOverlapped: Pointer): Integer; stdcall;
function ReadFileX(hFile: Integer; Buffer: Pointer; nNumberOfBytesToRead: Cardinal;
var lpNumberOfBytesRead: Cardinal; lpOverlapped: Pointer): Integer; stdcall;
external kernel name 'ReadFile';
function WriteFileX(hFile: Integer; Buffer: Pointer; nNumberOfBytesToWrite: Cardinal;
var lpNumberOfBytesWritten: Cardinal; lpOverlapped: Pointer): Integer; stdcall;
external kernel name 'WriteFile';
{$ENDIF}
{$IFDEF LINUX}
TIOProc = function (Handle: Integer; Buffer: Pointer; Count: Cardinal): Cardinal; cdecl;
{$ENDIF}
function BlockIO(var f: TFileRec; buffer: Pointer; recCnt: Cardinal; var recsDone: Longint;
ModeMask: Integer; IOProc: TIOProc; ErrorNo: Integer): Cardinal;
// Note: RecsDone ptr can be nil!
begin
if (f.Mode and ModeMask) = ModeMask then // fmOutput or fmInOut / fmInput or fmInOut
begin
{$IFDEF LINUX}
Result := IOProc(f.Handle, buffer, recCnt * f.RecSize);
if Integer(Result) = -1 then
{$ENDIF}
{$IFDEF MSWINDOWS}
if IOProc(f.Handle, buffer, recCnt * f.RecSize, Result, nil) = 0 then
{$ENDIF}
begin
SetInOutRes(GetLastError);
Result := 0;
end
else
begin
Result := Result div f.RecSize;
if @RecsDone <> nil then
RecsDone := Result
else if Result <> recCnt then
begin
SetInOutRes(ErrorNo);
Result := 0;
end
end;
end
else
begin
SetInOutRes(103); // file not open
Result := 0;
end;
end;
function _BlockRead(var f: TFileRec; buffer: Pointer; recCnt: Longint; var recsRead: Longint): Longint;
begin
Result := BlockIO(f, buffer, recCnt, recsRead, fmInput,
{$IFDEF MSWINDOWS} ReadFileX, {$ENDIF}
{$IFDEF LINUX} __read, {$ENDIF}
100);
end;
function _BlockWrite(var f: TFileRec; buffer: Pointer; recCnt: Longint; var recsWritten: Longint): Longint;
begin
Result := BlockIO(f, buffer, recCnt, recsWritten, fmOutput,
{$IFDEF MSWINDOWS} WriteFileX, {$ENDIF}
{$IFDEF LINUX} __write, {$ENDIF}
101);
end;
function _Close(var t: TTextRec): Integer;
begin
Result := 0;
if (t.Mode >= fmInput) and (t.Mode <= fmInOut) then
begin
if (t.Mode and fmOutput) = fmOutput then // fmOutput or fmInOut
Result := TTextIOFunc(t.InOutFunc)(t);
if Result = 0 then
Result := TTextIOFunc(t.CloseFunc)(t);
if Result <> 0 then
SetInOutRes(Result);
end
else
if @t <> @Input then
SetInOutRes(103);
end;
procedure _PStrCat;
asm
{ ->EAX = Pointer to destination string }
{ EDX = Pointer to source string }
PUSH ESI
PUSH EDI
{ load dest len into EAX }
MOV EDI,EAX
XOR EAX,EAX
MOV AL,[EDI]
{ load source address in ESI, source len in ECX }
MOV ESI,EDX
XOR ECX,ECX
MOV CL,[ESI]
INC ESI
{ calculate final length in DL and store it in the destination }
MOV DL,AL
ADD DL,CL
JC @@trunc
@@cont:
MOV [EDI],DL
{ calculate final dest address }
INC EDI
ADD EDI,EAX
{ do the copy }
REP MOVSB
{ done }
POP EDI
POP ESI
RET
@@trunc:
INC DL { DL = #chars to truncate }
SUB CL,DL { CL = source len - #chars to truncate }
MOV DL,255 { DL = maximum length }
JMP @@cont
end;
procedure _PStrNCat;
asm
{ ->EAX = Pointer to destination string }
{ EDX = Pointer to source string }
{ CL = max length of result (allocated size of dest - 1) }
PUSH ESI
PUSH EDI
{ load dest len into EAX }
MOV EDI,EAX
XOR EAX,EAX
MOV AL,[EDI]
{ load source address in ESI, source len in EDX }
MOV ESI,EDX
XOR EDX,EDX
MOV DL,[ESI]
INC ESI
{ calculate final length in AL and store it in the destination }
ADD AL,DL
JC @@trunc
CMP AL,CL
JA @@trunc
@@cont:
MOV ECX,EDX
MOV DL,[EDI]
MOV [EDI],AL
{ calculate final dest address }
INC EDI
ADD EDI,EDX
{ do the copy }
REP MOVSB
@@done:
POP EDI
POP ESI
RET
@@trunc:
{ CL = maxlen }
MOV AL,CL { AL = final length = maxlen }
SUB CL,[EDI] { CL = length to copy = maxlen - destlen }
JBE @@done
MOV DL,CL
JMP @@cont
end;
procedure _PStrCpy(Dest: PShortString; Source: PShortString);
begin
Move(Source^, Dest^, Byte(Source^[0])+1);
end;
procedure _PStrNCpy(Dest: PShortString; Source: PShortString; MaxLen: Byte);
begin
if MaxLen > Byte(Source^[0]) then
MaxLen := Byte(Source^[0]);
Byte(Dest^[0]) := MaxLen;
Move(Source^[1], Dest^[1], MaxLen);
end;
procedure _PStrCmp;
asm
{ ->EAX = Pointer to left string }
{ EDX = Pointer to right string }
PUSH EBX
PUSH ESI
PUSH EDI
MOV ESI,EAX
MOV EDI,EDX
XOR EAX,EAX
XOR EDX,EDX
MOV AL,[ESI]
MOV DL,[EDI]
INC ESI
INC EDI
SUB EAX,EDX { eax = len1 - len2 }
JA @@skip1
ADD EDX,EAX { edx = len2 + (len1 - len2) = len1 }
@@skip1:
PUSH EDX
SHR EDX,2
JE @@cmpRest
@@longLoop:
MOV ECX,[ESI]
MOV EBX,[EDI]
CMP ECX,EBX
JNE @@misMatch
DEC EDX
JE @@cmpRestP4
MOV ECX,[ESI+4]
MOV EBX,[EDI+4]
CMP ECX,EBX
JNE @@misMatch
ADD ESI,8
ADD EDI,8
DEC EDX
JNE @@longLoop
JMP @@cmpRest
@@cmpRestP4:
ADD ESI,4
ADD EDI,4
@@cmpRest:
POP EDX
AND EDX,3
JE @@equal
MOV CL,[ESI]
CMP CL,[EDI]
JNE @@exit
DEC EDX
JE @@equal
MOV CL,[ESI+1]
CMP CL,[EDI+1]
JNE @@exit
DEC EDX
JE @@equal
MOV CL,[ESI+2]
CMP CL,[EDI+2]
JNE @@exit
@@equal:
ADD EAX,EAX
JMP @@exit
@@misMatch:
POP EDX
CMP CL,BL
JNE @@exit
CMP CH,BH
JNE @@exit
SHR ECX,16
SHR EBX,16
CMP CL,BL
JNE @@exit
CMP CH,BH
@@exit:
POP EDI
POP ESI
POP EBX
end;
procedure _AStrCmp;
asm
{ ->EAX = Pointer to left string }
{ EDX = Pointer to right string }
{ ECX = Number of chars to compare}
PUSH EBX
PUSH ESI
PUSH ECX
MOV ESI,ECX
SHR ESI,2
JE @@cmpRest
@@longLoop:
MOV ECX,[EAX]
MOV EBX,[EDX]
CMP ECX,EBX
JNE @@misMatch
DEC ESI
JE @@cmpRestP4
MOV ECX,[EAX+4]
MOV EBX,[EDX+4]
CMP ECX,EBX
JNE @@misMatch
ADD EAX,8
ADD EDX,8
DEC ESI
JNE @@longLoop
JMP @@cmpRest
@@cmpRestp4:
ADD EAX,4
ADD EDX,4
@@cmpRest:
POP ESI
AND ESI,3
JE @@exit
MOV CL,[EAX]
CMP CL,[EDX]
JNE @@exit
DEC ESI
JE @@equal
MOV CL,[EAX+1]
CMP CL,[EDX+1]
JNE @@exit
DEC ESI
JE @@equal
MOV CL,[EAX+2]
CMP CL,[EDX+2]
JNE @@exit
@@equal:
XOR EAX,EAX
JMP @@exit
@@misMatch:
POP ESI
CMP CL,BL
JNE @@exit
CMP CH,BH
JNE @@exit
SHR ECX,16
SHR EBX,16
CMP CL,BL
JNE @@exit
CMP CH,BH
@@exit:
POP ESI
POP EBX
end;
function _EofFile(var f: TFileRec): Boolean;
begin
Result := _FilePos(f) >= _FileSize(f);
end;
function _EofText(var t: TTextRec): Boolean;
asm
// -> EAX Pointer to text record
// <- AL Boolean result
CMP [EAX].TTextRec.Mode,fmInput
JNE @@readChar
MOV EDX,[EAX].TTextRec.BufPos
CMP EDX,[EAX].TTextRec.BufEnd
JAE @@readChar
ADD EDX,[EAX].TTextRec.BufPtr
TEST [EAX].TTextRec.Flags,tfCRLF
JZ @@FalseExit
MOV CL,[EDX]
CMP CL,cEof
JNZ @@FalseExit
@@eof:
MOV AL,1
JMP @@exit
@@readChar:
PUSH EAX
CALL _ReadChar
POP EDX
CMP AH,cEof
JE @@eof
DEC [EDX].TTextRec.BufPos
@@FalseExit:
XOR EAX,EAX
@@exit:
end;
function _Eoln(var t: TTextRec): Boolean;
asm
// -> EAX Pointer to text record
// <- AL Boolean result
CMP [EAX].TTextRec.Mode,fmInput
JNE @@readChar
MOV EDX,[EAX].TTextRec.BufPos
CMP EDX,[EAX].TTextRec.BufEnd
JAE @@readChar
ADD EDX,[EAX].TTextRec.BufPtr
TEST [EAX].TTextRec.Flags,tfCRLF
MOV AL,0
MOV CL,[EDX]
JZ @@testLF
CMP CL,cCR
JE @@eol
CMP CL,cEOF
JE @@eof
JMP @@exit
@@testLF:
CMP CL,cLF
JE @@eol
CMP CL,cEOF
JE @@eof
JMP @@exit
@@readChar:
PUSH EAX
CALL _ReadChar
POP EDX
CMP AH,cEOF
JE @@eof
DEC [EDX].TTextRec.BufPos
XOR ECX,ECX
XCHG ECX,EAX
TEST [EDX].TTextRec.Mode,tfCRLF
JNE @@testLF
CMP CL,cCR
JE @@eol
JMP @@exit
@@eol:
@@eof:
MOV AL,1
@@exit:
end;
procedure _Erase(var f: TFileRec);
begin
if (f.Mode < fmClosed) or (f.Mode > fmInOut) then
SetInOutRes(102) // file not assigned
else
{$IFDEF LINUX}
if __remove(f.Name) < 0 then
SetInOutRes(GetLastError);
{$ENDIF}
{$IFDEF MSWINDOWS}
if not DeleteFileA(f.Name) then
SetInOutRes(GetLastError);
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
// Floating-point divide reverse routine
// ST(1) = ST(0) / ST(1), pop ST
procedure _FSafeDivideR;
asm
FXCH
JMP _FSafeDivide
end;
// Floating-point divide routine
// ST(1) = ST(1) / ST(0), pop ST
procedure _FSafeDivide;
type
Z = packed record // helper type to make parameter references more readable
Dividend: Extended; // (TBYTE PTR [ESP])
Pad: Word;
Divisor: Extended; // (TBYTE PTR [ESP+12])
end;
asm
CMP TestFDIV,0 //Check FDIV indicator
JLE @@FDivideChecked //Jump if flawed or don't know
FDIV //Known to be ok, so just do FDIV
RET
// FDIV constants
@@FDIVRiscTable: DB 0,1,0,0,4,0,0,7,0,0,10,0,0,13,0,0;
@@FDIVScale1: DD $3F700000 // 0.9375
@@FDIVScale2: DD $3F880000 // 1.0625
@@FDIV1SHL63: DD $5F000000 // 1 SHL 63
@@TestDividend: DD $C0000000,$4150017E // 4195835.0
@@TestDivisor: DD $80000000,$4147FFFF // 3145727.0
@@TestOne: DD $00000000,$3FF00000 // 1.0
// Flawed FDIV detection
@@FDivideDetect:
MOV TestFDIV,1 //Indicate correct FDIV
PUSH EAX
SUB ESP,12
FSTP TBYTE PTR [ESP] //Save off ST
FLD QWORD PTR @@TestDividend //Ok if x - (x / y) * y < 1.0
FDIV QWORD PTR @@TestDivisor
FMUL QWORD PTR @@TestDivisor
FSUBR QWORD PTR @@TestDividend
FCOMP QWORD PTR @@TestOne
FSTSW AX
SHR EAX,7
AND EAX,002H //Zero if FDIV is flawed
DEC EAX
MOV TestFDIV,AL //1 means Ok, -1 means flawed
FLD TBYTE PTR [ESP] //Restore ST
ADD ESP,12
POP EAX
JMP _FSafeDivide
@@FDivideChecked:
JE @@FDivideDetect //Do detection if TestFDIV = 0
@@1: PUSH EAX
SUB ESP,24
FSTP [ESP].Z.Divisor //Store Divisor and Dividend
FSTP [ESP].Z.Dividend
FLD [ESP].Z.Dividend
FLD [ESP].Z.Divisor
@@2: MOV EAX,DWORD PTR [ESP+4].Z.Divisor //Is Divisor a denormal?
ADD EAX,EAX
JNC @@20 //Yes, @@20
XOR EAX,0E000000H //If these three bits are not all
TEST EAX,0E000000H //ones, FDIV will work
JZ @@10 //Jump if all ones
@@3: FDIV //Do FDIV and exit
ADD ESP,24
POP EAX
RET
@@10: SHR EAX,28 //If the four bits following the MSB
//of the mantissa have a decimal
//of 1, 4, 7, 10, or 13, FDIV may
CMP byte ptr @@FDIVRiscTable[EAX],0 //not work correctly
JZ @@3 //Do FDIV if not 1, 4, 7, 10, or 13
MOV EAX,DWORD PTR [ESP+8].Z.Divisor //Get Divisor exponent
AND EAX,7FFFH
JZ @@3 //Ok to FDIV if denormal
CMP EAX,7FFFH
JE @@3 //Ok to FDIV if NAN or INF
MOV EAX,DWORD PTR [ESP+8].Z.Dividend //Get Dividend exponent
AND EAX,7FFFH
CMP EAX,1 //Small number?
JE @@11 //Yes, @@11
FMUL DWORD PTR @@FDIVScale1 //Scale by 15/16
FXCH
FMUL DWORD PTR @@FDIVScale1
FXCH
JMP @@3 //FDIV is now safe
@@11: FMUL DWORD PTR @@FDIVScale2 //Scale by 17/16
FXCH
FMUL DWORD PTR @@FDIVScale2
FXCH
JMP @@3 //FDIV is now safe
@@20: MOV EAX,DWORD PTR [ESP].Z.Divisor //Is entire Divisor zero?
OR EAX,DWORD PTR [ESP+4].Z.Divisor
JZ @@3 //Yes, ok to FDIV
MOV EAX,DWORD PTR [ESP+8].Z.Divisor //Get Divisor exponent
AND EAX,7FFFH //Non-zero exponent is invalid
JNZ @@3 //Ok to FDIV if invalid
MOV EAX,DWORD PTR [ESP+8].Z.Dividend //Get Dividend exponent
AND EAX,7FFFH //Denormal?
JZ @@21 //Yes, @@21
CMP EAX,7FFFH //NAN or INF?
JE @@3 //Yes, ok to FDIV
MOV EAX,DWORD PTR [ESP+4].Z.Dividend //If MSB of mantissa is zero,
ADD EAX,EAX //the number is invalid
JNC @@3 //Ok to FDIV if invalid
JMP @@22
@@21: MOV EAX,DWORD PTR [ESP+4].Z.Dividend //If MSB of mantissa is zero,
ADD EAX,EAX //the number is invalid
JC @@3 //Ok to FDIV if invalid
@@22: FXCH //Scale stored Divisor image by
FSTP ST(0) //1 SHL 63 and restart
FLD ST(0)
FMUL DWORD PTR @@FDIV1SHL63
FSTP [ESP].Z.Divisor
FLD [ESP].Z.Dividend
FXCH
JMP @@2
end;
{$ENDIF}
function _FilePos(var f: TFileRec): Longint;
begin
if (f.Mode > fmClosed) and (f.Mode <= fmInOut) then
begin
{$IFDEF LINUX}
Result := _lseek(f.Handle, 0, SEEK_CUR);
{$ENDIF}
{$IFDEF MSWINDOWS}
Result := SetFilePointer(f.Handle, 0, nil, FILE_CURRENT);
{$ENDIF}
if Result = -1 then
InOutError
else
Result := Cardinal(Result) div f.RecSize;
end
else
begin
SetInOutRes(103);
Result := -1;
end;
end;
function _FileSize(var f: TFileRec): Longint;
{$IFDEF MSWINDOWS}
begin
Result := -1;
if (f.Mode > fmClosed) and (f.Mode <= fmInOut) then
begin
Result := GetFileSize(f.Handle, 0);
if Result = -1 then
InOutError
else
Result := Cardinal(Result) div f.RecSize;
end
else
SetInOutRes(103);
{$ENDIF}
{$IFDEF LINUX}
var
stat: TStatStruct;
begin
Result := -1;
if (f.Mode > fmClosed) and (f.Mode <= fmInOut) then
begin
if _fxstat(STAT_VER_LINUX, f.Handle, stat) <> 0 then
InOutError
else
Result := stat.st_size div f.RecSize;
end
else
SetInOutRes(103);
{$ENDIF}
end;
procedure _FillChar(var Dest; count: Integer; Value: Char);
{$IFDEF PUREPASCAL}
var
I: Integer;
P: PChar;
begin
P := PChar(@Dest);
for I := count-1 downto 0 do
P[I] := Value;
end;
{$ELSE}
asm
{ ->EAX Pointer to destination }
{ EDX count }
{ CL value }
PUSH EDI
MOV EDI,EAX { Point EDI to destination }
MOV CH,CL { Fill EAX with value repeated 4 times }
MOV EAX,ECX
SHL EAX,16
MOV AX,CX
MOV ECX,EDX
SAR ECX,2
JS @@exit
REP STOSD { Fill count DIV 4 dwords }
MOV ECX,EDX
AND ECX,3
REP STOSB { Fill count MOD 4 bytes }
@@exit:
POP EDI
end;
{$ENDIF}
procedure Mark;
begin
Error(reInvalidPtr);
end;
procedure _RandInt;
asm
{ ->EAX Range }
{ <-EAX Result }
PUSH EBX
{$IFDEF PIC}
PUSH EAX
CALL GetGOT
MOV EBX,EAX
POP EAX
MOV ECX,[EBX].OFFSET RandSeed
IMUL EDX,[ECX],08088405H
INC EDX
MOV [ECX],EDX
{$ELSE}
XOR EBX, EBX
IMUL EDX,[EBX].RandSeed,08088405H
INC EDX
MOV [EBX].RandSeed,EDX
{$ENDIF}
MUL EDX
MOV EAX,EDX
POP EBX
end;
procedure _RandExt;
const two2neg32: double = ((1.0/$10000) / $10000); // 2^-32
asm
{ FUNCTION _RandExt: Extended; }
PUSH EBX
{$IFDEF PIC}
CALL GetGOT
MOV EBX,EAX
MOV ECX,[EBX].OFFSET RandSeed
IMUL EDX,[ECX],08088405H
INC EDX
MOV [ECX],EDX
{$ELSE}
XOR EBX, EBX
IMUL EDX,[EBX].RandSeed,08088405H
INC EDX
MOV [EBX].RandSeed,EDX
{$ENDIF}
FLD [EBX].two2neg32
PUSH 0
PUSH EDX
FILD qword ptr [ESP]
ADD ESP,8
FMULP ST(1), ST(0)
POP EBX
end;
function _ReadRec(var f: TFileRec; Buffer: Pointer): Integer;
{$IFDEF LINUX}
begin
if (f.Mode and fmInput) = fmInput then // fmInput or fmInOut
begin
Result := __read(f.Handle, Buffer, f.RecSize);
if Result = -1 then
InOutError
else if Cardinal(Result) <> f.RecSize then
SetInOutRes(100);
end
else
begin
SetInOutRes(103); // file not open for input
Result := 0;
end;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
asm
// -> EAX Pointer to file variable
// EDX Pointer to buffer
PUSH EBX
XOR ECX,ECX
MOV EBX,EAX
MOV CX,[EAX].TFileRec.Mode // File must be open
SUB ECX,fmInput
JE @@skip
SUB ECX,fmInOut-fmInput
JNE @@fileNotOpen
@@skip:
// ReadFile(f.Handle, buffer, f.RecSize, @result, Nil);
PUSH 0 // space for OS result
MOV EAX,ESP
PUSH 0 // pass lpOverlapped
PUSH EAX // pass @result
PUSH [EBX].TFileRec.RecSize // pass nNumberOfBytesToRead
PUSH EDX // pass lpBuffer
PUSH [EBX].TFileRec.Handle // pass hFile
CALL ReadFile
POP EDX // pop result
DEC EAX // check EAX = TRUE
JNZ @@error
CMP EDX,[EBX].TFileRec.RecSize // result = f.RecSize ?
JE @@exit
@@readError:
MOV EAX,100
JMP @@errExit
@@fileNotOpen:
MOV EAX,103
JMP @@errExit
@@error:
CALL GetLastError
@@errExit:
CALL SetInOutRes
@@exit:
POP EBX
end;
{$ENDIF}
// If the file is Input std variable, try to open it
// Otherwise, runtime error.
function TryOpenForInput(var t: TTextRec): Boolean;
begin
if @t = @Input then
begin
t.Flags := tfCRLF * Byte(DefaultTextLineBreakStyle);
_ResetText(t);
end;
Result := t.Mode = fmInput;
if not Result then
SetInOutRes(104);
end;
function _ReadChar(var t: TTextRec): Char;
asm
// -> EAX Pointer to text record
// <- AL Character read. (may be a pseudo cEOF in DOS mode)
// <- AH cEOF = End of File, else 0
// For eof, #$1A is returned in AL and in AH.
// For errors, InOutRes is set and #$1A is returned.
CMP [EAX].TTextRec.Mode, fmInput
JE @@checkBuf
PUSH EAX
CALL TryOpenForInput
TEST AL,AL
POP EAX
JZ @@eofexit
@@checkBuf:
MOV EDX,[EAX].TTextRec.BufPos
CMP EDX,[EAX].TTextRec.BufEnd
JAE @@fillBuf
@@cont:
TEST [EAX].TTextRec.Flags,tfCRLF
MOV ECX,[EAX].TTextRec.BufPtr
MOV CL,[ECX+EDX]
JZ @@cont2
CMP CL,cEof // Check for EOF char in DOS mode
JE @@eofexit
@@cont2:
INC EDX
MOV [EAX].TTextRec.BufPos,EDX
XOR EAX,EAX
JMP @@exit
@@fillBuf:
PUSH EAX
CALL [EAX].TTextRec.InOutFunc
TEST EAX,EAX
JNE @@error
POP EAX
MOV EDX,[EAX].TTextRec.BufPos
CMP EDX,[EAX].TTextRec.BufEnd
JB @@cont
// We didn't get characters. Must be eof then.
@@eof:
TEST [EAX].TTextRec.Flags,tfCRLF
JZ @@eofexit
// In DOS CRLF compatibility mode, synthesize an EOF char
// Store one eof in the buffer and increment BufEnd
MOV ECX,[EAX].TTextRec.BufPtr
MOV byte ptr [ECX+EDX],cEof
INC [EAX].TTextRec.BufEnd
JMP @@eofexit
@@error:
CALL SetInOutRes
POP EAX
@@eofexit:
MOV CL,cEof
MOV AH,CL
@@exit:
MOV AL,CL
end;
function _ReadLong(var t: TTextRec): Longint;
asm
// -> EAX Pointer to text record
// <- EAX Result
PUSH EBX
PUSH ESI
PUSH EDI
SUB ESP,36 // var numbuf: String[32];
MOV ESI,EAX
CALL _SeekEof
DEC AL
JZ @@eof
MOV EDI,ESP // EDI -> numBuf[0]
MOV BL,32
@@loop:
MOV EAX,ESI
CALL _ReadChar
CMP AL,' '
JBE @@endNum
STOSB
DEC BL
JNZ @@loop
@@convert:
MOV byte ptr [EDI],0
MOV EAX,ESP // EAX -> numBuf
PUSH EDX // allocate code result
MOV EDX,ESP // pass pointer to code
CALL _ValLong // convert
POP EDX // pop code result into EDX
TEST EDX,EDX
JZ @@exit
MOV EAX,106
CALL SetInOutRes
JMP @@exit
@@endNum:
CMP AH,cEof
JE @@convert
DEC [ESI].TTextRec.BufPos
JMP @@convert
@@eof:
XOR EAX,EAX
@@exit:
ADD ESP,36
POP EDI
POP ESI
POP EBX
end;
function ReadLine(var t: TTextRec; buf: Pointer; maxLen: Longint): Pointer;
asm
// -> EAX Pointer to text record
// EDX Pointer to buffer
// ECX Maximum count of chars to read
// <- ECX Actual count of chars in buffer
// <- EAX Pointer to text record
PUSH EBX
PUSH ESI
PUSH EDI
PUSH ECX
MOV ESI,ECX
MOV EDI,EDX
CMP [EAX].TTextRec.Mode,fmInput
JE @@start
PUSH EAX
CALL TryOpenForInput
TEST AL,AL
POP EAX
JZ @@exit
@@start:
MOV EBX,EAX
TEST ESI,ESI
JLE @@exit
MOV EDX,[EBX].TTextRec.BufPos
MOV ECX,[EBX].TTextRec.BufEnd
SUB ECX,EDX
ADD EDX,[EBX].TTextRec.BufPtr
@@loop:
DEC ECX
JL @@readChar
MOV AL,[EDX]
INC EDX
@@cont:
CMP AL,cLF
JE @@lf
CMP AL,cCR
JE @@cr
STOSB
DEC ESI
JG @@loop
JMP @@finish
@@cr:
MOV AL,[EDX]
CMP AL,cLF
JNE @@loop
@@lf:
DEC EDX
@@finish:
SUB EDX,[EBX].TTextRec.BufPtr
MOV [EBX].TTextRec.BufPos,EDX
JMP @@exit
@@readChar:
MOV [EBX].TTextRec.BufPos,EDX
MOV EAX,EBX
CALL _ReadChar
MOV EDX,[EBX].TTextRec.BufPos
MOV ECX,[EBX].TTextRec.BufEnd
SUB ECX,EDX
ADD EDX,[EBX].TTextRec.BufPtr
TEST AH,AH //eof
JZ @@cont
@@exit:
MOV EAX,EBX
POP ECX
SUB ECX,ESI
POP EDI
POP ESI
POP EBX
end;
procedure _ReadString(var t: TTextRec; s: PShortString; maxLen: Longint);
asm
// -> EAX Pointer to text record
// EDX Pointer to string
// ECX Maximum length of string
PUSH EDX
INC EDX
CALL ReadLine
POP EDX
MOV [EDX],CL
end;
procedure _ReadCString(var t: TTextRec; s: PChar; maxLen: Longint);
asm
// -> EAX Pointer to text record
// EDX Pointer to string
// ECX Maximum length of string
PUSH EDX
CALL ReadLine
POP EDX
MOV byte ptr [EDX+ECX],0
end;
procedure _ReadLString(var t: TTextRec; var s: AnsiString);
asm
{ -> EAX pointer to Text }
{ EDX pointer to AnsiString }
PUSH EBX
PUSH ESI
MOV EBX,EAX
MOV ESI,EDX
MOV EAX,EDX
CALL _LStrClr
SUB ESP,256
MOV EAX,EBX
MOV EDX,ESP
MOV ECX,255
CALL _ReadString
MOV EAX,ESI
MOV EDX,ESP
CALL _LStrFromString
CMP byte ptr [ESP],255
JNE @@exit
@@loop:
MOV EAX,EBX
MOV EDX,ESP
MOV ECX,255
CALL _ReadString
MOV EDX,ESP
PUSH 0
MOV EAX,ESP
CALL _LStrFromString
MOV EAX,ESI
MOV EDX,[ESP]
CALL _LStrCat
MOV EAX,ESP
CALL _LStrClr
POP EAX
CMP byte ptr [ESP],255
JE @@loop
@@exit:
ADD ESP,256
POP ESI
POP EBX
end;
function IsValidMultibyteChar(const Src: PChar; SrcBytes: Integer): Boolean;
{$IFDEF MSWINDOWS}
const
ERROR_NO_UNICODE_TRANSLATION = 1113; // Win32 GetLastError when result = 0
MB_ERR_INVALID_CHARS = 8;
var
Dest: WideChar;
begin
Result := MultiByteToWideChar(0, MB_ERR_INVALID_CHARS, Src, SrcBytes, @Dest, 1) <> 0;
{$ENDIF}
{$IFDEF LINUX}
begin
Result := mblen(Src, SrcBytes) <> -1;
{$ENDIF}
end;
function _ReadWChar(var t: TTextRec): WideChar;
var
scratch: array [0..7] of AnsiChar;
wc: WideChar;
i: Integer;
begin
i := 0;
while i < High(scratch) do
begin
scratch[i] := _ReadChar(t);
Inc(i);
scratch[i] := #0;
if IsValidMultibyteChar(scratch, i) then
begin
WCharFromChar(@wc, 1, scratch, i);
Result := wc;
Exit;
end;
end;
SetInOutRes(106); // Invalid Input
Result := #0;
end;
procedure _ReadWCString(var t: TTextRec; s: PWideChar; maxBytes: Longint);
var
i, maxLen: Integer;
wc: WideChar;
begin
if s = nil then Exit;
i := 0;
maxLen := maxBytes div sizeof(WideChar);
while i < maxLen do
begin
wc := _ReadWChar(t);
case Integer(wc) of
cEOF: if _EOFText(t) then Break;
cLF : begin
Dec(t.BufPos);
Break;
end;
cCR : if Byte(t.BufPtr[t.BufPos]) = cLF then
begin
Dec(t.BufPos);
Break;
end;
end;
s[i] := wc;
Inc(i);
end;
s[i] := #0;
end;
procedure _ReadWString(var t: TTextRec; var s: WideString);
var
Temp: AnsiString;
begin
_ReadLString(t, Temp);
s := Temp;
end;
function _ReadExt(var t: TTextRec): Extended;
asm
// -> EAX Pointer to text record
// <- FST(0) Result
PUSH EBX
PUSH ESI
PUSH EDI
SUB ESP,68 // var numbuf: array[0..64] of char;
MOV ESI,EAX
CALL _SeekEof
DEC AL
JZ @@eof
MOV EDI,ESP // EDI -> numBuf[0]
MOV BL,64
@@loop:
MOV EAX,ESI
CALL _ReadChar
CMP AL,' '
JBE @@endNum
STOSB
DEC BL
JNZ @@loop
@@convert:
MOV byte ptr [EDI],0
MOV EAX,ESP // EAX -> numBuf
PUSH EDX // allocate code result
MOV EDX,ESP // pass pointer to code
CALL _ValExt // convert
POP EDX // pop code result into EDX
TEST EDX,EDX
JZ @@exit
MOV EAX,106
CALL SetInOutRes
JMP @@exit
@@endNum:
CMP AH,cEOF
JE @@convert
DEC [ESI].TTextRec.BufPos
JMP @@convert
@@eof:
FLDZ
@@exit:
ADD ESP,68
POP EDI
POP ESI
POP EBX
end;
procedure _ReadLn(var t: TTextRec);
asm
// -> EAX Pointer to text record
PUSH EBX
MOV EBX,EAX
@@loop:
MOV EAX,EBX
CALL _ReadChar
CMP AL,cLF // accept LF as end of line
JE @@exit
CMP AH,cEOF
JE @@eof
CMP AL,cCR
JNE @@loop
MOV EAX,EBX
CALL _ReadChar
CMP AL,cLF // accept CR+LF as end of line
JE @@exit
CMP AH,cEOF // accept CR+EOF as end of line
JE @@eof
DEC [EBX].TTextRec.BufPos
JMP @@loop // else CR+ anything else is not a line break.
@@exit:
@@eof:
POP EBX
end;
procedure _Rename(var f: TFileRec; newName: PChar);
var
I: Integer;
begin
if f.Mode = fmClosed then
begin
if newName = nil then newName := '';
{$IFDEF LINUX}
if __rename(f.Name, newName) = 0 then
{$ENDIF}
{$IFDEF MSWINDOWS}
if MoveFileA(f.Name, newName) then
{$ENDIF}
begin
I := 0;
while (newName[I] <> #0) and (I < High(f.Name)) do
begin
f.Name[I] := newName[I];
Inc(I);
end
end
else
SetInOutRes(GetLastError);
end
else
SetInOutRes(102);
end;
procedure Release;
begin
Error(reInvalidPtr);
end;
function _CloseFile(var f: TFileRec): Integer;
begin
f.Mode := fmClosed;
Result := 0;
if not InternalClose(f.Handle) then
begin
InOutError;
Result := 1;
end;
end;
function OpenFile(var f: TFileRec; recSiz: Longint; mode: Longint): Integer;
{$IFDEF LINUX}
var
Flags: Integer;
begin
Result := 0;
if (f.Mode >= fmClosed) and (f.Mode <= fmInOut) then
begin
if f.Mode <> fmClosed then // not yet closed: close it
begin
Result := TFileIOFunc(f.CloseFunc)(f);
if Result <> 0 then
SetInOutRes(Result);
end;
if recSiz <= 0 then
SetInOutRes(106);
f.RecSize := recSiz;
f.InOutFunc := @FileNopProc;
if f.Name[0] <> #0 then
begin
f.CloseFunc := @_CloseFile;
case mode of
1: begin
Flags := O_APPEND or O_WRONLY;
f.Mode := fmOutput;
end;
2: begin
Flags := O_RDWR;
f.Mode := fmInOut;
end;
3: begin
Flags := O_CREAT or O_TRUNC or O_RDWR;
f.Mode := fmInOut;
end;
else
Flags := O_RDONLY;
f.Mode := fmInput;
end;
f.Handle := __open(f.Name, Flags, FileAccessRights);
end
else // stdin or stdout
begin
f.CloseFunc := @FileNopProc;
if mode = 3 then
f.Handle := STDOUT_FILENO
else
f.Handle := STDIN_FILENO;
end;
if f.Handle = -1 then
begin
f.Mode := fmClosed;
InOutError;
end;
end
else
SetInOutRes(102);
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
const
ShareTab: array [0..7] of Integer =
(FILE_SHARE_READ OR FILE_SHARE_WRITE, // OF_SHARE_COMPAT 0x00000000
0, // OF_SHARE_EXCLUSIVE 0x00000010
FILE_SHARE_READ, // OF_SHARE_DENY_WRITE 0x00000020
FILE_SHARE_WRITE, // OF_SHARE_DENY_READ 0x00000030
FILE_SHARE_READ OR FILE_SHARE_WRITE, // OF_SHARE_DENY_NONE 0x00000040
0,0,0);
asm
//-> EAX Pointer to file record
// EDX Record size
// ECX File mode
PUSH EBX
PUSH ESI
PUSH EDI
MOV ESI,EDX
MOV EDI,ECX
XOR EDX,EDX
MOV EBX,EAX
MOV DX,[EAX].TFileRec.Mode
SUB EDX,fmClosed
JE @@alreadyClosed
CMP EDX,fmInOut-fmClosed
JA @@notAssignedError
// not yet closed: close it. File parameter is still in EAX
CALL [EBX].TFileRec.CloseFunc
TEST EAX,EAX
JE @@alreadyClosed
CALL SetInOutRes
@@alreadyClosed:
MOV [EBX].TFileRec.Mode,fmInOut
MOV [EBX].TFileRec.RecSize,ESI
MOV [EBX].TFileRec.CloseFunc,offset _CloseFile
MOV [EBX].TFileRec.InOutFunc,offset FileNopProc
CMP byte ptr [EBX].TFileRec.Name,0
JE @@isCon
MOV EAX,GENERIC_READ OR GENERIC_WRITE
MOV DL,FileMode
AND EDX,070H
SHR EDX,4-2
MOV EDX,dword ptr [shareTab+EDX]
MOV ECX,CREATE_ALWAYS
SUB EDI,3
JE @@calledByRewrite
MOV ECX,OPEN_EXISTING
INC EDI
JE @@skip
MOV EAX,GENERIC_WRITE
INC EDI
MOV [EBX].TFileRec.Mode,fmOutput
JE @@skip
MOV EAX,GENERIC_READ
MOV [EBX].TFileRec.Mode,fmInput
@@skip:
@@calledByRewrite:
// CreateFile(t.FileName, EAX, EDX, Nil, ECX, FILE_ATTRIBUTE_NORMAL, 0);
PUSH 0
PUSH FILE_ATTRIBUTE_NORMAL
PUSH ECX
PUSH 0
PUSH EDX
PUSH EAX
LEA EAX,[EBX].TFileRec.Name
PUSH EAX
CALL CreateFileA
@@checkHandle:
CMP EAX,-1
JZ @@error
MOV [EBX].TFileRec.Handle,EAX
JMP @@exit
@@isCon:
MOV [EBX].TFileRec.CloseFunc,offset FileNopProc
CMP EDI,3
JE @@output
PUSH STD_INPUT_HANDLE
JMP @@1
@@output:
PUSH STD_OUTPUT_HANDLE
@@1:
CALL GetStdHandle
JMP @@checkHandle
@@notAssignedError:
MOV EAX,102
JMP @@errExit
@@error:
MOV [EBX].TFileRec.Mode,fmClosed
CALL GetLastError
@@errExit:
CALL SetInOutRes
@@exit:
POP EDI
POP ESI
POP EBX
end;
{$ENDIF}
function _ResetFile(var f: TFileRec; recSize: Longint): Integer;
var
m: Byte;
begin
m := FileMode and 3;
if m > 2 then m := 2;
Result := OpenFile(f, recSize, m);
end;
function _RewritFile(var f: TFileRec; recSize: Longint): Integer;
begin
Result := OpenFile(f, recSize, 3);
end;
procedure _Seek(var f: TFileRec; recNum: Cardinal);
{$IFDEF LINUX}
begin
if (f.Mode >= fmInput) and (f.Mode <= fmInOut) then
begin
if _lseek(f.Handle, f.RecSize * recNum, SEEK_SET) = -1 then
InOutError;
end
else
SetInOutRes(103);
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
asm
// -> EAX Pointer to file variable
// EDX Record number
MOV ECX,EAX
MOVZX EAX,[EAX].TFileRec.Mode // check whether file is open
SUB EAX,fmInput
CMP EAX,fmInOut-fmInput
JA @@fileNotOpen
// SetFilePointer(f.Handle, recNum*f.RecSize, FILE_BEGIN
PUSH FILE_BEGIN // pass dwMoveMethod
MOV EAX,[ECX].TFileRec.RecSize
MUL EDX
PUSH 0 // pass lpDistanceToMoveHigh
PUSH EAX // pass lDistanceToMove
PUSH [ECX].TFileRec.Handle // pass hFile
CALL SetFilePointer // get current position
INC EAX
JZ InOutError
JMP @@exit
@@fileNotOpen:
MOV EAX,103
JMP SetInOutRes
@@exit:
end;
{$ENDIF}
function _SeekEof(var t: TTextRec): Boolean;
asm
// -> EAX Pointer to text record
// <- AL Boolean result
PUSH EBX
MOV EBX,EAX
@@loop:
MOV EAX,EBX
CALL _ReadChar
CMP AL,' '
JA @@endloop
CMP AH,cEOF
JE @@eof
JMP @@loop
@@eof:
MOV AL,1
JMP @@exit
@@endloop:
DEC [EBX].TTextRec.BufPos
XOR AL,AL
@@exit:
POP EBX
end;
function _SeekEoln(var t: TTextRec): Boolean;
asm
// -> EAX Pointer to text record
// <- AL Boolean result
PUSH EBX
MOV EBX,EAX
@@loop:
MOV EAX,EBX
CALL _ReadChar
CMP AL,' '
JA @@falseExit
CMP AH,cEOF
JE @@eof
CMP AL,cLF
JE @@trueExit
CMP AL,cCR
JNE @@loop
@@trueExit:
MOV AL,1
JMP @@exitloop
@@falseExit:
XOR AL,AL
@@exitloop:
DEC [EBX].TTextRec.BufPos
JMP @@exit
@@eof:
MOV AL,1
@@exit:
POP EBX
end;
procedure _SetTextBuf(var t: TTextRec; p: Pointer; size: Longint);
begin
t.BufPtr := P;
t.BufSize := size;
t.BufPos := 0;
t.BufEnd := 0;
end;
procedure _StrLong(val, width: Longint; s: PShortString);
{$IFDEF PUREPASCAL}
var
I: Integer;
sign: Longint;
a: array [0..19] of char;
P: PChar;
begin
sign := val;
val := Abs(val);
I := 0;
repeat
a[I] := Chr((val mod 10) + Ord('0'));
Inc(I);
val := val div 10;
until val = 0;
if sign < 0 then
begin
a[I] := '-';
Inc(I);
end;
if width < I then
width := I;
if width > 255 then
width := 255;
s^[0] := Chr(width);
P := @S^[1];
while width > I do
begin
P^ := ' ';
Inc(P);
Dec(width);
end;
repeat
Dec(I);
P^ := a[I];
Inc(P);
until I <= 0;
end;
{$ELSE}
asm
{ PROCEDURE _StrLong( val: Longint; width: Longint; VAR s: ShortString );
->EAX Value
EDX Width
ECX Pointer to string }
PUSH EBX { VAR i: Longint; }
PUSH ESI { VAR sign : Longint; }
PUSH EDI
PUSH EDX { store width on the stack }
SUB ESP,20 { VAR a: array [0..19] of Char; }
MOV EDI,ECX
MOV ESI,EAX { sign := val }
CDQ { val := Abs(val); canned sequence }
XOR EAX,EDX
SUB EAX,EDX
MOV ECX,10
XOR EBX,EBX { i := 0; }
@@repeat1: { repeat }
XOR EDX,EDX { a[i] := Chr( val MOD 10 + Ord('0') );}
DIV ECX { val := val DIV 10; }
ADD EDX,'0'
MOV [ESP+EBX],DL
INC EBX { i := i + 1; }
TEST EAX,EAX { until val = 0; }
JNZ @@repeat1
TEST ESI,ESI
JGE @@2
MOV byte ptr [ESP+EBX],'-'
INC EBX
@@2:
MOV [EDI],BL { s^++ := Chr(i); }
INC EDI
MOV ECX,[ESP+20] { spaceCnt := width - i; }
CMP ECX,255
JLE @@3
MOV ECX,255
@@3:
SUB ECX,EBX
JLE @@repeat2 { for k := 1 to spaceCnt do s^++ := ' '; }
ADD [EDI-1],CL
MOV AL,' '
REP STOSB
@@repeat2: { repeat }
MOV AL,[ESP+EBX-1] { s^ := a[i-1]; }
MOV [EDI],AL
INC EDI { s := s + 1 }
DEC EBX { i := i - 1; }
JNZ @@repeat2 { until i = 0; }
ADD ESP,20+4
POP EDI
POP ESI
POP EBX
end;
{$ENDIF}
procedure _Str0Long(val: Longint; s: PShortString);
begin
_StrLong(val, 0, s);
end;
procedure _Truncate(var f: TFileRec);
{$IFDEF LINUX}
begin
if (f.Mode and fmOutput) = fmOutput then // fmOutput or fmInOut
begin
if _ftruncate(f.Handle, _lseek(f.Handle, 0, SEEK_CUR)) = -1 then
InOutError;
end
else
SetInOutRes(103);
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
asm
// -> EAX Pointer to text or file variable
MOVZX EDX,[EAX].TFileRec.Mode // check whether file is open
SUB EDX,fmInput
CMP EDX,fmInOut-fmInput
JA @@fileNotOpen
PUSH [EAX].TFileRec.Handle
CALL SetEndOfFile
DEC EAX
JZ @@exit
JMP InOutError
@@fileNotOpen:
MOV EAX,103
JMP SetInOutRes
@@exit:
end;
{$ENDIF}
function _ValLong(const s: String; var code: Integer): Longint;
{$IFDEF PUREPASCAL}
var
I: Integer;
Negative, Hex: Boolean;
begin
I := 1;
code := -1;
Result := 0;
Negative := False;
Hex := False;
while (I <= Length(s)) and (s[I] = ' ') do Inc(I);
if I > Length(s) then Exit;
case s[I] of
'$',
'x',
'X': begin
Hex := True;
Inc(I);
end;
'0': begin
Hex := (Length(s) > I) and (UpCase(s[I+1]) = 'X');
if Hex then Inc(I,2);
end;
'-': begin
Negative := True;
Inc(I);
end;
'+': Inc(I);
end;
if Hex then
while I <= Length(s) do
begin
if Result > (High(Result) div 16) then
begin
code := I;
Exit;
end;
case s[I] of
'0'..'9': Result := Result * 16 + Ord(s[I]) - Ord('0');
'a'..'f': Result := Result * 16 + Ord(s[I]) - Ord('a') + 10;
'A'..'F': Result := Result * 16 + Ord(s[I]) - Ord('A') + 10;
else
code := I;
Exit;
end;
end
else
while I <= Length(s) do
begin
if Result > (High(Result) div 10) then
begin
code := I;
Exit;
end;
Result := Result * 10 + Ord(s[I]) - Ord('0');
Inc(I);
end;
if Negative then
Result := -Result;
code := 0;
end;
{$ELSE}
asm
{ FUNCTION _ValLong( s: AnsiString; VAR code: Integer ) : Longint; }
{ ->EAX Pointer to string }
{ EDX Pointer to code result }
{ <-EAX Result }
PUSH EBX
PUSH ESI
PUSH EDI
MOV ESI,EAX
PUSH EAX { save for the error case }
TEST EAX,EAX
JE @@empty
XOR EAX,EAX
XOR EBX,EBX
MOV EDI,07FFFFFFFH / 10 { limit }
@@blankLoop:
MOV BL,[ESI]
INC ESI
CMP BL,' '
JE @@blankLoop
@@endBlanks:
MOV CH,0
CMP BL,'-'
JE @@minus
CMP BL,'+'
JE @@plus
CMP BL,'$'
JE @@dollar
CMP BL, 'x'
JE @@dollar
CMP BL, 'X'
JE @@dollar
CMP BL, '0'
JNE @@firstDigit
MOV BL, [ESI]
INC ESI
CMP BL, 'x'
JE @@dollar
CMP BL, 'X'
JE @@dollar
TEST BL, BL
JE @@endDigits
JMP @@digLoop
@@firstDigit:
TEST BL,BL
JE @@error
@@digLoop:
SUB BL,'0'
CMP BL,9
JA @@error
CMP EAX,EDI { value > limit ? }
JA @@overFlow
LEA EAX,[EAX+EAX*4]
ADD EAX,EAX
ADD EAX,EBX { fortunately, we can't have a carry }
MOV BL,[ESI]
INC ESI
TEST BL,BL
JNE @@digLoop
@@endDigits:
DEC CH
JE @@negate
TEST EAX,EAX
JGE @@successExit
JMP @@overFlow
@@empty:
INC ESI
JMP @@error
@@negate:
NEG EAX
JLE @@successExit
JS @@successExit { to handle 2**31 correctly, where the negate overflows }
@@error:
@@overFlow:
POP EBX
SUB ESI,EBX
JMP @@exit
@@minus:
INC CH
@@plus:
MOV BL,[ESI]
INC ESI
JMP @@firstDigit
@@dollar:
MOV EDI,0FFFFFFFH
MOV BL,[ESI]
INC ESI
TEST BL,BL
JZ @@empty
@@hDigLoop:
CMP BL,'a'
JB @@upper
SUB BL,'a' - 'A'
@@upper:
SUB BL,'0'
CMP BL,9
JBE @@digOk
SUB BL,'A' - '0'
CMP BL,5
JA @@error
ADD BL,10
@@digOk:
CMP EAX,EDI
JA @@overFlow
SHL EAX,4
ADD EAX,EBX
MOV BL,[ESI]
INC ESI
TEST BL,BL
JNE @@hDigLoop
@@successExit:
POP ECX { saved copy of string pointer }
XOR ESI,ESI { signal no error to caller }
@@exit:
MOV [EDX],ESI
POP EDI
POP ESI
POP EBX
end;
{$ENDIF}
function _WriteRec(var f: TFileRec; buffer: Pointer): Pointer;
{$IFDEF LINUX}
var
Dummy: Integer;
begin
_BlockWrite(f, Buffer, 1, Dummy);
Result := @F;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
asm
// -> EAX Pointer to file variable
// EDX Pointer to buffer
// <- EAX Pointer to file variable
PUSH EBX
MOV EBX,EAX
MOVZX EAX,[EAX].TFileRec.Mode
SUB EAX,fmOutput
CMP EAX,fmInOut-fmOutput // File must be fmInOut or fmOutput
JA @@fileNotOpen
// WriteFile(f.Handle, buffer, f.RecSize, @result, Nil);
PUSH 0 // space for OS result
MOV EAX,ESP
PUSH 0 // pass lpOverlapped
PUSH EAX // pass @result
PUSH [EBX].TFileRec.RecSize // pass nNumberOfBytesToRead
PUSH EDX // pass lpBuffer
PUSH [EBX].TFileRec.Handle // pass hFile
CALL WriteFile
POP EDX // pop result
DEC EAX // check EAX = TRUE
JNZ @@error
CMP EDX,[EBX].TFileRec.RecSize // result = f.RecSize ?
JE @@exit
@@writeError:
MOV EAX,101
JMP @@errExit
@@fileNotOpen:
MOV EAX,5
JMP @@errExit
@@error:
CALL GetLastError
@@errExit:
CALL SetInOutRes
@@exit:
MOV EAX,EBX
POP EBX
end;
{$ENDIF}
// If the file is Output or ErrOutput std variable, try to open it
// Otherwise, runtime error.
function TryOpenForOutput(var t: TTextRec): Boolean;
begin
if (@t = @Output) or (@t = @ErrOutput) then
begin
t.Flags := tfCRLF * Byte(DefaultTextLineBreakStyle);
_RewritText(t);
end;
Result := t.Mode = fmOutput;
if not Result then
SetInOutRes(105);
end;
function _WriteBytes(var t: TTextRec; const b; cnt : Longint): Pointer;
{$IFDEF PUREPASCAL}
var
P: PChar;
RemainingBytes: Longint;
Temp: Integer;
begin
Result := @t;
if t.Mode <> fmOutput and not TryOpenForOutput(t) then Exit;
P := t.BufPtr + t.BufPos;
RemainingBytes := t.BufSize - t.BufPos;
while RemainingBytes <= cnt do
begin
Inc(t.BufPos, RemainingBytes);
Dec(cnt, RemainingBytes);
Move(B, P^, RemainingBytes);
Temp := TTextIOFunc(t.InOutFunc)(t);
if Temp <> 0 then
begin
SetInOutRes(Temp);
Exit;
end;
P := t.BufPtr + t.BufPos;
RemainingBytes := t.BufSize - t.BufPos;
end;
Inc(t.BufPos, cnt);
Move(B, P^, cnt);
end;
{$ELSE}
asm
// -> EAX Pointer to file record
// EDX Pointer to buffer
// ECX Number of bytes to write
// <- EAX Pointer to file record
PUSH ESI
PUSH EDI
MOV ESI,EDX
CMP [EAX].TTextRec.Mode,fmOutput
JE @@loop
PUSH EAX
PUSH EDX
PUSH ECX
CALL TryOpenForOutput
TEST AL,AL
POP ECX
POP EDX
POP EAX
JE @@exit
@@loop:
MOV EDI,[EAX].TTextRec.BufPtr
ADD EDI,[EAX].TTextRec.BufPos
// remainingBytes = t.bufSize - t.bufPos
MOV EDX,[EAX].TTextRec.BufSize
SUB EDX,[EAX].TTextRec.BufPos
// if (remainingBytes <= cnt)
CMP EDX,ECX
JG @@1
// t.BufPos += remainingBytes, cnt -= remainingBytes
ADD [EAX].TTextRec.BufPos,EDX
SUB ECX,EDX
// copy remainingBytes, advancing ESI
PUSH EAX
PUSH ECX
MOV ECX,EDX
REP MOVSB
CALL [EAX].TTextRec.InOutFunc
TEST EAX,EAX
JNZ @@error
POP ECX
POP EAX
JMP @@loop
@@error:
CALL SetInOutRes
POP ECX
POP EAX
JMP @@exit
@@1:
ADD [EAX].TTextRec.BufPos,ECX
REP MOVSB
@@exit:
POP EDI
POP ESI
end;
{$ENDIF}
function _WriteSpaces(var t: TTextRec; cnt: Longint): Pointer;
{$IFDEF PUREPASCAL}
const
s64Spaces = ' ';
begin
Result := @t;
while cnt > 64 do
begin
_WriteBytes(t, s64Spaces, 64);
if InOutRes <> 0 then Exit;
Dec(cnt, 64);
end;
if cnt > 0 then
_WriteBytes(t, s64Spaces, cnt);
end;
{$ELSE}
const
spCnt = 64;
asm
// -> EAX Pointer to text record
// EDX Number of spaces (<= 0: None)
MOV ECX,EDX
@@loop:
{$IFDEF PIC}
LEA EDX, [EBX] + offset @@spBuf
{$ELSE}
MOV EDX,offset @@spBuf
{$ENDIF}
CMP ECX,spCnt
JLE @@1
SUB ECX,spCnt
PUSH EAX
PUSH ECX
MOV ECX,spCnt
CALL _WriteBytes
CALL SysInit.@GetTLS
CMP [EAX].InOutRes,0
JNE @@error
POP ECX
POP EAX
JMP @@loop
@@error:
POP ECX
POP EAX
JMP @@exit
@@spBuf: // 64 spaces
DB ' ';
@@1:
TEST ECX,ECX
JG _WriteBytes
@@exit:
end;
{$ENDIF}
function _Write0Char(var t: TTextRec; c: Char): Pointer;
{$IFDEF PUREPASCAL}
var
Temp: Integer;
begin
Result := @t;
if not TryOpenForOutput(t) then Exit;
if t.BufPos >= t.BufSize then
begin
Temp := TTextIOFunc(t.InOutFunc)(t);
if Temp <> 0 then
begin
SetInOutRes(Temp);
Exit;
end;
end;
t.BufPtr[t.BufPos] := c;
Inc(t.BufPos);
end;
{$ELSE}
asm
// -> EAX Pointer to text record
// DL Character
CMP [EAX].TTextRec.Mode,fmOutput
JE @@loop
PUSH EAX
PUSH EDX
CALL TryOpenForOutput
TEST AL,AL
POP EDX
POP EAX
JNE @@loop
JMP @@exit
@@flush:
PUSH EAX
PUSH EDX
CALL [EAX].TTextRec.InOutFunc
TEST EAX,EAX
JNZ @@error
POP EDX
POP EAX
JMP @@loop
@@error:
CALL SetInOutRes
POP EDX
POP EAX
JMP @@exit
@@loop:
MOV ECX,[EAX].TTextRec.BufPos
CMP ECX,[EAX].TTextRec.BufSize
JGE @@flush
ADD ECX,[EAX].TTextRec.BufPtr
MOV [ECX],DL
INC [EAX].TTextRec.BufPos
@@exit:
end;
{$ENDIF}
function _WriteChar(var t: TTextRec; c: Char; width: Integer): Pointer;
begin
_WriteSpaces(t, width-1);
Result := _WriteBytes(t, c, 1);
end;
function _WriteBool(var t: TTextRec; val: Boolean; width: Longint): Pointer;
const
BoolStrs: array [Boolean] of ShortString = ('FALSE', 'TRUE');
begin
Result := _WriteString(t, BoolStrs[val], width);
end;
function _Write0Bool(var t: TTextRec; val: Boolean): Pointer;
begin
Result := _WriteBool(t, val, 0);
end;
function _WriteLong(var t: TTextRec; val, width: Longint): Pointer;
var
S: string[31];
begin
Str(val:0, S);
Result := _WriteString(t, S, width);
end;
function _Write0Long(var t: TTextRec; val: Longint): Pointer;
begin
Result := _WriteLong(t, val, 0);
end;
function _Write0String(var t: TTextRec; const s: ShortString): Pointer;
begin
Result := _WriteBytes(t, S[1], Byte(S[0]));
end;
function _WriteString(var t: TTextRec; const s: ShortString; width: Longint): Pointer;
begin
_WriteSpaces(t, Width - Byte(S[0]));
Result := _WriteBytes(t, S[1], Byte(S[0]));
end;
function _Write0CString(var t: TTextRec; s: PChar): Pointer;
begin
Result := _WriteCString(t, s, 0);
end;
function _WriteCString(var t: TTextRec; s: PChar; width: Longint): Pointer;
var
len: Longint;
begin
len := _strlen(s);
_WriteSpaces(t, width - len);
Result := _WriteBytes(t, s^, len);
end;
procedure _Write2Ext;
asm
{ PROCEDURE _Write2Ext( VAR t: Text; val: Extended; width, prec: Longint);
->EAX Pointer to file record
[ESP+4] Extended value
EDX Field width
ECX precision (<0: scientific, >= 0: fixed point) }
FLD tbyte ptr [ESP+4] { load value }
SUB ESP,256 { VAR s: String; }
PUSH EAX
PUSH EDX
{ Str( val, width, prec, s ); }
SUB ESP,12
FSTP tbyte ptr [ESP] { pass value }
MOV EAX,EDX { pass field width }
MOV EDX,ECX { pass precision }
LEA ECX,[ESP+8+12] { pass destination string }
CALL _Str2Ext
{ Write( t, s, width ); }
POP ECX { pass width }
POP EAX { pass text }
MOV EDX,ESP { pass string }
CALL _WriteString
ADD ESP,256
RET 12
end;
procedure _Write1Ext;
asm
{ PROCEDURE _Write1Ext( VAR t: Text; val: Extended; width: Longint);
-> EAX Pointer to file record
[ESP+4] Extended value
EDX Field width }
OR ECX,-1
JMP _Write2Ext
end;
procedure _Write0Ext;
asm
{ PROCEDURE _Write0Ext( VAR t: Text; val: Extended);
->EAX Pointer to file record
[ESP+4] Extended value }
MOV EDX,23 { field width }
OR ECX,-1
JMP _Write2Ext
end;
function _WriteLn(var t: TTextRec): Pointer;
var
Buf: array [0..1] of Char;
begin
if (t.flags and tfCRLF) <> 0 then
begin
Buf[0] := #13;
Buf[1] := #10;
Result := _WriteBytes(t, Buf, 2);
end
else
begin
Buf[0] := #10;
Result := _WriteBytes(t, Buf, 1);
end;
_Flush(t);
end;
procedure __CToPasStr(Dest: PShortString; const Source: PChar);
begin
__CLenToPasStr(Dest, Source, 255);
end;
procedure __CLenToPasStr(Dest: PShortString; const Source: PChar; MaxLen: Integer);
{$IFDEF PUREPASCAL}
var
I: Integer;
begin
I := 0;
if MaxLen > 255 then MaxLen := 255;
while (Source[I] <> #0) and (I <= MaxLen) do
begin
Dest^[I+1] := Source[I];
Inc(I);
end;
if I > 0 then Dec(I);
Byte(Dest^[0]) := I;
end;
{$ELSE}
asm
{ ->EAX Pointer to destination }
{ EDX Pointer to source }
{ ECX cnt }
PUSH EBX
PUSH EAX { save destination }
CMP ECX,255
JBE @@loop
MOV ECX,255
@@loop:
MOV BL,[EDX] { ch = *src++; }
INC EDX
TEST BL,BL { if (ch == 0) break }
JE @@endLoop
INC EAX { *++dest = ch; }
MOV [EAX],BL
DEC ECX { while (--cnt != 0) }
JNZ @@loop
@@endLoop:
POP EDX
SUB EAX,EDX
MOV [EDX],AL
POP EBX
end;
{$ENDIF}
procedure __ArrayToPasStr(Dest: PShortString; const Source: PChar; Len: Integer);
begin
if Len > 255 then Len := 255;
Byte(Dest^[0]) := Len;
Move(Source^, Dest^[1], Len);
end;
procedure __PasToCStr(const Source: PShortString; const Dest: PChar);
begin
Move(Source^[1], Dest^, Byte(Source^[0]));
Dest[Byte(Source^[0])] := #0;
end;
procedure _SetElem;
asm
{ PROCEDURE _SetElem( VAR d: SET; elem, size: Byte); }
{ EAX = dest address }
{ DL = element number }
{ CL = size of set }
PUSH EBX
PUSH EDI
MOV EDI,EAX
XOR EBX,EBX { zero extend set size into ebx }
MOV BL,CL
MOV ECX,EBX { and use it for the fill }
XOR EAX,EAX { for zero fill }
REP STOSB
SUB EDI,EBX { point edi at beginning of set again }
INC EAX { eax is still zero - make it 1 }
MOV CL,DL
ROL AL,CL { generate a mask }
SHR ECX,3 { generate the index }
CMP ECX,EBX { if index >= siz then exit }
JAE @@exit
OR [EDI+ECX],AL{ set bit }
@@exit:
POP EDI
POP EBX
end;
procedure _SetRange;
asm
{ PROCEDURE _SetRange( lo, hi, size: Byte; VAR d: SET ); }
{ ->AL low limit of range }
{ DL high limit of range }
{ ECX Pointer to set }
{ AH size of set }
PUSH EBX
PUSH ESI
PUSH EDI
XOR EBX,EBX { EBX = set size }
MOV BL,AH
MOVZX ESI,AL { ESI = low zero extended }
MOVZX EDX,DL { EDX = high zero extended }
MOV EDI,ECX
{ clear the set }
MOV ECX,EBX
XOR EAX,EAX
REP STOSB
{ prepare for setting the bits }
SUB EDI,EBX { point EDI at start of set }
SHL EBX,3 { EBX = highest bit in set + 1 }
CMP EDX,EBX
JB @@inrange
LEA EDX,[EBX-1] { ECX = highest bit in set }
@@inrange:
CMP ESI,EDX { if lo > hi then exit; }
JA @@exit
DEC EAX { loMask = 0xff << (lo & 7) }
MOV ECX,ESI
AND CL,07H
SHL AL,CL
SHR ESI,3 { loIndex = lo >> 3; }
MOV CL,DL { hiMask = 0xff >> (7 - (hi & 7)); }
NOT CL
AND CL,07
SHR AH,CL
SHR EDX,3 { hiIndex = hi >> 3; }
ADD EDI,ESI { point EDI to set[loIndex] }
MOV ECX,EDX
SUB ECX,ESI { if ((inxDiff = (hiIndex - loIndex)) == 0) }
JNE @@else
AND AL,AH { set[loIndex] = hiMask & loMask; }
MOV [EDI],AL
JMP @@exit
@@else:
STOSB { set[loIndex++] = loMask; }
DEC ECX
MOV AL,0FFH { while (loIndex < hiIndex) }
REP STOSB { set[loIndex++] = 0xff; }
MOV [EDI],AH { set[hiIndex] = hiMask; }
@@exit:
POP EDI
POP ESI
POP EBX
end;
procedure _SetEq;
asm
{ FUNCTION _SetEq( CONST l, r: Set; size: Byte): ConditionCode; }
{ EAX = left operand }
{ EDX = right operand }
{ CL = size of set }
PUSH ESI
PUSH EDI
MOV ESI,EAX
MOV EDI,EDX
AND ECX,0FFH
REP CMPSB
POP EDI
POP ESI
end;
procedure _SetLe;
asm
{ FUNCTION _SetLe( CONST l, r: Set; size: Byte): ConditionCode; }
{ EAX = left operand }
{ EDX = right operand }
{ CL = size of set (>0 && <= 32) }
@@loop:
MOV CH,[EDX]
NOT CH
AND CH,[EAX]
JNE @@exit
INC EDX
INC EAX
DEC CL
JNZ @@loop
@@exit:
end;
procedure _SetIntersect;
asm
{ PROCEDURE _SetIntersect( VAR dest: Set; CONST src: Set; size: Byte);}
{ EAX = destination operand }
{ EDX = source operand }
{ CL = size of set (0 < size <= 32) }
@@loop:
MOV CH,[EDX]
INC EDX
AND [EAX],CH
INC EAX
DEC CL
JNZ @@loop
end;
procedure _SetIntersect3;
asm
{ PROCEDURE _SetIntersect3( VAR dest: Set; CONST src: Set; size: Longint; src2: Set);}
{ EAX = destination operand }
{ EDX = source operand }
{ ECX = size of set (0 < size <= 32) }
{ [ESP+4] = 2nd source operand }
PUSH EBX
PUSH ESI
MOV ESI,[ESP+8+4]
@@loop:
MOV BL,[EDX+ECX-1]
AND BL,[ESI+ECX-1]
MOV [EAX+ECX-1],BL
DEC ECX
JNZ @@loop
POP ESI
POP EBX
end;
procedure _SetUnion;
asm
{ PROCEDURE _SetUnion( VAR dest: Set; CONST src: Set; size: Byte); }
{ EAX = destination operand }
{ EDX = source operand }
{ CL = size of set (0 < size <= 32) }
@@loop:
MOV CH,[EDX]
INC EDX
OR [EAX],CH
INC EAX
DEC CL
JNZ @@loop
end;
procedure _SetUnion3;
asm
{ PROCEDURE _SetUnion3( VAR dest: Set; CONST src: Set; size: Longint; src2: Set);}
{ EAX = destination operand }
{ EDX = source operand }
{ ECX = size of set (0 < size <= 32) }
{ [ESP+4] = 2nd source operand }
PUSH EBX
PUSH ESI
MOV ESI,[ESP+8+4]
@@loop:
MOV BL,[EDX+ECX-1]
OR BL,[ESI+ECX-1]
MOV [EAX+ECX-1],BL
DEC ECX
JNZ @@loop
POP ESI
POP EBX
end;
procedure _SetSub;
asm
{ PROCEDURE _SetSub( VAR dest: Set; CONST src: Set; size: Byte); }
{ EAX = destination operand }
{ EDX = source operand }
{ CL = size of set (0 < size <= 32) }
@@loop:
MOV CH,[EDX]
NOT CH
INC EDX
AND [EAX],CH
INC EAX
DEC CL
JNZ @@loop
end;
procedure _SetSub3;
asm
{ PROCEDURE _SetSub3( VAR dest: Set; CONST src: Set; size: Longint; src2: Set);}
{ EAX = destination operand }
{ EDX = source operand }
{ ECX = size of set (0 < size <= 32) }
{ [ESP+4] = 2nd source operand }
PUSH EBX
PUSH ESI
MOV ESI,[ESP+8+4]
@@loop:
MOV BL,[ESI+ECX-1]
NOT BL
AND BL,[EDX+ECX-1]
MOV [EAX+ECX-1],BL
DEC ECX
JNZ @@loop
POP ESI
POP EBX
end;
procedure _SetExpand;
asm
{ PROCEDURE _SetExpand( CONST src: Set; VAR dest: Set; lo, hi: Byte); }
{ ->EAX Pointer to source (packed set) }
{ EDX Pointer to destination (expanded set) }
{ CH high byte of source }
{ CL low byte of source }
{ algorithm: }
{ clear low bytes }
{ copy high-low+1 bytes }
{ clear 31-high bytes }
PUSH ESI
PUSH EDI
MOV ESI,EAX
MOV EDI,EDX
MOV EDX,ECX { save low, high in dl, dh }
XOR ECX,ECX
XOR EAX,EAX
MOV CL,DL { clear low bytes }
REP STOSB
MOV CL,DH { copy high - low bytes }
SUB CL,DL
REP MOVSB
MOV CL,32 { copy 32 - high bytes }
SUB CL,DH
REP STOSB
POP EDI
POP ESI
end;
procedure _EmitDigits;
const
tenE17: Double = 1e17;
tenE18: Double = 1e18;
asm
// -> FST(0) Value, 0 <= value < 10.0
// EAX Count of digits to generate
// EDX Pointer to digit buffer
PUSH EBX
{$IFDEF PIC}
PUSH EAX
CALL GetGOT
MOV EBX,EAX
POP EAX
{$ELSE}
XOR EBX,EBX
{$ENDIF}
PUSH EDI
MOV EDI,EDX
MOV ECX,EAX
SUB ESP,10 // VAR bcdBuf: array [0..9] of Byte
MOV byte ptr [EDI],'0' // digBuf[0] := '0'//
FMUL qword ptr [EBX] + offset tenE17 // val := Round(val*1e17);
FRNDINT
FCOM qword ptr [EBX] + offset tenE18 // if val >= 1e18 then
FSTSW AX
SAHF
JB @@1
FSUB qword ptr [EBX] + offset tenE18 // val := val - 1e18;
MOV byte ptr [EDI],'1' // digBuf[0] := '1';
@@1:
FBSTP tbyte ptr [ESP] // store packed bcd digits in bcdBuf
MOV EDX,8
INC EDI
@@2:
WAIT
MOV AL,[ESP+EDX] // unpack 18 bcd digits in 9 bytes
MOV AH,AL // into 9 words = 18 bytes
SHR AL,4
AND AH,0FH
ADD AX,'00'
STOSW
DEC EDX
JNS @@2
SUB ECX,18 // we need at least digCnt digits
JL @@3 // we have generated 18
MOV AL,'0' // if this is not enough, append zeroes
REP STOSB
JMP @@4 // in this case, we don't need to round
@@3:
ADD EDI,ECX // point EDI to the round digit
CMP byte ptr [EDI],'5'
JL @@4
@@5:
DEC EDI
INC byte ptr [EDI]
CMP byte ptr [EDI],'9'
JLE @@4
MOV byte ptr [EDI],'0'
JMP @@5
@@4:
ADD ESP,10
POP EDI
POP EBX
end;
procedure _ScaleExt;
asm
// -> FST(0) Value
// <- EAX exponent (base 10)
// FST(0) Value / 10**eax
// PIC safe - uses EBX, but only call is to _POW10, which fixes up EBX itself
PUSH EBX
SUB ESP,12
XOR EBX,EBX
@@normLoop: // loop necessary for denormals
FLD ST(0)
FSTP tbyte ptr [ESP]
MOV AX,[ESP+8]
TEST AX,AX
JE @@testZero
@@cont:
SUB AX,3FFFH
MOV DX,4D10H // log10(2) * 2**16
IMUL DX
MOVSX EAX,DX // exp10 = exp2 * log10(2)
NEG EAX
JE @@exit
SUB EBX,EAX
CALL _Pow10
JMP @@normLoop
@@testZero:
CMP dword ptr [ESP+4],0
JNE @@cont
CMP dword ptr [ESP+0],0
JNE @@cont
@@exit:
ADD ESP,12
MOV EAX,EBX
POP EBX
end;
const
Ten: Double = 10.0;
NanStr: String[3] = 'Nan';
PlusInfStr: String[4] = '+Inf';
MinInfStr: String[4] = '-Inf';
procedure _Str2Ext;//( val: Extended; width, precision: Longint; var s: String );
const
MAXDIGS = 256;
asm
// -> [ESP+4] Extended value
// EAX Width
// EDX Precision
// ECX Pointer to string
FLD tbyte ptr [ESP+4]
PUSH EBX
PUSH ESI
PUSH EDI
MOV EBX,EAX
MOV ESI,EDX
PUSH ECX // save string pointer
SUB ESP,MAXDIGS // VAR digBuf: array [0..MAXDIGS-1] of Char
// limit width to 255
CMP EBX,255 // if width > 255 then width := 255;
JLE @@1
MOV EBX,255
@@1:
// save sign bit in bit 0 of EDI, take absolute value of val, check for
// Nan and infinity.
FLD ST(0)
FSTP tbyte ptr [ESP]
XOR EAX,EAX
MOV AX,word ptr [ESP+8]
MOV EDI,EAX
SHR EDI,15
AND AX,7FFFH
CMP AX,7FFFH
JE @@nanInf
FABS
// if precision < 0 then do scientific else do fixed;
TEST ESI,ESI
JGE @@fixed
// the following call finds a decimal exponent and a reduced
// mantissa such that val = mant * 10**exp
CALL _ScaleExt // val is FST(0), exp is EAX
// for scientific notation, we have width - 8 significant digits
// however, we can not have less than 2 or more than 18 digits.
@@scientific:
MOV ESI,EBX // digCnt := width - 8;
SUB ESI,8
CMP ESI,2 // if digCnt < 2 then digCnt := 2
JGE @@2
MOV ESI,2
JMP @@3
@@2:
CMP ESI,18 // else if digCnt > 18 then digCnt := 18;
JLE @@3
MOV ESI,18
@@3:
// _EmitDigits( val, digCnt, digBuf )
MOV EDX,ESP // pass digBuf
PUSH EAX // save exponent
MOV EAX,ESI // pass digCnt
CALL _EmitDigits // convert val to ASCII
MOV EDX,EDI // save sign in EDX
MOV EDI,[ESP+MAXDIGS+4] // load result string pointer
MOV [EDI],BL // length of result string := width
INC EDI
MOV AL,' ' // prepare for leading blanks and sign
MOV ECX,EBX // blankCnt := width - digCnt - 8
SUB ECX,ESI
SUB ECX,8
JLE @@4
REP STOSB // emit blankCnt blanks
@@4:
SUB [EDI-1],CL // if blankCnt < 0, adjust length
TEST DL,DL // emit the sign (' ' or '-')
JE @@5
MOV AL,'-'
@@5:
STOSB
POP EAX
MOV ECX,ESI // emit digCnt digits
MOV ESI,ESP // point ESI to digBuf
CMP byte ptr [ESI],'0'
JE @@5a // if rounding overflowed, adjust exponent and ESI
INC EAX
DEC ESI
@@5a:
INC ESI
MOVSB // emit one digit
MOV byte ptr [EDI],'.' // emit dot
INC EDI // adjust dest pointer
DEC ECX // adjust count
REP MOVSB
MOV byte ptr [EDI],'E'
MOV CL,'+' // emit sign of exponent ('+' or '-')
TEST EAX,EAX
JGE @@6
MOV CL,'-'
NEG EAX
@@6:
MOV [EDI+1],CL
XOR EDX,EDX // emit exponent
MOV CX,10
DIV CX
ADD DL,'0'
MOV [EDI+5],DL
XOR EDX,EDX
DIV CX
ADD DL,'0'
MOV [EDI+4],DL
XOR EDX,EDX
DIV CX
ADD DL,'0'
MOV [EDI+3],DL
ADD AL,'0'
MOV [EDI+2],AL
JMP @@exit
@@fixed:
// FST(0) = value >= 0.0
// EBX = width
// ESI = precision
// EDI = sign
CMP ESI,MAXDIGS-40 // else if precision > MAXDIGS-40 then precision := MAXDIGS-40;
JLE @@6a
MOV ESI,MAXDIGS-40
@@6a:
{$IFDEF PIC}
PUSH EAX
CALL GetGOT
FCOM qword ptr [EAX] + offset Ten
POP EAX
{$ELSE}
FCOM qword ptr ten
{$ENDIF}
FSTSW AX
SAHF
MOV EAX,0
JB @@7
CALL _ScaleExt // val is FST(0), exp is EAX
CMP EAX,35 // if val is too large, use scientific
JG @@scientific
@@7:
// FST(0) = scaled value, 0.0 <= value < 10.0
// EAX = exponent, 0 <= exponent
// intDigCnt := exponent + 1;
INC EAX
// _EmitDigits( value, intDigCnt + precision, digBuf );
MOV EDX,ESP
PUSH EAX
ADD EAX,ESI
CALL _EmitDigits
POP EAX
// Now we need to check whether rounding to the right number of
// digits overflowed, and if so, adjust things accordingly
MOV EDX,ESI // put precision in EDX
MOV ESI,ESP // point EDI to digBuf
CMP byte ptr [ESI],'0'
JE @@8
INC EAX
DEC ESI
@@8:
INC ESI
MOV ECX,EAX // numWidth := sign + intDigCnt;
ADD ECX,EDI
TEST EDX,EDX // if precision > 0 then
JE @@9
INC ECX // numWidth := numWidth + 1 + precision
ADD ECX,EDX
CMP EBX,ECX // if width <= numWidth
JG @@9
MOV EBX,ECX // width := numWidth
@@9:
PUSH EAX
PUSH EDI
MOV EDI,[ESP+MAXDIGS+2*4] // point EDI to dest string
MOV [EDI],BL // store final length in dest string
INC EDI
SUB EBX,ECX // width := width - numWidth
MOV ECX,EBX
JLE @@10
MOV AL,' ' // emit width blanks
REP STOSB
@@10:
SUB [EDI-1],CL // if blankCnt < 0, adjust length
POP EAX
POP ECX
TEST EAX,EAX
JE @@11
MOV byte ptr [EDI],'-'
INC EDI
@@11:
REP MOVSB // copy intDigCnt digits
TEST EDX,EDX // if precision > 0 then
JE @@12
MOV byte ptr [EDI],'.' // emit '.'
INC EDI
MOV ECX,EDX // emit precision digits
REP MOVSB
@@12:
@@exit:
ADD ESP,MAXDIGS
POP ECX
POP EDI
POP ESI
POP EBX
RET 12
@@nanInf:
// here: EBX = width, ECX = string pointer, EDI = sign, [ESP] = value
{$IFDEF PIC}
CALL GetGOT
{$ELSE}
XOR EAX,EAX
{$ENDIF}
FSTP ST(0)
CMP dword ptr [ESP+4],80000000H
LEA ESI,[EAX] + offset nanStr
JNE @@13
DEC EDI
LEA ESI,[EAX] + offset plusInfStr
JNZ @@13
LEA ESI,[EAX] + offset minInfStr
@@13:
MOV EDI,ECX
MOV ECX,EBX
MOV [EDI],CL
INC EDI
SUB CL,[ESI]
JBE @@14
MOV AL,' '
REP STOSB
@@14:
SUB [EDI-1],CL
MOV CL,[ESI]
INC ESI
REP MOVSB
JMP @@exit
end;
procedure _Str0Ext;
asm
// -> [ESP+4] Extended value
// EAX Pointer to string
MOV ECX,EAX // pass string
MOV EAX,23 // pass default field width
OR EDX,-1 // pass precision -1
JMP _Str2Ext
end;
procedure _Str1Ext;//( val: Extended; width: Longint; var s: String );
asm
// -> [ESP+4] Extended value
// EAX Field width
// EDX Pointer to string
MOV ECX,EDX
OR EDX,-1 // pass precision -1
JMP _Str2Ext
end;
//function _ValExt( s: AnsiString; VAR code: Integer ) : Extended;
procedure _ValExt;
asm
// -> EAX Pointer to string
// EDX Pointer to code result
// <- FST(0) Result
PUSH EBX
{$IFDEF PIC}
PUSH EAX
CALL GetGOT
MOV EBX,EAX
POP EAX
{$ELSE}
XOR EBX,EBX
{$ENDIF}
PUSH ESI
PUSH EDI
PUSH EBX // SaveGOT = ESP+8
MOV ESI,EAX
PUSH EAX // save for the error case
FLDZ
XOR EAX,EAX
XOR EBX,EBX
XOR EDI,EDI
PUSH EBX // temp to get digs to fpu
TEST ESI,ESI
JE @@empty
@@blankLoop:
MOV BL,[ESI]
INC ESI
CMP BL,' '
JE @@blankLoop
@@endBlanks:
MOV CH,0
CMP BL,'-'
JE @@minus
CMP BL,'+'
JE @@plus
JMP @@firstDigit
@@minus:
INC CH
@@plus:
MOV BL,[ESI]
INC ESI
@@firstDigit:
TEST BL,BL
JE @@error
MOV EDI,[ESP+8] // SaveGOT
@@digLoop:
SUB BL,'0'
CMP BL,9
JA @@dotExp
FMUL qword ptr [EDI] + offset Ten
MOV dword ptr [ESP],EBX
FIADD dword ptr [ESP]
MOV BL,[ESI]
INC ESI
TEST BL,BL
JNE @@digLoop
JMP @@prefinish
@@dotExp:
CMP BL,'.' - '0'
JNE @@exp
MOV BL,[ESI]
INC ESI
TEST BL,BL
JE @@prefinish
// EDI = SaveGot
@@fracDigLoop:
SUB BL,'0'
CMP BL,9
JA @@exp
FMUL qword ptr [EDI] + offset Ten
MOV dword ptr [ESP],EBX
FIADD dword ptr [ESP]
DEC EAX
MOV BL,[ESI]
INC ESI
TEST BL,BL
JNE @@fracDigLoop
@@prefinish:
XOR EDI,EDI
JMP @@finish
@@exp:
CMP BL,'E' - '0'
JE @@foundExp
CMP BL,'e' - '0'
JNE @@error
@@foundExp:
MOV BL,[ESI]
INC ESI
MOV AH,0
CMP BL,'-'
JE @@minusExp
CMP BL,'+'
JE @@plusExp
JMP @@firstExpDigit
@@minusExp:
INC AH
@@plusExp:
MOV BL,[ESI]
INC ESI
@@firstExpDigit:
SUB BL,'0'
CMP BL,9
JA @@error
MOV EDI,EBX
MOV BL,[ESI]
INC ESI
TEST BL,BL
JZ @@endExp
@@expDigLoop:
SUB BL,'0'
CMP BL,9
JA @@error
LEA EDI,[EDI+EDI*4]
ADD EDI,EDI
ADD EDI,EBX
MOV BL,[ESI]
INC ESI
TEST BL,BL
JNZ @@expDigLoop
@@endExp:
DEC AH
JNZ @@expPositive
NEG EDI
@@expPositive:
MOVSX EAX,AL
@@finish:
ADD EAX,EDI
PUSH EDX
PUSH ECX
CALL _Pow10
POP ECX
POP EDX
DEC CH
JE @@negate
@@successExit:
ADD ESP,12 // pop temp and saved copy of string pointer
XOR ESI,ESI // signal no error to caller
@@exit:
MOV [EDX],ESI
POP EDI
POP ESI
POP EBX
RET
@@negate:
FCHS
JMP @@successExit
@@empty:
INC ESI
@@error:
POP EAX
POP EBX
SUB ESI,EBX
ADD ESP,4
JMP @@exit
end;
procedure FPower10;
asm
JMP _Pow10
end;
//function _Pow10(val: Extended; Power: Integer): Extended;
procedure _Pow10;
asm
// -> FST(0) val
// -> EAX Power
// <- FST(0) val * 10**Power
// This routine generates 10**power with no more than two
// floating point multiplications. Up to 10**31, no multiplications
// are needed.
PUSH EBX
{$IFDEF PIC}
PUSH EAX
CALL GetGOT
MOV EBX,EAX
POP EAX
{$ELSE}
XOR EBX,EBX
{$ENDIF}
TEST EAX,EAX
JL @@neg
JE @@exit
CMP EAX,5120
JGE @@inf
MOV EDX,EAX
AND EDX,01FH
LEA EDX,[EDX+EDX*4]
FLD tbyte ptr @@tab0[EBX+EDX*2]
FMULP
SHR EAX,5
JE @@exit
MOV EDX,EAX
AND EDX,0FH
JE @@skip2ndMul
LEA EDX,[EDX+EDX*4]
FLD tbyte ptr @@tab1-10[EBX+EDX*2]
FMULP
@@skip2ndMul:
SHR EAX,4
JE @@exit
LEA EAX,[EAX+EAX*4]
FLD tbyte ptr @@tab2-10[EBX+EAX*2]
FMULP
JMP @@exit
@@neg:
NEG EAX
CMP EAX,5120
JGE @@zero
MOV EDX,EAX
AND EDX,01FH
LEA EDX,[EDX+EDX*4]
FLD tbyte ptr @@tab0[EBX+EDX*2]
FDIVP
SHR EAX,5
JE @@exit
MOV EDX,EAX
AND EDX,0FH
JE @@skip2ndDiv
LEA EDX,[EDX+EDX*4]
FLD tbyte ptr @@tab1-10[EBX+EDX*2]
FDIVP
@@skip2ndDiv:
SHR EAX,4
JE @@exit
LEA EAX,[EAX+EAX*4]
FLD tbyte ptr @@tab2-10[EBX+EAX*2]
FDIVP
JMP @@exit
@@inf:
FLD tbyte ptr @@infval[EBX]
JMP @@exit
@@zero:
FLDZ
@@exit:
POP EBX
RET
@@infval: DW $0000,$0000,$0000,$8000,$7FFF
@@tab0: DW $0000,$0000,$0000,$8000,$3FFF // 10**0
DW $0000,$0000,$0000,$A000,$4002 // 10**1
DW $0000,$0000,$0000,$C800,$4005 // 10**2
DW $0000,$0000,$0000,$FA00,$4008 // 10**3
DW $0000,$0000,$0000,$9C40,$400C // 10**4
DW $0000,$0000,$0000,$C350,$400F // 10**5
DW $0000,$0000,$0000,$F424,$4012 // 10**6
DW $0000,$0000,$8000,$9896,$4016 // 10**7
DW $0000,$0000,$2000,$BEBC,$4019 // 10**8
DW $0000,$0000,$2800,$EE6B,$401C // 10**9
DW $0000,$0000,$F900,$9502,$4020 // 10**10
DW $0000,$0000,$B740,$BA43,$4023 // 10**11
DW $0000,$0000,$A510,$E8D4,$4026 // 10**12
DW $0000,$0000,$E72A,$9184,$402A // 10**13
DW $0000,$8000,$20F4,$B5E6,$402D // 10**14
DW $0000,$A000,$A931,$E35F,$4030 // 10**15
DW $0000,$0400,$C9BF,$8E1B,$4034 // 10**16
DW $0000,$C500,$BC2E,$B1A2,$4037 // 10**17
DW $0000,$7640,$6B3A,$DE0B,$403A // 10**18
DW $0000,$89E8,$2304,$8AC7,$403E // 10**19
DW $0000,$AC62,$EBC5,$AD78,$4041 // 10**20
DW $8000,$177A,$26B7,$D8D7,$4044 // 10**21
DW $9000,$6EAC,$7832,$8786,$4048 // 10**22
DW $B400,$0A57,$163F,$A968,$404B // 10**23
DW $A100,$CCED,$1BCE,$D3C2,$404E // 10**24
DW $84A0,$4014,$5161,$8459,$4052 // 10**25
DW $A5C8,$9019,$A5B9,$A56F,$4055 // 10**26
DW $0F3A,$F420,$8F27,$CECB,$4058 // 10**27
DW $0984,$F894,$3978,$813F,$405C // 10**28
DW $0BE5,$36B9,$07D7,$A18F,$405F // 10**29
DW $4EDF,$0467,$C9CD,$C9F2,$4062 // 10**30
DW $2296,$4581,$7C40,$FC6F,$4065 // 10**31
@@tab1: DW $B59E,$2B70,$ADA8,$9DC5,$4069 // 10**32
DW $A6D5,$FFCF,$1F49,$C278,$40D3 // 10**64
DW $14A3,$C59B,$AB16,$EFB3,$413D // 10**96
DW $8CE0,$80E9,$47C9,$93BA,$41A8 // 10**128
DW $17AA,$7FE6,$A12B,$B616,$4212 // 10**160
DW $556B,$3927,$F78D,$E070,$427C // 10**192
DW $C930,$E33C,$96FF,$8A52,$42E7 // 10**224
DW $DE8E,$9DF9,$EBFB,$AA7E,$4351 // 10**256
DW $2F8C,$5C6A,$FC19,$D226,$43BB // 10**288
DW $E376,$F2CC,$2F29,$8184,$4426 // 10**320
DW $0AD2,$DB90,$2700,$9FA4,$4490 // 10**352
DW $AA17,$AEF8,$E310,$C4C5,$44FA // 10**384
DW $9C59,$E9B0,$9C07,$F28A,$4564 // 10**416
DW $F3D4,$EBF7,$4AE1,$957A,$45CF // 10**448
DW $A262,$0795,$D8DC,$B83E,$4639 // 10**480
@@tab2: DW $91C7,$A60E,$A0AE,$E319,$46A3 // 10**512
DW $0C17,$8175,$7586,$C976,$4D48 // 10**1024
DW $A7E4,$3993,$353B,$B2B8,$53ED // 10**1536
DW $5DE5,$C53D,$3B5D,$9E8B,$5A92 // 10**2048
DW $F0A6,$20A1,$54C0,$8CA5,$6137 // 10**2560
DW $5A8B,$D88B,$5D25,$F989,$67DB // 10**3072
DW $F3F8,$BF27,$C8A2,$DD5D,$6E80 // 10**3584
DW $979B,$8A20,$5202,$C460,$7525 // 10**4096
DW $59F0,$6ED5,$1162,$AE35,$7BCA // 10**4608
end;
const
RealBias = 129;
ExtBias = $3FFF;
procedure _Real2Ext;//( val : Real ) : Extended;
asm
// -> EAX Pointer to value
// <- FST(0) Result
// the REAL data type has the following format:
// 8 bit exponent (bias 129), 39 bit fraction, 1 bit sign
MOV DH,[EAX+5] // isolate the sign bit
AND DH,80H
MOV DL,[EAX] // fetch exponent
TEST DL,DL // exponent zero means number is zero
JE @@zero
ADD DX,ExtBias-RealBias // adjust exponent bias
PUSH EDX // the exponent is at the highest address
MOV EDX,[EAX+2] // load high fraction part, set hidden bit
OR EDX,80000000H
PUSH EDX // push high fraction part
MOV DL,[EAX+1] // load remaining low byte of fraction
SHL EDX,24 // clear low 24 bits
PUSH EDX
FLD tbyte ptr [ESP] // pop result onto chip
ADD ESP,12
RET
@@zero:
FLDZ
RET
end;
procedure _Ext2Real;//( val : Extended ) : Real;
asm
// -> FST(0) Value
// EAX Pointer to result
PUSH EBX
SUB ESP,12
FSTP tbyte ptr [ESP]
POP EBX // EBX is low half of fraction
POP EDX // EDX is high half of fraction
POP ECX // CX is exponent and sign
SHR EBX,24 // set carry to last bit shifted out
ADC BL,0 // if bit was 1, round up
ADC EDX,0
ADC CX,0
JO @@overflow
ADD EDX,EDX // shift fraction 1 bit left
ADD CX,CX // shift sign bit into carry
RCR EDX,1 // attach sign bit to fraction
SHR CX,1 // restore exponent, deleting sign
SUB CX,ExtBias-RealBias // adjust exponent
JLE @@underflow
TEST CH,CH // CX must be in 1..255
JG @@overflow
MOV [EAX],CL
MOV [EAX+1],BL
MOV [EAX+2],EDX
POP EBX
RET
@@underflow:
XOR ECX,ECX
MOV [EAX],ECX
MOV [EAX+4],CX
POP EBX
RET
@@overflow:
POP EBX
MOV AL,8
JMP Error
end;
const
ovtInstanceSize = -8; { Offset of instance size in OBJECTs }
ovtVmtPtrOffs = -4;
procedure _ObjSetup;
asm
{ FUNCTION _ObjSetup( self: ^OBJECT; vmt: ^VMT): ^OBJECT; }
{ ->EAX Pointer to self (possibly nil) }
{ EDX Pointer to vmt (possibly nil) }
{ <-EAX Pointer to self }
{ EDX <> 0: an object was allocated }
{ Z-Flag Set: failure, Cleared: Success }
CMP EDX,1 { is vmt = 0, indicating a call }
JAE @@skip1 { from a constructor? }
RET { return immediately with Z-flag cleared }
@@skip1:
PUSH ECX
TEST EAX,EAX { is self already allocated? }
JNE @@noAlloc
MOV EAX,[EDX].ovtInstanceSize
TEST EAX,EAX
JE @@zeroSize
PUSH EDX
CALL _GetMem
POP EDX
TEST EAX,EAX
JZ @@fail
{ Zero fill the memory }
PUSH EDI
MOV ECX,[EDX].ovtInstanceSize
MOV EDI,EAX
PUSH EAX
XOR EAX,EAX
SHR ECX,2
REP STOSD
MOV ECX,[EDX].ovtInstanceSize
AND ECX,3
REP STOSB
POP EAX
POP EDI
MOV ECX,[EDX].ovtVmtPtrOffs
TEST ECX,ECX
JL @@skip
MOV [EAX+ECX],EDX { store vmt in object at this offset }
@@skip:
TEST EAX,EAX { clear zero flag }
POP ECX
RET
@@fail:
XOR EDX,EDX
POP ECX
RET
@@zeroSize:
XOR EDX,EDX
CMP EAX,1 { clear zero flag - we were successful (kind of) }
POP ECX
RET
@@noAlloc:
MOV ECX,[EDX].ovtVmtPtrOffs
TEST ECX,ECX
JL @@exit
MOV [EAX+ECX],EDX { store vmt in object at this offset }
@@exit:
XOR EDX,EDX { clear allocated flag }
TEST EAX,EAX { clear zero flag }
POP ECX
end;
procedure _ObjCopy;
asm
{ PROCEDURE _ObjCopy( dest, src: ^OBJECT; vmtPtrOff: Longint); }
{ ->EAX Pointer to destination }
{ EDX Pointer to source }
{ ECX Offset of vmt in those objects. }
PUSH EBX
PUSH ESI
PUSH EDI
MOV ESI,EDX
MOV EDI,EAX
LEA EAX,[EDI+ECX] { remember pointer to dest vmt pointer }
MOV EDX,[EAX] { fetch dest vmt pointer }
MOV EBX,[EDX].ovtInstanceSize
MOV ECX,EBX { copy size DIV 4 dwords }
SHR ECX,2
REP MOVSD
MOV ECX,EBX { copy size MOD 4 bytes }
AND ECX,3
REP MOVSB
MOV [EAX],EDX { restore dest vmt }
POP EDI
POP ESI
POP EBX
end;
procedure _Fail;
asm
{ FUNCTION _Fail( self: ^OBJECT; allocFlag:Longint): ^OBJECT; }
{ ->EAX Pointer to self (possibly nil) }
{ EDX <> 0: Object must be deallocated }
{ <-EAX Nil }
TEST EDX,EDX
JE @@exit { if no object was allocated, return }
CALL _FreeMem
@@exit:
XOR EAX,EAX
end;
{$IFDEF MSWINDOWS}
function GetKeyboardType(nTypeFlag: Integer): Integer; stdcall;
external user name 'GetKeyboardType';
function _isNECWindows: Boolean;
var
KbSubType: Integer;
begin
Result := False;
if GetKeyboardType(0) = $7 then
begin
KbSubType := GetKeyboardType(1) and $FF00;
if (KbSubType = $0D00) or (KbSubType = $0400) then
Result := True;
end;
end;
const
HKEY_LOCAL_MACHINE = $80000002;
// workaround a Japanese Win95 bug
procedure _FpuMaskInit;
const
KEY_QUERY_VALUE = $00000001;
REG_DWORD = 4;
FPUMASKKEY = 'SOFTWARE\Borland\Delphi\RTL';
FPUMASKNAME = 'FPUMaskValue';
var
phkResult: LongWord;
lpData, DataSize: Longint;
begin
lpData := Default8087CW;
if RegOpenKeyEx(HKEY_LOCAL_MACHINE, FPUMASKKEY, 0, KEY_QUERY_VALUE, phkResult) = 0 then
try
DataSize := Sizeof(lpData);
RegQueryValueEx(phkResult, FPUMASKNAME, nil, nil, @lpData, @DataSize);
finally
RegCloseKey(phkResult);
end;
Default8087CW := (Default8087CW and $ffc0) or (lpData and $3f);
end;
{$ENDIF}
procedure _FpuInit;
asm
FNINIT
FWAIT
{$IFDEF PIC}
CALL GetGOT
MOV EAX,[EAX].OFFSET Default8087CW
FLDCW [EAX]
{$ELSE}
FLDCW Default8087CW
{$ENDIF}
end;
procedure _BoundErr;
asm
MOV AL,reRangeError
JMP Error
end;
procedure _IntOver;
asm
MOV AL,reIntOverflow
JMP Error
end;
function TObject.ClassType: TClass;
begin
Pointer(Result) := PPointer(Self)^;
end;
class function TObject.ClassName: ShortString;
{$IFDEF PUREPASCAL}
begin
Result := PShortString(PPointer(Integer(Self) + vmtClassName)^)^;
end;
{$ELSE}
asm
{ -> EAX VMT }
{ EDX Pointer to result string }
PUSH ESI
PUSH EDI
MOV EDI,EDX
MOV ESI,[EAX].vmtClassName
XOR ECX,ECX
MOV CL,[ESI]
INC ECX
REP MOVSB
POP EDI
POP ESI
end;
{$ENDIF}
class function TObject.ClassNameIs(const Name: string): Boolean;
{$IFDEF PUREPASCAL}
var
Temp: ShortString;
I: Byte;
begin
Result := False;
Temp := ClassName;
for I := 0 to Byte(Temp[0]) do
if Temp[I] <> Name[I] then Exit;
Result := True;
end;
{$ELSE}
asm
PUSH EBX
XOR EBX,EBX
OR EDX,EDX
JE @@exit
MOV EAX,[EAX].vmtClassName
XOR ECX,ECX
MOV CL,[EAX]
CMP ECX,[EDX-4]
JNE @@exit
DEC EDX
@@loop:
MOV BH,[EAX+ECX]
XOR BH,[EDX+ECX]
AND BH,0DFH
JNE @@exit
DEC ECX
JNE @@loop
INC EBX
@@exit:
MOV AL,BL
POP EBX
end;
{$ENDIF}
class function TObject.ClassParent: TClass;
{$IFDEF PUREPASCAL}
begin
Pointer(Result) := PPointer(Integer(Self) + vmtParent)^;
if Result <> nil then
Pointer(Result) := PPointer(Result)^;
end;
{$ELSE}
asm
MOV EAX,[EAX].vmtParent
TEST EAX,EAX
JE @@exit
MOV EAX,[EAX]
@@exit:
end;
{$ENDIF}
class function TObject.NewInstance: TObject;
begin
Result := InitInstance(_GetMem(InstanceSize));
end;
procedure TObject.FreeInstance;
begin
CleanupInstance;
_FreeMem(Self);
end;
class function TObject.InstanceSize: Longint;
begin
Result := PInteger(Integer(Self) + vmtInstanceSize)^;
end;
constructor TObject.Create;
begin
end;
destructor TObject.Destroy;
begin
end;
procedure TObject.Free;
begin
if Self <> nil then
Destroy;
end;
class function TObject.InitInstance(Instance: Pointer): TObject;
{$IFDEF PUREPASCAL}
var
IntfTable: PInterfaceTable;
ClassPtr: TClass;
I: Integer;
begin
FillChar(Instance^, InstanceSize, 0);
PInteger(Instance)^ := Integer(Self);
ClassPtr := Self;
while ClassPtr <> nil do
begin
IntfTable := ClassPtr.GetInterfaceTable;
if IntfTable <> nil then
for I := 0 to IntfTable.EntryCount-1 do
with IntfTable.Entries[I] do
begin
if VTable <> nil then
PInteger(@PChar(Instance)[IOffset])^ := Integer(VTable);
end;
ClassPtr := ClassPtr.ClassParent;
end;
Result := Instance;
end;
{$ELSE}
asm
PUSH EBX
PUSH ESI
PUSH EDI
MOV EBX,EAX
MOV EDI,EDX
STOSD
MOV ECX,[EBX].vmtInstanceSize
XOR EAX,EAX
PUSH ECX
SHR ECX,2
DEC ECX
REP STOSD
POP ECX
AND ECX,3
REP STOSB
MOV EAX,EDX
MOV EDX,ESP
@@0: MOV ECX,[EBX].vmtIntfTable
TEST ECX,ECX
JE @@1
PUSH ECX
@@1: MOV EBX,[EBX].vmtParent
TEST EBX,EBX
JE @@2
MOV EBX,[EBX]
JMP @@0
@@2: CMP ESP,EDX
JE @@5
@@3: POP EBX
MOV ECX,[EBX].TInterfaceTable.EntryCount
ADD EBX,4
@@4: MOV ESI,[EBX].TInterfaceEntry.VTable
TEST ESI,ESI
JE @@4a
MOV EDI,[EBX].TInterfaceEntry.IOffset
MOV [EAX+EDI],ESI
@@4a: ADD EBX,TYPE TInterfaceEntry
DEC ECX
JNE @@4
CMP ESP,EDX
JNE @@3
@@5: POP EDI
POP ESI
POP EBX
end;
{$ENDIF}
procedure TObject.CleanupInstance;
{$IFDEF PUREPASCAL}
var
ClassPtr: TClass;
InitTable: Pointer;
begin
ClassPtr := ClassType;
InitTable := PPointer(Integer(ClassPtr) + vmtInitTable)^;
while (ClassPtr <> nil) and (InitTable <> nil) do
begin
_FinalizeRecord(Self, InitTable);
ClassPtr := ClassPtr.ClassParent;
if ClassPtr <> nil then
InitTable := PPointer(Integer(ClassPtr) + vmtInitTable)^;
end;
end;
{$ELSE}
asm
PUSH EBX
PUSH ESI
MOV EBX,EAX
MOV ESI,EAX
@@loop:
MOV ESI,[ESI]
MOV EDX,[ESI].vmtInitTable
MOV ESI,[ESI].vmtParent
TEST EDX,EDX
JE @@skip
CALL _FinalizeRecord
MOV EAX,EBX
@@skip:
TEST ESI,ESI
JNE @@loop
POP ESI
POP EBX
end;
{$ENDIF}
function InvokeImplGetter(Self: TObject; ImplGetter: Cardinal): IInterface;
{$IFDEF PUREPASCAL}
var
M: function: IInterface of object;
begin
TMethod(M).Data := Self;
case ImplGetter of
$FF000000..$FFFFFFFF: // Field
Result := IInterface(Pointer(Cardinal(Self) + (ImplGetter and $00FFFFFF)));
$FE000000..$FEFFFFFF: // virtual method
begin
// sign extend vmt slot offset = smallint cast
TMethod(M).Code := PPointer(Integer(Self) + SmallInt(ImplGetter))^;
Result := M;
end;
else // static method
TMethod(M).Code := Pointer(ImplGetter);
Result := M;
end;
end;
{$ELSE}
asm
XCHG EDX,ECX
CMP ECX,$FF000000
JAE @@isField
CMP ECX,$FE000000
JB @@isStaticMethod
{ the GetProc is a virtual method }
MOVSX ECX,CX { sign extend slot offs }
ADD ECX,[EAX] { vmt + slotoffs }
JMP dword ptr [ECX] { call vmt[slot] }
@@isStaticMethod:
JMP ECX
@@isField:
AND ECX,$00FFFFFF
ADD ECX,EAX
MOV EAX,EDX
MOV EDX,[ECX]
JMP _IntfCopy
end;
{$ENDIF}
function TObject.GetInterface(const IID: TGUID; out Obj): Boolean;
var
InterfaceEntry: PInterfaceEntry;
begin
Pointer(Obj) := nil;
InterfaceEntry := GetInterfaceEntry(IID);
if InterfaceEntry <> nil then
begin
if InterfaceEntry^.IOffset <> 0 then
begin
Pointer(Obj) := Pointer(Integer(Self) + InterfaceEntry^.IOffset);
if Pointer(Obj) <> nil then IInterface(Obj)._AddRef;
end
else
IInterface(Obj) := InvokeImplGetter(Self, InterfaceEntry^.ImplGetter);
end;
Result := Pointer(Obj) <> nil;
end;
class function TObject.GetInterfaceEntry(const IID: TGUID): PInterfaceEntry;
{$IFDEF PUREPASCAL}
var
ClassPtr: TClass;
IntfTable: PInterfaceTable;
I: Integer;
begin
ClassPtr := Self;
while ClassPtr <> nil do
begin
IntfTable := ClassPtr.GetInterfaceTable;
if IntfTable <> nil then
for I := 0 to IntfTable.EntryCount-1 do
begin
Result := @IntfTable.Entries[I];
// if Result^.IID = IID then Exit;
if (Int64(Result^.IID.D1) = Int64(IID.D1)) and
(Int64(Result^.IID.D4) = Int64(IID.D4)) then Exit;
end;
ClassPtr := ClassPtr.ClassParent;
end;
Result := nil;
end;
{$ELSE}
asm
PUSH EBX
PUSH ESI
MOV EBX,EAX
@@1: MOV EAX,[EBX].vmtIntfTable
TEST EAX,EAX
JE @@4
MOV ECX,[EAX].TInterfaceTable.EntryCount
ADD EAX,4
@@2: MOV ESI,[EDX].Integer[0]
CMP ESI,[EAX].TInterfaceEntry.IID.Integer[0]
JNE @@3
MOV ESI,[EDX].Integer[4]
CMP ESI,[EAX].TInterfaceEntry.IID.Integer[4]
JNE @@3
MOV ESI,[EDX].Integer[8]
CMP ESI,[EAX].TInterfaceEntry.IID.Integer[8]
JNE @@3
MOV ESI,[EDX].Integer[12]
CMP ESI,[EAX].TInterfaceEntry.IID.Integer[12]
JE @@5
@@3: ADD EAX,type TInterfaceEntry
DEC ECX
JNE @@2
@@4: MOV EBX,[EBX].vmtParent
TEST EBX,EBX
JE @@4a
MOV EBX,[EBX]
JMP @@1
@@4a: XOR EAX,EAX
@@5: POP ESI
POP EBX
end;
{$ENDIF}
class function TObject.GetInterfaceTable: PInterfaceTable;
begin
Result := PPointer(Integer(Self) + vmtIntfTable)^;
end;
function _IsClass(Child: TObject; Parent: TClass): Boolean;
begin
Result := (Child <> nil) and Child.InheritsFrom(Parent);
end;
function _AsClass(Child: TObject; Parent: TClass): TObject;
{$IFDEF PUREPASCAL}
begin
Result := Child;
if not (Child is Parent) then
Error(reInvalidCast); // loses return address
end;
{$ELSE}
asm
{ -> EAX left operand (class) }
{ EDX VMT of right operand }
{ <- EAX if left is derived from right, else runtime error }
TEST EAX,EAX
JE @@exit
MOV ECX,EAX
@@loop:
MOV ECX,[ECX]
CMP ECX,EDX
JE @@exit
MOV ECX,[ECX].vmtParent
TEST ECX,ECX
JNE @@loop
{ do runtime error }
MOV AL,reInvalidCast
JMP Error
@@exit:
end;
{$ENDIF}
procedure GetDynaMethod;
{ function GetDynaMethod(vmt: TClass; selector: Smallint) : Pointer; }
asm
{ -> EAX vmt of class }
{ SI dynamic method index }
{ <- ESI pointer to routine }
{ ZF = 0 if found }
{ trashes: EAX, ECX }
PUSH EDI
XCHG EAX,ESI
JMP @@haveVMT
@@outerLoop:
MOV ESI,[ESI]
@@haveVMT:
MOV EDI,[ESI].vmtDynamicTable
TEST EDI,EDI
JE @@parent
MOVZX ECX,word ptr [EDI]
PUSH ECX
ADD EDI,2
REPNE SCASW
JE @@found
POP ECX
@@parent:
MOV ESI,[ESI].vmtParent
TEST ESI,ESI
JNE @@outerLoop
JMP @@exit
@@found:
POP EAX
ADD EAX,EAX
SUB EAX,ECX { this will always clear the Z-flag ! }
MOV ESI,[EDI+EAX*2-4]
@@exit:
POP EDI
end;
procedure _CallDynaInst;
asm
PUSH EAX
PUSH ECX
MOV EAX,[EAX]
CALL GetDynaMethod
POP ECX
POP EAX
JE @@Abstract
JMP ESI
@@Abstract:
POP ECX
JMP _AbstractError
end;
procedure _CallDynaClass;
asm
PUSH EAX
PUSH ECX
CALL GetDynaMethod
POP ECX
POP EAX
JE @@Abstract
JMP ESI
@@Abstract:
POP ECX
JMP _AbstractError
end;
procedure _FindDynaInst;
asm
PUSH ESI
MOV ESI,EDX
MOV EAX,[EAX]
CALL GetDynaMethod
MOV EAX,ESI
POP ESI
JNE @@exit
POP ECX
JMP _AbstractError
@@exit:
end;
procedure _FindDynaClass;
asm
PUSH ESI
MOV ESI,EDX
CALL GetDynaMethod
MOV EAX,ESI
POP ESI
JNE @@exit
POP ECX
JMP _AbstractError
@@exit:
end;
class function TObject.InheritsFrom(AClass: TClass): Boolean;
{$IFDEF PUREPASCAL}
var
ClassPtr: TClass;
begin
ClassPtr := Self;
while (ClassPtr <> nil) and (ClassPtr <> AClass) do
ClassPtr := PPointer(Integer(ClassPtr) + vmtParent)^;
Result := ClassPtr = AClass;
end;
{$ELSE}
asm
{ -> EAX Pointer to our class }
{ EDX Pointer to AClass }
{ <- AL Boolean result }
JMP @@haveVMT
@@loop:
MOV EAX,[EAX]
@@haveVMT:
CMP EAX,EDX
JE @@success
MOV EAX,[EAX].vmtParent
TEST EAX,EAX
JNE @@loop
JMP @@exit
@@success:
MOV AL,1
@@exit:
end;
{$ENDIF}
class function TObject.ClassInfo: Pointer;
begin
Result := PPointer(Integer(Self) + vmtTypeInfo)^;
end;
function TObject.SafeCallException(ExceptObject: TObject;
ExceptAddr: Pointer): HResult;
begin
Result := HResult($8000FFFF); { E_UNEXPECTED }
end;
procedure TObject.DefaultHandler(var Message);
begin
end;
procedure TObject.AfterConstruction;
begin
end;
procedure TObject.BeforeDestruction;
begin
end;
procedure TObject.Dispatch(var Message);
asm
PUSH ESI
MOV SI,[EDX]
OR SI,SI
JE @@default
CMP SI,0C000H
JAE @@default
PUSH EAX
MOV EAX,[EAX]
CALL GetDynaMethod
POP EAX
JE @@default
MOV ECX,ESI
POP ESI
JMP ECX
@@default:
POP ESI
MOV ECX,[EAX]
JMP dword ptr [ECX].vmtDefaultHandler
end;
class function TObject.MethodAddress(const Name: ShortString): Pointer;
asm
{ -> EAX Pointer to class }
{ EDX Pointer to name }
PUSH EBX
PUSH ESI
PUSH EDI
XOR ECX,ECX
XOR EDI,EDI
MOV BL,[EDX]
JMP @@haveVMT
@@outer: { upper 16 bits of ECX are 0 ! }
MOV EAX,[EAX]
@@haveVMT:
MOV ESI,[EAX].vmtMethodTable
TEST ESI,ESI
JE @@parent
MOV DI,[ESI] { EDI := method count }
ADD ESI,2
@@inner: { upper 16 bits of ECX are 0 ! }
MOV CL,[ESI+6] { compare length of strings }
CMP CL,BL
JE @@cmpChar
@@cont: { upper 16 bits of ECX are 0 ! }
MOV CX,[ESI] { fetch length of method desc }
ADD ESI,ECX { point ESI to next method }
DEC EDI
JNZ @@inner
@@parent:
MOV EAX,[EAX].vmtParent { fetch parent vmt }
TEST EAX,EAX
JNE @@outer
JMP @@exit { return NIL }
@@notEqual:
MOV BL,[EDX] { restore BL to length of name }
JMP @@cont
@@cmpChar: { upper 16 bits of ECX are 0 ! }
MOV CH,0 { upper 24 bits of ECX are 0 ! }
@@cmpCharLoop:
MOV BL,[ESI+ECX+6] { case insensitive string cmp }
XOR BL,[EDX+ECX+0] { last char is compared first }
AND BL,$DF
JNE @@notEqual
DEC ECX { ECX serves as counter }
JNZ @@cmpCharLoop
{ found it }
MOV EAX,[ESI+2]
@@exit:
POP EDI
POP ESI
POP EBX
end;
class function TObject.MethodName(Address: Pointer): ShortString;
asm
{ -> EAX Pointer to class }
{ EDX Address }
{ ECX Pointer to result }
PUSH EBX
PUSH ESI
PUSH EDI
MOV EDI,ECX
XOR EBX,EBX
XOR ECX,ECX
JMP @@haveVMT
@@outer:
MOV EAX,[EAX]
@@haveVMT:
MOV ESI,[EAX].vmtMethodTable { fetch pointer to method table }
TEST ESI,ESI
JE @@parent
MOV CX,[ESI]
ADD ESI,2
@@inner:
CMP EDX,[ESI+2]
JE @@found
MOV BX,[ESI]
ADD ESI,EBX
DEC ECX
JNZ @@inner
@@parent:
MOV EAX,[EAX].vmtParent
TEST EAX,EAX
JNE @@outer
MOV [EDI],AL
JMP @@exit
@@found:
ADD ESI,6
XOR ECX,ECX
MOV CL,[ESI]
INC ECX
REP MOVSB
@@exit:
POP EDI
POP ESI
POP EBX
end;
function TObject.FieldAddress(const Name: ShortString): Pointer;
asm
{ -> EAX Pointer to instance }
{ EDX Pointer to name }
PUSH EBX
PUSH ESI
PUSH EDI
XOR ECX,ECX
XOR EDI,EDI
MOV BL,[EDX]
PUSH EAX { save instance pointer }
@@outer:
MOV EAX,[EAX] { fetch class pointer }
MOV ESI,[EAX].vmtFieldTable
TEST ESI,ESI
JE @@parent
MOV DI,[ESI] { fetch count of fields }
ADD ESI,6
@@inner:
MOV CL,[ESI+6] { compare string lengths }
CMP CL,BL
JE @@cmpChar
@@cont:
LEA ESI,[ESI+ECX+7] { point ESI to next field }
DEC EDI
JNZ @@inner
@@parent:
MOV EAX,[EAX].vmtParent { fetch parent VMT }
TEST EAX,EAX
JNE @@outer
POP EDX { forget instance, return Nil }
JMP @@exit
@@notEqual:
MOV BL,[EDX] { restore BL to length of name }
MOV CL,[ESI+6] { ECX := length of field name }
JMP @@cont
@@cmpChar:
MOV BL,[ESI+ECX+6] { case insensitive string cmp }
XOR BL,[EDX+ECX+0] { starting with last char }
AND BL,$DF
JNE @@notEqual
DEC ECX { ECX serves as counter }
JNZ @@cmpChar
{ found it }
MOV EAX,[ESI] { result is field offset plus ... }
POP EDX
ADD EAX,EDX { instance pointer }
@@exit:
POP EDI
POP ESI
POP EBX
end;
function _ClassCreate(AClass: TClass; Alloc: Boolean): TObject;
asm
{ -> EAX = pointer to VMT }
{ <- EAX = pointer to instance }
PUSH EDX
PUSH ECX
PUSH EBX
TEST DL,DL
JL @@noAlloc
CALL dword ptr [EAX].vmtNewInstance
@@noAlloc:
{$IFNDEF PC_MAPPED_EXCEPTIONS}
XOR EDX,EDX
LEA ECX,[ESP+16]
MOV EBX,FS:[EDX]
MOV [ECX].TExcFrame.next,EBX
MOV [ECX].TExcFrame.hEBP,EBP
MOV [ECX].TExcFrame.desc,offset @desc
MOV [ECX].TexcFrame.ConstructedObject,EAX { trick: remember copy to instance }
MOV FS:[EDX],ECX
{$ENDIF}
POP EBX
POP ECX
POP EDX
RET
{$IFNDEF PC_MAPPED_EXCEPTIONS}
@desc:
JMP _HandleAnyException
{ destroy the object }
MOV EAX,[ESP+8+9*4]
MOV EAX,[EAX].TExcFrame.ConstructedObject
TEST EAX,EAX
JE @@skip
MOV ECX,[EAX]
MOV DL,$81
PUSH EAX
CALL dword ptr [ECX].vmtDestroy
POP EAX
CALL _ClassDestroy
@@skip:
{ reraise the exception }
CALL _RaiseAgain
{$ENDIF}
end;
procedure _ClassDestroy(Instance: TObject);
begin
Instance.FreeInstance;
end;
function _AfterConstruction(Instance: TObject): TObject;
begin
Instance.AfterConstruction;
Result := Instance;
end;
function _BeforeDestruction(Instance: TObject; OuterMost: ShortInt): TObject;
// Must preserve DL on return!
{$IFDEF PUREPASCAL}
begin
Result := Instance;
if OuterMost > 0 then Exit;
Instance.BeforeDestruction;
end;
{$ELSE}
asm
{ -> EAX = pointer to instance }
{ DL = dealloc flag }
TEST DL,DL
JG @@outerMost
RET
@@outerMost:
PUSH EAX
PUSH EDX
MOV EDX,[EAX]
CALL dword ptr [EDX].vmtBeforeDestruction
POP EDX
POP EAX
end;
{$ENDIF}
{
The following NotifyXXXX routines are used to "raise" special exceptions
as a signaling mechanism to an interested debugger. If the debugger sets
the DebugHook flag to 1 or 2, then all exception processing is tracked by
raising these special exceptions. The debugger *MUST* respond to the
debug event with DBG_CONTINE so that normal processing will occur.
}
{$IFDEF LINUX}
const
excRaise = 0; { an exception is being raised by the user (could be a reraise) }
excCatch = 1; { an exception is about to be caught }
excFinally = 2; { a finally block is about to be executed because of an exception }
excUnhandled = 3; { no user exception handler was found (the app will die) }
procedure _DbgExcNotify(
NotificationKind: Integer;
ExceptionObject: Pointer;
ExceptionName: PShortString;
ExceptionLocation: Pointer;
HandlerAddr: Pointer); cdecl; export;
begin
{$IFDEF DEBUG}
{
This code is just for debugging the exception handling system. The debugger
needs _DbgExcNotify, however to place breakpoints in, so the function itself
cannot be removed.
}
asm
PUSH EAX
PUSH EDX
end;
if Assigned(ExcNotificationProc) then
ExcNotificationProc(NotificationKind, ExceptionObject, ExceptionName, ExceptionLocation, HandlerAddr);
asm
POP EDX
POP EAX
end;
{$ENDIF}
end;
{
The following functions are used by the debugger for the evaluator. If you
change them IN ANY WAY, the debugger will cease to function correctly.
}
procedure _DbgEvalMarker;
begin
end;
procedure _DbgEvalExcept(E: TObject);
begin
end;
procedure _DbgEvalEnd;
begin
end;
{
This function is used by the debugger to provide a soft landing spot
when evaluating a function call that may raise an unhandled exception.
The return address of _DbgEvalMarker is pushed onto the stack so that
the unwinder will transfer control to the except block.
}
procedure _DbgEvalFrame;
begin
try
_DbgEvalMarker;
except on E: TObject do
_DbgEvalExcept(E);
end;
_DbgEvalEnd;
end;
{
These export names need to match the names that will be generated into
the .symtab section, so that the debugger can find them if stabs
debug information is being generated.
}
exports
_DbgExcNotify name '@DbgExcNotify',
_DbgEvalFrame name '@DbgEvalFrame',
_DbgEvalMarker name '@DbgEvalMarker',
_DbgEvalExcept name '@DbgEvalExcept',
_DbgEvalEnd name '@DbgEvalEnd';
{$ENDIF}
{ tell the debugger that the next raise is a re-raise of the current non-Delphi
exception }
procedure NotifyReRaise;
asm
{$IFDEF LINUX}
{ ->EAX Pointer to exception object }
{ EDX location of exception }
PUSH 0 { handler addr }
PUSH EDX { location of exception }
MOV ECX, [EAX]
PUSH [ECX].vmtClassName { exception name }
PUSH EAX { exception object }
PUSH excRaise { notification kind }
CALL _DbgExcNotify
ADD ESP, 20
{$ELSE}
CMP BYTE PTR DebugHook,1
JBE @@1
PUSH 0
PUSH 0
PUSH cContinuable
PUSH cDelphiReRaise
CALL RaiseExceptionProc
@@1:
{$ENDIF}
end;
{ tell the debugger about the raise of a non-Delphi exception }
{$IFNDEF LINUX}
procedure NotifyNonDelphiException;
asm
CMP BYTE PTR DebugHook,0
JE @@1
PUSH EAX
PUSH EAX
PUSH EDX
PUSH ESP
PUSH 2
PUSH cContinuable
PUSH cNonDelphiException
CALL RaiseExceptionProc
ADD ESP,8
POP EAX
@@1:
end;
{$ENDIF}
{ Tell the debugger where the handler for the current exception is located }
procedure NotifyExcept;
asm
{$IFDEF LINUX}
{ ->EAX Pointer to exception object }
{ EDX handler addr }
PUSH EAX
MOV EAX, [EAX].TRaisedException.ExceptObject
PUSH EDX { handler addr }
PUSH 0 { location of exception }
MOV ECX, [EAX]
PUSH [ECX].vmtClassName { exception name }
PUSH EAX { exception object }
PUSH excCatch { notification kind }
CALL _DbgExcNotify
ADD ESP, 20
POP EAX
{$ELSE}
PUSH ESP
PUSH 1
PUSH cContinuable
PUSH cDelphiExcept { our magic exception code }
CALL RaiseExceptionProc
ADD ESP,4
POP EAX
{$ENDIF}
end;
procedure NotifyOnExcept;
asm
{$IFDEF LINUX}
{ ->EAX Pointer to exception object }
{ EDX handler addr }
PUSH EDX { handler addr }
PUSH 0 { location of exception }
MOV ECX, [EAX]
PUSH [ECX].vmtClassName { exception name }
PUSH EAX { exception object }
PUSH excCatch { notification kind }
CALL _DbgExcNotify
ADD ESP, 20
{$ELSE}
CMP BYTE PTR DebugHook,1
JBE @@1
PUSH EAX
PUSH [EBX].TExcDescEntry.handler
JMP NotifyExcept
@@1:
{$ENDIF}
end;
{$IFNDEF LINUX}
procedure NotifyAnyExcept;
asm
CMP BYTE PTR DebugHook,1
JBE @@1
PUSH EAX
PUSH EBX
JMP NotifyExcept
@@1:
end;
procedure CheckJmp;
asm
TEST ECX,ECX
JE @@3
MOV EAX,[ECX + 1]
CMP BYTE PTR [ECX],0E9H { near jmp }
JE @@1
CMP BYTE PTR [ECX],0EBH { short jmp }
JNE @@3
MOVSX EAX,AL
INC ECX
INC ECX
JMP @@2
@@1:
ADD ECX,5
@@2:
ADD ECX,EAX
@@3:
end;
{$ENDIF} { not LINUX }
{ Notify debugger of a finally during an exception unwind }
procedure NotifyExceptFinally;
asm
{$IFDEF LINUX}
{ ->EAX Pointer to exception object }
{ EDX handler addr }
PUSH EDX { handler addr }
PUSH 0 { location of exception }
PUSH 0 { exception name }
PUSH 0 { exception object }
PUSH excFinally { notification kind }
CALL _DbgExcNotify
ADD ESP, 20
{$ELSE}
CMP BYTE PTR DebugHook,1
JBE @@1
PUSH EAX
PUSH EDX
PUSH ECX
CALL CheckJmp
PUSH ECX
PUSH ESP { pass pointer to arguments }
PUSH 1 { there is 1 argument }
PUSH cContinuable { continuable execution }
PUSH cDelphiFinally { our magic exception code }
CALL RaiseExceptionProc
POP ECX
POP ECX
POP EDX
POP EAX
@@1:
{$ENDIF}
end;
{ Tell the debugger that the current exception is handled and cleaned up.
Also indicate where execution is about to resume. }
{$IFNDEF LINUX}
procedure NotifyTerminate;
asm
CMP BYTE PTR DebugHook,1
JBE @@1
PUSH EDX
PUSH ESP
PUSH 1
PUSH cContinuable
PUSH cDelphiTerminate { our magic exception code }
CALL RaiseExceptionProc
POP EDX
@@1:
end;
{$ENDIF}
{ Tell the debugger that there was no handler found for the current exception
and we are about to go to the default handler }
procedure NotifyUnhandled;
asm
{$IFDEF LINUX}
{ ->EAX Pointer to exception object }
{ EDX location of exception }
PUSH EAX
MOV EAX, [EAX].TRaisedException.ExceptObject
PUSH 0 { handler addr }
PUSH EDX { location of exception }
MOV ECX, [EAX]
PUSH [ECX].vmtClassName { exception name }
PUSH EAX { exception object }
PUSH excUnhandled { notification kind }
CALL _DbgExcNotify
ADD ESP, 20
POP EAX
{$ELSE}
PUSH EAX
PUSH EDX
CMP BYTE PTR DebugHook,1
JBE @@1
PUSH ESP
PUSH 2
PUSH cContinuable
PUSH cDelphiUnhandled
CALL RaiseExceptionProc
@@1:
POP EDX
POP EAX
{$ENDIF}
end;
procedure _HandleAnyException;
asm
{$IFDEF PC_MAPPED_EXCEPTIONS}
CALL UnblockOSExceptions
OR [EAX].TRaisedException.Flags, excIsBeingHandled
MOV ESI, EBX
MOV EDX, [ESP]
CALL NotifyExcept
MOV EBX, ESI
{$ENDIF}
{$IFNDEF PC_MAPPED_EXCEPTIONS}
{ -> [ESP+ 4] excPtr: PExceptionRecord }
{ [ESP+ 8] errPtr: PExcFrame }
{ [ESP+12] ctxPtr: Pointer }
{ [ESP+16] dspPtr: Pointer }
{ <- EAX return value - always one }
MOV EAX,[ESP+4]
TEST [EAX].TExceptionRecord.ExceptionFlags,cUnwindInProgress
JNE @@exit
CMP [EAX].TExceptionRecord.ExceptionCode,cDelphiException
MOV EDX,[EAX].TExceptionRecord.ExceptObject
MOV ECX,[EAX].TExceptionRecord.ExceptAddr
JE @@DelphiException
CLD
CALL _FpuInit
MOV EDX,ExceptObjProc
TEST EDX,EDX
JE @@exit
CALL EDX
TEST EAX,EAX
JE @@exit
MOV EDX,[ESP+12]
MOV ECX,[ESP+4]
CMP [ECX].TExceptionRecord.ExceptionCode,cCppException
JE @@CppException
CALL NotifyNonDelphiException
{$IFDEF MSWINDOWS}
CMP BYTE PTR JITEnable,0
JBE @@CppException
CMP BYTE PTR DebugHook,0
JA @@CppException // Do not JIT if debugging
LEA ECX,[ESP+4]
PUSH EAX
PUSH ECX
CALL UnhandledExceptionFilter
CMP EAX,EXCEPTION_CONTINUE_SEARCH
POP EAX
JE @@exit
MOV EDX,EAX
MOV EAX,[ESP+4]
MOV ECX,[EAX].TExceptionRecord.ExceptionAddress
JMP @@GoUnwind
{$ENDIF}
@@CppException:
MOV EDX,EAX
MOV EAX,[ESP+4]
MOV ECX,[EAX].TExceptionRecord.ExceptionAddress
@@DelphiException:
{$IFDEF MSWINDOWS}
CMP BYTE PTR JITEnable,1
JBE @@GoUnwind
CMP BYTE PTR DebugHook,0 { Do not JIT if debugging }
JA @@GoUnwind
PUSH EAX
LEA EAX,[ESP+8]
PUSH EDX
PUSH ECX
PUSH EAX
CALL UnhandledExceptionFilter
CMP EAX,EXCEPTION_CONTINUE_SEARCH
POP ECX
POP EDX
POP EAX
JE @@exit
{$ENDIF}
@@GoUnwind:
OR [EAX].TExceptionRecord.ExceptionFlags,cUnwinding
PUSH EBX
XOR EBX,EBX
PUSH ESI
PUSH EDI
PUSH EBP
MOV EBX,FS:[EBX]
PUSH EBX { Save pointer to topmost frame }
PUSH EAX { Save OS exception pointer }
PUSH EDX { Save exception object }
PUSH ECX { Save exception address }
MOV EDX,[ESP+8+8*4]
PUSH 0
PUSH EAX
PUSH offset @@returnAddress
PUSH EDX
CALL RtlUnwindProc
@@returnAddress:
MOV EDI,[ESP+8+8*4]
{ Make the RaiseList entry on the stack }
CALL SysInit.@GetTLS
PUSH [EAX].RaiseListPtr
MOV [EAX].RaiseListPtr,ESP
MOV EBP,[EDI].TExcFrame.hEBP
MOV EBX,[EDI].TExcFrame.desc
MOV [EDI].TExcFrame.desc,offset @@exceptFinally
ADD EBX,TExcDesc.instructions
CALL NotifyAnyExcept
JMP EBX
@@exceptFinally:
JMP _HandleFinally
@@destroyExcept:
{ we come here if an exception handler has thrown yet another exception }
{ we need to destroy the exception object and pop the raise list. }
CALL SysInit.@GetTLS
MOV ECX,[EAX].RaiseListPtr
MOV EDX,[ECX].TRaiseFrame.NextRaise
MOV [EAX].RaiseListPtr,EDX
MOV EAX,[ECX].TRaiseFrame.ExceptObject
JMP TObject.Free
@@exit:
MOV EAX,1
{$ENDIF} { not PC_MAPPED_EXCEPTIONS }
end;
{$IFDEF PC_MAPPED_EXCEPTIONS}
{
Common code between the Win32 and PC mapped exception handling
scheme. This function takes a pointer to an object, and an exception
'on' descriptor table and finds the matching handler descriptor.
For support of Linux, we assume that EBX has been loaded with the GOT
that pertains to the code which is handling the exception currently.
If this function is being called from code which is not PIC, then
EBX should be zero on entry.
}
procedure FindOnExceptionDescEntry;
asm
{ -> EAX raised object: Pointer }
{ EDX descriptor table: ^TExcDesc }
{ EBX GOT of user code, or 0 if not an SO }
{ <- EAX matching descriptor: ^TExcDescEntry }
PUSH EBP
MOV EBP, ESP
SUB ESP, 8 { Room for vtable temp, and adjustor }
PUSH EBX
PUSH ESI
PUSH EDI
MOV [EBP - 8], EBX { Store the potential GOT }
MOV EAX, [EAX] { load vtable of exception object }
MOV EBX,[EDX].TExcDesc.cnt
LEA ESI,[EDX].TExcDesc.excTab { point ECX to exc descriptor table }
MOV [EBP - 4], EAX { temp for vtable of exception object }
@@innerLoop:
MOV EAX,[ESI].TExcDescEntry.vTable
TEST EAX,EAX { catch all clause? }
JE @@found { yes: This is the handler }
ADD EAX, [EBP - 8] { add in the adjustor (could be 0) }
MOV EDI,[EBP - 4] { load vtable of exception object }
JMP @@haveVMT
@@vtLoop:
MOV EDI,[EDI]
@@haveVMT:
MOV EAX,[EAX]
CMP EAX,EDI
JE @@found
MOV ECX,[EAX].vmtInstanceSize
CMP ECX,[EDI].vmtInstanceSize
JNE @@parent
MOV EAX,[EAX].vmtClassName
MOV EDX,[EDI].vmtClassName
XOR ECX,ECX
MOV CL,[EAX]
CMP CL,[EDX]
JNE @@parent
INC EAX
INC EDX
CALL _AStrCmp
JE @@found
@@parent:
MOV EDI,[EDI].vmtParent { load vtable of parent }
MOV EAX,[ESI].TExcDescEntry.vTable
ADD EAX, [EBP - 8] { add in the adjustor (could be 0) }
TEST EDI,EDI
JNE @@vtLoop
ADD ESI,8
DEC EBX
JNZ @@innerLoop
{ Didn't find a handler. }
XOR ESI, ESI
@@found:
MOV EAX, ESI
@@done:
POP EDI
POP ESI
POP EBX
MOV ESP, EBP
POP EBP
end;
{$ENDIF}
{$IFDEF PC_MAPPED_EXCEPTIONS}
procedure _HandleOnExceptionPIC;
asm
{ -> EAX obj : Exception object }
{ [RA] desc: ^TExcDesc }
{ <- Doesn't return }
// Mark the exception as being handled
OR [EAX].TRaisedException.Flags, excIsBeingHandled
MOV ESI, EBX // Save the GOT
MOV EDX, [ESP] // Get the addr of the TExcDesc
PUSH EAX // Save the object
MOV EAX, [EAX].TRaisedException.ExceptObject
CALL FindOnExceptionDescEntry
OR EAX, EAX
JE @@NotForMe
MOV EBX, ESI // Set back to user's GOT
MOV EDX, EAX
POP EAX // Get the object back
POP ECX // Ditch the return addr
// Get the Pascal object itself.
MOV EAX, [EAX].TRaisedException.ExceptObject
MOV EDX, [EDX].TExcDescEntry.handler
ADD EDX, EBX // adjust for GOT
CALL NotifyOnExcept
MOV EBX, ESI // Make sure of user's GOT
JMP EDX // Back to the user code
// never returns
@@NotForMe:
POP EAX // Get the exception object
// Mark that we're reraising this exception, so that the
// compiler generated exception handler for the 'except on' clause
// will not get confused
OR [EAX].TRaisedException.Flags, excIsBeingReRaised
JMP SysRaiseException // Should be using resume here
end;
{$ENDIF}
procedure _HandleOnException;
{$IFDEF PC_MAPPED_EXCEPTIONS}
asm
{ -> EAX obj : Exception object }
{ [RA] desc: ^TExcDesc }
{ <- Doesn't return }
// Mark the exception as being handled
OR [EAX].TRaisedException.Flags, excIsBeingHandled
MOV EDX, [ESP] // Get the addr of the TExcDesc
PUSH EAX // Save the object
PUSH EBX // Save EBX
XOR EBX, EBX // No GOT
MOV EAX, [EAX].TRaisedException.ExceptObject
CALL FindOnExceptionDescEntry
POP EBX // Restore EBX
OR EAX, EAX // Is the exception for me?
JE @@NotForMe
MOV EDX, EAX
POP EAX // Get the object back
POP ECX // Ditch the return addr
// Get the Pascal object itself.
MOV EAX, [EAX].TRaisedException.ExceptObject
MOV EDX, [EDX].TExcDescEntry.handler
CALL NotifyOnExcept // Tell the debugger about it
JMP EDX // Back to the user code
// never returns
@@NotForMe:
POP EAX // Get the exception object
// Mark that we're reraising this exception, so that the
// compiler generated exception handler for the 'except on' clause
// will not get confused
OR [EAX].TRaisedException.Flags, excIsBeingReRaised
JMP SysRaiseException // Should be using resume here
end;
{$ENDIF}
{$IFNDEF PC_MAPPED_EXCEPTIONS}
asm
{ -> [ESP+ 4] excPtr: PExceptionRecord }
{ [ESP+ 8] errPtr: PExcFrame }
{ [ESP+12] ctxPtr: Pointer }
{ [ESP+16] dspPtr: Pointer }
{ <- EAX return value - always one }
MOV EAX,[ESP+4]
TEST [EAX].TExceptionRecord.ExceptionFlags,cUnwindInProgress
JNE @@exit
CMP [EAX].TExceptionRecord.ExceptionCode,cDelphiException
JE @@DelphiException
CLD
CALL _FpuInit
MOV EDX,ExceptClsProc
TEST EDX,EDX
JE @@exit
CALL EDX
TEST EAX,EAX
JNE @@common
JMP @@exit
@@DelphiException:
MOV EAX,[EAX].TExceptionRecord.ExceptObject
MOV EAX,[EAX] { load vtable of exception object }
@@common:
MOV EDX,[ESP+8]
PUSH EBX
PUSH ESI
PUSH EDI
PUSH EBP
MOV ECX,[EDX].TExcFrame.desc
MOV EBX,[ECX].TExcDesc.cnt
LEA ESI,[ECX].TExcDesc.excTab { point ECX to exc descriptor table }
MOV EBP,EAX { load vtable of exception object }
@@innerLoop:
MOV EAX,[ESI].TExcDescEntry.vTable
TEST EAX,EAX { catch all clause? }
JE @@doHandler { yes: go execute handler }
MOV EDI,EBP { load vtable of exception object }
JMP @@haveVMT
@@vtLoop:
MOV EDI,[EDI]
@@haveVMT:
MOV EAX,[EAX]
CMP EAX,EDI
JE @@doHandler
MOV ECX,[EAX].vmtInstanceSize
CMP ECX,[EDI].vmtInstanceSize
JNE @@parent
MOV EAX,[EAX].vmtClassName
MOV EDX,[EDI].vmtClassName
XOR ECX,ECX
MOV CL,[EAX]
CMP CL,[EDX]
JNE @@parent
INC EAX
INC EDX
CALL _AStrCmp
JE @@doHandler
@@parent:
MOV EDI,[EDI].vmtParent { load vtable of parent }
MOV EAX,[ESI].TExcDescEntry.vTable
TEST EDI,EDI
JNE @@vtLoop
ADD ESI,8
DEC EBX
JNZ @@innerLoop
POP EBP
POP EDI
POP ESI
POP EBX
JMP @@exit
@@doHandler:
MOV EAX,[ESP+4+4*4]
CMP [EAX].TExceptionRecord.ExceptionCode,cDelphiException
MOV EDX,[EAX].TExceptionRecord.ExceptObject
MOV ECX,[EAX].TExceptionRecord.ExceptAddr
JE @@haveObject
CALL ExceptObjProc
MOV EDX,[ESP+12+4*4]
CALL NotifyNonDelphiException
{$IFDEF MSWINDOWS}
CMP BYTE PTR JITEnable,0
JBE @@NoJIT
CMP BYTE PTR DebugHook,0
JA @@noJIT { Do not JIT if debugging }
LEA ECX,[ESP+4]
PUSH EAX
PUSH ECX
CALL UnhandledExceptionFilter
CMP EAX,EXCEPTION_CONTINUE_SEARCH
POP EAX
JE @@exit
{$ENDIF}
@@noJIT:
MOV EDX,EAX
MOV EAX,[ESP+4+4*4]
MOV ECX,[EAX].TExceptionRecord.ExceptionAddress
JMP @@GoUnwind
@@haveObject:
{$IFDEF MSWINDOWS}
CMP BYTE PTR JITEnable,1
JBE @@GoUnwind
CMP BYTE PTR DebugHook,0
JA @@GoUnwind
PUSH EAX
LEA EAX,[ESP+8]
PUSH EDX
PUSH ECX
PUSH EAX
CALL UnhandledExceptionFilter
CMP EAX,EXCEPTION_CONTINUE_SEARCH
POP ECX
POP EDX
POP EAX
JE @@exit
{$ENDIF}
@@GoUnwind:
XOR EBX,EBX
MOV EBX,FS:[EBX]
PUSH EBX { Save topmost frame }
PUSH EAX { Save exception record }
PUSH EDX { Save exception object }
PUSH ECX { Save exception address }
MOV EDX,[ESP+8+8*4]
OR [EAX].TExceptionRecord.ExceptionFlags,cUnwinding
PUSH ESI { Save handler entry }
PUSH 0
PUSH EAX
PUSH offset @@returnAddress
PUSH EDX
CALL RtlUnwindProc
@@returnAddress:
POP EBX { Restore handler entry }
MOV EDI,[ESP+8+8*4]
{ Make the RaiseList entry on the stack }
CALL SysInit.@GetTLS
PUSH [EAX].RaiseListPtr
MOV [EAX].RaiseListPtr,ESP
MOV EBP,[EDI].TExcFrame.hEBP
MOV [EDI].TExcFrame.desc,offset @@exceptFinally
MOV EAX,[ESP].TRaiseFrame.ExceptObject
CALL NotifyOnExcept
JMP [EBX].TExcDescEntry.handler
@@exceptFinally:
JMP _HandleFinally
@@destroyExcept:
{ we come here if an exception handler has thrown yet another exception }
{ we need to destroy the exception object and pop the raise list. }
CALL SysInit.@GetTLS
MOV ECX,[EAX].RaiseListPtr
MOV EDX,[ECX].TRaiseFrame.NextRaise
MOV [EAX].RaiseListPtr,EDX
MOV EAX,[ECX].TRaiseFrame.ExceptObject
JMP TObject.Free
@@exit:
MOV EAX,1
end;
{$ENDIF}
procedure _HandleFinally;
asm
{$IFDEF PC_MAPPED_EXCEPTIONS}
{$IFDEF PIC}
MOV ESI, EBX
{$ENDIF}
CALL UnblockOSExceptions
MOV EDX, [ESP]
CALL NotifyExceptFinally
PUSH EAX
{$IFDEF PIC}
MOV EBX, ESI
{$ENDIF}
{
Mark the current exception with the EBP of the handler. If
an exception is raised from the finally block, then this
exception will be orphaned. We will catch this later, when
we clean up the next except block to complete execution.
See DoneExcept.
}
MOV [EAX].TRaisedException.HandlerEBP, EBP
CALL EDX
POP EAX
{
We executed the finally handler without adverse reactions.
It's safe to clear the marker now.
}
MOV [EAX].TRaisedException.HandlerEBP, $FFFFFFFF
PUSH EBP
MOV EBP, ESP
CALL SysRaiseException // Should be using resume here
{$ENDIF}
{$IFDEF MSWINDOWS}
{ -> [ESP+ 4] excPtr: PExceptionRecord }
{ [ESP+ 8] errPtr: PExcFrame }
{ [ESP+12] ctxPtr: Pointer }
{ [ESP+16] dspPtr: Pointer }
{ <- EAX return value - always one }
MOV EAX,[ESP+4]
MOV EDX,[ESP+8]
TEST [EAX].TExceptionRecord.ExceptionFlags,cUnwindInProgress
JE @@exit
MOV ECX,[EDX].TExcFrame.desc
MOV [EDX].TExcFrame.desc,offset @@exit
PUSH EBX
PUSH ESI
PUSH EDI
PUSH EBP
MOV EBP,[EDX].TExcFrame.hEBP
ADD ECX,TExcDesc.instructions
CALL NotifyExceptFinally
CALL ECX
POP EBP
POP EDI
POP ESI
POP EBX
@@exit:
MOV EAX,1
{$ENDIF}
end;
procedure _HandleAutoException;
{$IFDEF LINUX}
{$IFDEF PC_MAPPED_EXCEPTIONS}
asm
// EAX = TObject reference, or nil
// [ESP] = ret addr
CALL UnblockOSExceptions
//
// The compiler wants the stack to look like this:
// ESP+4-> HRESULT
// ESP+0-> ret addr
//
// Make it so.
//
POP EDX
PUSH 8000FFFFH
PUSH EDX
OR EAX, EAX // Was this a method call?
JE @@Done
PUSH EAX
CALL CurrentException
MOV EDX, [EAX].TRaisedException.ExceptObject
MOV ECX, [EAX].TRaisedException.ExceptionAddr;
POP EAX
MOV EAX, [EAX]
CALL [EAX].vmtSafeCallException.Pointer;
MOV [ESP+4], EAX
@@Done:
CALL _DoneExcept
end;
{$ELSE}
begin
Error(reSafeCallError); //!!
end;
{$ENDIF}
{$ENDIF}
{$IFDEF MSWINDOWS}
asm
{ -> [ESP+ 4] excPtr: PExceptionRecord }
{ [ESP+ 8] errPtr: PExcFrame }
{ [ESP+12] ctxPtr: Pointer }
{ [ESP+16] dspPtr: Pointer }
{ <- EAX return value - always one }
MOV EAX,[ESP+4]
TEST [EAX].TExceptionRecord.ExceptionFlags,cUnwindInProgress
JNE @@exit
CMP [EAX].TExceptionRecord.ExceptionCode,cDelphiException
CLD
CALL _FpuInit
JE @@DelphiException
CMP BYTE PTR JITEnable,0
JBE @@DelphiException
CMP BYTE PTR DebugHook,0
JA @@DelphiException
@@DoUnhandled:
LEA EAX,[ESP+4]
PUSH EAX
CALL UnhandledExceptionFilter
CMP EAX,EXCEPTION_CONTINUE_SEARCH
JE @@exit
MOV EAX,[ESP+4]
JMP @@GoUnwind
@@DelphiException:
CMP BYTE PTR JITEnable,1
JBE @@GoUnwind
CMP BYTE PTR DebugHook,0
JA @@GoUnwind
JMP @@DoUnhandled
@@GoUnwind:
OR [EAX].TExceptionRecord.ExceptionFlags,cUnwinding
PUSH ESI
PUSH EDI
PUSH EBP
MOV EDX,[ESP+8+3*4]
PUSH 0
PUSH EAX
PUSH offset @@returnAddress
PUSH EDX
CALL RtlUnwindProc
@@returnAddress:
POP EBP
POP EDI
POP ESI
MOV EAX,[ESP+4]
MOV EBX,8000FFFFH
CMP [EAX].TExceptionRecord.ExceptionCode,cDelphiException
JNE @@done
MOV EDX,[EAX].TExceptionRecord.ExceptObject
MOV ECX,[EAX].TExceptionRecord.ExceptAddr
MOV EAX,[ESP+8]
MOV EAX,[EAX].TExcFrame.SelfOfMethod
TEST EAX,EAX
JZ @@freeException
MOV EBX,[EAX]
CALL [EBX].vmtSafeCallException.Pointer
MOV EBX,EAX
@@freeException:
MOV EAX,[ESP+4]
MOV EAX,[EAX].TExceptionRecord.ExceptObject
CALL TObject.Free
@@done:
XOR EAX,EAX
MOV ESP,[ESP+8]
POP ECX
MOV FS:[EAX],ECX
POP EDX
POP EBP
LEA EDX,[EDX].TExcDesc.instructions
POP ECX
JMP EDX
@@exit:
MOV EAX,1
end;
{$ENDIF}
{$IFDEF PC_MAPPED_EXCEPTIONS}
procedure _RaiseAtExcept;
asm
{ -> EAX Pointer to exception object }
{ -> EDX Purported addr of exception }
{ Be careful: EBX is not set up in PIC mode. }
{ Outward bound calls must go through an exported fn, like SysRaiseException }
OR EAX, EAX
JNE @@GoAhead
MOV EAX, 216
CALL _RunError
@@GoAhead:
CALL BlockOSExceptions
PUSH EBP
MOV EBP, ESP
CALL NotifyReRaise
CALL AllocateException
CALL SysRaiseException
{
This can only return if there was a terrible error. In this event,
we have to bail out.
}
JMP _Run0Error
end;
{$ENDIF}
procedure _RaiseExcept;
asm
{$IFDEF PC_MAPPED_EXCEPTIONS}
{ -> EAX Pointer to exception object }
MOV EDX, [ESP]
JMP _RaiseAtExcept
{$ENDIF}
{$IFDEF MSWINDOWS}
{ When making changes to the way Delphi Exceptions are raised, }
{ please realize that the C++ Exception handling code reraises }
{ some exceptions as Delphi Exceptions. Of course we want to }
{ keep exception raising compatible between Delphi and C++, so }
{ when you make changes here, consult with the relevant C++ }
{ exception handling engineer. The C++ code is in xx.cpp, in }
{ the RTL sources, in function tossAnException. }
{ -> EAX Pointer to exception object }
{ [ESP] Error address }
OR EAX, EAX
JNE @@GoAhead
MOV EAX, 216
CALL _RunError
@@GoAhead:
POP EDX
PUSH ESP
PUSH EBP
PUSH EDI
PUSH ESI
PUSH EBX
PUSH EAX { pass class argument }
PUSH EDX { pass address argument }
PUSH ESP { pass pointer to arguments }
PUSH 7 { there are seven arguments }
PUSH cNonContinuable { we can't continue execution }
PUSH cDelphiException { our magic exception code }
PUSH EDX { pass the user's return address }
JMP RaiseExceptionProc
{$ENDIF}
end;
{$IFDEF PC_MAPPED_EXCEPTIONS}
{
Used in the PC mapping exception implementation to handle exceptions in constructors.
}
procedure _ClassHandleException;
asm
{
EAX = self
EDX = top flag
}
TEST DL, DL
JE _RaiseAgain
MOV ECX,[EAX]
MOV DL,$81
PUSH EAX
CALL dword ptr [ECX].vmtDestroy
POP EAX
CALL _ClassDestroy
JMP _RaiseAgain
end;
{$ENDIF}
procedure _RaiseAgain;
asm
{$IFDEF PC_MAPPED_EXCEPTIONS}
CALL CurrentException
// The following notifies the debugger of a reraise of exceptions. This will
// be supported in a later release, but is disabled for now.
// PUSH EAX
// MOV EDX, [EAX].TRaisedException.ExceptionAddr
// MOV EAX, [EAX].TRaisedException.ExceptObject
// CALL NotifyReRaise { Tell the debugger }
// POP EAX
TEST [EAX].TRaisedException.Flags, excIsBeingHandled
JZ @@DoIt
OR [EAX].TRaisedException.Flags, excIsBeingReRaised
@@DoIt:
MOV EDX, [ESP] { Get the user's addr }
JMP SysRaiseException
{$ENDIF}
{$IFDEF MSWINDOWS}
{ -> [ESP ] return address to user program }
{ [ESP+ 4 ] raise list entry (4 dwords) }
{ [ESP+ 4+ 4*4] saved topmost frame }
{ [ESP+ 4+ 5*4] saved registers (4 dwords) }
{ [ESP+ 4+ 9*4] return address to OS }
{ -> [ESP+ 4+10*4] excPtr: PExceptionRecord }
{ [ESP+ 8+10*4] errPtr: PExcFrame }
{ Point the error handler of the exception frame to something harmless }
MOV EAX,[ESP+8+10*4]
MOV [EAX].TExcFrame.desc,offset @@exit
{ Pop the RaiseList }
CALL SysInit.@GetTLS
MOV EDX,[EAX].RaiseListPtr
MOV ECX,[EDX].TRaiseFrame.NextRaise
MOV [EAX].RaiseListPtr,ECX
{ Destroy any objects created for non-delphi exceptions }
MOV EAX,[EDX].TRaiseFrame.ExceptionRecord
AND [EAX].TExceptionRecord.ExceptionFlags,NOT cUnwinding
CMP [EAX].TExceptionRecord.ExceptionCode,cDelphiException
JE @@delphiException
MOV EAX,[EDX].TRaiseFrame.ExceptObject
CALL TObject.Free
CALL NotifyReRaise
@@delphiException:
XOR EAX,EAX
ADD ESP,5*4
MOV EDX,FS:[EAX]
POP ECX
MOV EDX,[EDX].TExcFrame.next
MOV [ECX].TExcFrame.next,EDX
POP EBP
POP EDI
POP ESI
POP EBX
@@exit:
MOV EAX,1
{$ENDIF}
end;
{$IFDEF DEBUG_EXCEPTIONS}
procedure NoteDE;
begin
Writeln('DoneExcept: Skipped the destructor');
end;
procedure NoteDE2;
begin
Writeln('DoneExcept: Destroyed the object');
end;
{$ENDIF}
{$IFDEF PC_MAPPED_EXCEPTIONS}
{
This is implemented slow and dumb. The theory is that it is rare
to throw an exception past an except handler, and that the penalty
can be particularly high here. Partly it's done the dumb way for
the sake of maintainability. It could be inlined.
}
procedure _DestroyException;
var
Exc: PRaisedException;
RefCount: Integer;
ExcObj: Pointer;
ExcAddr: Pointer;
begin
asm
MOV Exc, EAX
end;
if (Exc^.Flags and excIsBeingReRaised) = 0 then
begin
RefCount := Exc^.RefCount;
ExcObj := Exc^.ExceptObject;
ExcAddr := Exc^.ExceptionAddr;
Exc^.RefCount := 1;
FreeException;
_DoneExcept;
Exc := AllocateException(ExcObj, ExcAddr);
Exc^.RefCount := RefCount;
end;
Exc^.Flags := Exc^.Flags and not (excIsBeingReRaised or excIsBeingHandled);
SysRaiseException(Exc);
end;
{$ENDIF}
procedure _DoneExcept;
asm
{$IFDEF PC_MAPPED_EXCEPTIONS}
CALL FreeException
OR EAX, EAX
JE @@Done
CALL TObject.Free
@@Done:
{
Take a peek at the next exception object on the stack.
If its EBP marker is at an address lower than our current
EBP, then we know that it was orphaned when an exception was
thrown from within the execution of a finally block. We clean
it up now, so that we won't leak exception records/objects.
}
CALL CurrentException
OR EAX, EAX
JE @@Done2
CMP [EAX].TRaisedException.HandlerEBP, EBP
JA @@Done2
CALL FreeException
OR EAX, EAX
JE @@Done2
CALL TObject.Free
@@Done2:
{$ENDIF}
{$IFDEF MSWINDOWS}
{ -> [ESP+ 4+10*4] excPtr: PExceptionRecord }
{ [ESP+ 8+10*4] errPtr: PExcFrame }
{ Pop the RaiseList }
CALL SysInit.@GetTLS
MOV EDX,[EAX].RaiseListPtr
MOV ECX,[EDX].TRaiseFrame.NextRaise
MOV [EAX].RaiseListPtr,ECX
{ Destroy exception object }
MOV EAX,[EDX].TRaiseFrame.ExceptObject
CALL TObject.Free
POP EDX
MOV ESP,[ESP+8+9*4]
XOR EAX,EAX
POP ECX
MOV FS:[EAX],ECX
POP EAX
POP EBP
CALL NotifyTerminate
JMP EDX
{$ENDIF}
end;
{$IFNDEF PC_MAPPED_EXCEPTIONS}
procedure _TryFinallyExit;
asm
{$IFDEF MSWINDOWS}
XOR EDX,EDX
MOV ECX,[ESP+4].TExcFrame.desc
MOV EAX,[ESP+4].TExcFrame.next
ADD ECX,TExcDesc.instructions
MOV FS:[EDX],EAX
CALL ECX
@@1: RET 12
{$ENDIF}
end;
{$ENDIF}
var
InitContext: TInitContext;
{$IFNDEF PC_MAPPED_EXCEPTIONS}
procedure MapToRunError(P: PExceptionRecord); stdcall;
const
STATUS_ACCESS_VIOLATION = $C0000005;
STATUS_ARRAY_BOUNDS_EXCEEDED = $C000008C;
STATUS_FLOAT_DENORMAL_OPERAND = $C000008D;
STATUS_FLOAT_DIVIDE_BY_ZERO = $C000008E;
STATUS_FLOAT_INEXACT_RESULT = $C000008F;
STATUS_FLOAT_INVALID_OPERATION = $C0000090;
STATUS_FLOAT_OVERFLOW = $C0000091;
STATUS_FLOAT_STACK_CHECK = $C0000092;
STATUS_FLOAT_UNDERFLOW = $C0000093;
STATUS_INTEGER_DIVIDE_BY_ZERO = $C0000094;
STATUS_INTEGER_OVERFLOW = $C0000095;
STATUS_PRIVILEGED_INSTRUCTION = $C0000096;
STATUS_STACK_OVERFLOW = $C00000FD;
STATUS_CONTROL_C_EXIT = $C000013A;
var
ErrCode: Byte;
begin
case P.ExceptionCode of
STATUS_INTEGER_DIVIDE_BY_ZERO: ErrCode := 200;
STATUS_ARRAY_BOUNDS_EXCEEDED: ErrCode := 201;
STATUS_FLOAT_OVERFLOW: ErrCode := 205;
STATUS_FLOAT_INEXACT_RESULT,
STATUS_FLOAT_INVALID_OPERATION,
STATUS_FLOAT_STACK_CHECK: ErrCode := 207;
STATUS_FLOAT_DIVIDE_BY_ZERO: ErrCode := 200;
STATUS_INTEGER_OVERFLOW: ErrCode := 215;
STATUS_FLOAT_UNDERFLOW,
STATUS_FLOAT_DENORMAL_OPERAND: ErrCode := 206;
STATUS_ACCESS_VIOLATION: ErrCode := 216;
STATUS_PRIVILEGED_INSTRUCTION: ErrCode := 218;
STATUS_CONTROL_C_EXIT: ErrCode := 217;
STATUS_STACK_OVERFLOW: ErrCode := 202;
else ErrCode := 255;
end;
RunErrorAt(ErrCode, P.ExceptionAddress);
end;
procedure _ExceptionHandler;
asm
MOV EAX,[ESP+4]
TEST [EAX].TExceptionRecord.ExceptionFlags,cUnwindInProgress
JNE @@exit
{$IFDEF MSWINDOWS}
CMP BYTE PTR DebugHook,0
JA @@ExecuteHandler
LEA EAX,[ESP+4]
PUSH EAX
CALL UnhandledExceptionFilter
CMP EAX,EXCEPTION_CONTINUE_SEARCH
JNE @@ExecuteHandler
JMP @@exit
{$ENDIF}
@@ExecuteHandler:
MOV EAX,[ESP+4]
CLD
CALL _FpuInit
MOV EDX,[ESP+8]
PUSH 0
PUSH EAX
PUSH offset @@returnAddress
PUSH EDX
CALL RtlUnwindProc
@@returnAddress:
MOV EBX,[ESP+4]
CMP [EBX].TExceptionRecord.ExceptionCode,cDelphiException
MOV EDX,[EBX].TExceptionRecord.ExceptAddr
MOV EAX,[EBX].TExceptionRecord.ExceptObject
JE @@DelphiException2
MOV EDX,ExceptObjProc
TEST EDX,EDX
JE MapToRunError
MOV EAX,EBX
CALL EDX
TEST EAX,EAX
JE MapToRunError
MOV EDX,[EBX].TExceptionRecord.ExceptionAddress
@@DelphiException2:
CALL NotifyUnhandled
MOV ECX,ExceptProc
TEST ECX,ECX
JE @@noExceptProc
CALL ECX { call ExceptProc(ExceptObject, ExceptAddr) }
@@noExceptProc:
MOV ECX,[ESP+4]
MOV EAX,217
MOV EDX,[ECX].TExceptionRecord.ExceptAddr
MOV [ESP],EDX
JMP _RunError
@@exit:
XOR EAX,EAX
end;
procedure SetExceptionHandler;
asm
XOR EDX,EDX { using [EDX] saves some space over [0] }
LEA EAX,[EBP-12]
MOV ECX,FS:[EDX] { ECX := head of chain }
MOV FS:[EDX],EAX { head of chain := @exRegRec }
MOV [EAX].TExcFrame.next,ECX
{$IFDEF PIC}
LEA EDX, [EBX]._ExceptionHandler
MOV [EAX].TExcFrame.desc, EDX
{$ELSE}
MOV [EAX].TExcFrame.desc,offset _ExceptionHandler
{$ENDIF}
MOV [EAX].TExcFrame.hEBP,EBP
{$IFDEF PIC}
MOV [EBX].InitContext.ExcFrame,EAX
{$ELSE}
MOV InitContext.ExcFrame,EAX
{$ENDIF}
end;
procedure UnsetExceptionHandler;
asm
XOR EDX,EDX
{$IFDEF PIC}
MOV EAX,[EBX].InitContext.ExcFrame
{$ELSE}
MOV EAX,InitContext.ExcFrame
{$ENDIF}
TEST EAX,EAX
JZ @@exit
MOV ECX,FS:[EDX] { ECX := head of chain }
CMP EAX,ECX { simple case: our record is first }
JNE @@search
MOV EAX,[EAX] { head of chain := exRegRec.next }
MOV FS:[EDX],EAX
JMP @@exit
@@loop:
MOV ECX,[ECX]
@@search:
CMP ECX,-1 { at end of list? }
JE @@exit { yes - didn't find it }
CMP [ECX],EAX { is it the next one on the list? }
JNE @@loop { no - look at next one on list }
@@unlink: { yes - unlink our record }
MOV EAX,[EAX] { get next record on list }
MOV [ECX],EAX { unlink our record }
@@exit:
end;
{$ENDIF} // not PC_MAPPED_EXCEPTIONS
type
TProc = procedure;
{$IFDEF LINUX}
procedure CallProc(Proc: Pointer; GOT: Cardinal);
asm
PUSH EBX
MOV EBX,EDX
ADD EAX,EBX
CALL EAX
POP EBX
end;
{$ENDIF}
procedure FinalizeUnits;
var
Count: Integer;
Table: PUnitEntryTable;
P: Pointer;
begin
if InitContext.InitTable = nil then
exit;
Count := InitContext.InitCount;
Table := InitContext.InitTable^.UnitInfo;
{$IFDEF LINUX}
Inc(Cardinal(Table), InitContext.Module^.GOT);
{$ENDIF}
try
while Count > 0 do
begin
Dec(Count);
InitContext.InitCount := Count;
P := Table^[Count].FInit;
if Assigned(P) then
begin
{$IFDEF LINUX}
CallProc(P, InitContext.Module^.GOT);
{$ENDIF}
{$IFDEF MSWINDOWS}
TProc(P)();
{$ENDIF}
end;
end;
except
FinalizeUnits; { try to finalize the others }
raise;
end;
end;
procedure InitUnits;
var
Count, I: Integer;
Table: PUnitEntryTable;
P: Pointer;
begin
if InitContext.InitTable = nil then
exit;
Count := InitContext.InitTable^.UnitCount;
I := 0;
Table := InitContext.InitTable^.UnitInfo;
{$IFDEF LINUX}
Inc(Cardinal(Table), InitContext.Module^.GOT);
{$ENDIF}
try
while I < Count do
begin
P := Table^[I].Init;
Inc(I);
InitContext.InitCount := I;
if Assigned(P) then
begin
{$IFDEF LINUX}
CallProc(P, InitContext.Module^.GOT);
{$ENDIF}
{$IFDEF MSWINDOWS}
TProc(P)();
{$ENDIF}
end;
end;
except
FinalizeUnits;
raise;
end;
end;
procedure _PackageLoad(const Table : PackageInfo; Module: PLibModule);
var
SavedContext: TInitContext;
begin
SavedContext := InitContext;
InitContext.DLLInitState := 0;
InitContext.InitTable := Table;
InitContext.InitCount := 0;
InitContext.Module := Module;
InitContext.OuterContext := @SavedContext;
try
InitUnits;
finally
InitContext := SavedContext;
end;
end;
procedure _PackageUnload(const Table : PackageInfo; Module: PLibModule);
var
SavedContext: TInitContext;
begin
SavedContext := InitContext;
InitContext.DLLInitState := 0;
InitContext.InitTable := Table;
InitContext.InitCount := Table^.UnitCount;
InitContext.Module := Module;
InitContext.OuterContext := @SavedContext;
try
FinalizeUnits;
finally
InitContext := SavedContext;
end;
end;
{$IFDEF LINUX}
procedure _StartExe(InitTable: PackageInfo; Module: PLibModule; Argc: Integer; Argv: Pointer);
begin
ArgCount := Argc;
ArgValues := Argv;
{$ENDIF}
{$IFDEF MSWINDOWS}
procedure _StartExe(InitTable: PackageInfo; Module: PLibModule);
begin
RaiseExceptionProc := @RaiseException;
RTLUnwindProc := @RTLUnwind;
{$ENDIF}
InitContext.InitTable := InitTable;
InitContext.InitCount := 0;
InitContext.Module := Module;
MainInstance := Module.Instance;
{$IFNDEF PC_MAPPED_EXCEPTIONS}
SetExceptionHandler;
{$ENDIF}
IsLibrary := False;
InitUnits;
end;
{$IFDEF MSWINDOWS}
procedure _StartLib;
asm
{ -> EAX InitTable }
{ EDX Module }
{ ECX InitTLS }
{ [ESP+4] DllProc }
{ [EBP+8] HInst }
{ [EBP+12] Reason }
{ Push some desperately needed registers }
PUSH ECX
PUSH ESI
PUSH EDI
{ Save the current init context into the stackframe of our caller }
MOV ESI,offset InitContext
LEA EDI,[EBP- (type TExcFrame) - (type TInitContext)]
MOV ECX,(type TInitContext)/4
REP MOVSD
{ Setup the current InitContext }
POP InitContext.DLLSaveEDI
POP InitContext.DLLSaveESI
MOV InitContext.DLLSaveEBP,EBP
MOV InitContext.DLLSaveEBX,EBX
MOV InitContext.InitTable,EAX
MOV InitContext.Module,EDX
LEA ECX,[EBP- (type TExcFrame) - (type TInitContext)]
MOV InitContext.OuterContext,ECX
XOR ECX,ECX
CMP dword ptr [EBP+12],0
JNE @@notShutDown
MOV ECX,[EAX].PackageInfoTable.UnitCount
@@notShutDown:
MOV InitContext.InitCount,ECX
MOV EAX, offset RaiseException
MOV RaiseExceptionProc, EAX
MOV EAX, offset RTLUnwind
MOV RTLUnwindProc, EAX
CALL SetExceptionHandler
MOV EAX,[EBP+12]
INC EAX
MOV InitContext.DLLInitState,AL
DEC EAX
{ Init any needed TLS }
POP ECX
MOV EDX,[ECX]
MOV InitContext.ExitProcessTLS,EDX
JE @@skipTLSproc
CMP AL,3 // DLL_THREAD_DETACH
JGE @@skipTLSproc // call ExitThreadTLS proc after DLLProc
CALL dword ptr [ECX+EAX*4]
@@skipTLSproc:
{ Call any DllProc }
PUSH ECX
MOV ECX,[ESP+4]
TEST ECX,ECX
JE @@noDllProc
MOV EAX,[EBP+12]
MOV EDX,[EBP+16]
CALL ECX
@@noDllProc:
POP ECX
MOV EAX, [EBP+12]
CMP AL,3 // DLL_THREAD_DETACH
JL @@afterDLLproc // don't free TLS on process shutdown
CALL dword ptr [ECX+EAX*4]
@@afterDLLProc:
{ Set IsLibrary if there was no exe yet }
CMP MainInstance,0
JNE @@haveExe
MOV IsLibrary,1
FNSTCW Default8087CW // save host exe's FPU preferences
@@haveExe:
MOV EAX,[EBP+12]
DEC EAX
JNE _Halt0
CALL InitUnits
RET 4
end;
{$ENDIF MSWINDOWS}
{$IFDEF LINUX}
procedure _StartLib(Context: PInitContext; Module: PLibModule; DLLProc: TDLLProcEx);
var
TempSwap: TInitContext;
begin
// Context's register save fields are already initialized.
// Save the current InitContext and activate the new Context by swapping them
TempSwap := InitContext;
InitContext := PInitContext(Context)^;
PInitContext(Context)^ := TempSwap;
InitContext.Module := Module;
InitContext.OuterContext := Context;
// DLLInitState is initialized by SysInit to 0 for shutdown, 1 for startup
// Inc DLLInitState to distinguish from package init:
// 0 for package, 1 for DLL shutdown, 2 for DLL startup
Inc(InitContext.DLLInitState);
if InitContext.DLLInitState = 1 then
begin
InitContext.InitTable := Module.InitTable;
if Assigned(InitContext.InitTable) then
InitContext.InitCount := InitContext.InitTable.UnitCount // shutdown
end
else
begin
Module.InitTable := InitContext.InitTable; // save for shutdown
InitContext.InitCount := 0; // startup
end;
if Assigned(DLLProc) then
DLLProc(InitContext.DLLInitState-1,0);
if MainInstance = 0 then { Set IsLibrary if there was no exe yet }
begin
IsLibrary := True;
Default8087CW := Get8087CW;
end;
if InitContext.DLLInitState = 1 then
_Halt0
else
InitUnits;
end;
{$ENDIF}
procedure _InitResStrings;
asm
{ -> EAX Pointer to init table }
{ record }
{ cnt: Integer; }
{ tab: array [1..cnt] record }
{ variableAddress: Pointer; }
{ resStringAddress: Pointer; }
{ end; }
{ end; }
{ EBX = caller's GOT for PIC callers, 0 for non-PIC }
{$IFDEF MSWINDOWS}
PUSH EBX
XOR EBX,EBX
{$ENDIF}
PUSH EDI
PUSH ESI
MOV EDI,[EBX+EAX]
LEA ESI,[EBX+EAX+4]
@@loop:
MOV EAX,[ESI+4] { load resStringAddress }
MOV EDX,[ESI] { load variableAddress }
ADD EAX,EBX
ADD EDX,EBX
CALL LoadResString
ADD ESI,8
DEC EDI
JNZ @@loop
POP ESI
POP EDI
{$IFDEF MSWINDOWS}
POP EBX
{$ENDIF}
end;
procedure _InitResStringImports;
asm
{ -> EAX Pointer to init table }
{ record }
{ cnt: Integer; }
{ tab: array [1..cnt] record }
{ variableAddress: Pointer; }
{ resStringAddress: ^Pointer; }
{ end; }
{ end; }
{ EBX = caller's GOT for PIC callers, 0 for non-PIC }
{$IFDEF MSWINDOWS}
PUSH EBX
XOR EBX,EBX
{$ENDIF}
PUSH EDI
PUSH ESI
MOV EDI,[EBX+EAX]
LEA ESI,[EBX+EAX+4]
@@loop:
MOV EAX,[ESI+4] { load address of import }
MOV EDX,[ESI] { load address of variable }
MOV EAX,[EBX+EAX] { load contents of import }
ADD EDX,EBX
CALL LoadResString
ADD ESI,8
DEC EDI
JNZ @@loop
POP ESI
POP EDI
{$IFDEF MSWINDOWS}
POP EBX
{$ENDIF}
end;
procedure _InitImports;
asm
{ -> EAX Pointer to init table }
{ record }
{ cnt: Integer; }
{ tab: array [1..cnt] record }
{ variableAddress: Pointer; }
{ sourceAddress: ^Pointer; }
{ sourceOffset: Longint; }
{ end; }
{ end; }
{ EBX = caller's GOT for PIC callers, 0 for non-PIC }
{$IFDEF MSWINDOWS}
PUSH EBX
XOR EBX,EBX
{$ENDIF}
PUSH EDI
PUSH ESI
MOV EDI,[EBX+EAX]
LEA ESI,[EBX+EAX+4]
@@loop:
MOV EAX,[ESI+4] { load address of import }
MOV EDX,[ESI] { load address of variable }
MOV EAX,[EBX+EAX] { load contents of import }
ADD EAX,[ESI+8] { calc address of variable }
MOV [EBX+EDX],EAX { store result }
ADD ESI,12
DEC EDI
JNZ @@loop
POP ESI
POP EDI
{$IFDEF MSWINDOWS}
POP EBX
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
procedure _InitWideStrings;
asm
{ -> EAX Pointer to init table }
{ record }
{ cnt: Integer; }
{ tab: array [1..cnt] record }
{ variableAddress: Pointer; }
{ stringAddress: ^Pointer; }
{ end; }
{ end; }
PUSH EBX
PUSH ESI
MOV EBX,[EAX]
LEA ESI,[EAX+4]
@@loop:
MOV EDX,[ESI+4] { load address of string }
MOV EAX,[ESI] { load address of variable }
CALL _WStrAsg
ADD ESI,8
DEC EBX
JNZ @@loop
POP ESI
POP EBX
end;
{$ENDIF}
var
runErrMsg: array[0..29] of Char = 'Runtime error at 00000000'#0;
// columns: 0123456789012345678901234567890
errCaption: array[0..5] of Char = 'Error'#0;
procedure MakeErrorMessage;
const
dig : array [0..15] of Char = '0123456789ABCDEF';
var
digit: Byte;
Temp: Integer;
Addr: Cardinal;
begin
digit := 16;
Temp := ExitCode;
repeat
runErrMsg[digit] := Char(Ord('0') + (Temp mod 10));
Temp := Temp div 10;
Dec(digit);
until Temp = 0;
digit := 28;
Addr := Cardinal(ErrorAddr);
repeat
runErrMsg[digit] := dig[Addr and $F];
Addr := Addr div 16;
Dec(digit);
until Addr = 0;
end;
procedure ExitDll;
asm
{ Return False if ExitCode <> 0, and set ExitCode to 0 }
XOR EAX,EAX
{$IFDEF PIC}
MOV ECX,[EBX].ExitCode
XCHG EAX,[ECX]
{$ELSE}
XCHG EAX, ExitCode
{$ENDIF}
NEG EAX
SBB EAX,EAX
INC EAX
{ Restore the InitContext }
{$IFDEF PIC}
LEA EDI, [EBX].InitContext
{$ELSE}
MOV EDI, offset InitContext
{$ENDIF}
MOV EBX,[EDI].TInitContext.DLLSaveEBX
MOV EBP,[EDI].TInitContext.DLLSaveEBP
PUSH [EDI].TInitContext.DLLSaveESI
PUSH [EDI].TInitContext.DLLSaveEDI
MOV ESI,[EDI].TInitContext.OuterContext
MOV ECX,(type TInitContext)/4
REP MOVSD
POP EDI
POP ESI
LEAVE
{$IFDEF MSWINDOWS}
RET 12
{$ENDIF}
{$IFDEF LINUX}
RET
{$ENDIF}
end;
procedure WriteErrorMessage;
{$IFDEF MSWINDOWS}
var
Dummy: Cardinal;
begin
if IsConsole then
begin
with TTextRec(Output) do
begin
if (Mode = fmOutput) and (BufPos > 0) then
TTextIOFunc(InOutFunc)(TTextRec(Output)); // flush out text buffer
end;
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), runErrMsg, Sizeof(runErrMsg), Dummy, nil);
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), sLineBreak, 2, Dummy, nil);
end
else if not NoErrMsg then
MessageBox(0, runErrMsg, errCaption, 0);
{$ENDIF}
{$IFDEF LINUX}
var
c: Char;
begin
with TTextRec(Output) do
begin
if (Mode = fmOutput) and (BufPos > 0) then
TTextIOFunc(InOutFunc)(TTextRec(Output)); // flush out text buffer
end;
__write(STDERR_FILENO, @runErrMsg, Sizeof(runErrMsg)-1);
c := sLineBreak;
__write(STDERR_FILENO, @c, 1);
{$ENDIF}
end;
procedure _Halt0;
var
P: procedure;
begin
{$IFDEF LINUX}
if (ExitCode <> 0) and CoreDumpEnabled then
__raise(SIGABRT);
{$ENDIF}
if InitContext.DLLInitState = 0 then
while ExitProc <> nil do
begin
@P := ExitProc;
ExitProc := nil;
P;
end;
{ If there was some kind of runtime error, alert the user }
if ErrorAddr <> nil then
begin
MakeErrorMessage;
WriteErrorMessage;
ErrorAddr := nil;
end;
{ This loop exists because we might be nested in PackageLoad calls when }
{ Halt got called. We need to unwind these contexts. }
while True do
begin
{ If we are a library, and we are starting up fine, there are no units to finalize }
if (InitContext.DLLInitState = 2) and (ExitCode = 0) then
InitContext.InitCount := 0;
{ Undo any unit initializations accomplished so far }
FinalizeUnits;
if (InitContext.DLLInitState <= 1) or (ExitCode <> 0) then
begin
if InitContext.Module <> nil then
with InitContext do
begin
UnregisterModule(Module);
{$IFDEF PC_MAPPED_EXCEPTIONS}
SysUnregisterIPLookup(Module.CodeSegStart);
{$ENDIF}
if (Module.ResInstance <> Module.Instance) and (Module.ResInstance <> 0) then
FreeLibrary(Module.ResInstance);
end;
end;
{$IFNDEF PC_MAPPED_EXCEPTIONS}
UnsetExceptionHandler;
{$ENDIF}
{$IFDEF MSWINDOWS}
if InitContext.DllInitState = 1 then
InitContext.ExitProcessTLS;
{$ENDIF}
if InitContext.DllInitState <> 0 then
ExitDll;
if InitContext.OuterContext = nil then
begin
{
If an ExitProcessProc is set, we call it. Note that at this
point the RTL is completely shutdown. The only thing this is used
for right now is the proper semantic handling of signals under Linux.
}
if Assigned(ExitProcessProc) then
ExitProcessProc;
ExitProcess(ExitCode);
end;
InitContext := InitContext.OuterContext^
end;
end;
procedure _Halt;
begin
ExitCode := Code;
_Halt0;
end;
procedure _Run0Error;
{$IFDEF PUREPASCAL}
begin
_RunError(0); // loses return address
end;
{$ELSE}
asm
XOR EAX,EAX
JMP _RunError
end;
{$ENDIF}
procedure _RunError(errorCode: Byte);
{$IFDEF PUREPASCAL}
begin
ErrorAddr := Pointer(-1); // no return address available
Halt(errorCode);
end;
{$ELSE}
asm
{$IFDEF PIC}
PUSH EAX
CALL GetGOT
MOV EBX, EAX
POP EAX
MOV ECX, [EBX].ErrorAddr
POP [ECX]
{$ELSE}
POP ErrorAddr
{$ENDIF}
JMP _Halt
end;
{$ENDIF}
procedure _UnhandledException;
type TExceptProc = procedure (Obj: TObject; Addr: Pointer);
begin
if Assigned(ExceptProc) then
TExceptProc(ExceptProc)(ExceptObject, ExceptAddr)
else
RunError(230);
end;
procedure _Assert(const Message, Filename: AnsiString; LineNumber: Integer);
{$IFDEF PUREPASCAL}
begin
if Assigned(AssertErrorProc) then
AssertErrorProc(Message, Filename, LineNumber, Pointer(-1))
else
Error(reAssertionFailed); // loses return address
end;
{$ELSE}
asm
PUSH EBX
{$IFDEF PIC}
PUSH EAX
PUSH ECX
CALL GetGOT
MOV EBX, EAX
MOV EAX, [EBX].AssertErrorProc
CMP [EAX], 0
POP ECX
POP EAX
{$ELSE}
CMP AssertErrorProc,0
{$ENDIF}
JNZ @@1
MOV AL,reAssertionFailed
CALL Error
JMP @@exit
@@1: PUSH [ESP+4].Pointer
{$IFDEF PIC}
MOV EBX, [EBX].AssertErrorProc
CALL [EBX]
{$ELSE}
CALL AssertErrorProc
{$ENDIF}
@@exit:
POP EBX
end;
{$ENDIF}
type
PThreadRec = ^TThreadRec;
TThreadRec = record
Func: TThreadFunc;
Parameter: Pointer;
end;
{$IFDEF MSWINDOWS}
function ThreadWrapper(Parameter: Pointer): Integer; stdcall;
{$ELSE}
function ThreadWrapper(Parameter: Pointer): Pointer; cdecl;
{$ENDIF}
asm
{$IFDEF PC_MAPPED_EXCEPTIONS}
{ Mark the top of the stack with a signature }
PUSH UNWINDFI_TOPOFSTACK
{$ENDIF}
CALL _FpuInit
PUSH EBP
{$IFNDEF PC_MAPPED_EXCEPTIONS}
XOR ECX,ECX
PUSH offset _ExceptionHandler
MOV EDX,FS:[ECX]
PUSH EDX
MOV FS:[ECX],ESP
{$ENDIF}
MOV EAX,Parameter
MOV ECX,[EAX].TThreadRec.Parameter
MOV EDX,[EAX].TThreadRec.Func
PUSH ECX
PUSH EDX
CALL _FreeMem
POP EDX
POP EAX
CALL EDX
{$IFNDEF PC_MAPPED_EXCEPTIONS}
XOR EDX,EDX
POP ECX
MOV FS:[EDX],ECX
POP ECX
{$ENDIF}
POP EBP
{$IFDEF PC_MAPPED_EXCEPTIONS}
{ Ditch our TOS marker }
ADD ESP, 4
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
function BeginThread(SecurityAttributes: Pointer; StackSize: LongWord;
ThreadFunc: TThreadFunc; Parameter: Pointer; CreationFlags: LongWord;
var ThreadId: LongWord): Integer;
var
P: PThreadRec;
begin
New(P);
P.Func := ThreadFunc;
P.Parameter := Parameter;
IsMultiThread := TRUE;
Result := CreateThread(SecurityAttributes, StackSize, @ThreadWrapper, P,
CreationFlags, ThreadID);
end;
procedure EndThread(ExitCode: Integer);
begin
ExitThread(ExitCode);
end;
{$ENDIF}
{$IFDEF LINUX}
function BeginThread(Attribute: PThreadAttr;
ThreadFunc: TThreadFunc;
Parameter: Pointer;
var ThreadId: Cardinal): Integer;
var
P: PThreadRec;
begin
if Assigned(BeginThreadProc) then
Result := BeginThreadProc(Attribute, ThreadFunc, Parameter, ThreadId)
else
begin
New(P);
P.Func := ThreadFunc;
P.Parameter := Parameter;
IsMultiThread := True;
Result := _pthread_create(ThreadID, Attribute, @ThreadWrapper, P);
end;
end;
procedure EndThread(ExitCode: Integer);
begin
if Assigned(EndThreadProc) then
EndThreadProc(ExitCode);
// No "else" required since EndThreadProc does not (!!should not!!) return.
_pthread_detach(GetCurrentThreadID);
_pthread_exit(ExitCode);
end;
{$ENDIF}
type
PStrRec = ^StrRec;
StrRec = packed record
refCnt: Longint;
length: Longint;
end;
const
skew = sizeof(StrRec);
rOff = sizeof(StrRec); { refCnt offset }
overHead = sizeof(StrRec) + 1;
procedure _LStrClr(var S);
{$IFDEF PUREPASCAL}
var
P: PStrRec;
begin
if Pointer(S) <> nil then
begin
P := Pointer(Integer(S) - Sizeof(StrRec));
Pointer(S) := nil;
if P.refCnt > 0 then
if InterlockedDecrement(P.refCnt) = 0 then
FreeMem(P);
end;
end;
{$ELSE}
asm
{ -> EAX pointer to str }
MOV EDX,[EAX] { fetch str }
TEST EDX,EDX { if nil, nothing to do }
JE @@done
MOV dword ptr [EAX],0 { clear str }
MOV ECX,[EDX-skew].StrRec.refCnt { fetch refCnt }
DEC ECX { if < 0: literal str }
JL @@done
LOCK DEC [EDX-skew].StrRec.refCnt { threadsafe dec refCount }
JNE @@done
PUSH EAX
LEA EAX,[EDX-skew].StrRec.refCnt { if refCnt now zero, deallocate}
CALL _FreeMem
POP EAX
@@done:
end;
{$ENDIF}
procedure _LStrArrayClr(var StrArray; cnt: longint);
{$IFDEF PUREPASCAL}
var
P: Pointer;
begin
P := @StrArray;
while cnt > 0 do
begin
_LStrClr(P^);
Dec(cnt);
Inc(Integer(P), sizeof(Pointer));
end;
end;
{$ELSE}
asm
{ -> EAX pointer to str }
{ EDX cnt }
PUSH EBX
PUSH ESI
MOV EBX,EAX
MOV ESI,EDX
@@loop:
MOV EDX,[EBX] { fetch str }
TEST EDX,EDX { if nil, nothing to do }
JE @@doneEntry
MOV dword ptr [EBX],0 { clear str }
MOV ECX,[EDX-skew].StrRec.refCnt { fetch refCnt }
DEC ECX { if < 0: literal str }
JL @@doneEntry
LOCK DEC [EDX-skew].StrRec.refCnt { threadsafe dec refCount }
JNE @@doneEntry
LEA EAX,[EDX-skew].StrRec.refCnt { if refCnt now zero, deallocate}
CALL _FreeMem
@@doneEntry:
ADD EBX,4
DEC ESI
JNE @@loop
POP ESI
POP EBX
end;
{$ENDIF}
{ 99.03.11
This function is used when assigning to global variables.
Literals are copied to prevent a situation where a dynamically
allocated DLL or package assigns a literal to a variable and then
is unloaded -- thereby causing the string memory (in the code
segment of the DLL) to be removed -- and therefore leaving the
global variable pointing to invalid memory.
}
procedure _LStrAsg(var dest; const source);
{$IFDEF PUREPASCAL}
var
S, D: Pointer;
P: PStrRec;
Temp: Longint;
begin
S := Pointer(source);
if S <> nil then
begin
P := PStrRec(Integer(S) - sizeof(StrRec));
if P.refCnt < 0 then // make copy of string literal
begin
Temp := P.length;
S := _NewAnsiString(Temp);
Move(Pointer(source)^, S^, Temp);
P := PStrRec(Integer(S) - sizeof(StrRec));
end;
InterlockedIncrement(P.refCnt);
end;
D := Pointer(dest);
Pointer(dest) := S;
if D <> nil then
begin
P := PStrRec(Integer(D) - sizeof(StrRec));
if P.refCnt > 0 then
if InterlockedDecrement(P.refCnt) = 0 then
FreeMem(P);
end;
end;
{$ELSE}
asm
{ -> EAX pointer to dest str }
{ -> EDX pointer to source str }
TEST EDX,EDX { have a source? }
JE @@2 { no -> jump }
MOV ECX,[EDX-skew].StrRec.refCnt
INC ECX
JG @@1 { literal string -> jump not taken }
PUSH EAX
PUSH EDX
MOV EAX,[EDX-skew].StrRec.length
CALL _NewAnsiString
MOV EDX,EAX
POP EAX
PUSH EDX
MOV ECX,[EAX-skew].StrRec.length
CALL Move
POP EDX
POP EAX
JMP @@2
@@1:
LOCK INC [EDX-skew].StrRec.refCnt
@@2: XCHG EDX,[EAX]
TEST EDX,EDX
JE @@3
MOV ECX,[EDX-skew].StrRec.refCnt
DEC ECX
JL @@3
LOCK DEC [EDX-skew].StrRec.refCnt
JNE @@3
LEA EAX,[EDX-skew].StrRec.refCnt
CALL _FreeMem
@@3:
end;
{$ENDIF}
procedure _LStrLAsg(var dest; const source);
{$IFDEF PUREPASCAL}
var
P: Pointer;
begin
P := Pointer(source);
_LStrAddRef(P);
P := Pointer(dest);
Pointer(dest) := Pointer(source);
_LStrClr(P);
end;
{$ELSE}
asm
{ -> EAX pointer to dest }
{ EDX source }
TEST EDX,EDX
JE @@sourceDone
{ bump up the ref count of the source }
MOV ECX,[EDX-skew].StrRec.refCnt
INC ECX
JLE @@sourceDone { literal assignment -> jump taken }
LOCK INC [EDX-skew].StrRec.refCnt
@@sourceDone:
{ we need to release whatever the dest is pointing to }
XCHG EDX,[EAX] { fetch str }
TEST EDX,EDX { if nil, nothing to do }
JE @@done
MOV ECX,[EDX-skew].StrRec.refCnt { fetch refCnt }
DEC ECX { if < 0: literal str }
JL @@done
LOCK DEC [EDX-skew].StrRec.refCnt { threadsafe dec refCount }
JNE @@done
LEA EAX,[EDX-skew].StrRec.refCnt { if refCnt now zero, deallocate}
CALL _FreeMem
@@done:
end;
{$ENDIF}
function _NewAnsiString(length: Longint): Pointer;
{$IFDEF PUREPASCAL}
var
P: PStrRec;
begin
Result := nil;
if length <= 0 then Exit;
// Alloc an extra null for strings with even length. This has no actual cost
// since the allocator will round up the request to an even size anyway.
// All widestring allocations have even length, and need a double null terminator.
GetMem(P, length + sizeof(StrRec) + 1 + ((length + 1) and 1));
Result := Pointer(Integer(P) + sizeof(StrRec));
P.length := length;
P.refcnt := 1;
PWideChar(Result)[length div 2] := #0; // length guaranteed >= 2
end;
{$ELSE}
asm
{ -> EAX length }
{ <- EAX pointer to new string }
TEST EAX,EAX
JLE @@null
PUSH EAX
ADD EAX,rOff+2 // one or two nulls (Ansi/Wide)
AND EAX, not 1 // round up to even length
PUSH EAX
CALL _GetMem
POP EDX // actual allocated length (>= 2)
MOV word ptr [EAX+EDX-2],0 // double null terminator
ADD EAX,rOff
POP EDX // requested string length
MOV [EAX-skew].StrRec.length,EDX
MOV [EAX-skew].StrRec.refCnt,1
RET
@@null:
XOR EAX,EAX
end;
{$ENDIF}
procedure _LStrFromPCharLen(var Dest: AnsiString; Source: PAnsiChar; Length: Integer);
asm
{ -> EAX pointer to dest }
{ EDX source }
{ ECX length }
PUSH EBX
PUSH ESI
PUSH EDI
MOV EBX,EAX
MOV ESI,EDX
MOV EDI,ECX
{ allocate new string }
MOV EAX,EDI
CALL _NewAnsiString
MOV ECX,EDI
MOV EDI,EAX
TEST ESI,ESI
JE @@noMove
MOV EDX,EAX
MOV EAX,ESI
CALL Move
{ assign the result to dest }
@@noMove:
MOV EAX,EBX
CALL _LStrClr
MOV [EBX],EDI
POP EDI
POP ESI
POP EBX
end;
{$IFDEF LINUX}
function BufConvert(var Dest; DestBytes: Integer;
const Source; SrcBytes: Integer;
context: Integer): Integer;
var
SrcBytesLeft, DestBytesLeft: Integer;
s, d: Pointer;
begin
if context = -1 then
begin
Result := -1;
Exit;
end;
// make copies of params... iconv modifies param ptrs
DestBytesLeft := DestBytes;
SrcBytesLeft := SrcBytes;
s := Pointer(Source);
d := Pointer(Dest);
if (SrcBytes = 0) or (DestBytes = 0) then
Result := 0
else
begin
Result := iconv(context, s, SrcBytesLeft, d, DestBytesLeft);
while (SrcBytesLeft > 0) and (DestBytesLeft > 0)
and (Result = -1) and (GetLastError = 7) do
begin
Result := iconv(context, s, SrcBytesLeft, d, DestBytesLeft);
end;
if Result <> -1 then
Result := DestBytes - DestBytesLeft;
end;
iconv_close(context);
end;
{$ENDIF}
function CharFromWChar(CharDest: PChar; DestBytes: Integer; const WCharSource: PWideChar; SrcChars: Integer): Integer;
begin
{$IFDEF LINUX}
Result := BufConvert(CharDest, DestBytes, WCharSource, SrcChars * sizeof(WideChar),
iconv_open(nl_langinfo(_NL_CTYPE_CODESET_NAME), 'UNICODELITTLE'));
{$ENDIF}
{$IFDEF MSWINDOWS}
Result := WideCharToMultiByte(0, 0, WCharSource, SrcChars,
CharDest, DestBytes, nil, nil);
{$ENDIF}
end;
function WCharFromChar(WCharDest: PWideChar; DestChars: Integer; const CharSource: PChar; SrcBytes: Integer): Integer;
begin
{$IFDEF LINUX}
Result := BufConvert(WCharDest, DestChars * sizeof(WideChar), CharSource, SrcBytes,
iconv_open('UNICODELITTLE', nl_langinfo(_NL_CTYPE_CODESET_NAME))) div sizeof(WideChar);
{$ENDIF}
{$IFDEF MSWINDOWS}
Result := MultiByteToWideChar(0, 0, CharSource, SrcBytes,
WCharDest, DestChars);
{$ENDIF}
end;
procedure _LStrFromPWCharLen(var Dest: AnsiString; Source: PWideChar; Length: Integer);
var
DestLen: Integer;
Buffer: array[0..4095] of Char;
begin
if Length <= 0 then
begin
_LStrClr(Dest);
Exit;
end;
if Length+1 < (High(Buffer) div sizeof(WideChar)) then
begin
DestLen := CharFromWChar(Buffer, High(Buffer), Source, Length);
if DestLen >= 0 then
begin
_LStrFromPCharLen(Dest, Buffer, DestLen);
Exit;
end;
end;
DestLen := (Length + 1) * sizeof(WideChar);
SetLength(Dest, DestLen); // overallocate, trim later
DestLen := CharFromWChar(Pointer(Dest), DestLen, Source, Length);
if DestLen < 0 then DestLen := 0;
SetLength(Dest, DestLen);
end;
procedure _LStrFromChar(var Dest: AnsiString; Source: AnsiChar);
asm
PUSH EDX
MOV EDX,ESP
MOV ECX,1
CALL _LStrFromPCharLen
POP EDX
end;
procedure _LStrFromWChar(var Dest: AnsiString; Source: WideChar);
asm
PUSH EDX
MOV EDX,ESP
MOV ECX,1
CALL _LStrFromPWCharLen
POP EDX
end;
procedure _LStrFromPChar(var Dest: AnsiString; Source: PAnsiChar);
asm
XOR ECX,ECX
TEST EDX,EDX
JE @@5
PUSH EDX
@@0: CMP CL,[EDX+0]
JE @@4
CMP CL,[EDX+1]
JE @@3
CMP CL,[EDX+2]
JE @@2
CMP CL,[EDX+3]
JE @@1
ADD EDX,4
JMP @@0
@@1: INC EDX
@@2: INC EDX
@@3: INC EDX
@@4: MOV ECX,EDX
POP EDX
SUB ECX,EDX
@@5: JMP _LStrFromPCharLen
end;
procedure _LStrFromPWChar(var Dest: AnsiString; Source: PWideChar);
asm
XOR ECX,ECX
TEST EDX,EDX
JE @@5
PUSH EDX
@@0: CMP CX,[EDX+0]
JE @@4
CMP CX,[EDX+2]
JE @@3
CMP CX,[EDX+4]
JE @@2
CMP CX,[EDX+6]
JE @@1
ADD EDX,8
JMP @@0
@@1: ADD EDX,2
@@2: ADD EDX,2
@@3: ADD EDX,2
@@4: MOV ECX,EDX
POP EDX
SUB ECX,EDX
SHR ECX,1
@@5: JMP _LStrFromPWCharLen
end;
procedure _LStrFromString(var Dest: AnsiString; const Source: ShortString);
asm
XOR ECX,ECX
MOV CL,[EDX]
INC EDX
JMP _LStrFromPCharLen
end;
procedure _LStrFromArray(var Dest: AnsiString; Source: PAnsiChar; Length: Integer);
asm
PUSH EDI
PUSH EAX
PUSH ECX
MOV EDI,EDX
XOR EAX,EAX
REPNE SCASB
JNE @@1
NOT ECX
@@1: POP EAX
ADD ECX,EAX
POP EAX
POP EDI
JMP _LStrFromPCharLen
end;
procedure _LStrFromWArray(var Dest: AnsiString; Source: PWideChar; Length: Integer);
asm
PUSH EDI
PUSH EAX
PUSH ECX
MOV EDI,EDX
XOR EAX,EAX
REPNE SCASW
JNE @@1
NOT ECX
@@1: POP EAX
ADD ECX,EAX
POP EAX
POP EDI
JMP _LStrFromPWCharLen
end;
procedure _LStrFromWStr(var Dest: AnsiString; const Source: WideString);
asm
{ -> EAX pointer to dest }
{ EDX pointer to WideString data }
XOR ECX,ECX
TEST EDX,EDX
JE @@1
MOV ECX,[EDX-4]
SHR ECX,1
@@1: JMP _LStrFromPWCharLen
end;
procedure _LStrToString{(var Dest: ShortString; const Source: AnsiString; MaxLen: Integer)};
asm
{ -> EAX pointer to result }
{ EDX AnsiString s }
{ ECX length of result }
PUSH EBX
TEST EDX,EDX
JE @@empty
MOV EBX,[EDX-skew].StrRec.length
TEST EBX,EBX
JE @@empty
CMP ECX,EBX
JL @@truncate
MOV ECX,EBX
@@truncate:
MOV [EAX],CL
INC EAX
XCHG EAX,EDX
CALL Move
JMP @@exit
@@empty:
MOV byte ptr [EAX],0
@@exit:
POP EBX
end;
function _LStrLen(const s: AnsiString): Longint;
{$IFDEF PUREPASCAL}
begin
Result := 0;
if Pointer(s) <> nil then
Result := PStrRec(Integer(s) - sizeof(StrRec)).length;
end;
{$ELSE}
asm
{ -> EAX str }
TEST EAX,EAX
JE @@done
MOV EAX,[EAX-skew].StrRec.length;
@@done:
end;
{$ENDIF}
procedure _LStrCat{var dest: AnsiString; source: AnsiString};
asm
{ -> EAX pointer to dest }
{ EDX source }
TEST EDX,EDX
JE @@exit
MOV ECX,[EAX]
TEST ECX,ECX
JE _LStrAsg
PUSH EBX
PUSH ESI
PUSH EDI
MOV EBX,EAX
MOV ESI,EDX
MOV EDI,[ECX-skew].StrRec.length
MOV EDX,[ESI-skew].StrRec.length
ADD EDX,EDI
CMP ESI,ECX
JE @@appendSelf
CALL _LStrSetLength
MOV EAX,ESI
MOV ECX,[ESI-skew].StrRec.length
@@appendStr:
MOV EDX,[EBX]
ADD EDX,EDI
CALL Move
POP EDI
POP ESI
POP EBX
RET
@@appendSelf:
CALL _LStrSetLength
MOV EAX,[EBX]
MOV ECX,EDI
JMP @@appendStr
@@exit:
end;
procedure _LStrCat3{var dest:AnsiString; source1: AnsiString; source2: AnsiString};
asm
{ ->EAX = Pointer to dest }
{ EDX = source1 }
{ ECX = source2 }
TEST EDX,EDX
JE @@assignSource2
TEST ECX,ECX
JE _LStrAsg
CMP EDX,[EAX]
JE @@appendToDest
CMP ECX,[EAX]
JE @@theHardWay
PUSH EAX
PUSH ECX
CALL _LStrAsg
POP EDX
POP EAX
JMP _LStrCat
@@theHardWay:
PUSH EBX
PUSH ESI
PUSH EDI
MOV EBX,EDX
MOV ESI,ECX
PUSH EAX
MOV EAX,[EBX-skew].StrRec.length
ADD EAX,[ESI-skew].StrRec.length
CALL _NewAnsiString
MOV EDI,EAX
MOV EDX,EAX
MOV EAX,EBX
MOV ECX,[EBX-skew].StrRec.length
CALL Move
MOV EDX,EDI
MOV EAX,ESI
MOV ECX,[ESI-skew].StrRec.length
ADD EDX,[EBX-skew].StrRec.length
CALL Move
POP EAX
MOV EDX,EDI
TEST EDI,EDI
JE @@skip
DEC [EDI-skew].StrRec.refCnt // EDI = local temp str
@@skip:
CALL _LStrAsg
POP EDI
POP ESI
POP EBX
JMP @@exit
@@assignSource2:
MOV EDX,ECX
JMP _LStrAsg
@@appendToDest:
MOV EDX,ECX
JMP _LStrCat
@@exit:
end;
procedure _LStrCatN{var dest:AnsiString; argCnt: Integer; ...};
asm
{ ->EAX = Pointer to dest }
{ EDX = number of args (>= 3) }
{ [ESP+4], [ESP+8], ... crgCnt AnsiString arguments, reverse order }
PUSH EBX
PUSH ESI
PUSH EDI
PUSH EDX
PUSH EAX
MOV EBX,EDX
XOR EDI,EDI
MOV ECX,[ESP+EDX*4+5*4] // first arg is furthest out
TEST ECX,ECX
JZ @@0
CMP [EAX],ECX // is dest = first arg?
JNE @@0
MOV EDI,EAX // EDI nonzero -> potential appendstr case
@@0:
XOR EAX,EAX
@@loop1:
MOV ECX,[ESP+EDX*4+5*4]
TEST ECX,ECX
JE @@1
ADD EAX,[ECX-skew].StrRec.length
CMP EDI,ECX // is dest an arg besides arg1?
JNE @@1
XOR EDI,EDI // can't appendstr - dest is multiple args
@@1:
DEC EDX
JNE @@loop1
@@append:
TEST EDI,EDI // dest is 1st and only 1st arg?
JZ @@copy
MOV EDX,EAX // length into EDX
MOV EAX,EDI // ptr to str into EAX
MOV ESI,[EDI]
MOV ESI,[ESI-skew].StrRec.Length // save old size before realloc
CALL _LStrSetLength
PUSH EDI // append other strs to dest
ADD ESI,[EDI] // end of old string
DEC EBX
JMP @@loop2
@@copy:
CALL _NewAnsiString
PUSH EAX
MOV ESI,EAX
@@loop2:
MOV EAX,[ESP+EBX*4+6*4]
MOV EDX,ESI
TEST EAX,EAX
JE @@2
MOV ECX,[EAX-skew].StrRec.length
ADD ESI,ECX
CALL Move
@@2:
DEC EBX
JNE @@loop2
POP EDX
POP EAX
TEST EDI,EDI
JNZ @@exit
TEST EDX,EDX
JE @@skip
DEC [EDX-skew].StrRec.refCnt // EDX = local temp str
@@skip:
CALL _LStrAsg
@@exit:
POP EDX
POP EDI
POP ESI
POP EBX
POP EAX
LEA ESP,[ESP+EDX*4]
JMP EAX
end;
procedure _LStrCmp{left: AnsiString; right: AnsiString};
asm
{ ->EAX = Pointer to left string }
{ EDX = Pointer to right string }
PUSH EBX
PUSH ESI
PUSH EDI
MOV ESI,EAX
MOV EDI,EDX
CMP EAX,EDX
JE @@exit
TEST ESI,ESI
JE @@str1null
TEST EDI,EDI
JE @@str2null
MOV EAX,[ESI-skew].StrRec.length
MOV EDX,[EDI-skew].StrRec.length
SUB EAX,EDX { eax = len1 - len2 }
JA @@skip1
ADD EDX,EAX { edx = len2 + (len1 - len2) = len1 }
@@skip1:
PUSH EDX
SHR EDX,2
JE @@cmpRest
@@longLoop:
MOV ECX,[ESI]
MOV EBX,[EDI]
CMP ECX,EBX
JNE @@misMatch
DEC EDX
JE @@cmpRestP4
MOV ECX,[ESI+4]
MOV EBX,[EDI+4]
CMP ECX,EBX
JNE @@misMatch
ADD ESI,8
ADD EDI,8
DEC EDX
JNE @@longLoop
JMP @@cmpRest
@@cmpRestP4:
ADD ESI,4
ADD EDI,4
@@cmpRest:
POP EDX
AND EDX,3
JE @@equal
MOV ECX,[ESI]
MOV EBX,[EDI]
CMP CL,BL
JNE @@exit
DEC EDX
JE @@equal
CMP CH,BH
JNE @@exit
DEC EDX
JE @@equal
AND EBX,$00FF0000
AND ECX,$00FF0000
CMP ECX,EBX
JNE @@exit
@@equal:
ADD EAX,EAX
JMP @@exit
@@str1null:
MOV EDX,[EDI-skew].StrRec.length
SUB EAX,EDX
JMP @@exit
@@str2null:
MOV EAX,[ESI-skew].StrRec.length
SUB EAX,EDX
JMP @@exit
@@misMatch:
POP EDX
CMP CL,BL
JNE @@exit
CMP CH,BH
JNE @@exit
SHR ECX,16
SHR EBX,16
CMP CL,BL
JNE @@exit
CMP CH,BH
@@exit:
POP EDI
POP ESI
POP EBX
end;
function _LStrAddRef(var str): Pointer;
{$IFDEF PUREPASCAL}
var
P: PStrRec;
begin
P := Pointer(Integer(str) - sizeof(StrRec));
if P <> nil then
if P.refcnt >= 0 then
InterlockedIncrement(P.refcnt);
Result := Pointer(str);
end;
{$ELSE}
asm
{ -> EAX str }
TEST EAX,EAX
JE @@exit
MOV EDX,[EAX-skew].StrRec.refCnt
INC EDX
JLE @@exit
LOCK INC [EAX-skew].StrRec.refCnt
@@exit:
end;
{$ENDIF}
function PICEmptyString: PWideChar;
begin
Result := '';
end;
function _LStrToPChar(const s: AnsiString): PChar;
{$IFDEF PUREPASCAL}
const
EmptyString = '';
begin
if Pointer(s) = nil then
Result := EmptyString
else
Result := Pointer(s);
end;
{$ELSE}
asm
{ -> EAX pointer to str }
{ <- EAX pointer to PChar }
TEST EAX,EAX
JE @@handle0
RET
{$IFDEF PIC}
@@handle0:
JMP PICEmptyString
{$ELSE}
@@zeroByte:
DB 0
@@handle0:
MOV EAX,offset @@zeroByte
{$ENDIF}
end;
{$ENDIF}
function InternalUniqueString(var str): Pointer;
asm
{ -> EAX pointer to str }
{ <- EAX pointer to unique copy }
MOV EDX,[EAX]
TEST EDX,EDX
JE @@exit
MOV ECX,[EDX-skew].StrRec.refCnt
DEC ECX
JE @@exit
PUSH EBX
MOV EBX,EAX
MOV EAX,[EDX-skew].StrRec.length
CALL _NewAnsiString
MOV EDX,EAX
MOV EAX,[EBX]
MOV [EBX],EDX
PUSH EAX
MOV ECX,[EAX-skew].StrRec.length
CALL Move
POP EAX
MOV ECX,[EAX-skew].StrRec.refCnt
DEC ECX
JL @@skip
LOCK DEC [EAX-skew].StrRec.refCnt
JNZ @@skip
LEA EAX,[EAX-skew].StrRec.refCnt { if refCnt now zero, deallocate}
CALL _FreeMem
@@skip:
MOV EDX,[EBX]
POP EBX
@@exit:
MOV EAX,EDX
end;
procedure UniqueString(var str: AnsiString);
asm
JMP InternalUniqueString
end;
procedure _UniqueStringA(var str: AnsiString);
asm
JMP InternalUniqueString
end;
procedure UniqueString(var str: WideString);
asm
{$IFDEF LINUX}
JMP InternalUniqueString
{$ENDIF}
{$IFDEF MSWINDOWS}
// nothing to do - Windows WideStrings are always single reference
{$ENDIF}
end;
procedure _UniqueStringW(var str: WideString);
asm
{$IFDEF LINUX}
JMP InternalUniqueString
{$ENDIF}
{$IFDEF MSWINDOWS}
// nothing to do - Windows WideStrings are always single reference
{$ENDIF}
end;
procedure _LStrCopy{ const s : AnsiString; index, count : Integer) : AnsiString};
asm
{ ->EAX Source string }
{ EDX index }
{ ECX count }
{ [ESP+4] Pointer to result string }
PUSH EBX
TEST EAX,EAX
JE @@srcEmpty
MOV EBX,[EAX-skew].StrRec.length
TEST EBX,EBX
JE @@srcEmpty
{ make index 0-based and limit to 0 <= index < Length(src) }
DEC EDX
JL @@smallInx
CMP EDX,EBX
JGE @@bigInx
@@cont1:
{ limit count to satisfy 0 <= count <= Length(src) - index }
SUB EBX,EDX { calculate Length(src) - index }
TEST ECX,ECX
JL @@smallCount
CMP ECX,EBX
JG @@bigCount
@@cont2:
ADD EDX,EAX
MOV EAX,[ESP+4+4]
CALL _LStrFromPCharLen
JMP @@exit
@@smallInx:
XOR EDX,EDX
JMP @@cont1
@@bigCount:
MOV ECX,EBX
JMP @@cont2
@@bigInx:
@@smallCount:
@@srcEmpty:
MOV EAX,[ESP+4+4]
CALL _LStrClr
@@exit:
POP EBX
RET 4
end;
procedure _LStrDelete{ var s : AnsiString; index, count : Integer };
asm
{ ->EAX Pointer to s }
{ EDX index }
{ ECX count }
PUSH EBX
PUSH ESI
PUSH EDI
MOV EBX,EAX
MOV ESI,EDX
MOV EDI,ECX
CALL UniqueString
MOV EDX,[EBX]
TEST EDX,EDX { source already empty: nothing to do }
JE @@exit
MOV ECX,[EDX-skew].StrRec.length
{ make index 0-based, if not in [0 .. Length(s)-1] do nothing }
DEC ESI
JL @@exit
CMP ESI,ECX
JGE @@exit
{ limit count to [0 .. Length(s) - index] }
TEST EDI,EDI
JLE @@exit
SUB ECX,ESI { ECX = Length(s) - index }
CMP EDI,ECX
JLE @@1
MOV EDI,ECX
@@1:
{ move length - index - count characters from s+index+count to s+index }
SUB ECX,EDI { ECX = Length(s) - index - count }
ADD EDX,ESI { EDX = s+index }
LEA EAX,[EDX+EDI] { EAX = s+index+count }
CALL Move
{ set length(s) to length(s) - count }
MOV EDX,[EBX]
MOV EAX,EBX
MOV EDX,[EDX-skew].StrRec.length
SUB EDX,EDI
CALL _LStrSetLength
@@exit:
POP EDI
POP ESI
POP EBX
end;
procedure _LStrInsert{ const source : AnsiString; var s : AnsiString; index : Integer };
asm
{ -> EAX source string }
{ EDX pointer to destination string }
{ ECX index }
TEST EAX,EAX
JE @@nothingToDo
PUSH EBX
PUSH ESI
PUSH EDI
PUSH EBP
MOV EBX,EAX
MOV ESI,EDX
MOV EDI,ECX
{ make index 0-based and limit to 0 <= index <= Length(s) }
MOV EDX,[EDX]
PUSH EDX
TEST EDX,EDX
JE @@sIsNull
MOV EDX,[EDX-skew].StrRec.length
@@sIsNull:
DEC EDI
JGE @@indexNotLow
XOR EDI,EDI
@@indexNotLow:
CMP EDI,EDX
JLE @@indexNotHigh
MOV EDI,EDX
@@indexNotHigh:
MOV EBP,[EBX-skew].StrRec.length
{ set length of result to length(source) + length(s) }
MOV EAX,ESI
ADD EDX,EBP
CALL _LStrSetLength
POP EAX
CMP EAX,EBX
JNE @@notInsertSelf
MOV EBX,[ESI]
@@notInsertSelf:
{ move length(s) - length(source) - index chars from s+index to s+index+length(source) }
MOV EAX,[ESI] { EAX = s }
LEA EDX,[EDI+EBP] { EDX = index + length(source) }
MOV ECX,[EAX-skew].StrRec.length
SUB ECX,EDX { ECX = length(s) - length(source) - index }
ADD EDX,EAX { EDX = s + index + length(source) }
ADD EAX,EDI { EAX = s + index }
CALL Move
{ copy length(source) chars from source to s+index }
MOV EAX,EBX
MOV EDX,[ESI]
MOV ECX,EBP
ADD EDX,EDI
CALL Move
@@exit:
POP EBP
POP EDI
POP ESI
POP EBX
@@nothingToDo:
end;
procedure _LStrPos{ const substr : AnsiString; const s : AnsiString ) : Integer};
asm
{ ->EAX Pointer to substr }
{ EDX Pointer to string }
{ <-EAX Position of substr in s or 0 }
TEST EAX,EAX
JE @@noWork
TEST EDX,EDX
JE @@stringEmpty
PUSH EBX
PUSH ESI
PUSH EDI
MOV ESI,EAX { Point ESI to substr }
MOV EDI,EDX { Point EDI to s }
MOV ECX,[EDI-skew].StrRec.length { ECX = Length(s) }
PUSH EDI { remember s position to calculate index }
MOV EDX,[ESI-skew].StrRec.length { EDX = Length(substr) }
DEC EDX { EDX = Length(substr) - 1 }
JS @@fail { < 0 ? return 0 }
MOV AL,[ESI] { AL = first char of substr }
INC ESI { Point ESI to 2'nd char of substr }
SUB ECX,EDX { #positions in s to look at }
{ = Length(s) - Length(substr) + 1 }
JLE @@fail
@@loop:
REPNE SCASB
JNE @@fail
MOV EBX,ECX { save outer loop counter }
PUSH ESI { save outer loop substr pointer }
PUSH EDI { save outer loop s pointer }
MOV ECX,EDX
REPE CMPSB
POP EDI { restore outer loop s pointer }
POP ESI { restore outer loop substr pointer }
JE @@found
MOV ECX,EBX { restore outer loop counter }
JMP @@loop
@@fail:
POP EDX { get rid of saved s pointer }
XOR EAX,EAX
JMP @@exit
@@stringEmpty:
XOR EAX,EAX
JMP @@noWork
@@found:
POP EDX { restore pointer to first char of s }
MOV EAX,EDI { EDI points of char after match }
SUB EAX,EDX { the difference is the correct index }
@@exit:
POP EDI
POP ESI
POP EBX
@@noWork:
end;
procedure _LStrSetLength{ var str: AnsiString; newLength: Integer};
asm
{ -> EAX Pointer to str }
{ EDX new length }
PUSH EBX
PUSH ESI
PUSH EDI
MOV EBX,EAX
MOV ESI,EDX
XOR EDI,EDI
TEST EDX,EDX
JLE @@setString
MOV EAX,[EBX]
TEST EAX,EAX
JE @@copyString
CMP [EAX-skew].StrRec.refCnt,1
JNE @@copyString
SUB EAX,rOff
ADD EDX,rOff+1
PUSH EAX
MOV EAX,ESP
CALL _ReallocMem
POP EAX
ADD EAX,rOff
MOV [EBX],EAX
MOV [EAX-skew].StrRec.length,ESI
MOV BYTE PTR [EAX+ESI],0
JMP @@exit
@@copyString:
MOV EAX,EDX
CALL _NewAnsiString
MOV EDI,EAX
MOV EAX,[EBX]
TEST EAX,EAX
JE @@setString
MOV EDX,EDI
MOV ECX,[EAX-skew].StrRec.length
CMP ECX,ESI
JL @@moveString
MOV ECX,ESI
@@moveString:
CALL Move
@@setString:
MOV EAX,EBX
CALL _LStrClr
MOV [EBX],EDI
@@exit:
POP EDI
POP ESI
POP EBX
end;
procedure _LStrOfChar{ c: Char; count: Integer): AnsiString };
asm
{ -> AL c }
{ EDX count }
{ ECX result }
PUSH EBX
PUSH ESI
PUSH EDI
MOV EBX,EAX
MOV ESI,EDX
MOV EDI,ECX
MOV EAX,ECX
CALL _LStrClr
TEST ESI,ESI
JLE @@exit
MOV EAX,ESI
CALL _NewAnsiString
MOV [EDI],EAX
MOV EDX,ESI
MOV CL,BL
CALL _FillChar
@@exit:
POP EDI
POP ESI
POP EBX
end;
function _Write0LString(var t: TTextRec; const s: AnsiString): Pointer;
begin
Result := _WriteLString(t, s, 0);
end;
function _WriteLString(var t: TTextRec; const s: AnsiString; width: Longint): Pointer;
{$IFDEF PUREPASCAL}
var
i: Integer;
begin
i := Length(s);
_WriteSpaces(t, width - i);
Result := _WriteBytes(t, s[1], i);
end;
{$ELSE}
asm
{ -> EAX Pointer to text record }
{ EDX Pointer to AnsiString }
{ ECX Field width }
PUSH EBX
MOV EBX,EDX
MOV EDX,ECX
XOR ECX,ECX
TEST EBX,EBX
JE @@skip
MOV ECX,[EBX-skew].StrRec.length
SUB EDX,ECX
@@skip:
PUSH ECX
CALL _WriteSpaces
POP ECX
MOV EDX,EBX
POP EBX
JMP _WriteBytes
end;
{$ENDIF}
function _Write0WString(var t: TTextRec; const s: WideString): Pointer;
begin
Result := _WriteWString(t, s, 0);
end;
function _WriteWString(var t: TTextRec; const s: WideString; width: Longint): Pointer;
var
i: Integer;
begin
i := Length(s);
_WriteSpaces(t, width - i);
Result := _WriteLString(t, AnsiString(s), 0);
end;
function _Write0WCString(var t: TTextRec; s: PWideChar): Pointer;
begin
Result := _WriteWCString(t, s, 0);
end;
function _WriteWCString(var t: TTextRec; s: PWideChar; width: Longint): Pointer;
var
i: Integer;
begin
i := 0;
if (s <> nil) then
while s[i] <> #0 do
Inc(i);
_WriteSpaces(t, width - i);
Result := _WriteLString(t, AnsiString(s), 0);
end;
function _Write0WChar(var t: TTextRec; c: WideChar): Pointer;
begin
Result := _WriteWChar(t, c, 0);
end;
function _WriteWChar(var t: TTextRec; c: WideChar; width: Integer): Pointer;
begin
_WriteSpaces(t, width - 1);
Result := _WriteLString(t, AnsiString(c), 0);
end;
{$IFDEF MSWINDOWS}
procedure WStrError;
asm
MOV AL,reOutOfMemory
JMP Error
end;
{$ENDIF}
function _NewWideString(CharLength: Longint): Pointer;
{$IFDEF LINUX}
begin
Result := _NewAnsiString(CharLength*2);
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
asm
TEST EAX,EAX
JE @@1
PUSH EAX
PUSH 0
CALL SysAllocStringLen
TEST EAX,EAX
JE WStrError
@@1:
end;
{$ENDIF}
procedure WStrSet(var S: WideString; P: PWideChar);
{$IFDEF PUREPASCAL}
var
Temp: Pointer;
begin
Temp := Pointer(InterlockedExchange(Pointer(S), Pointer(P)));
if Temp <> nil then
_WStrClr(Temp);
end;
{$ELSE}
asm
{$IFDEF LINUX}
XCHG [EAX],EDX
TEST EDX,EDX
JZ @@1
PUSH EDX
MOV EAX, ESP
CALL _WStrClr
POP EAX
{$ENDIF}
{$IFDEF MSWINDOWS}
XCHG [EAX],EDX
TEST EDX,EDX
JZ @@1
PUSH EDX
CALL SysFreeString
{$ENDIF}
@@1:
end;
{$ENDIF}
procedure _WStrClr(var S);
{$IFDEF LINUX}
asm
JMP _LStrClr;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
asm
{ -> EAX Pointer to WideString }
MOV EDX,[EAX]
TEST EDX,EDX
JE @@1
MOV DWORD PTR [EAX],0
PUSH EAX
PUSH EDX
CALL SysFreeString
POP EAX
@@1:
end;
{$ENDIF}
procedure _WStrArrayClr(var StrArray; Count: Integer);
{$IFDEF LINUX}
asm
JMP _LStrArrayClr
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
asm
PUSH EBX
PUSH ESI
MOV EBX,EAX
MOV ESI,EDX
@@1: MOV EAX,[EBX]
TEST EAX,EAX
JE @@2
MOV DWORD PTR [EBX],0
PUSH EAX
CALL SysFreeString
@@2: ADD EBX,4
DEC ESI
JNE @@1
POP ESI
POP EBX
end;
{$ENDIF}
procedure _WStrAsg(var Dest: WideString; const Source: WideString);
{$IFDEF LINUX}
asm
JMP _LStrAsg
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
asm
{ -> EAX Pointer to WideString }
{ EDX Pointer to data }
TEST EDX,EDX
JE _WStrClr
MOV ECX,[EDX-4]
SHR ECX,1
JE _WStrClr
PUSH ECX
PUSH EDX
PUSH EAX
CALL SysReAllocStringLen
TEST EAX,EAX
JE WStrError
end;
{$ENDIF}
procedure _WStrLAsg(var Dest: WideString; const Source: WideString);
{$IFDEF LINUX}
asm
JMP _LStrLAsg
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
asm
JMP _WStrAsg
end;
{$ENDIF}
procedure _WStrFromPCharLen(var Dest: WideString; Source: PAnsiChar; Length: Integer);
var
DestLen: Integer;
Buffer: array[0..2047] of WideChar;
begin
if Length <= 0 then
begin
_WStrClr(Dest);
Exit;
end;
if Length+1 < High(Buffer) then
begin
DestLen := WCharFromChar(Buffer, High(Buffer), Source, Length);
if DestLen > 0 then
begin
_WStrFromPWCharLen(Dest, @Buffer, DestLen);
Exit;
end;
end;
DestLen := (Length + 1);
_WStrSetLength(Dest, DestLen); // overallocate, trim later
DestLen := WCharFromChar(Pointer(Dest), DestLen, Source, Length);
if DestLen < 0 then DestLen := 0;
_WStrSetLength(Dest, DestLen);
end;
procedure _WStrFromPWCharLen(var Dest: WideString; Source: PWideChar; CharLength: Integer);
{$IFDEF LINUX}
var
Temp: Pointer;
begin
Temp := Pointer(Dest);
if CharLength > 0 then
begin
Pointer(Dest) := _NewWideString(CharLength);
if Source <> nil then
Move(Source^, Pointer(Dest)^, CharLength * sizeof(WideChar));
end
else
Pointer(Dest) := nil;
_WStrClr(Temp);
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
asm
{ -> EAX Pointer to WideString (dest) }
{ EDX Pointer to characters (source) }
{ ECX number of characters (not bytes) }
TEST ECX,ECX
JE _WStrClr
PUSH EAX
PUSH ECX
PUSH EDX
CALL SysAllocStringLen
TEST EAX,EAX
JE WStrError
POP EDX
PUSH [EDX].PWideChar
MOV [EDX],EAX
CALL SysFreeString
end;
{$ENDIF}
procedure _WStrFromChar(var Dest: WideString; Source: AnsiChar);
asm
PUSH EDX
MOV EDX,ESP
MOV ECX,1
CALL _WStrFromPCharLen
POP EDX
end;
procedure _WStrFromWChar(var Dest: WideString; Source: WideChar);
asm
{ -> EAX Pointer to WideString (dest) }
{ EDX character (source) }
PUSH EDX
MOV EDX,ESP
MOV ECX,1
CALL _WStrFromPWCharLen
POP EDX
end;
procedure _WStrFromPChar(var Dest: WideString; Source: PAnsiChar);
asm
{ -> EAX Pointer to WideString (dest) }
{ EDX Pointer to character (source) }
XOR ECX,ECX
TEST EDX,EDX
JE @@5
PUSH EDX
@@0: CMP CL,[EDX+0]
JE @@4
CMP CL,[EDX+1]
JE @@3
CMP CL,[EDX+2]
JE @@2
CMP CL,[EDX+3]
JE @@1
ADD EDX,4
JMP @@0
@@1: INC EDX
@@2: INC EDX
@@3: INC EDX
@@4: MOV ECX,EDX
POP EDX
SUB ECX,EDX
@@5: JMP _WStrFromPCharLen
end;
procedure _WStrFromPWChar(var Dest: WideString; Source: PWideChar);
asm
{ -> EAX Pointer to WideString (dest) }
{ EDX Pointer to character (source) }
XOR ECX,ECX
TEST EDX,EDX
JE @@5
PUSH EDX
@@0: CMP CX,[EDX+0]
JE @@4
CMP CX,[EDX+2]
JE @@3
CMP CX,[EDX+4]
JE @@2
CMP CX,[EDX+6]
JE @@1
ADD EDX,8
JMP @@0
@@1: ADD EDX,2
@@2: ADD EDX,2
@@3: ADD EDX,2
@@4: MOV ECX,EDX
POP EDX
SUB ECX,EDX
SHR ECX,1
@@5: JMP _WStrFromPWCharLen
end;
procedure _WStrFromString(var Dest: WideString; const Source: ShortString);
asm
XOR ECX,ECX
MOV CL,[EDX]
INC EDX
JMP _WStrFromPCharLen
end;
procedure _WStrFromArray(var Dest: WideString; Source: PAnsiChar; Length: Integer);
asm
PUSH EDI
PUSH EAX
PUSH ECX
MOV EDI,EDX
XOR EAX,EAX
REPNE SCASB
JNE @@1
NOT ECX
@@1: POP EAX
ADD ECX,EAX
POP EAX
POP EDI
JMP _WStrFromPCharLen
end;
procedure _WStrFromWArray(var Dest: WideString; Source: PWideChar; Length: Integer);
asm
PUSH EDI
PUSH EAX
PUSH ECX
MOV EDI,EDX
XOR EAX,EAX
REPNE SCASW
JNE @@1
NOT ECX
@@1: POP EAX
ADD ECX,EAX
POP EAX
POP EDI
JMP _WStrFromPWCharLen
end;
procedure _WStrFromLStr(var Dest: WideString; const Source: AnsiString);
asm
XOR ECX,ECX
TEST EDX,EDX
JE @@1
MOV ECX,[EDX-4]
@@1: JMP _WStrFromPCharLen
end;
procedure _WStrToString(Dest: PShortString; const Source: WideString; MaxLen: Integer);
var
SourceLen, DestLen: Integer;
Buffer: array[0..511] of Char;
begin
if MaxLen > 255 then MaxLen := 255;
SourceLen := Length(Source);
if SourceLen >= MaxLen then SourceLen := MaxLen;
if SourceLen = 0 then
DestLen := 0
else
begin
DestLen := CharFromWChar(Buffer, High(Buffer), PWideChar(Pointer(Source)), SourceLen);
if DestLen < 0 then
DestLen := 0
else if DestLen > MaxLen then
DestLen := MaxLen;
end;
Dest^[0] := Chr(DestLen);
if DestLen > 0 then Move(Buffer, Dest^[1], DestLen);
end;
function _WStrToPWChar(const S: WideString): PWideChar;
{$IFDEF PUREPASCAL}
const
EmptyString = '';
begin
if Pointer(S) = nil then
Result := EmptyString
else
Result := Pointer(S);
end;
{$ELSE}
asm
TEST EAX,EAX
JE @@1
RET
{$IFDEF PIC}
@@1: JMP PICEmptyString
{$ELSE}
NOP
@@0: DW 0
@@1: MOV EAX,OFFSET @@0
{$ENDIF}
end;
{$ENDIF}
function _WStrLen(const S: WideString): Integer;
{$IFDEF PUREPASCAL}
begin
if Pointer(S) = nil then
Result := 0
else
Result := PInteger(Integer(S) - 4)^ div sizeof(WideChar);
end;
{$ELSE}
asm
{ -> EAX Pointer to WideString data }
TEST EAX,EAX
JE @@1
MOV EAX,[EAX-4]
SHR EAX,1
@@1:
end;
{$ENDIF}
procedure _WStrCat(var Dest: WideString; const Source: WideString);
var
DestLen, SourceLen: Integer;
NewStr: PWideChar;
begin
SourceLen := Length(Source);
if SourceLen <> 0 then
begin
DestLen := Length(Dest);
NewStr := _NewWideString(DestLen + SourceLen);
if DestLen > 0 then
Move(Pointer(Dest)^, NewStr^, DestLen * sizeof(WideChar));
Move(Pointer(Source)^, NewStr[DestLen], SourceLen * sizeof(WideChar));
WStrSet(Dest, NewStr);
end;
end;
procedure _WStrCat3(var Dest: WideString; const Source1, Source2: WideString);
var
Source1Len, Source2Len: Integer;
NewStr: PWideChar;
begin
Source1Len := Length(Source1);
Source2Len := Length(Source2);
if (Source1Len <> 0) or (Source2Len <> 0) then
begin
NewStr := _NewWideString(Source1Len + Source2Len);
Move(Pointer(Source1)^, Pointer(NewStr)^, Source1Len * sizeof(WideChar));
Move(Pointer(Source2)^, NewStr[Source1Len], Source2Len * sizeof(WideChar));
WStrSet(Dest, NewStr);
end;
end;
procedure _WStrCatN{var Dest: WideString; ArgCnt: Integer; ...};
asm
{ ->EAX = Pointer to dest }
{ EDX = number of args (>= 3) }
{ [ESP+4], [ESP+8], ... crgCnt WideString arguments }
PUSH EBX
PUSH ESI
PUSH EDX
PUSH EAX
MOV EBX,EDX
XOR EAX,EAX
@@loop1:
MOV ECX,[ESP+EDX*4+4*4]
TEST ECX,ECX
JE @@1
ADD EAX,[ECX-4]
@@1:
DEC EDX
JNE @@loop1
SHR EAX,1
CALL _NewWideString
PUSH EAX
MOV ESI,EAX
@@loop2:
MOV EAX,[ESP+EBX*4+5*4]
MOV EDX,ESI
TEST EAX,EAX
JE @@2
MOV ECX,[EAX-4]
ADD ESI,ECX
CALL Move
@@2:
DEC EBX
JNE @@loop2
POP EDX
POP EAX
CALL WStrSet
POP EDX
POP ESI
POP EBX
POP EAX
LEA ESP,[ESP+EDX*4]
JMP EAX
end;
procedure _WStrCmp{left: WideString; right: WideString};
asm
{ ->EAX = Pointer to left string }
{ EDX = Pointer to right string }
PUSH EBX
PUSH ESI
PUSH EDI
MOV ESI,EAX
MOV EDI,EDX
CMP EAX,EDX
JE @@exit
TEST ESI,ESI
JE @@str1null
TEST EDI,EDI
JE @@str2null
MOV EAX,[ESI-4]
MOV EDX,[EDI-4]
SUB EAX,EDX { eax = len1 - len2 }
JA @@skip1
ADD EDX,EAX { edx = len2 + (len1 - len2) = len1 }
@@skip1:
PUSH EDX
SHR EDX,2
JE @@cmpRest
@@longLoop:
MOV ECX,[ESI]
MOV EBX,[EDI]
CMP ECX,EBX
JNE @@misMatch
DEC EDX
JE @@cmpRestP4
MOV ECX,[ESI+4]
MOV EBX,[EDI+4]
CMP ECX,EBX
JNE @@misMatch
ADD ESI,8
ADD EDI,8
DEC EDX
JNE @@longLoop
JMP @@cmpRest
@@cmpRestP4:
ADD ESI,4
ADD EDI,4
@@cmpRest:
POP EDX
AND EDX,2
JE @@equal
MOV CX,[ESI]
MOV BX,[EDI]
CMP CX,BX
JNE @@exit
@@equal:
ADD EAX,EAX
JMP @@exit
@@str1null:
MOV EDX,[EDI-4]
SUB EAX,EDX
JMP @@exit
@@str2null:
MOV EAX,[ESI-4]
SUB EAX,EDX
JMP @@exit
@@misMatch:
POP EDX
CMP CX,BX
JNE @@exit
SHR ECX,16
SHR EBX,16
CMP CX,BX
@@exit:
POP EDI
POP ESI
POP EBX
end;
function _WStrCopy(const S: WideString; Index, Count: Integer): WideString;
var
L, N: Integer;
begin
L := Length(S);
if Index < 1 then Index := 0 else
begin
Dec(Index);
if Index > L then Index := L;
end;
if Count < 0 then N := 0 else
begin
N := L - Index;
if N > Count then N := Count;
end;
_WStrFromPWCharLen(Result, PWideChar(Pointer(S)) + Index, N);
end;
procedure _WStrDelete(var S: WideString; Index, Count: Integer);
var
L, N: Integer;
NewStr: PWideChar;
begin
L := Length(S);
if (L > 0) and (Index >= 1) and (Index <= L) and (Count > 0) then
begin
Dec(Index);
N := L - Index - Count;
if N < 0 then N := 0;
if (Index = 0) and (N = 0) then NewStr := nil else
begin
NewStr := _NewWideString(Index + N);
if Index > 0 then
Move(Pointer(S)^, NewStr^, Index * 2);
if N > 0 then
Move(PWideChar(Pointer(S))[L - N], NewStr[Index], N * 2);
end;
WStrSet(S, NewStr);
end;
end;
procedure _WStrInsert(const Source: WideString; var Dest: WideString; Index: Integer);
var
SourceLen, DestLen: Integer;
NewStr: PWideChar;
begin
SourceLen := Length(Source);
if SourceLen > 0 then
begin
DestLen := Length(Dest);
if Index < 1 then Index := 0 else
begin
Dec(Index);
if Index > DestLen then Index := DestLen;
end;
NewStr := _NewWideString(DestLen + SourceLen);
if Index > 0 then
Move(Pointer(Dest)^, NewStr^, Index * 2);
Move(Pointer(Source)^, NewStr[Index], SourceLen * 2);
if Index < DestLen then
Move(PWideChar(Pointer(Dest))[Index], NewStr[Index + SourceLen],
(DestLen - Index) * 2);
WStrSet(Dest, NewStr);
end;
end;
procedure _WStrPos{ const substr : WideString; const s : WideString ) : Integer};
asm
{ ->EAX Pointer to substr }
{ EDX Pointer to string }
{ <-EAX Position of substr in s or 0 }
TEST EAX,EAX
JE @@noWork
TEST EDX,EDX
JE @@stringEmpty
PUSH EBX
PUSH ESI
PUSH EDI
MOV ESI,EAX { Point ESI to substr }
MOV EDI,EDX { Point EDI to s }
MOV ECX,[EDI-4] { ECX = Length(s) }
SHR ECX,1
PUSH EDI { remember s position to calculate index }
MOV EDX,[ESI-4] { EDX = Length(substr) }
SHR EDX,1
DEC EDX { EDX = Length(substr) - 1 }
JS @@fail { < 0 ? return 0 }
MOV AX,[ESI] { AL = first char of substr }
ADD ESI,2 { Point ESI to 2'nd char of substr }
SUB ECX,EDX { #positions in s to look at }
{ = Length(s) - Length(substr) + 1 }
JLE @@fail
@@loop:
REPNE SCASW
JNE @@fail
MOV EBX,ECX { save outer loop counter }
PUSH ESI { save outer loop substr pointer }
PUSH EDI { save outer loop s pointer }
MOV ECX,EDX
REPE CMPSW
POP EDI { restore outer loop s pointer }
POP ESI { restore outer loop substr pointer }
JE @@found
MOV ECX,EBX { restore outer loop counter }
JMP @@loop
@@fail:
POP EDX { get rid of saved s pointer }
XOR EAX,EAX
JMP @@exit
@@stringEmpty:
XOR EAX,EAX
JMP @@noWork
@@found:
POP EDX { restore pointer to first char of s }
MOV EAX,EDI { EDI points of char after match }
SUB EAX,EDX { the difference is the correct index }
SHR EAX,1
@@exit:
POP EDI
POP ESI
POP EBX
@@noWork:
end;
procedure _WStrSetLength(var S: WideString; NewLength: Integer);
var
NewStr: PWideChar;
Count: Integer;
begin
NewStr := nil;
if NewLength > 0 then
begin
NewStr := _NewWideString(NewLength);
Count := Length(S);
if Count > 0 then
begin
if Count > NewLength then Count := NewLength;
Move(Pointer(S)^, NewStr^, Count * 2);
end;
end;
WStrSet(S, NewStr);
end;
function _WStrOfWChar(Ch: WideChar; Count: Integer): WideString;
var
P: PWideChar;
begin
_WStrFromPWCharLen(Result, nil, Count);
P := Pointer(Result);
while Count > 0 do
begin
Dec(Count);
P[Count] := Ch;
end;
end;
function _WStrAddRef(var str: WideString): Pointer;
{$IFDEF LINUX}
asm
JMP _LStrAddRef
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
asm
MOV EDX,[EAX]
TEST EDX,EDX
JE @@1
PUSH EAX
MOV ECX,[EDX-4]
SHR ECX,1
PUSH ECX
PUSH EDX
CALL SysAllocStringLen
POP EDX
TEST EAX,EAX
JE WStrError
MOV [EDX],EAX
@@1:
end;
{$ENDIF}
type
PPTypeInfo = ^PTypeInfo;
PTypeInfo = ^TTypeInfo;
TTypeInfo = packed record
Kind: Byte;
Name: ShortString;
{TypeData: TTypeData}
end;
TFieldInfo = packed record
TypeInfo: PPTypeInfo;
Offset: Cardinal;
end;
PFieldTable = ^TFieldTable;
TFieldTable = packed record
X: Word;
Size: Cardinal;
Count: Cardinal;
Fields: array [0..0] of TFieldInfo;
end;
{ ===========================================================================
InitializeRecord, InitializeArray, and Initialize are PIC safe even though
they alter EBX because they only call each other. They never call out to
other functions and they don't access global data.
FinalizeRecord, Finalize, and FinalizeArray are PIC safe because they call
Pascal routines which will have EBX fixup prologs.
===========================================================================}
procedure _InitializeRecord(p: Pointer; typeInfo: Pointer);
{$IFDEF PUREPASCAL}
var
FT: PFieldTable;
I: Cardinal;
begin
FT := PFieldTable(Integer(typeInfo) + Byte(PTypeInfo(typeInfo).Name[0]));
for I := FT.Count-1 downto 0 do
_InitializeArray(Pointer(Cardinal(P) + FT.Fields[I].Offset), FT.Fields[I].TypeInfo^, 1);
end;
{$ELSE}
asm
{ -> EAX pointer to record to be initialized }
{ EDX pointer to type info }
XOR ECX,ECX
PUSH EBX
MOV CL,[EDX+1] { type name length }
PUSH ESI
PUSH EDI
MOV EBX,EAX // PIC safe. See comment above
LEA ESI,[EDX+ECX+2+8] { address of destructable fields }
MOV EDI,[EDX+ECX+2+4] { number of destructable fields }
@@loop:
MOV EDX,[ESI]
MOV EAX,[ESI+4]
ADD EAX,EBX
MOV EDX,[EDX]
MOV ECX,1
CALL _InitializeArray
ADD ESI,8
DEC EDI
JG @@loop
POP EDI
POP ESI
POP EBX
end;
{$ENDIF}
const
tkLString = 10;
tkWString = 11;
tkVariant = 12;
tkArray = 13;
tkRecord = 14;
tkInterface = 15;
tkDynArray = 17;
procedure _InitializeArray(p: Pointer; typeInfo: Pointer; elemCount: Cardinal);
{$IFDEF PUREPASCAL}
var
FT: PFieldTable;
begin
if elemCount = 0 then Exit;
case PTypeInfo(typeInfo).Kind of
tkLString, tkWString, tkInterface, tkDynArray:
while elemCount > 0 do
begin
PInteger(P)^ := 0;
Inc(Integer(P), 4);
Dec(elemCount);
end;
tkVariant:
while elemCount > 0 do
begin
PInteger(P)^ := 0;
PInteger(Integer(P)+4)^ := 0;
PInteger(Integer(P)+8)^ := 0;
PInteger(Integer(P)+12)^ := 0;
Inc(Integer(P), sizeof(Variant));
Dec(elemCount);
end;
tkArray:
begin
FT := PFieldTable(Integer(typeInfo) + Byte(PTypeInfo(typeInfo).Name[0]));
while elemCount > 0 do
begin
_InitializeArray(P, FT.Fields[0].TypeInfo^, FT.Count);
Inc(Integer(P), FT.Size);
Dec(elemCount);
end;
end;
tkRecord:
begin
FT := PFieldTable(Integer(typeInfo) + Byte(PTypeInfo(typeInfo).Name[0]));
while elemCount > 0 do
begin
_InitializeRecord(P, typeInfo);
Inc(Integer(P), FT.Size);
Dec(elemCount);
end;
end;
else
Error(reInvalidPtr);
end;
end;
{$ELSE}
asm
{ -> EAX pointer to data to be initialized }
{ EDX pointer to type info describing data }
{ ECX number of elements of that type }
TEST ECX, ECX
JZ @@zerolength
PUSH EBX
PUSH ESI
PUSH EDI
MOV EBX,EAX // PIC safe. See comment above
MOV ESI,EDX
MOV EDI,ECX
XOR EDX,EDX
MOV AL,[ESI]
MOV DL,[ESI+1]
XOR ECX,ECX
CMP AL,tkLString
JE @@LString
CMP AL,tkWString
JE @@WString
CMP AL,tkVariant
JE @@Variant
CMP AL,tkArray
JE @@Array
CMP AL,tkRecord
JE @@Record
CMP AL,tkInterface
JE @@Interface
CMP AL,tkDynArray
JE @@DynArray
MOV AL,reInvalidPtr
POP EDI
POP ESI
POP EBX
JMP Error
@@LString:
@@WString:
@@Interface:
@@DynArray:
MOV [EBX],ECX
ADD EBX,4
DEC EDI
JG @@LString
JMP @@exit
@@Variant:
MOV [EBX ],ECX
MOV [EBX+ 4],ECX
MOV [EBX+ 8],ECX
MOV [EBX+12],ECX
ADD EBX,16
DEC EDI
JG @@Variant
JMP @@exit
@@Array:
PUSH EBP
MOV EBP,EDX
@@ArrayLoop:
MOV EDX,[ESI+EBP+2+8] // address of destructable fields typeinfo
MOV EAX,EBX
ADD EBX,[ESI+EBP+2] // size in bytes of the array data
MOV ECX,[ESI+EBP+2+4] // number of destructable fields
MOV EDX,[EDX]
CALL _InitializeArray
DEC EDI
JG @@ArrayLoop
POP EBP
JMP @@exit
@@Record:
PUSH EBP
MOV EBP,EDX
@@RecordLoop:
MOV EAX,EBX
ADD EBX,[ESI+EBP+2]
MOV EDX,ESI
CALL _InitializeRecord
DEC EDI
JG @@RecordLoop
POP EBP
@@exit:
POP EDI
POP ESI
POP EBX
@@zerolength:
end;
{$ENDIF}
procedure _Initialize(p: Pointer; typeInfo: Pointer);
{$IFDEF PUREPASCAL}
begin
_InitializeArray(p, typeInfo, 1);
end;
{$ELSE}
asm
MOV ECX,1
JMP _InitializeArray
end;
{$ENDIF}
procedure _FinalizeRecord(p: Pointer; typeInfo: Pointer);
{$IFDEF PUREPASCAL}
var
FT: PFieldTable;
I: Cardinal;
begin
FT := PFieldTable(Integer(typeInfo) + Byte(PTypeInfo(typeInfo).Name[0]));
for I := 0 to FT.Count-1 do
_FinalizeArray(Pointer(Cardinal(P) + FT.Fields[I].Offset), FT.Fields[I].TypeInfo^, 1);
end;
{$ELSE}
asm
{ -> EAX pointer to record to be finalized }
{ EDX pointer to type info }
XOR ECX,ECX
PUSH EBX
MOV CL,[EDX+1]
PUSH ESI
PUSH EDI
MOV EBX,EAX
LEA ESI,[EDX+ECX+2+8]
MOV EDI,[EDX+ECX+2+4]
@@loop:
MOV EDX,[ESI]
MOV EAX,[ESI+4]
ADD EAX,EBX
MOV EDX,[EDX]
MOV ECX,1
CALL _FinalizeArray
ADD ESI,8
DEC EDI
JG @@loop
MOV EAX,EBX
POP EDI
POP ESI
POP EBX
end;
{$ENDIF}
procedure _FinalizeArray(p: Pointer; typeInfo: Pointer; elemCount: Cardinal);
{$IFDEF PUREPASCAL}
var
FT: PFieldTable;
begin
if elemCount = 0 then Exit;
case PTypeInfo(typeInfo).Kind of
tkLString: _LStrArrayClr(P^, elemCount);
tkWString: _WStrArrayClr(P^, elemCount);
tkVariant:
while elemCount > 0 do
begin
_VarClr(P);
Inc(Integer(P), sizeof(Variant));
Dec(elemCount);
end;
tkArray:
begin
FT := PFieldTable(Integer(typeInfo) + Byte(PTypeInfo(typeInfo).Name[0]));
while elemCount > 0 do
begin
_FinalizeArray(P, FT.Fields[0].TypeInfo^, FT.Count);
Inc(Integer(P), FT.Size);
Dec(elemCount);
end;
end;
tkRecord:
begin
FT := PFieldTable(Integer(typeInfo) + Byte(PTypeInfo(typeInfo).Name[0]));
while elemCount > 0 do
begin
_FinalizeRecord(P, typeInfo);
Inc(Integer(P), FT.Size);
Dec(elemCount);
end;
end;
tkInterface:
while elemCount > 0 do
begin
_IntfClear(IInterface(P^));
Inc(Integer(P), 4);
Dec(elemCount);
end;
tkDynArray:
while elemCount > 0 do
begin
_DynArrayClr(P);
Inc(Integer(P), 4);
Dec(elemCount);
end;
else
Error(reInvalidPtr);
end;
end;
{$ELSE}
asm
{ -> EAX pointer to data to be finalized }
{ EDX pointer to type info describing data }
{ ECX number of elements of that type }
{ This code appears to be PIC safe. The functions called from
here either don't make external calls or call Pascal
routines that will fix up EBX in their prolog code
(FreeMem, VarClr, IntfClr). }
CMP ECX, 0 { no array -> nop }
JE @@zerolength
PUSH EAX
PUSH EBX
PUSH ESI
PUSH EDI
MOV EBX,EAX
MOV ESI,EDX
MOV EDI,ECX
XOR EDX,EDX
MOV AL,[ESI]
MOV DL,[ESI+1]
CMP AL,tkLString
JE @@LString
CMP AL,tkWString
JE @@WString
CMP AL,tkVariant
JE @@Variant
CMP AL,tkArray
JE @@Array
CMP AL,tkRecord
JE @@Record
CMP AL,tkInterface
JE @@Interface
CMP AL,tkDynArray
JE @@DynArray
JMP @@error
@@LString:
CMP ECX,1
MOV EAX,EBX
JG @@LStringArray
CALL _LStrClr
JMP @@exit
@@LStringArray:
MOV EDX,ECX
CALL _LStrArrayClr
JMP @@exit
@@WString:
CMP ECX,1
MOV EAX,EBX
JG @@WStringArray
CALL _WStrClr
JMP @@exit
@@WStringArray:
MOV EDX,ECX
CALL _WStrArrayClr
JMP @@exit
@@Variant:
MOV EAX,EBX
ADD EBX,16
CALL _VarClr
DEC EDI
JG @@Variant
JMP @@exit
@@Array:
PUSH EBP
MOV EBP,EDX
@@ArrayLoop:
MOV EDX,[ESI+EBP+2+8]
MOV EAX,EBX
ADD EBX,[ESI+EBP+2]
MOV ECX,[ESI+EBP+2+4]
MOV EDX,[EDX]
CALL _FinalizeArray
DEC EDI
JG @@ArrayLoop
POP EBP
JMP @@exit
@@Record:
PUSH EBP
MOV EBP,EDX
@@RecordLoop:
{ inv: EDI = number of array elements to finalize }
MOV EAX,EBX
ADD EBX,[ESI+EBP+2]
MOV EDX,ESI
CALL _FinalizeRecord
DEC EDI
JG @@RecordLoop
POP EBP
JMP @@exit
@@Interface:
MOV EAX,EBX
ADD EBX,4
CALL _IntfClear
DEC EDI
JG @@Interface
JMP @@exit
@@DynArray:
MOV EAX,EBX
MOV EDX,ESI
ADD EBX,4
CALL _DynArrayClear
DEC EDI
JG @@DynArray
JMP @@exit
@@error:
POP EDI
POP ESI
POP EBX
POP EAX
MOV AL,reInvalidPtr
JMP Error
@@exit:
POP EDI
POP ESI
POP EBX
POP EAX
@@zerolength:
end;
{$ENDIF}
procedure _Finalize(p: Pointer; typeInfo: Pointer);
{$IFDEF PUREPASCAL}
begin
_FinalizeArray(p, typeInfo, 1);
end;
{$ELSE}
asm
MOV ECX,1
JMP _FinalizeArray
end;
{$ENDIF}
procedure _AddRefRecord{ p: Pointer; typeInfo: Pointer };
asm
{ -> EAX pointer to record to be referenced }
{ EDX pointer to type info }
XOR ECX,ECX
PUSH EBX
MOV CL,[EDX+1]
PUSH ESI
PUSH EDI
MOV EBX,EAX
LEA ESI,[EDX+ECX+2+8]
MOV EDI,[EDX+ECX+2+4]
@@loop:
MOV EDX,[ESI]
MOV EAX,[ESI+4]
ADD EAX,EBX
MOV EDX,[EDX]
MOV ECX, 1
CALL _AddRefArray
ADD ESI,8
DEC EDI
JG @@loop
POP EDI
POP ESI
POP EBX
end;
procedure _AddRefArray{ p: Pointer; typeInfo: Pointer; elemCount: Longint};
asm
{ -> EAX pointer to data to be referenced }
{ EDX pointer to type info describing data }
{ ECX number of elements of that type }
{ This code appears to be PIC safe. The functions called from
here either don't make external calls (LStrAddRef, WStrAddRef) or
are Pascal routines that will fix up EBX in their prolog code
(VarAddRef, IntfAddRef). }
PUSH EBX
PUSH ESI
PUSH EDI
TEST ECX,ECX
JZ @@exit
MOV EBX,EAX
MOV ESI,EDX
MOV EDI,ECX
XOR EDX,EDX
MOV AL,[ESI]
MOV DL,[ESI+1]
CMP AL,tkLString
JE @@LString
CMP AL,tkWString
JE @@WString
CMP AL,tkVariant
JE @@Variant
CMP AL,tkArray
JE @@Array
CMP AL,tkRecord
JE @@Record
CMP AL,tkInterface
JE @@Interface
CMP AL,tkDynArray
JE @@DynArray
MOV AL,reInvalidPtr
POP EDI
POP ESI
POP EBX
JMP Error
@@LString:
MOV EAX,[EBX]
ADD EBX,4
CALL _LStrAddRef
DEC EDI
JG @@LString
JMP @@exit
@@WString:
MOV EAX,EBX
ADD EBX,4
CALL _WStrAddRef
DEC EDI
JG @@WString
JMP @@exit
@@Variant:
MOV EAX,EBX
ADD EBX,16
CALL _VarAddRef
DEC EDI
JG @@Variant
JMP @@exit
@@Array:
PUSH EBP
MOV EBP,EDX
@@ArrayLoop:
MOV EDX,[ESI+EBP+2+8]
MOV EAX,EBX
ADD EBX,[ESI+EBP+2]
MOV ECX,[ESI+EBP+2+4]
MOV EDX,[EDX]
CALL _AddRefArray
DEC EDI
JG @@ArrayLoop
POP EBP
JMP @@exit
@@Record:
PUSH EBP
MOV EBP,EDX
@@RecordLoop:
MOV EAX,EBX
ADD EBX,[ESI+EBP+2]
MOV EDX,ESI
CALL _AddRefRecord
DEC EDI
JG @@RecordLoop
POP EBP
JMP @@exit
@@Interface:
MOV EAX,[EBX]
ADD EBX,4
CALL _IntfAddRef
DEC EDI
JG @@Interface
JMP @@exit
@@DynArray:
MOV EAX,[EBX]
ADD EBX,4
CALL _DynArrayAddRef
DEC EDI
JG @@DynArray
@@exit:
POP EDI
POP ESI
POP EBX
end;
procedure _AddRef{ p: Pointer; typeInfo: Pointer};
asm
MOV ECX,1
JMP _AddRefArray
end;
procedure _CopyRecord{ dest, source, typeInfo: Pointer };
asm
{ -> EAX pointer to dest }
{ EDX pointer to source }
{ ECX pointer to typeInfo }
PUSH EBX
PUSH ESI
PUSH EDI
PUSH EBP
MOV EBX,EAX
MOV ESI,EDX
XOR EAX,EAX
MOV AL,[ECX+1]
LEA EDI,[ECX+EAX+2+8]
MOV EBP,[EDI-4]
XOR EAX,EAX
MOV ECX,[EDI-8]
PUSH ECX
@@loop:
MOV ECX,[EDI+4]
SUB ECX,EAX
JLE @@nomove1
MOV EDX,EAX
ADD EAX,ESI
ADD EDX,EBX
CALL Move
@@noMove1:
MOV EAX,[EDI+4]
MOV EDX,[EDI]
MOV EDX,[EDX]
MOV CL,[EDX]
CMP CL,tkLString
JE @@LString
CMP CL,tkWString
JE @@WString
CMP CL,tkVariant
JE @@Variant
CMP CL,tkArray
JE @@Array
CMP CL,tkRecord
JE @@Record
CMP CL,tkInterface
JE @@Interface
CMP CL,tkDynArray
JE @@DynArray
MOV AL,reInvalidPtr
POP EBP
POP EDI
POP ESI
POP EBX
JMP Error
@@LString:
MOV EDX,[ESI+EAX]
ADD EAX,EBX
CALL _LStrAsg
MOV EAX,4
JMP @@common
@@WString:
MOV EDX,[ESI+EAX]
ADD EAX,EBX
CALL _WStrAsg
MOV EAX,4
JMP @@common
@@Variant:
LEA EDX,[ESI+EAX]
ADD EAX,EBX
CALL _VarCopy
MOV EAX,16
JMP @@common
@@Array:
XOR ECX,ECX
MOV CL,[EDX+1]
PUSH dword ptr [EDX+ECX+2]
PUSH dword ptr [EDX+ECX+2+4]
MOV ECX,[EDX+ECX+2+8]
MOV ECX,[ECX]
LEA EDX,[ESI+EAX]
ADD EAX,EBX
CALL _CopyArray
POP EAX
JMP @@common
@@Record:
XOR ECX,ECX
MOV CL,[EDX+1]
MOV ECX,[EDX+ECX+2]
PUSH ECX
MOV ECX,EDX
LEA EDX,[ESI+EAX]
ADD EAX,EBX
CALL _CopyRecord
POP EAX
JMP @@common
@@Interface:
MOV EDX,[ESI+EAX]
ADD EAX,EBX
CALL _IntfCopy
MOV EAX,4
JMP @@common
@@DynArray:
MOV ECX,EDX
MOV EDX,[ESI+EAX]
ADD EAX,EBX
CALL _DynArrayAsg
MOV EAX,4
@@common:
ADD EAX,[EDI+4]
ADD EDI,8
DEC EBP
JNZ @@loop
POP ECX
SUB ECX,EAX
JLE @@noMove2
LEA EDX,[EBX+EAX]
ADD EAX,ESI
CALL Move
@@noMove2:
POP EBP
POP EDI
POP ESI
POP EBX
end;
procedure _CopyObject{ dest, source: Pointer; vmtPtrOffs: Longint; typeInfo: Pointer };
asm
{ -> EAX pointer to dest }
{ EDX pointer to source }
{ ECX offset of vmt in object }
{ [ESP+4] pointer to typeInfo }
ADD ECX,EAX { pointer to dest vmt }
PUSH dword ptr [ECX] { save dest vmt }
PUSH ECX
MOV ECX,[ESP+4+4+4]
CALL _CopyRecord
POP ECX
POP dword ptr [ECX] { restore dest vmt }
RET 4
end;
procedure _CopyArray{ dest, source, typeInfo: Pointer; cnt: Integer };
asm
{ -> EAX pointer to dest }
{ EDX pointer to source }
{ ECX pointer to typeInfo }
{ [ESP+4] count }
PUSH EBX
PUSH ESI
PUSH EDI
PUSH EBP
MOV EBX,EAX
MOV ESI,EDX
MOV EDI,ECX
MOV EBP,[ESP+4+4*4]
MOV CL,[EDI]
CMP CL,tkLString
JE @@LString
CMP CL,tkWString
JE @@WString
CMP CL,tkVariant
JE @@Variant
CMP CL,tkArray
JE @@Array
CMP CL,tkRecord
JE @@Record
CMP CL,tkInterface
JE @@Interface
CMP CL,tkDynArray
JE @@DynArray
MOV AL,reInvalidPtr
POP EBP
POP EDI
POP ESI
POP EBX
JMP Error
@@LString:
MOV EAX,EBX
MOV EDX,[ESI]
CALL _LStrAsg
ADD EBX,4
ADD ESI,4
DEC EBP
JNE @@LString
JMP @@exit
@@WString:
MOV EAX,EBX
MOV EDX,[ESI]
CALL _WStrAsg
ADD EBX,4
ADD ESI,4
DEC EBP
JNE @@WString
JMP @@exit
@@Variant:
MOV EAX,EBX
MOV EDX,ESI
CALL _VarCopy
ADD EBX,16
ADD ESI,16
DEC EBP
JNE @@Variant
JMP @@exit
@@Array:
XOR ECX,ECX
MOV CL,[EDI+1]
LEA EDI,[EDI+ECX+2]
@@ArrayLoop:
MOV EAX,EBX
MOV EDX,ESI
MOV ECX,[EDI+8]
PUSH dword ptr [EDI+4]
CALL _CopyArray
ADD EBX,[EDI]
ADD ESI,[EDI]
DEC EBP
JNE @@ArrayLoop
JMP @@exit
@@Record:
MOV EAX,EBX
MOV EDX,ESI
MOV ECX,EDI
CALL _CopyRecord
XOR EAX,EAX
MOV AL,[EDI+1]
ADD EBX,[EDI+EAX+2]
ADD ESI,[EDI+EAX+2]
DEC EBP
JNE @@Record
JMP @@exit
@@Interface:
MOV EAX,EBX
MOV EDX,[ESI]
CALL _IntfCopy
ADD EBX,4
ADD ESI,4
DEC EBP
JNE @@Interface
JMP @@exit
@@DynArray:
MOV EAX,EBX
MOV EDX,[ESI]
MOV ECX,EDI
CALL _DynArrayAsg
ADD EBX,4
ADD ESI,4
DEC EBP
JNE @@DynArray
@@exit:
POP EBP
POP EDI
POP ESI
POP EBX
RET 4
end;
function _New(size: Longint; typeInfo: Pointer): Pointer;
{$IFDEF PUREPASCAL}
begin
GetMem(Result, size);
if Result <> nil then
_Initialize(Result, typeInfo);
end;
{$ELSE}
asm
{ -> EAX size of object to allocate }
{ EDX pointer to typeInfo }
PUSH EDX
CALL _GetMem
POP EDX
TEST EAX,EAX
JE @@exit
PUSH EAX
CALL _Initialize
POP EAX
@@exit:
end;
{$ENDIF}
procedure _Dispose(p: Pointer; typeInfo: Pointer);
{$IFDEF PUREPASCAL}
begin
_Finalize(p, typeinfo);
FreeMem(p);
end;
{$ELSE}
asm
{ -> EAX Pointer to object to be disposed }
{ EDX Pointer to type info }
PUSH EAX
CALL _Finalize
POP EAX
CALL _FreeMem
end;
{$ENDIF}
{ ----------------------------------------------------- }
{ Wide character support }
{ ----------------------------------------------------- }
function WideCharToString(Source: PWideChar): string;
begin
WideCharToStrVar(Source, Result);
end;
function WideCharLenToString(Source: PWideChar; SourceLen: Integer): string;
begin
WideCharLenToStrVar(Source, SourceLen, Result);
end;
procedure WideCharToStrVar(Source: PWideChar; var Dest: string);
begin
_LStrFromPWChar(Dest, Source);
end;
procedure WideCharLenToStrVar(Source: PWideChar; SourceLen: Integer;
var Dest: string);
begin
_LStrFromPWCharLen(Dest, Source, SourceLen);
end;
function StringToWideChar(const Source: string; Dest: PWideChar;
DestSize: Integer): PWideChar;
begin
Dest[WCharFromChar(Dest, DestSize - 1, PChar(Source), Length(Source))] := #0;
Result := Dest;
end;
{ ----------------------------------------------------- }
{ OLE string support }
{ ----------------------------------------------------- }
function OleStrToString(Source: PWideChar): string;
begin
OleStrToStrVar(Source, Result);
end;
procedure OleStrToStrVar(Source: PWideChar; var Dest: string);
begin
WideCharLenToStrVar(Source, Length(WideString(Pointer(Source))), Dest);
end;
function StringToOleStr(const Source: string): PWideChar;
begin
Result := nil;
_WStrFromPCharLen(WideString(Pointer(Result)), PChar(Pointer(Source)), Length(Source));
end;
{ ----------------------------------------------------- }
{ Variant manager support }
{ ----------------------------------------------------- }
var
VariantManager: TVariantManager;
procedure VariantSystemUndefinedError;
asm
MOV AL,reVarInvalidOp
JMP Error;
end;
procedure VariantSystemDefaultVarClear(var V: TVarData);
begin
case V.VType of
varEmpty, varNull, varError:;
else
VariantSystemUndefinedError;
end;
end;
procedure InitVariantManager;
type
TPtrArray = array [Word] of Pointer;
var
P: ^TPtrArray;
I: Integer;
begin
P := @VariantManager;
for I := 0 to (SizeOf(VariantManager) div SizeOf(Pointer))-1 do
P[I] := @VariantSystemUndefinedError;
VariantManager.VarClear := @VariantSystemDefaultVarClear;
end;
procedure GetVariantManager(var VarMgr: TVariantManager);
begin
VarMgr := VariantManager;
end;
procedure SetVariantManager(const VarMgr: TVariantManager);
begin
VariantManager := VarMgr;
end;
function IsVariantManagerSet: Boolean;
type
TPtrArray = array [Word] of Pointer;
var
P: ^TPtrArray;
I: Integer;
begin
Result := True;
P := @VariantManager;
for I := 0 to (SizeOf(VariantManager) div SizeOf(Pointer))-1 do
if P[I] <> @VariantSystemUndefinedError then
begin
Result := False;
Break;
end;
end;
{ ----------------------------------------------------- }
{ Variant support }
{ ----------------------------------------------------- }
procedure _DispInvoke;//(var Dest: Variant; const Source: Variant;
//CallDesc: PCallDesc; Params: Pointer); cdecl;
asm
{$IFDEF PIC}
CALL GetGOT
LEA EAX,[EAX].OFFSET VariantManager
JMP [EAX].TVariantManager.DispInvoke
{$ELSE}
JMP VariantManager.DispInvoke
{$ENDIF}
end;
procedure _VarClear(var V : Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarClear(V);
{$ELSE}
asm
JMP VariantManager.VarClear
{$IFEND}
end;
procedure _VarCopy(var Dest: Variant; const Source: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarCopy(Dest, Source);
{$ELSE}
asm
JMP VariantManager.VarCopy
{$IFEND}
end;
procedure _VarCast(var Dest: Variant; const Source: Variant; VarType: Integer);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarCast(Dest, Source, VarType);
{$ELSE}
asm
JMP VariantManager.VarCast
{$IFEND}
end;
procedure _VarCastOle(var Dest: Variant; const Source: Variant; VarType: Integer);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarCastOle(Dest, Source, VarType);
{$ELSE}
asm
JMP VariantManager.VarCastOle
{$IFEND}
end;
function _VarToInt(const V: Variant): Integer;
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
Result := VariantManager.VarToInt(V);
{$ELSE}
asm
JMP VariantManager.VarToInt
{$IFEND}
end;
function _VarToInt64(const V: Variant): Int64;
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
Result := VariantManager.VarToInt64(V);
{$ELSE}
asm
JMP VariantManager.VarToInt64
{$IFEND}
end;
function _VarToBool(const V: Variant): Boolean;
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
Result := VariantManager.VarToBool(V);
{$ELSE}
asm
JMP VariantManager.VarToBool
{$IFEND}
end;
function _VarToReal(const V: Variant): Extended;
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
Result := VariantManager.VarToReal(V);
{$ELSE}
asm
JMP VariantManager.VarToReal
{$IFEND}
end;
function _VarToCurr(const V: Variant): Currency;
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
Result := VariantManager.VarToCurr(V);
{$ELSE}
asm
JMP VariantManager.VarToCurr
{$IFEND}
end;
procedure _VarToPStr(var S; const V: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarToPStr(S, V);
{$ELSE}
asm
JMP VariantManager.VarToPStr
{$IFEND}
end;
procedure _VarToLStr(var S: string; const V: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarToLStr(S, V);
{$ELSE}
asm
JMP VariantManager.VarToLStr
{$IFEND}
end;
procedure _VarToWStr(var S: WideString; const V: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarToWStr(S, V);
{$ELSE}
asm
JMP VariantManager.VarToWStr
{$IFEND}
end;
procedure _VarToIntf(var Unknown: IInterface; const V: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarToIntf(Unknown, V);
{$ELSE}
asm
JMP VariantManager.VarToIntf
{$IFEND}
end;
procedure _VarToDisp(var Dispatch: IDispatch; const V: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarToDisp(Dispatch, V);
{$ELSE}
asm
JMP VariantManager.VarToDisp
{$IFEND}
end;
procedure _VarToDynArray(var DynArray: Pointer; const V: Variant; TypeInfo: Pointer);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarToDynArray(DynArray, V, TypeInfo);
{$ELSE}
asm
JMP VariantManager.VarToDynArray
{$IFEND}
end;
procedure _VarFromInt(var V: Variant; const Value, Range: Integer);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarFromInt(V, Value, Range);
{$ELSE}
asm
JMP VariantManager.VarFromInt
{$IFEND}
end;
procedure _VarFromInt64(var V: Variant; const Value: Int64);
begin
VariantManager.VarFromInt64(V, Value);
end;
procedure _VarFromBool(var V: Variant; const Value: Boolean);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarFromBool(V, Value);
{$ELSE}
asm
JMP VariantManager.VarFromBool
{$IFEND}
end;
procedure _VarFromReal; // var V: Variant; const Value: Real
asm
{$IFDEF PIC}
PUSH EAX
PUSH ECX
CALL GetGOT
POP ECX
LEA EAX,[EAX].OFFSET VariantManager
MOV EAX,[EAX].TVariantManager.VarFromReal
XCHG EAX,[ESP]
RET
{$ELSE}
JMP VariantManager.VarFromReal
{$ENDIF}
end;
procedure _VarFromTDateTime; // var V: Variant; const Value: TDateTime
asm
{$IFDEF PIC}
PUSH EAX
PUSH ECX
CALL GetGOT
POP ECX
LEA EAX,[EAX].OFFSET VariantManager
MOV EAX,[EAX].TVariantManager.VarFromTDateTime
XCHG EAX,[ESP]
RET
{$ELSE}
JMP VariantManager.VarFromTDateTime
{$ENDIF}
end;
procedure _VarFromCurr; // var V: Variant; const Value: Currency
asm
{$IFDEF PIC}
PUSH EAX
PUSH ECX
CALL GetGOT
POP ECX
LEA EAX,[EAX].OFFSET VariantManager
MOV EAX,[EAX].TVariantManager.VarFromCurr
XCHG EAX,[ESP]
RET
{$ELSE}
JMP VariantManager.VarFromCurr
{$ENDIF}
end;
procedure _VarFromPStr(var V: Variant; const Value: ShortString);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarFromPStr(V, Value);
{$ELSE}
asm
JMP VariantManager.VarFromPStr
{$IFEND}
end;
procedure _VarFromLStr(var V: Variant; const Value: string);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarFromLStr(V, Value);
{$ELSE}
asm
JMP VariantManager.VarFromLStr
{$IFEND}
end;
procedure _VarFromWStr(var V: Variant; const Value: WideString);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarFromWStr(V, Value);
{$ELSE}
asm
JMP VariantManager.VarFromWStr
{$IFEND}
end;
procedure _VarFromIntf(var V: Variant; const Value: IInterface);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarFromIntf(V, Value);
{$ELSE}
asm
JMP VariantManager.VarFromIntf
{$IFEND}
end;
procedure _VarFromDisp(var V: Variant; const Value: IDispatch);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarFromDisp(V, Value);
{$ELSE}
asm
JMP VariantManager.VarFromDisp
{$IFEND}
end;
procedure _VarFromDynArray(var V: Variant; const DynArray: Pointer; TypeInfo: Pointer);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarFromDynArray(V, DynArray, TypeInfo);
{$ELSE}
asm
JMP VariantManager.VarFromDynArray
{$IFEND}
end;
procedure _OleVarFromPStr(var V: OleVariant; const Value: ShortString);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.OleVarFromPStr(V, Value);
{$ELSE}
asm
JMP VariantManager.OleVarFromPStr
{$IFEND}
end;
procedure _OleVarFromLStr(var V: OleVariant; const Value: string);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.OleVarFromLStr(V, Value);
{$ELSE}
asm
JMP VariantManager.OleVarFromLStr
{$IFEND}
end;
procedure _OleVarFromVar(var V: OleVariant; const Value: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.OleVarFromVar(V, Value);
{$ELSE}
asm
JMP VariantManager.OleVarFromVar
{$IFEND}
end;
procedure _OleVarFromInt(var V: OleVariant; const Value, Range: Integer);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.OleVarFromInt(V, Value, Range);
{$ELSE}
asm
JMP VariantManager.OleVarFromInt
{$IFEND}
end;
procedure _VarAdd(var Left: Variant; const Right: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarOp(Left, Right, opAdd);
{$ELSE}
asm
MOV ECX,opAdd
JMP VariantManager.VarOp
{$IFEND}
end;
procedure _VarSub(var Left: Variant; const Right: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarOp(Left, Right, opSubtract);
{$ELSE}
asm
MOV ECX,opSubtract
JMP VariantManager.VarOp
{$IFEND}
end;
procedure _VarMul(var Left: Variant; const Right: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarOp(Left, Right, opMultiply);
{$ELSE}
asm
MOV ECX,opMultiply
JMP VariantManager.VarOp
{$IFEND}
end;
procedure _VarDiv(var Left: Variant; const Right: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarOp(Left, Right, opIntDivide);
{$ELSE}
asm
MOV ECX,opIntDivide
JMP VariantManager.VarOp
{$IFEND}
end;
procedure _VarMod(var Left: Variant; const Right: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarOp(Left, Right, opModulus);
{$ELSE}
asm
MOV ECX,opModulus
JMP VariantManager.VarOp
{$IFEND}
end;
procedure _VarAnd(var Left: Variant; const Right: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarOp(Left, Right, opAnd);
{$ELSE}
asm
MOV ECX,opAnd
JMP VariantManager.VarOp
{$IFEND}
end;
procedure _VarOr(var Left: Variant; const Right: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarOp(Left, Right, opOr);
{$ELSE}
asm
MOV ECX,opOr
JMP VariantManager.VarOp
{$IFEND}
end;
procedure _VarXor(var Left: Variant; const Right: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarOp(Left, Right, opXor);
{$ELSE}
asm
MOV ECX,opXor
JMP VariantManager.VarOp
{$IFEND}
end;
procedure _VarShl(var Left: Variant; const Right: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarOp(Left, Right, opShiftLeft);
{$ELSE}
asm
MOV ECX,opShiftLeft
JMP VariantManager.VarOp
{$IFEND}
end;
procedure _VarShr(var Left: Variant; const Right: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarOp(Left, Right, opShiftRight);
{$ELSE}
asm
MOV ECX,opShiftRight
JMP VariantManager.VarOp
{$IFEND}
end;
procedure _VarRDiv(var Left: Variant; const Right: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarOp(Left, Right, opDivide);
{$ELSE}
asm
MOV ECX,opDivide
JMP VariantManager.VarOp
{$IFEND}
end;
{$IF Defined(PIC) or Defined(PUREPASCAL)}
// result is set in the flags
procedure DoVarCmp(const Left, Right: Variant; OpCode: Integer);
begin
VariantManager.VarCmp(TVarData(Left), TVarData(Right), OpCode);
end;
{$IFEND}
procedure _VarCmpEQ(const Left, Right: Variant); // result is set in the flags
asm
MOV ECX, opCmpEQ
{$IFDEF PIC}
JMP DoVarCmp
{$ELSE}
JMP VariantManager.VarCmp
{$ENDIF}
end;
procedure _VarCmpNE(const Left, Right: Variant); // result is set in the flags
asm
MOV ECX, opCmpNE
{$IFDEF PIC}
JMP DoVarCmp
{$ELSE}
JMP VariantManager.VarCmp
{$ENDIF}
end;
procedure _VarCmpLT(const Left, Right: Variant); // result is set in the flags
asm
MOV ECX, opCmpLT
{$IFDEF PIC}
JMP DoVarCmp
{$ELSE}
JMP VariantManager.VarCmp
{$ENDIF}
end;
procedure _VarCmpLE(const Left, Right: Variant); // result is set in the flags
asm
MOV ECX, opCmpLE
{$IFDEF PIC}
JMP DoVarCmp
{$ELSE}
JMP VariantManager.VarCmp
{$ENDIF}
end;
procedure _VarCmpGT(const Left, Right: Variant); // result is set in the flags
asm
MOV ECX, opCmpGT
{$IFDEF PIC}
JMP DoVarCmp
{$ELSE}
JMP VariantManager.VarCmp
{$ENDIF}
end;
procedure _VarCmpGE(const Left, Right: Variant); // result is set in the flags
asm
MOV ECX, opCmpGE
{$IFDEF PIC}
JMP DoVarCmp
{$ELSE}
JMP VariantManager.VarCmp
{$ENDIF}
end;
procedure _VarNeg(var V: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarNeg(V);
{$ELSE}
asm
JMP VariantManager.VarNeg
{$IFEND}
end;
procedure _VarNot(var V: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarNot(V);
{$ELSE}
asm
JMP VariantManager.VarNot
{$IFEND}
end;
procedure _VarCopyNoInd;
asm
{$IFDEF PIC}
PUSH EAX
PUSH ECX
CALL GetGOT
POP ECX
LEA EAX,[EAX].OFFSET VariantManager
MOV EAX,[EAX].TVariantManager.VarCopyNoInd
XCHG EAX,[ESP]
RET
{$ELSE}
JMP VariantManager.VarCopyNoInd
{$ENDIF}
end;
procedure _VarClr(var V: Variant);
asm
PUSH EAX
CALL _VarClear
POP EAX
end;
procedure _VarAddRef(var V: Variant);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarAddRef(V);
{$ELSE}
asm
JMP VariantManager.VarAddRef
{$IFEND}
end;
procedure _IntfDispCall;
asm
{$IFDEF PIC}
PUSH EAX
PUSH ECX
CALL GetGOT
POP ECX
LEA EAX,[EAX].OFFSET DispCallByIDProc
MOV EAX,[EAX]
XCHG EAX,[ESP]
RET
{$ELSE}
JMP DispCallByIDProc
{$ENDIF}
end;
procedure _DispCallByIDError;
asm
MOV AL,reVarDispatch
JMP Error
end;
procedure _IntfVarCall;
asm
end;
function _WriteVariant(var T: Text; const V: Variant; Width: Integer): Pointer;
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
Result := VariantManager.WriteVariant(T, V, Width);
{$ELSE}
asm
JMP VariantManager.WriteVariant
{$IFEND}
end;
function _Write0Variant(var T: Text; const V: Variant): Pointer;
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
Result := VariantManager.Write0Variant(T, V);
{$ELSE}
asm
JMP VariantManager.Write0Variant
{$IFEND}
end;
{ ----------------------------------------------------- }
{ Variant array support }
{ ----------------------------------------------------- }
procedure _VarArrayRedim(var A : Variant; HighBound: Integer);
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
VariantManager.VarArrayRedim(A, HighBound);
{$ELSE}
asm
JMP VariantManager.VarArrayRedim
{$IFEND}
end;
function _VarArrayGet(var A: Variant; IndexCount: Integer;
Indices: Integer): Variant; cdecl;
asm
POP EBP
{$IFDEF PIC}
CALL GetGOT
LEA EAX,[EAX].OFFSET VariantManager
MOV EAX,[EAX].TVariantManager.VarArrayGet
PUSH EAX
RET
{$ELSE}
JMP VariantManager.VarArrayGet
{$ENDIF}
end;
procedure _VarArrayPut(var A: Variant; const Value: Variant;
IndexCount: Integer; Indices: Integer); cdecl;
asm
POP EBP
{$IFDEF PIC}
CALL GetGOT
LEA EAX,[EAX].OFFSET VariantManager
MOV EAX,[EAX].TVariantManager.VarArrayPut
PUSH EAX
RET
{$ELSE}
JMP VariantManager.VarArrayPut
{$ENDIF}
end;
// 64 bit integer helper routines
//
// These functions always return the 64-bit result in EAX:EDX
// ------------------------------------------------------------------------------
// 64-bit signed multiply
// ------------------------------------------------------------------------------
//
// Param 1(EAX:EDX), Param 2([ESP+8]:[ESP+4]) ; before reg pushing
//
procedure __llmul;
asm
push edx
push eax
// Param2 : [ESP+16]:[ESP+12] (hi:lo)
// Param1 : [ESP+4]:[ESP] (hi:lo)
mov eax, [esp+16]
mul dword ptr [esp]
mov ecx, eax
mov eax, [esp+4]
mul dword ptr [esp+12]
add ecx, eax
mov eax, [esp]
mul dword ptr [esp+12]
add edx, ecx
pop ecx
pop ecx
ret 8
end;
// ------------------------------------------------------------------------------
// 64-bit signed multiply, with overflow check (98.05.15: overflow not supported yet)
// ------------------------------------------------------------------------------
//
// Param1 ~= U (Uh, Ul)
// Param2 ~= V (Vh, Vl)
//
// Param 1(EAX:EDX), Param 2([ESP+8]:[ESP+4]) ; before reg pushing
//
// compiler-helper function
// O-flag set on exit => result is invalid
// O-flag clear on exit => result is valid
procedure __llmulo;
asm
push edx
push eax
// Param2 : [ESP+16]:[ESP+12] (hi:lo)
// Param1 : [ESP+4]:[ESP] (hi:lo)
mov eax, [esp+16]
mul dword ptr [esp]
mov ecx, eax
mov eax, [esp+4]
mul dword ptr [esp+12]
add ecx, eax
mov eax, [esp]
mul dword ptr [esp+12]
add edx, ecx
pop ecx
pop ecx
ret 8
end;
// ------------------------------------------------------------------------------
// 64-bit signed division
// ------------------------------------------------------------------------------
//
// Dividend = Numerator, Divisor = Denominator
//
// Dividend(EAX:EDX), Divisor([ESP+8]:[ESP+4]) ; before reg pushing
//
//
procedure __lldiv;
asm
push ebp
push ebx
push esi
push edi
xor edi,edi
mov ebx,20[esp] // get the divisor low dword
mov ecx,24[esp] // get the divisor high dword
or ecx,ecx
jnz @__lldiv@slow_ldiv // both high words are zero
or edx,edx
jz @__lldiv@quick_ldiv
or ebx,ebx
jz @__lldiv@quick_ldiv // if ecx:ebx == 0 force a zero divide
// we don't expect this to actually
// work
@__lldiv@slow_ldiv:
//
// Signed division should be done. Convert negative
// values to positive and do an unsigned division.
// Store the sign value in the next higher bit of
// di (test mask of 4). Thus when we are done, testing
// that bit will determine the sign of the result.
//
or edx,edx // test sign of dividend
jns @__lldiv@onepos
neg edx
neg eax
sbb edx,0 // negate dividend
or edi,1
@__lldiv@onepos:
or ecx,ecx // test sign of divisor
jns @__lldiv@positive
neg ecx
neg ebx
sbb ecx,0 // negate divisor
xor edi,1
@__lldiv@positive:
mov ebp,ecx
mov ecx,64 // shift counter
push edi // save the flags
//
// Now the stack looks something like this:
//
// 24[esp]: divisor (high dword)
// 20[esp]: divisor (low dword)
// 16[esp]: return EIP
// 12[esp]: previous EBP
// 8[esp]: previous EBX
// 4[esp]: previous ESI
// [esp]: previous EDI
//
xor edi,edi // fake a 64 bit dividend
xor esi,esi
@__lldiv@xloop:
shl eax,1 // shift dividend left one bit
rcl edx,1
rcl esi,1
rcl edi,1
cmp edi,ebp // dividend larger?
jb @__lldiv@nosub
ja @__lldiv@subtract
cmp esi,ebx // maybe
jb @__lldiv@nosub
@__lldiv@subtract:
sub esi,ebx
sbb edi,ebp // subtract the divisor
inc eax // build quotient
@__lldiv@nosub:
loop @__lldiv@xloop
//
// When done with the loop the four registers values' look like:
//
// | edi | esi | edx | eax |
// | remainder | quotient |
//
pop ebx // get control bits
test ebx,1 // needs negative
jz @__lldiv@finish
neg edx
neg eax
sbb edx,0 // negate
@__lldiv@finish:
pop edi
pop esi
pop ebx
pop ebp
ret 8
@__lldiv@quick_ldiv:
div ebx // unsigned divide
xor edx,edx
jmp @__lldiv@finish
end;
// ------------------------------------------------------------------------------
// 64-bit signed division with overflow check (98.05.15: not implementated yet)
// ------------------------------------------------------------------------------
//
// Dividend = Numerator, Divisor = Denominator
//
// Dividend(EAX:EDX), Divisor([ESP+8]:[ESP+4])
// Param 1 (EAX:EDX), Param 2([ESP+8]:[ESP+4])
//
// Param1 ~= U (Uh, Ul)
// Param2 ~= V (Vh, Vl)
//
// compiler-helper function
// O-flag set on exit => result is invalid
// O-flag clear on exit => result is valid
//
procedure __lldivo;
asm
// check for overflow condition: min(int64) DIV -1
push esi
mov esi, [esp+12] // Vh
and esi, [esp+8] // Vl
cmp esi, 0ffffffffh // V = -1?
jne @@divok
mov esi, eax
or esi, edx
cmp esi, 80000000H // U = min(int64)?
jne @@divok
@@divOvl:
mov eax, esi
pop esi
dec eax // turn on O-flag
ret
@@divok:
pop esi
push dword ptr [esp+8] // Vh
push dword ptr [esp+8] // Vl (offset is changed from push)
call __lldiv
and eax, eax // turn off O-flag
ret 8
end;
// ------------------------------------------------------------------------------
// 64-bit unsigned division
// ------------------------------------------------------------------------------
// Dividend(EAX(hi):EDX(lo)), Divisor([ESP+8](hi):[ESP+4](lo)) // before reg pushing
procedure __lludiv;
asm
push ebp
push ebx
push esi
push edi
//
// Now the stack looks something like this:
//
// 24[esp]: divisor (high dword)
// 20[esp]: divisor (low dword)
// 16[esp]: return EIP
// 12[esp]: previous EBP
// 8[esp]: previous EBX
// 4[esp]: previous ESI
// [esp]: previous EDI
//
// dividend is pushed last, therefore the first in the args
// divisor next.
//
mov ebx,20[esp] // get the first low word
mov ecx,24[esp] // get the first high word
or ecx,ecx
jnz @__lludiv@slow_ldiv // both high words are zero
or edx,edx
jz @__lludiv@quick_ldiv
or ebx,ebx
jz @__lludiv@quick_ldiv // if ecx:ebx == 0 force a zero divide
// we don't expect this to actually
// work
@__lludiv@slow_ldiv:
mov ebp,ecx
mov ecx,64 // shift counter
xor edi,edi // fake a 64 bit dividend
xor esi,esi
@__lludiv@xloop:
shl eax,1 // shift dividend left one bit
rcl edx,1
rcl esi,1
rcl edi,1
cmp edi,ebp // dividend larger?
jb @__lludiv@nosub
ja @__lludiv@subtract
cmp esi,ebx // maybe
jb @__lludiv@nosub
@__lludiv@subtract:
sub esi,ebx
sbb edi,ebp // subtract the divisor
inc eax // build quotient
@__lludiv@nosub:
loop @__lludiv@xloop
//
// When done with the loop the four registers values' look like:
//
// | edi | esi | edx | eax |
// | remainder | quotient |
//
@__lludiv@finish:
pop edi
pop esi
pop ebx
pop ebp
ret 8
@__lludiv@quick_ldiv:
div ebx // unsigned divide
xor edx,edx
jmp @__lludiv@finish
end;
// ------------------------------------------------------------------------------
// 64-bit modulo
// ------------------------------------------------------------------------------
// Dividend(EAX:EDX), Divisor([ESP+8]:[ESP+4]) // before reg pushing
procedure __llmod;
asm
push ebp
push ebx
push esi
push edi
xor edi,edi
//
// dividend is pushed last, therefore the first in the args
// divisor next.
//
mov ebx,20[esp] // get the first low word
mov ecx,24[esp] // get the first high word
or ecx,ecx
jnz @__llmod@slow_ldiv // both high words are zero
or edx,edx
jz @__llmod@quick_ldiv
or ebx,ebx
jz @__llmod@quick_ldiv // if ecx:ebx == 0 force a zero divide
// we don't expect this to actually
// work
@__llmod@slow_ldiv:
//
// Signed division should be done. Convert negative
// values to positive and do an unsigned division.
// Store the sign value in the next higher bit of
// di (test mask of 4). Thus when we are done, testing
// that bit will determine the sign of the result.
//
or edx,edx // test sign of dividend
jns @__llmod@onepos
neg edx
neg eax
sbb edx,0 // negate dividend
or edi,1
@__llmod@onepos:
or ecx,ecx // test sign of divisor
jns @__llmod@positive
neg ecx
neg ebx
sbb ecx,0 // negate divisor
@__llmod@positive:
mov ebp,ecx
mov ecx,64 // shift counter
push edi // save the flags
//
// Now the stack looks something like this:
//
// 24[esp]: divisor (high dword)
// 20[esp]: divisor (low dword)
// 16[esp]: return EIP
// 12[esp]: previous EBP
// 8[esp]: previous EBX
// 4[esp]: previous ESI
// [esp]: previous EDI
//
xor edi,edi // fake a 64 bit dividend
xor esi,esi
@__llmod@xloop:
shl eax,1 // shift dividend left one bit
rcl edx,1
rcl esi,1
rcl edi,1
cmp edi,ebp // dividend larger?
jb @__llmod@nosub
ja @__llmod@subtract
cmp esi,ebx // maybe
jb @__llmod@nosub
@__llmod@subtract:
sub esi,ebx
sbb edi,ebp // subtract the divisor
inc eax // build quotient
@__llmod@nosub:
loop @__llmod@xloop
//
// When done with the loop the four registers values' look like:
//
// | edi | esi | edx | eax |
// | remainder | quotient |
//
mov eax,esi
mov edx,edi // use remainder
pop ebx // get control bits
test ebx,1 // needs negative
jz @__llmod@finish
neg edx
neg eax
sbb edx,0 // negate
@__llmod@finish:
pop edi
pop esi
pop ebx
pop ebp
ret 8
@__llmod@quick_ldiv:
div ebx // unsigned divide
xchg eax,edx
xor edx,edx
jmp @__llmod@finish
end;
// ------------------------------------------------------------------------------
// 64-bit signed modulo with overflow (98.05.15: overflow not yet supported)
// ------------------------------------------------------------------------------
// Dividend(EAX:EDX), Divisor([ESP+8]:[ESP+4])
// Param 1 (EAX:EDX), Param 2([ESP+8]:[ESP+4])
//
// Param1 ~= U (Uh, Ul)
// Param2 ~= V (Vh, Vl)
//
// compiler-helper function
// O-flag set on exit => result is invalid
// O-flag clear on exit => result is valid
//
procedure __llmodo;
asm
// check for overflow condition: min(int64) MOD -1
push esi
mov esi, [esp+12] // Vh
and esi, [esp+8] // Vl
cmp esi, 0ffffffffh // V = -1?
jne @@modok
mov esi, eax
or esi, edx
cmp esi, 80000000H // U = min(int64)?
jne @@modok
@@modOvl:
mov eax, esi
pop esi
dec eax // turn on O-flag
ret
@@modok:
pop esi
push dword ptr [esp+8] // Vh
push dword ptr [esp+8] // Vl (offset is changed from push)
call __llmod
and eax, eax // turn off O-flag
ret 8
end;
// ------------------------------------------------------------------------------
// 64-bit unsigned modulo
// ------------------------------------------------------------------------------
// Dividend(EAX(hi):EDX(lo)), Divisor([ESP+8](hi):[ESP+4](lo)) // before reg pushing
procedure __llumod;
asm
push ebp
push ebx
push esi
push edi
//
// Now the stack looks something like this:
//
// 24[esp]: divisor (high dword)
// 20[esp]: divisor (low dword)
// 16[esp]: return EIP
// 12[esp]: previous EBP
// 8[esp]: previous EBX
// 4[esp]: previous ESI
// [esp]: previous EDI
//
// dividend is pushed last, therefore the first in the args
// divisor next.
//
mov ebx,20[esp] // get the first low word
mov ecx,24[esp] // get the first high word
or ecx,ecx
jnz @__llumod@slow_ldiv // both high words are zero
or edx,edx
jz @__llumod@quick_ldiv
or ebx,ebx
jz @__llumod@quick_ldiv // if ecx:ebx == 0 force a zero divide
// we don't expect this to actually
// work
@__llumod@slow_ldiv:
mov ebp,ecx
mov ecx,64 // shift counter
xor edi,edi // fake a 64 bit dividend
xor esi,esi //
@__llumod@xloop:
shl eax,1 // shift dividend left one bit
rcl edx,1
rcl esi,1
rcl edi,1
cmp edi,ebp // dividend larger?
jb @__llumod@nosub
ja @__llumod@subtract
cmp esi,ebx // maybe
jb @__llumod@nosub
@__llumod@subtract:
sub esi,ebx
sbb edi,ebp // subtract the divisor
inc eax // build quotient
@__llumod@nosub:
loop @__llumod@xloop
//
// When done with the loop the four registers values' look like:
//
// | edi | esi | edx | eax |
// | remainder | quotient |
//
mov eax,esi
mov edx,edi // use remainder
@__llumod@finish:
pop edi
pop esi
pop ebx
pop ebp
ret 8
@__llumod@quick_ldiv:
div ebx // unsigned divide
xchg eax,edx
xor edx,edx
jmp @__llumod@finish
end;
// ------------------------------------------------------------------------------
// 64-bit shift left
// ------------------------------------------------------------------------------
//
// target (EAX:EDX) count (ECX)
//
procedure __llshl;
asm
cmp cl, 32
jl @__llshl@below32
cmp cl, 64
jl @__llshl@below64
xor edx, edx
xor eax, eax
ret
@__llshl@below64:
mov edx, eax
shl edx, cl
xor eax, eax
ret
@__llshl@below32:
shld edx, eax, cl
shl eax, cl
ret
end;
// ------------------------------------------------------------------------------
// 64-bit signed shift right
// ------------------------------------------------------------------------------
// target (EAX:EDX) count (ECX)
procedure __llshr;
asm
cmp cl, 32
jl @__llshr@below32
cmp cl, 64
jl @__llshr@below64
sar edx, 1fh
mov eax,edx
ret
@__llshr@below64:
mov eax, edx
cdq
sar eax,cl
ret
@__llshr@below32:
shrd eax, edx, cl
sar edx, cl
ret
end;
// ------------------------------------------------------------------------------
// 64-bit unsigned shift right
// ------------------------------------------------------------------------------
// target (EAX:EDX) count (ECX)
procedure __llushr;
asm
cmp cl, 32
jl @__llushr@below32
cmp cl, 64
jl @__llushr@below64
xor edx, edx
xor eax, eax
ret
@__llushr@below64:
mov eax, edx
xor edx, edx
shr eax, cl
ret
@__llushr@below32:
shrd eax, edx, cl
shr edx, cl
ret
end;
function _StrInt64(val: Int64; width: Integer): ShortString;
var
d: array[0..31] of Char; { need 19 digits and a sign }
i, k: Integer;
sign: Boolean;
spaces: Integer;
begin
{ Produce an ASCII representation of the number in reverse order }
i := 0;
sign := val < 0;
repeat
d[i] := Chr( Abs(val mod 10) + Ord('0') );
Inc(i);
val := val div 10;
until val = 0;
if sign then
begin
d[i] := '-';
Inc(i);
end;
{ Fill the Result with the appropriate number of blanks }
if width > 255 then
width := 255;
k := 1;
spaces := width - i;
while k <= spaces do
begin
Result[k] := ' ';
Inc(k);
end;
{ Fill the Result with the number }
while i > 0 do
begin
Dec(i);
Result[k] := d[i];
Inc(k);
end;
{ Result is k-1 characters long }
SetLength(Result, k-1);
end;
function _Str0Int64(val: Int64): ShortString;
begin
Result := _StrInt64(val, 0);
end;
procedure _WriteInt64;
asm
{ PROCEDURE _WriteInt64( VAR t: Text; val: Int64; with: Longint); }
{ ->EAX Pointer to file record }
{ [ESP+4] Value }
{ EDX Field width }
SUB ESP,32 { VAR s: String[31]; }
PUSH EAX
PUSH EDX
PUSH dword ptr [ESP+8+32+8] { Str( val : 0, s ); }
PUSH dword ptr [ESP+8+32+8]
XOR EAX,EAX
LEA EDX,[ESP+8+8]
CALL _StrInt64
POP ECX
POP EAX
MOV EDX,ESP { Write( t, s : width );}
CALL _WriteString
ADD ESP,32
RET 8
end;
procedure _Write0Int64;
asm
{ PROCEDURE _Write0Long( VAR t: Text; val: Longint); }
{ ->EAX Pointer to file record }
{ EDX Value }
XOR EDX,EDX
JMP _WriteInt64
end;
procedure _ReadInt64;
asm
// -> EAX Pointer to text record
// <- EAX:EDX Result
PUSH EBX
PUSH ESI
PUSH EDI
SUB ESP,36 // var numbuf: String[32];
MOV ESI,EAX
CALL _SeekEof
DEC AL
JZ @@eof
MOV EDI,ESP // EDI -> numBuf[0]
MOV BL,32
@@loop:
MOV EAX,ESI
CALL _ReadChar
CMP AL,' '
JBE @@endNum
STOSB
DEC BL
JNZ @@loop
@@convert:
MOV byte ptr [EDI],0
MOV EAX,ESP // EAX -> numBuf
PUSH EDX // allocate code result
MOV EDX,ESP // pass pointer to code
CALL _ValInt64 // convert
POP ECX // pop code result into EDX
TEST ECX,ECX
JZ @@exit
MOV EAX,106
CALL SetInOutRes
@@exit:
ADD ESP,36
POP EDI
POP ESI
POP EBX
RET
@@endNum:
CMP AH,cEof
JE @@convert
DEC [ESI].TTextRec.BufPos
JMP @@convert
@@eof:
XOR EAX,EAX
JMP @@exit
end;
function _ValInt64(const s: AnsiString; var code: Integer): Int64;
var
i: Integer;
dig: Integer;
sign: Boolean;
empty: Boolean;
begin
i := 1;
dig := 0;
Result := 0;
if s = '' then
begin
code := i;
exit;
end;
while s[i] = ' ' do
Inc(i);
sign := False;
if s[i] = '-' then
begin
sign := True;
Inc(i);
end
else if s[i] = '+' then
Inc(i);
empty := True;
if (s[i] = '$') or (s[i] = '0') and (Upcase(s[i+1]) = 'X') then
begin
if s[i] = '0' then
Inc(i);
Inc(i);
while True do
begin
case s[i] of
'0'..'9': dig := Ord(s[i]) - Ord('0');
'A'..'F': dig := Ord(s[i]) - (Ord('A') - 10);
'a'..'f': dig := Ord(s[i]) - (Ord('a') - 10);
else
break;
end;
if (Result < 0) or (Result > (High(Int64) div 16)) then
break;
Result := Result shl 4 + dig;
Inc(i);
empty := False;
end;
if sign then
Result := - Result;
end
else
begin
while True do
begin
case s[i] of
'0'..'9': dig := Ord(s[i]) - Ord('0');
else
break;
end;
if (Result < 0) or (Result > (High(Int64) div 10)) then
break;
Result := Result*10 + dig;
Inc(i);
empty := False;
end;
if sign then
Result := - Result;
if (Result <> 0) and (sign <> (Result < 0)) then
Dec(i);
end;
if (s[i] <> #0) or empty then
code := i
else
code := 0;
end;
procedure _DynArrayLength;
asm
{ FUNCTION _DynArrayLength(const a: array of ...): Longint; }
{ ->EAX Pointer to array or nil }
{ <-EAX High bound of array + 1 or 0 }
TEST EAX,EAX
JZ @@skip
MOV EAX,[EAX-4]
@@skip:
end;
procedure _DynArrayHigh;
asm
{ FUNCTION _DynArrayHigh(const a: array of ...): Longint; }
{ ->EAX Pointer to array or nil }
{ <-EAX High bound of array or -1 }
CALL _DynArrayLength
DEC EAX
end;
procedure CopyArray(dest, source, typeInfo: Pointer; cnt: Integer);
asm
PUSH dword ptr [EBP+8]
CALL _CopyArray
end;
procedure FinalizeArray(p, typeInfo: Pointer; cnt: Integer);
asm
JMP _FinalizeArray
end;
procedure DynArrayClear(var a: Pointer; typeInfo: Pointer);
asm
CALL _DynArrayClear
end;
procedure DynArraySetLength(var a: Pointer; typeInfo: Pointer; dimCnt: Longint; lengthVec: PLongint);
var
i: Integer;
newLength, oldLength, minLength: Longint;
elSize: Longint;
neededSize: Longint;
p, pp: Pointer;
begin
p := a;
// Fetch the new length of the array in this dimension, and the old length
newLength := PLongint(lengthVec)^;
if newLength <= 0 then
begin
if newLength < 0 then
Error(reRangeError);
DynArrayClear(a, typeInfo);
exit;
end;
oldLength := 0;
if p <> nil then
begin
Dec(PLongint(p));
oldLength := PLongint(p)^;
Dec(PLongint(p));
end;
// Calculate the needed size of the heap object
Inc(PChar(typeInfo), Length(PDynArrayTypeInfo(typeInfo).name));
elSize := PDynArrayTypeInfo(typeInfo).elSize;
if PDynArrayTypeInfo(typeInfo).elType <> nil then
typeInfo := PDynArrayTypeInfo(typeInfo).elType^
else
typeInfo := nil;
neededSize := newLength*elSize;
if neededSize div newLength <> elSize then
Error(reRangeError);
Inc(neededSize, Sizeof(Longint)*2);
// If the heap object isn't shared (ref count = 1), just resize it. Otherwise, we make a copy
if (p = nil) or (PLongint(p)^ = 1) then
begin
pp := p;
if (newLength < oldLength) and (typeInfo <> nil) then
FinalizeArray(PChar(p) + Sizeof(Longint)*2 + newLength*elSize, typeInfo, oldLength - newLength);
ReallocMem(pp, neededSize);
p := pp;
end
else
begin
Dec(PLongint(p)^);
GetMem(p, neededSize);
minLength := oldLength;
if minLength > newLength then
minLength := newLength;
if typeInfo <> nil then
begin
FillChar((PChar(p) + Sizeof(Longint)*2)^, minLength*elSize, 0);
CopyArray(PChar(p) + Sizeof(Longint)*2, a, typeInfo, minLength)
end
else
Move(PChar(a)^, (PChar(p) + Sizeof(Longint)*2)^, minLength*elSize);
end;
// The heap object will now have a ref count of 1 and the new length
PLongint(p)^ := 1;
Inc(PLongint(p));
PLongint(p)^ := newLength;
Inc(PLongint(p));
// Set the new memory to all zero bits
FillChar((PChar(p) + elSize * oldLength)^, elSize * (newLength - oldLength), 0);
// Take care of the inner dimensions, if any
if dimCnt > 1 then
begin
Inc(lengthVec);
Dec(dimCnt);
for i := 0 to newLength-1 do
DynArraySetLength(PPointerArray(p)[i], typeInfo, dimCnt, lengthVec);
end;
a := p;
end;
procedure _DynArraySetLength;
asm
{ PROCEDURE _DynArraySetLength(var a: dynarray; typeInfo: PDynArrayTypeInfo; dimCnt: Longint; lengthVec: ^Longint) }
{ ->EAX Pointer to dynamic array (= pointer to pointer to heap object) }
{ EDX Pointer to type info for the dynamic array }
{ ECX number of dimensions }
{ [ESP+4] dimensions }
PUSH ESP
ADD dword ptr [ESP],4
CALL DynArraySetLength
end;
procedure _DynArrayCopy(a: Pointer; typeInfo: Pointer; var Result: Pointer);
begin
if a <> nil then
_DynArrayCopyRange(a, typeInfo, 0, PLongint(PChar(a)-4)^, Result)
else
_DynArrayClear(Result, typeInfo);
end;
procedure _DynArrayCopyRange(a: Pointer; typeInfo: Pointer; index, count : Integer; var Result: Pointer);
var
arrayLength: Integer;
elSize: Integer;
typeInf: PDynArrayTypeInfo;
p: Pointer;
begin
p := nil;
if a <> nil then
begin
typeInf := typeInfo;
// Limit index and count to values within the array
if index < 0 then
begin
Inc(count, index);
index := 0;
end;
arrayLength := PLongint(PChar(a)-4)^;
if index > arrayLength then
index := arrayLength;
if count > arrayLength - index then
count := arrayLength - index;
if count < 0 then
count := 0;
if count > 0 then
begin
// Figure out the size and type descriptor of the element type
Inc(PChar(typeInf), Length(typeInf.name));
elSize := typeInf.elSize;
if typeInf.elType <> nil then
typeInf := typeInf.elType^
else
typeInf := nil;
// Allocate the amount of memory needed
GetMem(p, count*elSize + Sizeof(Longint)*2);
// The reference count of the new array is 1, the length is count
PLongint(p)^ := 1;
Inc(PLongint(p));
PLongint(p)^ := count;
Inc(PLongint(p));
Inc(PChar(a), index*elSize);
// If the element type needs destruction, we must copy each element,
// otherwise we can just copy the bits
if count > 0 then
begin
if typeInf <> nil then
begin
FillChar(p^, count*elSize, 0);
CopyArray(p, a, typeInf, count)
end
else
Move(a^, p^, count*elSize);
end;
end;
end;
DynArrayClear(Result, typeInfo);
Result := p;
end;
procedure _DynArrayClear;
asm
{ ->EAX Pointer to dynamic array (Pointer to pointer to heap object }
{ EDX Pointer to type info }
{ Nothing to do if Pointer to heap object is nil }
MOV ECX,[EAX]
TEST ECX,ECX
JE @@exit
{ Set the variable to be finalized to nil }
MOV dword ptr [EAX],0
{ Decrement ref count. Nothing to do if not zero now. }
LOCK DEC dword ptr [ECX-8]
JNE @@exit
{ Save the source - we're supposed to return it }
PUSH EAX
MOV EAX,ECX
{ Fetch the type descriptor of the elements }
XOR ECX,ECX
MOV CL,[EDX].TDynArrayTypeInfo.name;
MOV EDX,[EDX+ECX].TDynArrayTypeInfo.elType;
{ If it's non-nil, finalize the elements }
TEST EDX,EDX
JE @@noFinalize
MOV ECX,[EAX-4]
TEST ECX,ECX
JE @@noFinalize
MOV EDX,[EDX]
CALL _FinalizeArray
@@noFinalize:
{ Now deallocate the array }
SUB EAX,8
CALL _FreeMem
POP EAX
@@exit:
end;
procedure _DynArrayAsg;
asm
{ ->EAX Pointer to destination (pointer to pointer to heap object }
{ EDX source (pointer to heap object }
{ ECX Pointer to rtti describing dynamic array }
PUSH EBX
MOV EBX,[EAX]
{ Increment ref count of source if non-nil }
TEST EDX,EDX
JE @@skipInc
LOCK INC dword ptr [EDX-8]
@@skipInc:
{ Dec ref count of destination - if it becomes 0, clear dest }
TEST EBX,EBX
JE @@skipClear
LOCK DEC dword ptr[EBX-8]
JNZ @@skipClear
PUSH EAX
PUSH EDX
MOV EDX,ECX
INC dword ptr[EBX-8]
CALL _DynArrayClear
POP EDX
POP EAX
@@skipClear:
{ Finally store source into destination }
MOV [EAX],EDX
POP EBX
end;
procedure _DynArrayAddRef;
asm
{ ->EAX Pointer to heap object }
TEST EAX,EAX
JE @@exit
LOCK INC dword ptr [EAX-8]
@@exit:
end;
function DynArrayIndex(const P: Pointer; const Indices: array of Integer; const TypInfo: Pointer): Pointer;
asm
{ ->EAX P }
{ EDX Pointer to Indices }
{ ECX High bound of Indices }
{ [EBP+8] TypInfo }
PUSH EBX
PUSH ESI
PUSH EDI
PUSH EBP
MOV ESI,EDX
MOV EDI,[EBP+8]
MOV EBP,EAX
XOR EBX,EBX { for i := 0 to High(Indices) do }
TEST ECX,ECX
JGE @@start
@@loop:
MOV EBP,[EBP]
@@start:
XOR EAX,EAX
MOV AL,[EDI].TDynArrayTypeInfo.name
ADD EDI,EAX
MOV EAX,[ESI+EBX*4] { P := P + Indices[i]*TypInfo.elSize }
MUL [EDI].TDynArrayTypeInfo.elSize
MOV EDI,[EDI].TDynArrayTypeInfo.elType
TEST EDI,EDI
JE @@skip
MOV EDI,[EDI]
@@skip:
ADD EBP,EAX
INC EBX
CMP EBX,ECX
JLE @@loop
@@loopEnd:
MOV EAX,EBP
POP EBP
POP EDI
POP ESI
POP EBX
end;
{ Returns the DynArrayTypeInfo of the Element Type of the specified DynArrayTypeInfo }
function DynArrayElTypeInfo(typeInfo: PDynArrayTypeInfo): PDynArrayTypeInfo;
begin
Result := nil;
if typeInfo <> nil then
begin
Inc(PChar(typeInfo), Length(typeInfo.name));
if typeInfo.elType <> nil then
Result := typeInfo.elType^;
end;
end;
{ Returns # of dimemsions of the DynArray described by the specified DynArrayTypeInfo}
function DynArrayDim(typeInfo: PDynArrayTypeInfo): Integer;
begin
Result := 0;
while (typeInfo <> nil) and (typeInfo.kind = tkDynArray) do
begin
Inc(Result);
typeInfo := DynArrayElTypeInfo(typeInfo);
end;
end;
{ Returns size of the Dynamic Array}
function DynArraySize(a: Pointer): Integer;
asm
TEST EAX, EAX
JZ @@exit
MOV EAX, [EAX-4]
@@exit:
end;
// Returns whether array is rectangular
function IsDynArrayRectangular(const DynArray: Pointer; typeInfo: PDynArrayTypeInfo): Boolean;
var
Dim, I, J, Size, SubSize: Integer;
P: Pointer;
begin
// Assume we have a rectangular array
Result := True;
P := DynArray;
Dim := DynArrayDim(typeInfo);
{NOTE: Start at 1. Don't need to test the first dimension - it's rectangular by definition}
for I := 1 to dim-1 do
begin
if P <> nil then
begin
{ Get size of this dimension }
Size := DynArraySize(P);
{ Get Size of first sub. dimension }
SubSize := DynArraySize(PPointerArray(P)[0]);
{ Walk through every dimension making sure they all have the same size}
for J := 1 to Size-1 do
if DynArraySize(PPointerArray(P)[J]) <> SubSize then
begin
Result := False;
Exit;
end;
{ Point to next dimension}
P := PPointerArray(P)[0];
end;
end;
end;
// Returns Bounds of Dynamic array as an array of integer containing the 'high' of each dimension
function DynArrayBounds(const DynArray: Pointer; typeInfo: PDynArrayTypeInfo): TBoundArray;
var
Dim, I: Integer;
P: Pointer;
begin
P := DynArray;
Dim := DynArrayDim(typeInfo);
SetLength(Result, Dim);
for I := 0 to dim-1 do
if P <> nil then
begin
Result[I] := DynArraySize(P)-1;
P := PPointerArray(P)[0]; // Assume rectangular arrays
end;
end;
{ Decrements to next lower index - Returns True if successful }
{ Indices: Indices to be decremented }
{ Bounds : High bounds of each dimension }
function DecIndices(var Indices: TBoundArray; const Bounds: TBoundArray): Boolean;
var
I, J: Integer;
begin
{ Find out if we're done: all at zeroes }
Result := False;
for I := Low(Indices) to High(Indices) do
if Indices[I] <> 0 then
begin
Result := True;
break;
end;
if not Result then
Exit;
{ Two arrays must be of same length }
Assert(Length(Indices) = Length(Bounds));
{ Find index of item to tweak }
for I := High(Indices) downto Low(Bounds) do
begin
// If not reach zero, dec and bail out
if Indices[I] <> 0 then
begin
Dec(Indices[I]);
Exit;
end
else
begin
J := I;
while Indices[J] = 0 do
begin
// Restore high bound when we've reached zero on a particular dimension
Indices[J] := Bounds[J];
// Move to higher dimension
Dec(J);
Assert(J >= 0);
end;
Dec(Indices[J]);
Exit;
end;
end;
end;
{ Package/Module registration/unregistration }
{$IFDEF MSWINDOWS}
const
LOCALE_SABBREVLANGNAME = $00000003; { abbreviated language name }
LOAD_LIBRARY_AS_DATAFILE = 2;
HKEY_CURRENT_USER = $80000001;
KEY_ALL_ACCESS = $000F003F;
KEY_READ = $000F0019;
OldLocaleOverrideKey = 'Software\Borland\Delphi\Locales'; // do not localize
NewLocaleOverrideKey = 'Software\Borland\Locales'; // do not localize
{$ENDIF}
function FindModule(Instance: LongWord): PLibModule;
begin
Result := LibModuleList;
while Result <> nil do
begin
if (Instance = Result.Instance) or
(Instance = Result.CodeInstance) or
(Instance = Result.DataInstance) or
(Instance = Result.ResInstance) then
Exit;
Result := Result.Next;
end;
end;
function FindHInstance(Address: Pointer): LongWord;
{$IFDEF MSWINDOWS}
var
MemInfo: TMemInfo;
begin
VirtualQuery(Address, MemInfo, SizeOf(MemInfo));
if MemInfo.State = $1000{MEM_COMMIT} then
Result := LongWord(MemInfo.AllocationBase)
else
Result := 0;
end;
{$ENDIF}
{$IFDEF LINUX}
var
Info: TDLInfo;
begin
if (dladdr(Address, Info) = 0) or (Info.BaseAddress = ExeBaseAddress) then
Info.Filename := nil; // if it's not in a library, assume the exe
Result := LongWord(dlopen(Info.Filename, RTLD_LAZY));
if Result <> 0 then
dlclose(Result);
end;
{$ENDIF}
function FindClassHInstance(ClassType: TClass): LongWord;
begin
Result := FindHInstance(Pointer(ClassType));
end;
{$IFDEF LINUX}
function GetModuleFileName(Module: HMODULE; Buffer: PChar; BufLen: Integer): Integer;
var
Addr: Pointer;
Info: TDLInfo;
FoundInModule: HMODULE;
begin
Result := 0;
if (Module = MainInstance) or (Module = 0) then
begin
// First, try the dlsym approach.
// dladdr fails to return the name of the main executable
// in glibc prior to 2.1.91
{ Look for a dynamic symbol exported from this program.
_DYNAMIC is not required in a main program file.
If the main program is compiled with Delphi, it will always
have a resource section, named @Sysinit@ResSym.
If the main program is not compiled with Delphi, dlsym
will search the global name space, potentially returning
the address of a symbol in some other shared object library
loaded by the program. To guard against that, we check
that the address of the symbol found is within the
main program address range. }
dlerror; // clear error state; dlsym doesn't
Addr := dlsym(Module, '@Sysinit@ResSym');
if (Addr <> nil) and (dlerror = nil)
and (dladdr(Addr, Info) <> 0)
and (Info.FileName <> nil)
and (Info.BaseAddress = ExeBaseAddress) then
begin
Result := _strlen(Info.FileName);
if Result >= BufLen then Result := BufLen-1;
Move(Info.FileName^, Buffer^, Result);
Buffer[Result] := #0;
Exit;
end;
// Try inspecting the /proc/ virtual file system
// to find the program filename in the process info
Result := _readlink('/proc/self/exe', Buffer, BufLen);
if Result <> -1 then
begin
if Result >= BufLen then Result := BufLen-1;
Buffer[Result] := #0;
end;
{$IFDEF AllowParamStrModuleName}
{ Using ParamStr(0) to obtain a module name presents a potential
security hole. Resource modules are loaded based upon the filename
of a given module. We use dlopen() to load resource modules, which
means the .init code of the resource module will be executed.
Normally, resource modules contain no code at all - they're just
carriers of resource data.
An unpriviledged user program could launch our trusted,
priviledged program with a bogus parameter list, tricking us
into loading a module that contains malicious code in its
.init section.
Without this ParamStr(0) section, GetModuleFilename cannot be
misdirected by unpriviledged code (unless the system program loader
or the /proc file system or system root directory has been compromised).
Resource modules are always loaded from the same directory as the
given module. Trusted code (programs, packages, and libraries)
should reside in directories that unpriviledged code cannot alter.
If you need GetModuleFilename to have a chance of working on systems
where glibc < 2.1.91 and /proc is not available, and your
program will not run as a priviledged user (or you don't care),
you can define AllowParamStrModuleNames and rebuild the System unit
and baseCLX package. Note that even with ParamStr(0) support
enabled, GetModuleFilename can still fail to find the name of
a module. C'est la Unix. }
if Result = -1 then // couldn't access the /proc filesystem
begin // return less accurate ParamStr(0)
{ ParamStr(0) returns the name of the link used
to launch the app, not the name of the app itself.
Also, if this app was launched by some other program,
there is no guarantee that the launching program has set
up our environment at all. (example: Apache CGI) }
if (ArgValues = nil) or (ArgValues^ = nil) or
(PCharArray(ArgValues^)[0] = nil) then
begin
Result := 0;
Exit;
end;
Result := _strlen(PCharArray(ArgValues^)[0]);
if Result >= BufLen then Result := BufLen-1;
Move(PCharArray(ArgValues^)[0]^, Buffer^, Result);
Buffer[Result] := #0;
end;
{$ENDIF}
end
else
begin
{ For shared object libraries, we can rely on the dlsym technique.
Look for a dynamic symbol in the requested module.
Don't assume the module was compiled with Delphi.
We look for a dynamic symbol with the name _DYNAMIC. This
exists in all ELF shared object libraries that export
or import symbols; If someone has a shared object library that
contains no imports or exports of any kind, this will probably fail.
If dlsym can't find the requested symbol in the given module, it
will search the global namespace and could return the address
of a symbol from some other module that happens to be loaded
into this process. That would be bad, so we double check
that the module handle of the symbol found matches the
module handle we asked about.}
dlerror; // clear error state; dlsym doesn't
Addr := dlsym(Module, '_DYNAMIC');
if (Addr <> nil) and (dlerror = nil)
and (dladdr(Addr, Info) <> 0) then
begin
if Info.BaseAddress = ExeBaseAddress then
Info.FileName := nil;
FoundInModule := HMODULE(dlopen(Info.FileName, RTLD_LAZY));
if FoundInModule <> 0 then
dlclose(FoundInModule);
if Module = FoundInModule then
begin
Result := _strlen(Info.FileName);
if Result >= BufLen then Result := BufLen-1;
Move(Info.FileName^, Buffer^, Result);
Buffer[Result] := #0;
end;
end;
end;
if Result < 0 then Result := 0;
end;
{$ENDIF}
function DelayLoadResourceModule(Module: PLibModule): LongWord;
var
FileName: array[0..MAX_PATH] of Char;
begin
if Module.ResInstance = 0 then
begin
GetModuleFileName(Module.Instance, FileName, SizeOf(FileName));
Module.ResInstance := LoadResourceModule(FileName);
if Module.ResInstance = 0 then
Module.ResInstance := Module.Instance;
end;
Result := Module.ResInstance;
end;
function FindResourceHInstance(Instance: LongWord): LongWord;
var
CurModule: PLibModule;
begin
CurModule := LibModuleList;
while CurModule <> nil do
begin
if (Instance = CurModule.Instance) or
(Instance = CurModule.CodeInstance) or
(Instance = CurModule.DataInstance) then
begin
Result := DelayLoadResourceModule(CurModule);
Exit;
end;
CurModule := CurModule.Next;
end;
Result := Instance;
end;
function LoadResourceModule(ModuleName: PChar; CheckOwner: Boolean): LongWord;
{$IFDEF LINUX}
var
FileName: array [0..MAX_PATH] of Char;
LangCode: PChar; // Language and country code. Example: en_US
P: PChar;
ModuleNameLen, FileNameLen, i: Integer;
st1, st2: TStatStruct;
begin
LangCode := __getenv('LANG');
Result := 0;
if (LangCode = nil) or (LangCode^ = #0) then Exit;
// look for modulename.en_US (ignoring codeset and modifier suffixes)
P := LangCode;
while P^ in ['a'..'z', 'A'..'Z', '_'] do
Inc(P);
if P = LangCode then Exit;
if CheckOwner and (__xstat(STAT_VER_LINUX, ModuleName, st1) = -1) then
Exit;
ModuleNameLen := _strlen(ModuleName);
if (ModuleNameLen + P - LangCode) >= MAX_PATH then Exit;
Move(ModuleName[0], Filename[0], ModuleNameLen);
Filename[ModuleNameLen] := '.';
Move(LangCode[0], Filename[ModuleNameLen + 1], P - LangCode);
FileNameLen := ModuleNameLen + 1 + (P - LangCode);
Filename[FileNameLen] := #0;
{ Security check: make sure the user id (owner) and group id of
the base module matches the user id and group id of the resource
module we're considering loading. This is to prevent loading
of malicious code dropped into the base module's directory by
a hostile user. The app and all its resource modules must
have the same owner and group. To disable this security check,
call this function with CheckOwner set to False. }
if (not CheckOwner) or
((__xstat(STAT_VER_LINUX, FileName, st2) <> -1)
and (st1.st_uid = st2.st_uid)
and (st1.st_gid = st2.st_gid)) then
begin
Result := dlopen(Filename, RTLD_LAZY);
if Result <> 0 then Exit;
end;
// look for modulename.en (ignoring country code and suffixes)
i := ModuleNameLen + 1;
while (i <= FileNameLen) and (Filename[i] in ['a'..'z', 'A'..'Z']) do
Inc(i);
if (i = ModuleNameLen + 1) or (i > FileNameLen) then Exit;
FileName[i] := #0;
{ Security check. See notes above. }
if (not CheckOwner) or
((__xstat(STAT_VER_LINUX, FileName, st2) <> -1)
and (st1.st_uid = st2.st_uid)
and (st1.st_gid = st2.st_gid)) then
begin
Result := dlopen(FileName, RTLD_LAZY);
end;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
var
FileName: array[0..MAX_PATH] of Char;
Key: LongWord;
LocaleName, LocaleOverride: array[0..4] of Char;
Size: Integer;
P: PChar;
function FindBS(Current: PChar): PChar;
begin
Result := Current;
while (Result^ <> #0) and (Result^ <> '\') do
Result := CharNext(Result);
end;
function ToLongPath(AFileName: PChar; BufSize: Integer): PChar;
var
CurrBS, NextBS: PChar;
Handle, L: Integer;
FindData: TWin32FindData;
Buffer: array[0..MAX_PATH] of Char;
GetLongPathName: function (ShortPathName: PChar; LongPathName: PChar;
cchBuffer: Integer): Integer stdcall;
begin
Result := AFileName;
Handle := GetModuleHandle(kernel);
if Handle <> 0 then
begin
@GetLongPathName := GetProcAddress(Handle, 'GetLongPathNameA');
if Assigned(GetLongPathName) and
(GetLongPathName(AFileName, Buffer, SizeOf(Buffer)) <> 0) then
begin
lstrcpyn(AFileName, Buffer, BufSize);
Exit;
end;
end;
if AFileName[0] = '\' then
begin
if AFileName[1] <> '\' then Exit;
CurrBS := FindBS(AFileName + 2); // skip server name
if CurrBS^ = #0 then Exit;
CurrBS := FindBS(CurrBS + 1); // skip share name
if CurrBS^ = #0 then Exit;
end else
CurrBS := AFileName + 2; // skip drive name
L := CurrBS - AFileName;
lstrcpyn(Buffer, AFileName, L + 1);
while CurrBS^ <> #0 do
begin
NextBS := FindBS(CurrBS + 1);
if L + (NextBS - CurrBS) + 1 > SizeOf(Buffer) then Exit;
lstrcpyn(Buffer + L, CurrBS, (NextBS - CurrBS) + 1);
Handle := FindFirstFile(Buffer, FindData);
if (Handle = -1) then Exit;
FindClose(Handle);
if L + 1 + _strlen(FindData.cFileName) + 1 > SizeOf(Buffer) then Exit;
Buffer[L] := '\';
lstrcpyn(Buffer + L + 1, FindData.cFileName, Sizeof(Buffer) - L - 1);
Inc(L, _strlen(FindData.cFileName) + 1);
CurrBS := NextBS;
end;
lstrcpyn(AFileName, Buffer, BufSize);
end;
begin
GetModuleFileName(0, FileName, SizeOf(FileName)); // Get host application name
LocaleOverride[0] := #0;
if (RegOpenKeyEx(HKEY_CURRENT_USER, NewLocaleOverrideKey, 0, KEY_READ, Key) = 0) or
(RegOpenKeyEx(HKEY_LOCAL_MACHINE, NewLocaleOverrideKey, 0, KEY_READ, Key) = 0) or
(RegOpenKeyEx(HKEY_CURRENT_USER, OldLocaleOverrideKey, 0, KEY_READ, Key) = 0) then
try
Size := sizeof(LocaleOverride);
ToLongPath(FileName, sizeof(FileName));
if RegQueryValueEx(Key, FileName, nil, nil, LocaleOverride, @Size) <> 0 then
if RegQueryValueEx(Key, '', nil, nil, LocaleOverride, @Size) <> 0 then
LocaleOverride[0] := #0;
LocaleOverride[sizeof(LocaleOverride)-1] := #0;
finally
RegCloseKey(Key);
end;
lstrcpyn(FileName, ModuleName, sizeof(FileName));
GetLocaleInfo(GetThreadLocale, LOCALE_SABBREVLANGNAME, LocaleName, sizeof(LocaleName));
Result := 0;
if (FileName[0] <> #0) and ((LocaleName[0] <> #0) or (LocaleOverride[0] <> #0)) then
begin
P := PChar(@FileName) + _strlen(FileName);
while (P^ <> '.') and (P <> @FileName) do Dec(P);
if P <> @FileName then
begin
Inc(P);
// First look for a locale registry override
if LocaleOverride[0] <> #0 then
begin
lstrcpyn(P, LocaleOverride, sizeof(FileName) - (P - FileName));
Result := LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE);
end;
if (Result = 0) and (LocaleName[0] <> #0) then
begin
// Then look for a potential language/country translation
lstrcpyn(P, LocaleName, sizeof(FileName) - (P - FileName));
Result := LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE);
if Result = 0 then
begin
// Finally look for a language only translation
LocaleName[2] := #0;
lstrcpyn(P, LocaleName, sizeof(FileName) - (P - FileName));
Result := LoadLibraryEx(FileName, 0, LOAD_LIBRARY_AS_DATAFILE);
end;
end;
end;
end;
end;
{$ENDIF}
procedure EnumModules(Func: TEnumModuleFunc; Data: Pointer); assembler;
begin
EnumModules(TEnumModuleFuncLW(Func), Data);
end;
procedure EnumResourceModules(Func: TEnumModuleFunc; Data: Pointer);
begin
EnumResourceModules(TEnumModuleFuncLW(Func), Data);
end;
procedure EnumModules(Func: TEnumModuleFuncLW; Data: Pointer);
var
CurModule: PLibModule;
begin
CurModule := LibModuleList;
while CurModule <> nil do
begin
if not Func(CurModule.Instance, Data) then Exit;
CurModule := CurModule.Next;
end;
end;
procedure EnumResourceModules(Func: TEnumModuleFuncLW; Data: Pointer);
var
CurModule: PLibModule;
begin
CurModule := LibModuleList;
while CurModule <> nil do
begin
if not Func(DelayLoadResourceModule(CurModule), Data) then Exit;
CurModule := CurModule.Next;
end;
end;
procedure AddModuleUnloadProc(Proc: TModuleUnloadProc);
begin
AddModuleUnloadProc(TModuleUnloadProcLW(Proc));
end;
procedure RemoveModuleUnloadProc(Proc: TModuleUnloadProc);
begin
RemoveModuleUnloadProc(TModuleUnloadProcLW(Proc));
end;
procedure AddModuleUnloadProc(Proc: TModuleUnloadProcLW);
var
P: PModuleUnloadRec;
begin
New(P);
P.Next := ModuleUnloadList;
@P.Proc := @Proc;
ModuleUnloadList := P;
end;
procedure RemoveModuleUnloadProc(Proc: TModuleUnloadProcLW);
var
P, C: PModuleUnloadRec;
begin
P := ModuleUnloadList;
if (P <> nil) and (@P.Proc = @Proc) then
begin
ModuleUnloadList := ModuleUnloadList.Next;
Dispose(P);
end else
begin
C := P;
while C <> nil do
begin
if (C.Next <> nil) and (@C.Next.Proc = @Proc) then
begin
P := C.Next;
C.Next := C.Next.Next;
Dispose(P);
Break;
end;
C := C.Next;
end;
end;
end;
procedure NotifyModuleUnload(HInstance: LongWord);
var
P: PModuleUnloadRec;
begin
P := ModuleUnloadList;
while P <> nil do
begin
try
P.Proc(HInstance);
except
// Make sure it doesn't stop notifications
end;
P := P.Next;
end;
{$IFDEF LINUX}
InvalidateModuleCache;
{$ENDIF}
end;
procedure RegisterModule(LibModule: PLibModule);
begin
LibModule.Next := LibModuleList;
LibModuleList := LibModule;
end;
procedure UnregisterModule(LibModule: PLibModule);
var
CurModule: PLibModule;
begin
try
NotifyModuleUnload(LibModule.Instance);
finally
if LibModule = LibModuleList then
LibModuleList := LibModule.Next
else
begin
CurModule := LibModuleList;
while CurModule <> nil do
begin
if CurModule.Next = LibModule then
begin
CurModule.Next := LibModule.Next;
Break;
end;
CurModule := CurModule.Next;
end;
end;
end;
end;
function _IntfClear(var Dest: IInterface): Pointer;
{$IFDEF PUREPASCAL}
var
P: Pointer;
begin
Result := @Dest;
if Dest <> nil then
begin
P := Pointer(Dest);
Pointer(Dest) := nil;
IInterface(P)._Release;
end;
end;
{$ELSE}
asm
MOV EDX,[EAX]
TEST EDX,EDX
JE @@1
MOV DWORD PTR [EAX],0
PUSH EAX
PUSH EDX
MOV EAX,[EDX]
CALL DWORD PTR [EAX] + VMTOFFSET IInterface._Release
POP EAX
@@1:
end;
{$ENDIF}
procedure _IntfCopy(var Dest: IInterface; const Source: IInterface);
{$IFDEF PUREPASCAL}
var
P: Pointer;
begin
P := Pointer(Dest);
if Source <> nil then
Source._AddRef;
Pointer(Dest) := Pointer(Source);
if P <> nil then
IInterface(P)._Release;
end;
{$ELSE}
asm
{
The most common case is the single assignment of a non-nil interface
to a nil interface. So we streamline that case here. After this,
we give essentially equal weight to other outcomes.
The semantics are: The source intf must be addrefed *before* it
is assigned to the destination. The old intf must be released
after the new intf is addrefed to support self assignment (I := I).
Either intf can be nil. The first requirement is really to make an
error case function a little better, and to improve the behaviour
of multithreaded applications - if the addref throws an exception,
you don't want the interface to have been assigned here, and if the
assignment is made to a global and another thread references it,
again you don't want the intf to be available until the reference
count is bumped.
}
TEST EDX,EDX // is source nil?
JE @@NilSource
PUSH EDX // save source
PUSH EAX // save dest
MOV EAX,[EDX] // get source vmt
PUSH EDX // source as arg
CALL DWORD PTR [EAX] + VMTOFFSET IInterface._AddRef
POP EAX // retrieve dest
MOV ECX, [EAX] // get current value
POP [EAX] // set dest in place
TEST ECX, ECX // is current value nil?
JNE @@ReleaseDest // no, release it
RET // most common case, we return here
@@ReleaseDest:
MOV EAX,[ECX] // get current value vmt
PUSH ECX // current value as arg
CALL DWORD PTR [EAX] + VMTOFFSET IInterface._Release
RET
{ Now we're into the less common cases. }
@@NilSource:
MOV ECX, [EAX] // get current value
TEST ECX, ECX // is it nil?
MOV [EAX], EDX // store in dest (which is nil)
JE @@Done
MOV EAX, [ECX] // get current vmt
PUSH ECX // current value as arg
CALL [EAX].vmtRelease.Pointer
@@Done:
end;
{$ENDIF}
procedure _IntfCast(var Dest: IInterface; const Source: IInterface; const IID: TGUID);
{$IFDEF PUREPASCAL}
// PIC: EBX must be correct before calling QueryInterface
begin
if Source = nil then
Dest := nil
else if Source.QueryInterface(IID, Dest) <> 0 then
Error(reIntfCastError);
end;
{$ELSE}
asm
TEST EDX,EDX
JE _IntfClear
PUSH EAX
PUSH ECX
PUSH EDX
MOV ECX,[EAX]
TEST ECX,ECX
JE @@1
PUSH ECX
MOV EAX,[ECX]
CALL DWORD PTR [EAX] + VMTOFFSET IInterface._Release
MOV EDX,[ESP]
@@1: MOV EAX,[EDX]
CALL DWORD PTR [EAX] + VMTOFFSET IInterface.QueryInterface
TEST EAX,EAX
JE @@2
MOV AL,reIntfCastError
JMP Error
@@2:
end;
{$ENDIF}
procedure _IntfAddRef(const Dest: IInterface);
begin
if Dest <> nil then Dest._AddRef;
end;
procedure TInterfacedObject.AfterConstruction;
begin
// Release the constructor's implicit refcount
InterlockedDecrement(FRefCount);
end;
procedure TInterfacedObject.BeforeDestruction;
begin
if RefCount <> 0 then
Error(reInvalidPtr);
end;
// Set an implicit refcount so that refcounting
// during construction won't destroy the object.
class function TInterfacedObject.NewInstance: TObject;
begin
Result := inherited NewInstance;
TInterfacedObject(Result).FRefCount := 1;
end;
function TInterfacedObject.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
function TInterfacedObject._AddRef: Integer;
begin
Result := InterlockedIncrement(FRefCount);
end;
function TInterfacedObject._Release: Integer;
begin
Result := InterlockedDecrement(FRefCount);
if Result = 0 then
Destroy;
end;
{ TAggregatedObject }
constructor TAggregatedObject.Create(const Controller: IInterface);
begin
// weak reference to controller - don't keep it alive
FController := Pointer(Controller);
end;
function TAggregatedObject.GetController: IInterface;
begin
Result := IInterface(FController);
end;
function TAggregatedObject.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
Result := IInterface(FController).QueryInterface(IID, Obj);
end;
function TAggregatedObject._AddRef: Integer;
begin
Result := IInterface(FController)._AddRef;
end;
function TAggregatedObject._Release: Integer; stdcall;
begin
Result := IInterface(FController)._Release;
end;
{ TContainedObject }
function TContainedObject.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := S_OK
else
Result := E_NOINTERFACE;
end;
function _CheckAutoResult(ResultCode: HResult): HResult;
{$IF Defined(PIC) or Defined(PUREPASCAL)}
begin
if ResultCode < 0 then
begin
if Assigned(SafeCallErrorProc) then
SafeCallErrorProc(ResultCode, Pointer(-1)); // loses error address
Error(reSafeCallError);
end;
Result := ResultCode;
end;
{$ELSE}
asm
TEST EAX,EAX
JNS @@2
MOV ECX,SafeCallErrorProc
TEST ECX,ECX
JE @@1
MOV EDX,[ESP]
CALL ECX
@@1: MOV AL,reSafeCallError
JMP Error
@@2:
end;
{$IFEND}
function CompToDouble(Value: Comp): Double; cdecl;
begin
Result := Value;
end;
procedure DoubleToComp(Value: Double; var Result: Comp); cdecl;
begin
Result := Value;
end;
function CompToCurrency(Value: Comp): Currency; cdecl;
begin
Result := Value;
end;
procedure CurrencyToComp(Value: Currency; var Result: Comp); cdecl;
begin
Result := Value;
end;
function GetMemory(Size: Integer): Pointer; cdecl;
begin
Result := MemoryManager.GetMem(Size);
end;
function FreeMemory(P: Pointer): Integer; cdecl;
begin
if P = nil then
Result := 0
else
Result := MemoryManager.FreeMem(P);
end;
function ReallocMemory(P: Pointer; Size: Integer): Pointer; cdecl;
begin
Result := MemoryManager.ReallocMem(P, Size);
end;
procedure SetLineBreakStyle(var T: Text; Style: TTextLineBreakStyle);
begin
if TTextRec(T).Mode = fmClosed then
TTextRec(T).Flags := TTextRec(T).Flags or (tfCRLF * Byte(Style))
else
SetInOutRes(107); // can't change mode of open file
end;
// UnicodeToUTF8(3):
// Scans the source data to find the null terminator, up to MaxBytes
// Dest must have MaxBytes available in Dest.
function UnicodeToUtf8(Dest: PChar; Source: PWideChar; MaxBytes: Integer): Integer;
var
len: Cardinal;
begin
len := 0;
if Source <> nil then
while Source[len] <> #0 do
Inc(len);
Result := UnicodeToUtf8(Dest, MaxBytes, Source, len);
end;
// UnicodeToUtf8(4):
// MaxDestBytes includes the null terminator (last char in the buffer will be set to null)
// Function result includes the null terminator.
// Nulls in the source data are not considered terminators - SourceChars must be accurate
function UnicodeToUtf8(Dest: PChar; MaxDestBytes: Cardinal; Source: PWideChar; SourceChars: Cardinal): Cardinal;
var
i, count: Cardinal;
c: Cardinal;
begin
Result := 0;
if Source = nil then Exit;
count := 0;
i := 0;
if Dest <> nil then
begin
while (i < SourceChars) and (count < MaxDestBytes) do
begin
c := Cardinal(Source[i]);
Inc(i);
if c <= $7F then
begin
Dest[count] := Char(c);
Inc(count);
end
else if c > $7FF then
begin
if count + 3 > MaxDestBytes then
break;
Dest[count] := Char($E0 or (c shr 12));
Dest[count+1] := Char($80 or ((c shr 6) and $3F));
Dest[count+2] := Char($80 or (c and $3F));
Inc(count,3);
end
else // $7F < Source[i] <= $7FF
begin
if count + 2 > MaxDestBytes then
break;
Dest[count] := Char($C0 or (c shr 6));
Dest[count+1] := Char($80 or (c and $3F));
Inc(count,2);
end;
end;
if count >= MaxDestBytes then count := MaxDestBytes-1;
Dest[count] := #0;
end
else
begin
while i < SourceChars do
begin
c := Integer(Source[i]);
Inc(i);
if c > $7F then
begin
if c > $7FF then
Inc(count);
Inc(count);
end;
Inc(count);
end;
end;
Result := count+1; // convert zero based index to byte count
end;
function Utf8ToUnicode(Dest: PWideChar; Source: PChar; MaxChars: Integer): Integer;
var
len: Cardinal;
begin
len := 0;
if Source <> nil then
while Source[len] <> #0 do
Inc(len);
Result := Utf8ToUnicode(Dest, MaxChars, Source, len);
end;
function Utf8ToUnicode(Dest: PWideChar; MaxDestChars: Cardinal; Source: PChar; SourceBytes: Cardinal): Cardinal;
var
i, count: Cardinal;
c: Byte;
wc: Cardinal;
begin
if Source = nil then
begin
Result := 0;
Exit;
end;
Result := Cardinal(-1);
count := 0;
i := 0;
if Dest <> nil then
begin
while (i < SourceBytes) and (count < MaxDestChars) do
begin
wc := Cardinal(Source[i]);
Inc(i);
if (wc and $80) <> 0 then
begin
wc := wc and $3F;
if i > SourceBytes then Exit; // incomplete multibyte char
if (wc and $20) <> 0 then
begin
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then Exit; // malformed trail byte or out of range char
if i > SourceBytes then Exit; // incomplete multibyte char
wc := (wc shl 6) or (c and $3F);
end;
c := Byte(Source[i]);
Inc(i);
if (c and $C0) <> $80 then Exit; // malformed trail byte
Dest[count] := WideChar((wc shl 6) or (c and $3F));
end
else
Dest[count] := WideChar(wc);
Inc(count);
end;
if count >= MaxDestChars then count := MaxDestChars-1;
Dest[count] := #0;
end
else
begin
while (i <= SourceBytes) do
begin
c := Byte(Source[i]);
Inc(i);
if (c and $80) <> 0 then
begin
if (c and $F0) = $F0 then Exit; // too many bytes for UCS2
if (c and $40) = 0 then Exit; // malformed lead byte
if i > SourceBytes then Exit; // incomplete multibyte char
if (Byte(Source[i]) and $C0) <> $80 then Exit; // malformed trail byte
Inc(i);
if i > SourceBytes then Exit; // incomplete multibyte char
if ((c and $20) <> 0) and ((Byte(Source[i]) and $C0) <> $80) then Exit; // malformed trail byte
Inc(i);
end;
Inc(count);
end;
end;
Result := count+1;
end;
function Utf8Encode(const WS: WideString): UTF8String;
var
L: Integer;
Temp: UTF8String;
begin
Result := '';
if WS = '' then Exit;
SetLength(Temp, Length(WS) * 3); // SetLength includes space for null terminator
L := UnicodeToUtf8(PChar(Temp), Length(Temp)+1, PWideChar(WS), Length(WS));
if L > 0 then
SetLength(Temp, L-1)
else
Temp := '';
Result := Temp;
end;
function Utf8Decode(const S: UTF8String): WideString;
var
L: Integer;
Temp: WideString;
begin
Result := '';
if S = '' then Exit;
SetLength(Temp, Length(S));
L := Utf8ToUnicode(PWideChar(Temp), Length(Temp)+1, PChar(S), Length(S));
if L > 0 then
SetLength(Temp, L-1)
else
Temp := '';
Result := Temp;
end;
function AnsiToUtf8(const S: string): UTF8String;
begin
Result := Utf8Encode(S);
end;
function Utf8ToAnsi(const S: UTF8String): string;
begin
Result := Utf8Decode(S);
end;
{$IFDEF LINUX}
function GetCPUType: Integer;
asm
PUSH EBX
// this code assumes ESP is 4 byte aligned
// test for 80386: see if bit #18 of EFLAGS (Alignment fault) can be toggled
PUSHF
POP EAX
MOV ECX, EAX
XOR EAX, $40000 // flip AC bit in EFLAGS
PUSH EAX
POPF
PUSHF
POP EAX
XOR EAX, ECX // zero = 80386 CPU (can't toggle AC bit)
MOV EAX, CPUi386
JZ @@Exit
PUSH ECX
POPF // restore original flags before next test
// test for 80486: see if bit #21 of EFLAGS (CPUID supported) can be toggled
MOV EAX, ECX // get original EFLAGS
XOR EAX, $200000 // flip CPUID bit in EFLAGS
PUSH EAX
POPF
PUSHF
POP EAX
XOR EAX, ECX // zero = 80486 (can't toggle EFLAGS bit #21)
MOV EAX, CPUi486
JZ @@Exit
// Use CPUID instruction to get CPU family
XOR EAX, EAX
CPUID
CMP EAX, 1
JL @@Exit // unknown processor response: report as 486
XOR EAX, EAX
INC EAX // we only care about info level 1
CPUID
AND EAX, $F00
SHR EAX, 8
// Test8086 values are one less than the CPU model number, for historical reasons
DEC EAX
@@Exit:
POP EBX
end;
const
sResSymExport = '@Sysinit@ResSym';
sResStrExport = '@Sysinit@ResStr';
sResHashExport = '@Sysinit@ResHash';
type
TElf32Sym = record
Name: Cardinal;
Value: Pointer;
Size: Cardinal;
Info: Byte;
Other: Byte;
Section: Word;
end;
PElf32Sym = ^TElf32Sym;
TElfSymTab = array [0..0] of TElf32Sym;
PElfSymTab = ^TElfSymTab;
TElfWordTab = array [0..2] of Cardinal;
PElfWordTab = ^TElfWordTab;
{ If Name encodes a numeric identifier, return it, else return -1. }
function NameToId(Name: PChar): Longint;
var digit: Longint;
begin
if Longint(Name) and $ffff0000 = 0 then
begin
Result := Longint(Name) and $ffff;
end
else if Name^ = '#' then
begin
Result := 0;
inc (Name);
while (Ord(Name^) <> 0) do
begin
digit := Ord(Name^) - Ord('0');
if (LongWord(digit) > 9) then
begin
Result := -1;
exit;
end;
Result := Result * 10 + digit;
inc (Name);
end;
end
else
Result := -1;
end;
// Return ELF hash value for NAME converted to lower case.
function ElfHashLowercase(Name: PChar): Cardinal;
var
g: Cardinal;
c: Char;
begin
Result := 0;
while name^ <> #0 do
begin
c := name^;
case c of
'A'..'Z': Inc(c, Ord('a') - Ord('A'));
end;
Result := (Result shl 4) + Ord(c);
g := Result and $f0000000;
Result := (Result xor (g shr 24)) and not g;
Inc(name);
end;
end;
type
PFindResourceCache = ^TFindResourceCache;
TFindResourceCache = record
ModuleHandle: HMODULE;
Version: Cardinal;
SymbolTable: PElfSymTab;
StringTable: PChar;
HashTable: PElfWordTab;
BaseAddress: Cardinal;
end;
threadvar
FindResourceCache: TFindResourceCache;
function GetResourceCache(ModuleHandle: HMODULE): PFindResourceCache;
var
info: TDLInfo;
begin
Result := @FindResourceCache;
if (ModuleHandle <> Result^.ModuleHandle) or (ModuleCacheVersion <> Result^.Version) then
begin
Result^.SymbolTable := dlsym(ModuleHandle, sResSymExport);
Result^.StringTable := dlsym(ModuleHandle, sResStrExport);
Result^.HashTable := dlsym(ModuleHandle, sResHashExport);
Result^.ModuleHandle := ModuleHandle;
if (dladdr(Result^.HashTable, Info) = 0) or (Info.BaseAddress = ExeBaseAddress) then
Result^.BaseAddress := 0 // if it's not in a library, assume the exe
else
Result^.BaseAddress := Cardinal(Info.BaseAddress);
Result^.Version := ModuleCacheVersion;
end;
end;
function FindResource(ModuleHandle: HMODULE; ResourceName: PChar; ResourceType: PChar): TResourceHandle;
var
P: PFindResourceCache;
nid, tid: Longint;
ucs2_key: array [0..2] of WideChar;
key: array [0..127] of Char;
len: Integer;
pc: PChar;
ch: Char;
nbucket: Cardinal;
bucket, chain: PElfWordTab;
syndx: Cardinal;
begin
Result := 0;
if ResourceName = nil then Exit;
P := GetResourceCache(ModuleHandle);
tid := NameToId (ResourceType);
if tid = -1 then Exit; { not supported (yet?) }
{ This code must match util-common/elfres.c }
nid := NameToId (ResourceName);
if nid = -1 then
begin
ucs2_key[0] := WideChar(2*tid+2);
ucs2_key[1] := WideChar(0);
len := UnicodeToUtf8 (key, ucs2_key, SizeOf (key));
pc := key+len;
while Ord(ResourceName^) <> 0 do
begin
ch := ResourceName^;
if Ord(ch) > 127 then exit; { insist on 7bit ASCII for now }
if ('A' <= ch) and (ch <= 'Z') then Inc(ch, Ord('a') - Ord('A'));
pc^ := ch;
inc (pc);
if pc = key + SizeOf(key) then exit;
inc (ResourceName);
end;
pc^ := Char(0);
end
else
begin
ucs2_key[0] := WideChar(2*tid+1);
ucs2_key[1] := WideChar(nid);
ucs2_key[2] := WideChar(0);
UnicodeToUtf8 (key, ucs2_key, SizeOf (key));
end;
with P^ do
begin
nbucket := HashTable[0];
// nsym := HashTable[1];
bucket := @HashTable[2];
chain := @HashTable[2+nbucket];
syndx := bucket[ElfHashLowercase(key) mod nbucket];
while (syndx <> 0)
and (strcasecmp(key, @StringTable[SymbolTable[syndx].Name]) <> 0) do
syndx := chain[syndx];
if syndx = 0 then
Result := 0
else
Result := TResourceHandle(@SymbolTable[syndx]);
end;
end;
function LoadResource(ModuleHandle: HMODULE; ResHandle: TResourceHandle): HGLOBAL;
var
P: PFindResourceCache;
begin
if ResHandle <> 0 then
begin
P := GetResourceCache(ModuleHandle);
Result := HGLOBAL(PElf32Sym(ResHandle)^.Value);
Inc (Cardinal(Result), P^.BaseAddress);
end
else
Result := 0;
end;
function SizeofResource(ModuleHandle: HMODULE; ResHandle: TResourceHandle): Integer;
begin
if ResHandle <> 0 then
Result := PElf32Sym(ResHandle)^.Size
else
Result := 0;
end;
function LockResource(ResData: HGLOBAL): Pointer;
begin
Result := Pointer(ResData);
end;
function UnlockResource(ResData: HGLOBAL): LongBool;
begin
Result := False;
end;
function FreeResource(ResData: HGLOBAL): LongBool;
begin
Result := True;
end;
{$ENDIF}
{ ResString support function }
{$IFDEF MSWINDOWS}
function LoadResString(ResStringRec: PResStringRec): string;
var
Buffer: array [0..1023] of char;
begin
if ResStringRec = nil then Exit;
if ResStringRec.Identifier < 64*1024 then
SetString(Result, Buffer,
LoadString(FindResourceHInstance(ResStringRec.Module^),
ResStringRec.Identifier, Buffer, SizeOf(Buffer)))
else
Result := PChar(ResStringRec.Identifier);
end;
{$ENDIF}
{$IFDEF LINUX}
const
ResStringTableLen = 16;
type
ResStringTable = array [0..ResStringTableLen-1] of LongWord;
function LoadResString(ResStringRec: PResStringRec): string;
var
Handle: TResourceHandle;
Tab: ^ResStringTable;
ResMod: HMODULE;
begin
if ResStringRec = nil then Exit;
ResMod := FindResourceHInstance(ResStringRec^.Module^);
Handle := FindResource(ResMod,
PChar(ResStringRec^.Identifier div ResStringTableLen),
PChar(6)); // RT_STRING
Tab := Pointer(LoadResource(ResMod, Handle));
if Tab = nil then
Result := ''
else
Result := PChar (Tab) + Tab[ResStringRec^.Identifier mod ResStringTableLen];
end;
procedure DbgUnlockX;
begin
if Assigned(DbgUnlockXProc) then
DbgUnlockXProc;
end;
{ The Win32 program loader sets up the first 64k of process address space
with no read or write access, to help detect use of invalid pointers
(whose integer value is 0..64k). Linux doesn't do this.
Parts of the Delphi RTL and IDE design environment
rely on the notion that pointer values in the [0..64k] range are
invalid pointers. To accomodate this in Linux, we reserve the range
at startup. If the range is already allocated, we keep going anyway. }
var
ZeroPageReserved: Boolean = False;
procedure ReserveZeroPage;
const
PROT_NONE = 0;
MAP_PRIVATE = $02;
MAP_FIXED = $10;
MAP_ANONYMOUS = $20;
var
P: Pointer;
begin
if IsLibrary then Exit; // page reserve is app's job, not .so's
if not ZeroPageReserved then
begin
P := mmap(nil, High(Word), PROT_NONE,
MAP_ANONYMOUS or MAP_PRIVATE or MAP_FIXED, 0, 0);
ZeroPageReserved := P = nil;
if (Integer(P) <> -1) and (P <> nil) then // we didn't get it
munmap(P, High(Word));
end;
end;
procedure ReleaseZeroPage;
begin
if ZeroPageReserved then
begin
munmap(nil, High(Word) - 4096);
ZeroPageReserved := False;
end;
end;
{$ENDIF}
function PUCS4Chars(const S: UCS4String): PUCS4Char;
const
Null: UCS4Char = 0;
PNull: PUCS4Char = @Null;
begin
if Length(S) > 0 then
Result := @S[0]
else
Result := PNull;
end;
function WideStringToUCS4String(const S: WideString): UCS4String;
var
I: Integer;
begin
SetLength(Result, Length(S) + 1);
for I := 0 to Length(S) - 1 do
Result[I] := UCS4Char(S[I + 1]);
Result[Length(S)] := 0;
end;
function UCS4StringToWidestring(const S: UCS4String): WideString;
var
I: Integer;
begin
SetLength(Result, Length(S));
for I := 0 to Length(S)-1 do
Result[I+1] := WideChar(S[I]);
Result[Length(S)] := #0;
end;
initialization
FileMode := 2;
{$IFDEF LINUX}
FileAccessRights := S_IRUSR or S_IWUSR or S_IRGRP or S_IWGRP or S_IROTH or S_IWOTH;
Test8086 := GetCPUType;
IsConsole := True;
FindResourceCache.ModuleHandle := LongWord(-1);
ReserveZeroPage;
{$ELSE}
Test8086 := 2;
{$ENDIF}
DispCallByIDProc := @_DispCallByIDError;
{$IFDEF MSWINDOWS}
if _isNECWindows then _FpuMaskInit;
{$ENDIF}
_FpuInit();
TTextRec(Input).Mode := fmClosed;
TTextRec(Output).Mode := fmClosed;
TTextRec(ErrOutput).Mode := fmClosed;
InitVariantManager;
{$IFDEF MSWINDOWS}
CmdLine := GetCommandLine;
CmdShow := GetCmdShow;
{$ENDIF}
MainThreadID := GetCurrentThreadID;
{$IFDEF LINUX}
// Ensure DbgUnlockX is linked in, calling it now does nothing
DbgUnlockX;
{$ENDIF}
finalization
Close(Input);
Close(Output);
Close(ErrOutput);
{$IFDEF LINUX}
ReleaseZeroPage;
{$ENDIF}
{$IFDEF MSWINDOWS}
UninitAllocator;
{$ENDIF}
end.
|
unit crcmodel;
{"Rocksoft^tm Model CRC Algorithm" for up to 32 bits}
interface
(*************************************************************************
DESCRIPTION : "Rocksoft^tm Model CRC Algorithm" for up to 32 bits
REQUIREMENTS : TP6/7, D1-D7/D9-D10/D12/D17-D18/D25S, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : [1] Ross Williams' public domain C sources crcmodel.c, crcmodel.h
in "A Painless Guide to CRC Error Detection Algorithms"
http://www.ross.net/crc/download/crc_v3.txt
[2] Mark Adler's crc32_combine in crc32-c from zlib 1.2.3
http://www.gzip.org/zlib/
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 14.04.06 W.Ehrhardt Initial version for table calculation, CRC32_Zip
0.11 06.12.06 we CRC standard functions for tableless versions
0.12 06.12.06 we For Pascals without const
0.13 06.12.06 we Code for cm_File
0.14 06.12.06 we Update for table versions
0.15 21.01.07 we cm_next updated to use ptab<>nil
Interfaced cm_reflect, cm_next
0.16 10.02.07 we cm_File: no eof, XL and filemode via $ifdef
0.17 05.07.07 we Force $I- in cm_File
0.18 11.07.08 we Moved to crcm_cat: CRC32_Zip, CRC16_CCITT, CRC24_PGP
0.19 11.07.08 we cm_next for width<8, ptab=nil
0.20 11.07.08 we name: string[19], no tables for width<8
0.21 12.07.08 we Reflect for table version with refin<>refout, e.g. CRC-16/BT-CHIP
0.22 12.11.08 we uses BTypes, Ptr2Inc and/or Str255
0.23 14.11.08 we char8
0.24 25.04.09 we cm_Init: cm_reflect(init,width) for table version with refin
0.25 11.06.09 we type PCRCParam = ^TCRCParam
0.26 19.07.09 we D12 fix: assign with typecast string(fname)
0.27 06.09.09 we cm_combine
0.28 10.03.12 we cm_File: {$ifndef BIT16} instead of {$ifdef WIN32}
0.29 16.08.15 we Removed $ifdef DLL / stdcall
0.30 29.11.17 we cm_File - fname: string
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2006-2017 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
{$i STD.INC}
uses
BTypes;
type
PCRCParam = ^TCRCParam;
TCRCParam = packed record
poly : longint; {CRC polynomial, top bit omitted}
init : longint; {Initial value of crc register}
xorout: longint; {final xormask for crc register}
check : longint; {CRC value for '123456789'}
width : word; {width of algorithm, deg(poly)-1}
refin : boolean; {reflect input bytes before processing}
refout: boolean; {reflect reg before xor with xorout}
name : string[19]; {name of the CRC algorithm}
end;
type
PCRC32Tab = ^TCRC32Tab; {Pointer to CRC table}
TCRC32Tab = array[byte] of longint; {CRC table type}
type
TCRC_ctx = packed record
reg : longint; {CRC state register}
poly : longint; {CRC polynomial, top bit omitted}
init : longint; {Initial value of crc register}
xorout: longint; {final xormask for crc register}
check : longint; {CRC value for '123456789'}
wmask : longint; {mask with lowest width bits set}
ptab : PCRC32Tab; {pointer to table, may be nil}
width : word; {width of algorithm, deg(poly)-1}
shift : word; {shift value for table processing}
refin : boolean; {reflect input bytes before processing}
refout: boolean; {reflect reg before xor with xorout}
name : string[19]; {name of the CRC algorithm}
end;
procedure cm_CalcTab({$ifdef CONST}const {$else} var {$endif} CRCPara: TCRCParam; var Tab: TCRC32Tab);
{-Calculate CRC table from CRCPara, does nothing if CRCPara.width<8}
procedure cm_Create({$ifdef CONST}const {$else} var {$endif} CRCPara: TCRCParam; ptab: PCRC32Tab; var ctx: TCRC_ctx);
{-Create crc context from CRCPara, ptab may be nil}
procedure cm_Init(var ctx: TCRC_ctx);
{-initialize context}
procedure cm_Update(var ctx: TCRC_ctx; Msg: pointer; Len: word);
{-update ctx with Msg data}
procedure cm_Final(var ctx: TCRC_ctx; var CRC: longint);
{-finalize calculation and return CRC}
function cm_SelfTest({$ifdef CONST}const {$else} var {$endif} CRCPara: TCRCParam) : boolean;
{-Self test for CRCPara (no table version)}
procedure cm_Full(var ctx: TCRC_ctx; var CRC: longint; Msg: pointer; Len: word);
{-process Msg with init/update/final using ctx}
procedure cm_File({$ifdef CONST} const {$endif} fname: string;
var ctx: TCRC_ctx; var CRC: longint; var buf; bsize: word; var Err: word);
{-CRC of file, buf: buffer with at least bsize bytes}
function cm_combine({$ifdef CONST}const{$else}var{$endif} para: TCRCParam; crc1, crc2: longint; len2: longint): longint;
{-combine two CRCs calculated with para, i.e. if crc1 = CRC(m1) and}
{ crc2 = CRC(m2) then cm_combine = CRC(m1||m2); len2 = length(m2).}
procedure cm_next(var ctx: TCRC_ctx; b: byte);
{-update ctx with data byte b}
function cm_reflect(v: longint; b: integer): longint;
{-returns the reflected lowest b bits of v}
implementation
{---------------------------------------------------------------------------}
function BitMaskW(w: word): longint;
{-Bit mask for w bits}
begin
if w>31 then BitMaskW := longint($FFFFFFFF)
else BitMaskW := (longint(1) shl w)-1;
end;
{---------------------------------------------------------------------------}
function cm_reflect(v: longint; b: integer): longint;
{-returns the reflected lowest b bits of v}
var
r: longint;
begin
r := 0;
b := b and $3F;
while b>0 do begin
inc(r,r);
if odd(v) then inc(r);
v := v shr 1;
dec(b);
end;
cm_reflect := r;
end;
{---------------------------------------------------------------------------}
function cm_tab({$ifdef CONST}const {$else} var {$endif} CRCPara: TCRCParam; idx: integer): longint;
{-calculate tab entry for idx}
var
i: integer;
r, topbit, inbyte: longint;
begin
topbit := longint(1) shl (CRCPara.width - 1);
inbyte := idx;
if CRCPara.refin then inbyte := cm_reflect(inbyte,8);
r := inbyte shl (CRCPara.width-8);
for i:=0 to 7 do begin
if r and topbit = 0 then r := r shl 1
else r := (r shl 1) xor CRCPara.poly
end;
if CRCPara.refin then r := cm_reflect(r, CRCPara.width);
cm_tab := r and BitMaskW(CRCPara.width);
end;
{---------------------------------------------------------------------------}
procedure cm_CalcTab({$ifdef CONST}const {$else} var {$endif} CRCPara: TCRCParam; var Tab: TCRC32Tab);
{-Calculate CRC table from CRCPara, does nothing if CRCPara.width<8}
var
i: integer;
begin
if CRCPara.width>7 then begin
for i:=0 to 255 do Tab[i] := cm_tab(CRCPara, i);
end;
end;
{---------------------------------------------------------------------------}
procedure cm_Create({$ifdef CONST}const {$else} var {$endif} CRCPara: TCRCParam; ptab: PCRC32Tab; var ctx: TCRC_ctx);
{-Create crc context from CRCPara, ptab may be nil}
begin
ctx.poly := CRCPara.poly;
ctx.init := CRCPara.init;
ctx.xorout:= CRCPara.xorout;
ctx.check := CRCPara.check;
ctx.refin := CRCPara.refin;
ctx.refout:= CRCPara.refout;
ctx.name := CRCPara.name;
ctx.width := CRCPara.width;
ctx.wmask := BitMaskW(CRCPara.width);
ctx.reg := ctx.init;
if ctx.width>7 then begin
ctx.ptab := ptab;
ctx.shift := ctx.width-8;
end
else begin
ctx.ptab := nil;
ctx.shift := 0;
end;
end;
{---------------------------------------------------------------------------}
procedure cm_next(var ctx: TCRC_ctx; b: byte);
{-update ctx with data byte b}
var
i,j: integer;
topbit, uch: longint;
begin
with ctx do begin
if ptab=nil then begin
topbit := longint(1) shl (ctx.width - 1);
uch := b;
if refin then uch := cm_reflect(uch,8);
if width>7 then begin
reg := reg xor (uch shl shift);
for i:=0 to 7 do begin
if reg and topbit = 0 then reg := (reg shl 1) and wmask
else reg := ((reg shl 1) xor poly) and wmask;
end;
end
else begin
i := $80;
while i>0 do begin
if uch and i = 0 then j := reg and topbit
else j := (reg and topbit) xor topbit;
if j=0 then reg := (reg shl 1) and wmask
else reg := ((reg shl 1) xor poly) and wmask;
i := i shr 1;
end;
end;
end
else begin
if refin then reg := ptab^[byte(reg) xor b] xor (reg shr 8)
else reg := ptab^[byte(reg shr shift) xor b] xor (reg shl 8);
end;
end;
end;
{---------------------------------------------------------------------------}
procedure cm_Init(var ctx: TCRC_ctx);
{-initialize context}
begin
with ctx do begin
if (ptab<>nil) and refin then reg := cm_reflect(init,width)
else reg := init;
end;
end;
{---------------------------------------------------------------------------}
procedure cm_Update_normal(var ctx: TCRC_ctx; Msg: pointer; Len: word);
{-update ctx with Msg data, normal/table}
var
i: word;
begin
with ctx do begin
for i:=1 to Len do begin
reg := ptab^[byte(reg shr shift) xor pByte(Msg)^] xor (reg shl 8);
inc(Ptr2Inc(Msg));
end;
end;
end;
{---------------------------------------------------------------------------}
procedure cm_Update_reflect(var ctx: TCRC_ctx; Msg: pointer; Len: word);
{-update ctx with Msg data, reflected/table}
var
i: word;
begin
with ctx do begin
for i:=1 to Len do begin
reg := ptab^[byte(reg) xor pByte(Msg)^] xor (reg shr 8);
inc(Ptr2Inc(Msg));
end;
end;
end;
{---------------------------------------------------------------------------}
procedure cm_Update_byte(var ctx: TCRC_ctx; Msg: pointer; Len: word);
{-bytewise update ctx with Msg data}
var
i: word;
begin
for i:=1 to Len do begin
cm_next(ctx, pByte(Msg)^);
inc(Ptr2Inc(Msg));
end;
end;
{---------------------------------------------------------------------------}
procedure cm_Update(var ctx: TCRC_ctx; Msg: pointer; Len: word);
{-update ctx with Msg data}
begin
with ctx do begin
if ptab=nil then cm_Update_byte(ctx,Msg,Len)
else if refin then cm_Update_reflect(ctx,Msg,Len)
else cm_Update_normal(ctx,Msg,Len);
end;
end;
{---------------------------------------------------------------------------}
procedure cm_Final(var ctx: TCRC_ctx; var CRC: longint);
{-finalize calculation and return CRC}
begin
with ctx do begin
{Reflect for table version with refin<>refout, e.g. CRC-16/BT-CHIP}
if (refout and (ptab=nil)) or ((ptab<>nil) and (refin<>refout)) then begin
CRC := xorout xor cm_reflect(reg,width)
end
else CRC := xorout xor reg;
CRC := CRC and wmask;
end;
end;
{---------------------------------------------------------------------------}
function cm_SelfTest({$ifdef CONST}const {$else} var {$endif} CRCPara: TCRCParam) : boolean;
{-Self test for CRCPara (no table version)}
var
ctx: TCRC_ctx;
CRC: longint;
const
cs: array[0..8] of char8 = '123456789';
begin
cm_Create(CRCPara,nil,ctx);
cm_Full(ctx,CRC,@cs,9);
cm_SelfTest := CRC = ctx.check;
end;
{---------------------------------------------------------------------------}
procedure cm_Full(var ctx: TCRC_ctx; var CRC: longint; Msg: pointer; Len: word);
{-process Msg with init/update/final using ctx}
begin
cm_init(ctx);
cm_update(ctx, Msg, Len);
cm_final(ctx, CRC);
end;
{---------------------------------------------------------------------------}
function cm_combine({$ifdef CONST}const{$else}var{$endif} para: TCRCParam; crc1, crc2: longint; len2: longint): longint;
{-combine two CRCs calculated with para, i.e. if crc1 = CRC(m1) and}
{ crc2 = CRC(m2) then cm_combine = CRC(m1||m2); len2 = length(m2).}
type
TMat32 = array[0..31] of longint;
{---------------------------------------------------------------------------}
function gf2_matrix_times({$ifdef CONST}const{$else}var{$endif} mat: TMat32; vec: longint): longint;
{-return mat*vec using GF(2) arithmetic}
var
i: integer;
sum: longint;
begin
i := 0;
sum := 0;
while vec<>0 do begin
if odd(vec) then sum := sum xor mat[i];
vec := vec shr 1;
inc(i);
end;
gf2_matrix_times := sum;
end;
{---------------------------------------------------------------------------}
procedure gf2_matrix_square(w: word; var square: TMat32; {$ifdef CONST}const{$else}var{$endif} mat: TMat32);
{-Calculate the square of a w x w matrix mat using GF(2) arithmetic}
var
i: integer;
begin
for i:=0 to w-1 do square[i] := gf2_matrix_times(mat, mat[i]);
end;
var
w,i: integer;
row: longint;
M1,M2: TMat32;
begin
{This function is essentially based on Mark Adler's crc32_combine from}
{the crc32.c zlib source. I generalized it to the full Rocksoft range }
{upto 32 bit, i.e. added support for non 32 bit CRCs, reflection code,}
{different and/or non-symmetric values of xorout/init, etc.}
{The main loop has an iteration count of log2(len2). The key ideas are}
{the linearity of CRC and the CRC calculation of len2 zero bytes using}
{a fast matrix powering algorithm. See Mark's comments posted to the}
{comp.compression and sci.crypt news groups from 2008-09-17, Message-ID:}
{<95e1583e-3def-4931-92d3-c33b00373ff6@p10g2000prf.googlegroups.com>}
{handle degenerate cases}
if len2<1 then begin
{nothing to do}
cm_combine := crc1;
exit;
end;
w := para.width;
if (w<1) or (w>32) then begin
{This should be treated as an error, but normally it will not happen}
{because in almost all cases pre-defined parameter records are used.}
cm_combine := 0;
exit;
end;
{Reflect start crc value if necessary}
if para.refin<>para.refout then crc1 := cm_reflect(crc1,w);
{Put operator for one zero bit in M1, i.e. for i=0..w-1 initialize the}
{CRC state ctx.reg = 1 shl i, feed in a 0 bit and set M1[i] = ctx.reg.}
{In praxis we don't not have to perform these calculation since we know}
{in advance the outcomes (depending on the refin parameter).}
if para.refin then begin
{adjust start crc if xorout and init are different and/or not symmetric}
crc1 := crc1 xor cm_reflect(para.xorout,w) xor cm_reflect(para.init,w);
M1[0] := cm_reflect(para.poly,w);
row := 1;
for i:=1 to pred(w) do begin
M1[i] := row;
row := row shl 1;
end;
end
else begin
{adjust start crc if xorout and init are different}
crc1 := crc1 xor para.xorout xor para.init;
row := 2;
for i:=0 to w-2 do begin
M1[i] := row;
row := row shl 1;
end;
M1[w-1] := para.poly;
end;
{Put operator for two zero bits in M2 = M1.M1}
gf2_matrix_square(w, M2, M1);
{Put operator for four zero bits in M1}
gf2_matrix_square(w, M1, M2);
{Apply len2 zeros to crc1 (first square will put the}
{operator for one zero byte, eight zero bits, in M2)}
repeat
{apply zeros operator for this bit of len2}
gf2_matrix_square(w, M2, M1);
if odd(len2) then crc1 := gf2_matrix_times(M2, crc1);
len2 := len2 shr 1;
{if no more bits set, then done}
if len2<>0 then begin
{another iteration of the loop with M1 and M2 swapped}
gf2_matrix_square(w, M1, M2);
if odd(len2) then crc1 := gf2_matrix_times(M1, crc1);
len2 := len2 shr 1;
end;
until len2=0;
{Reflect final crc if necessary}
if para.refin<>para.refout then crc1 := cm_reflect(crc1,w);
{Return combined crc}
cm_combine := crc1 xor crc2;
end;
{$i-} {Force I-}
{---------------------------------------------------------------------------}
procedure cm_File({$ifdef CONST} const {$endif} fname: string;
var ctx: TCRC_ctx; var CRC: longint; var buf; bsize: word; var Err: word);
{-CRC of file, buf: buffer with at least bsize bytes}
var
{$ifdef VirtualPascal}
fms: word;
{$else}
fms: byte;
{$endif}
{$ifndef BIT16}
L: longint;
{$else}
L: word;
{$endif}
f: file;
begin
fms := FileMode;
{$ifdef VirtualPascal}
FileMode := $40; {open_access_ReadOnly or open_share_DenyNone;}
{$else}
FileMode := 0;
{$endif}
system.assign(f,{$ifdef D12Plus} string {$endif} (fname));
system.reset(f,1);
Err := IOResult;
FileMode := fms;
if Err<>0 then exit;
cm_init(ctx);
L := bsize;
while (Err=0) and (L=bsize) do begin
system.blockread(f,buf,bsize,L);
Err := IOResult;
cm_update(ctx, @buf, L);
end;
system.close(f);
if IOResult=0 then;
cm_final(ctx, CRC);
end;
end.
|
unit uTranslateDataWinADOConst;
interface
uses
Windows,
Data.Win.ADOConst,
uTranslate;
Type
TTranslateDataWinADOConst = Class(TTranslate)
private
public
class procedure ChangeValues; override;
End;
Implementation
class procedure TTranslateDataWinADOConst.ChangeValues;
begin
SetResourceString(@SInvalidEnumValue, 'Valor Numérico Inválido');
SetResourceString(@SMissingConnection, 'Faltando a Conexão ou String de Conexão');
SetResourceString(@SNoDetailFilter, 'Propriedade Filter não pode ser usada em uma tabela de detalhes');
SetResourceString(@SBookmarksRequired, 'Dataset não suporta bookmarks, no qual são requeridos para controle de dados com múltiplos registros');
SetResourceString(@SMissingCommandText, 'Faltando propriedade %s');
SetResourceString(@SNoResultSet, 'CommandText não retorna um result set');
SetResourceString(@SADOCreateError, 'Erro criando objeto. Favor verificar se o Microsoft Data Access Components 2.1 (ou superior) foi instalado adequadamente');
SetResourceString(@SEventsNotSupported, 'Eventos não são suportados com os cursores do lado TableDirect do servidor');
SetResourceString(@SUsupportedFieldType, 'Não suportado tipo de campo (%s) em campo %s');
SetResourceString(@SNoMatchingADOType, 'Nenhum tipo combinando dos dados do ADO para %s');
SetResourceString(@SConnectionRequired, 'Um componente de conexão é requerido para ExecuteOptions assíncrono');
SetResourceString(@SCantRequery, 'Não é possível executar um Requery depois que a conexão mudou');
SetResourceString(@SNoFilterOptions, 'Não é suportada as opções de Filtro');
SetResourceString(@SRecordsetNotOpen, 'O Recordset não está aberto');
SetResourceString(@sNameAttr, 'Nome');
SetResourceString(@sValueAttr, 'Valor');
end;
End. |
unit dm.tcpip.tcp.client;
interface
uses
System.SysUtils,
System.Classes,
WinApi.Windows,
superobject,
org.utilities,
org.algorithms.heap,
org.tcpip.tcp,
org.tcpip.tcp.client;
type
TDMTCPClientSocket = class(TTCPClientSocket)
protected
procedure ParseProtocol; override;
procedure FillProtocol(pHead: PTCPSocketProtocolHead); override;
procedure ParseAndProcessBody; override;
procedure ParseAndProcessBodyEx; override;
end;
implementation
{ TDMTCPClientSocket }
procedure TDMTCPClientSocket.FillProtocol(pHead: PTCPSocketProtocolHead);
begin
inherited;
end;
procedure TDMTCPClientSocket.ParseAndProcessBody;
var
IOBuffer: PTCPIOBuffer;
buf: TMemoryStream;
PC: PAnsiChar;
Unfilled: Int64;
Length: DWORD;
JO: ISuperObject;
Cmd: string;
ErrDesc: string;
begin
if not FBodyInFile then begin
Unfilled := FHead^.Length;
buf := TMemoryStream.Create();
while (Unfilled > 0) and FOutstandingIOs.Pop(IOBuffer) do begin
PC := IOBuffer^.Buffers[0].buf;
Inc(PC, IOBuffer^.Position);
Length := IOBuffer^.BytesTransferred - IOBuffer^.Position;
if Length <= Unfilled then begin
buf.Write(PC^, Length);
Dec(Unfilled, Length);
FOwner.EnqueueIOBuffer(IOBuffer);
end
else begin
buf.Write(PC^, Unfilled);
IOBuffer^.Position := IOBuffer^.Position + Unfilled;
Unfilled := 0;
FOutstandingIOs.Push(IOBuffer^.SequenceNumber, IOBuffer);
end;
end;
buf.Seek(0, soBeginning);
JO := TSuperObject.ParseStream(buf, False);
buf.Free();
Cmd := JO.S['Cmd'];
{$IfDef DEBUG}
ErrDesc := Format('[%d][%d]<%s.ParseAndProcessBody> Peer response Body: %s',
[ FSocket,
GetCurrentThreadId(),
ClassName,
JO.AsString()]);
FOwner.WriteLog(llDebug, ErrDesc);
{$Endif}
if (Cmd = 'Echo') or (Cmd = 'UploadFile') then begin
end
else if Cmd = 'DownloadFile' then begin
FBodyExInFile := True;
FBodyExFileName := FOwner.TempDirectory + JO.S['FileName'];
end;
// dxm 2018.11.14
// IO_OPTION_ONCEMORE
// 1....
// 2....
if FHead^.Options and IO_OPTION_ONCEMORE = IO_OPTION_ONCEMORE then begin
end;
end
else begin
end;
inherited;
end;
procedure TDMTCPClientSocket.ParseAndProcessBodyEx;
begin
inherited;
end;
procedure TDMTCPClientSocket.ParseProtocol;
begin
inherited;
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{$HPPEMIT '#pragma link "Data.Bind.DBScope"'} {Do not Localize}
unit Data.Bind.DBScope;
interface
uses
System.Classes, System.SysUtils, Data.DB, Data.Bind.Components,
System.Bindings.Helper, System.Generics.Collections, System.Bindings.CustomScope,
System.Bindings.CustomWrapper, System.Bindings.Factories, System.Bindings.EvalProtocol;
type
TBindDataSetScope = class(TCustomScope)
protected
function DoLookup(const Name: String): IInterface; override;
end;
TBaseDataLink = class;
// DataSource.DataSet defines the object scope
TCustomBindScopeDB = class(TBaseBindScopeComponent, IScopeEditLink, IScopeRecordEnumerable,
IScopeNavigator, IScopeActive, IScopeState, IScopeEditor, IScopeMemberNames, IScopeCurrentRecord)
private
FDataLink: TBaseDataLink;
FDataSource: TDataSource;
FDataLinks: TDictionary<TBasicBindComponent, TBaseDataLink>;
FActiveChanged: TBindEventList;
FDataSetChanged: TBindEventList;
FEditingChanged: TBindEventList;
FDataSetScrolled: TBindEventList1<Integer>;
procedure SetDataSource(const Value: TDataSource);
function CheckDataSet: Boolean;
procedure OnActiveChanged(Sender: TObject);
procedure OnDataSetChanged(Sender: TObject);
procedure OnDataSetScrolled(Sender: TObject; ADistance: Integer);
procedure OnEditingChanged(Sender: TObject);
protected
function GetValue: TObject; override;
function GetMember(const AMemberName: string): TObject; override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure AddExpression(AExpression: TBasicBindComponent); override;
procedure RemoveExpression(AExpression: TBasicBindComponent); override;
{ IScopeEditLink }
function Edit(ABindComp: TBasicBindComponent): Boolean;overload; virtual;
function GetIsEditing(ABindComp: TBasicBindComponent): Boolean; virtual;
procedure SetModified(ABindComp: TBasicBindComponent); virtual;
function GetIsModified(ABindComp: TBasicBindComponent): Boolean; virtual;
function GetCanModify(ABindComp: TBasicBindComponent): Boolean; overload; virtual;
procedure UpdateRecord(ABindComp: TBasicBindComponent); virtual;
procedure Reset(ABindComp: TBasicBindComponent); virtual;
procedure SetReadOnly(ABindComp: TBasicBindComponent; const Value: Boolean); virtual;
procedure SetField(ABindComp: TBasicBindComponent; const FieldName: string); virtual;
procedure ClearModified(ABindComp: TBasicBindComponent); virtual;
{ IScopeRecordEnumerable }
function GetEnumerator(const AMemberName: string; ABufferCount: Integer): IScopeRecordEnumerator;
{ IScopeNavigator }
function GetBOF: Boolean; virtual;
function GetEOF: Boolean; virtual;
function GetSelected: Boolean; virtual;
procedure Next; virtual;
procedure Prior; virtual;
procedure First; virtual;
procedure Last; virtual;
{ IScopeState }
function GetActive: Boolean; virtual;
function GetCanModify: Boolean; overload; virtual;
function GetEditing: Boolean; virtual;
procedure AddActiveChanged(LNotify: TNotifyEvent); virtual;
procedure RemoveActiveChanged(LNotify: TNotifyEvent); virtual;
procedure AddEditingChanged(LNotify: TNotifyEvent); virtual;
procedure RemoveEditingChanged(LNotify: TNotifyEvent); virtual;
procedure AddDataSetScrolled(LNotify: TNotifyDistanceEvent); virtual;
procedure RemoveDataSetScrolled(LNotify: TNotifyDistanceEvent); virtual;
procedure AddDataSetChanged(LNotify: TNotifyEvent); virtual;
procedure RemoveDataSetChanged(LNotify: TNotifyEvent); virtual;
{ IScopeEditor }
procedure Insert; virtual;
procedure Delete; virtual;
procedure Cancel; virtual;
procedure Post; virtual;
procedure Edit; overload; virtual;
procedure Refresh; virtual;
function IsValidChar(const AFieldName: string; const AChar: Char): Boolean;
function IsRequired(const AFieldName: string): Boolean;
{ IScopeMemberNames }
procedure GetMemberNames(AList: TStrings); virtual;
{ IScopeCurrentRecord }
function GetCurrentRecord(const AMemberName: string): IScope;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property DataSource: TDataSource read FDataSource write SetDataSource;
end;
TBindScopeDB = class(TCustomBindScopeDB)
published
property DataSource;
end;
TBaseDataLink = class(TDataLink)
protected
function Edit: Boolean; virtual;
end;
TBindScopeDBEnumerator = class(TInterfacedObject, IScopeRecordEnumerator,
IScopeRecordEnumeratorCount)
private
FBindScope: TCustomBindScopeDB;
FSaveActiveRecord: Integer;
FMemberName: string;
FNextRecord: Integer;
public
constructor Create(ABindScope: TCustomBindScopeDB; const AMemberName: string;
ABufferCount: Integer);
destructor Destroy; override;
procedure First;
function GetCurrent: IScope;
function GetRecordCount: Integer;
function GetMemberCurrent(const AMemberName: string): IScope;
function MoveNext: Boolean;
property Current: IScope read GetCurrent;
end;
implementation
uses System.Rtti, System.Bindings.Outputs, System.Bindings.Methods, Data.Bind.Consts;
type
TScopeDataLink = class(TBaseDataLink)
private
FDBScopeComponent: TCustomBindScopeDB;
FOnDataSetChanged: TNotifyEvent;
FOnEditingChanged: TNotifyEvent;
FOnActiveChanged: TNotifyEvent;
FOnDataSetScrolled: TNotifyDistanceEvent;
public
constructor Create(ADBScopeComponent: TCustomBindScopeDB);
procedure DataSetChanged; override;
procedure ActiveChanged; override;
procedure EditingChanged; override;
procedure DataSetScrolled(Distance: Integer); override;
property OnDataSetChanged: TNotifyEvent read FOnDataSetChanged write FOnDataSetChanged;
property OnDataSetScrolled: TNotifyDistanceEvent read FOnDataSetScrolled write FOnDataSetScrolled;
property OnActiveChanged: TNotifyEvent read FOnActiveChanged write FOnActiveChanged;
property OnEditingChanged: TNotifyEvent read FOnEditingChanged write FOnEditingChanged;
end;
TBindLinkDataLink = class(TBaseDataLink)
strict private
FBindLink: IBindLink;
FBindLayoutChanged: IBindLayoutChanged;
FBindPosition: IBindPosition;
FBindListUpdate: IBindListUpdate;
FEditing: Boolean;
FField: TField;
FFieldName: string;
FModified: Boolean;
function GetCanModify: Boolean;
private
function GetField: TField;
procedure SetEditing(Value: Boolean);
function GetFieldName: string;
procedure SetField(Value: TField);
procedure SetFieldName(Value: string);
procedure UpdateField;
procedure DoDataChange(Sender: TObject; AField: TField);
protected
procedure RecordChanged(Field: TField); override;
procedure DataEvent(Event: TDataEvent; Info: NativeInt); override;
procedure DataSetChanged; override;
procedure DataSetScrolled(ADistance: Integer); override;
procedure LayoutChanged; override;
procedure ActiveChanged; override;
procedure EditingChanged; override;
procedure UpdateData; override;
function Edit: Boolean; override;
public
constructor Create(ABindLink: IBindLink); overload;
constructor Create(ABindPosition: IBindPosition); overload;
constructor Create(ABindListUpdate: IBindListUpdate); overload;
procedure Modified;
function IsModified: Boolean;
procedure ClearModified;
procedure Reset;
property CanModify: Boolean read GetCanModify;
property Editing: Boolean read FEditing;
property Field: TField read GetField;
end;
constructor TBindLinkDataLink.Create(ABindLink: IBindLink);
begin
inherited Create;
FBindLink := ABindLink;
FFieldName := '';
Supports(FBindLink, IBindPosition, FBindPosition);
Supports(FBindLink, IBindListUpdate, FBindListUpdate);
Supports(FBindLink, IBindLayoutChanged, FBindLayoutChanged);
end;
constructor TBindLinkDataLink.Create(ABindPosition: IBindPosition);
begin
inherited Create;
FBindPosition := ABindPosition;
FFieldName := '';
Supports(FBindPosition, IBindLink, FBindLink);
Supports(FBindPosition, IBindListUpdate, FBindListUpdate);
Supports(FBindPosition, IBindLayoutChanged, FBindLayoutChanged);
end;
procedure TBindLinkDataLink.ClearModified;
begin
FModified := False;
end;
constructor TBindLinkDataLink.Create(ABindListUpdate: IBindListUpdate);
begin
inherited Create;
FBindListUpdate := ABindListUpdate;
FFieldName := '';
Supports(FBindListUpdate, IBindLink, FBindLink);
Supports(FBindListUpdate, IBindPosition, FBindPosition);
Supports(FBindListUpdate, IBindLayoutChanged, FBindLayoutChanged);
end;
procedure TBindLinkDataLink.SetField(Value: TField);
begin
if FField <> Value then
begin
FField := Value;
EditingChanged;
RecordChanged(nil);
//UpdateRightToLeft;
end;
end;
procedure TBindLinkDataLink.SetFieldName(Value: string);
begin
FFieldName := Value;
UpdateField;
end;
procedure TBindLinkDataLink.ActiveChanged;
begin
try
UpdateField;
except
on E: Exception do
// Don't raise exception while destroying
if not ((DataSource <> nil) and (csDestroying in DataSource.ComponentState)) then
raise;
end;
end;
procedure TBindLinkDataLink.LayoutChanged;
begin
if FBindLayoutChanged <> nil then
FBindLayoutChanged.LayoutChanged;
UpdateField;
end;
procedure TBindLinkDataLink.DataEvent(Event: TDataEvent; Info: NativeInt);
begin
inherited;
if Event = deFieldChange then
begin
if Boolean(Info) then
UpdateField
else
FField := nil;
end
else if (Event = deDisabledStateChange) then
begin
if Boolean(Info) then
UpdateField
else
FField := nil;
end;
end;
procedure TBindLinkDataLink.DataSetChanged;
var
LBindListRefresh: IBindListRefresh;
LRefreshed: Boolean;
begin
if (FBindListUpdate <> nil) and Active then
begin
LRefreshed := False;
if Supports(FBindListUpdate, IBindListRefresh, LBindListRefresh) then
if LBindListRefresh.RefreshNeeded then
begin
LBindListRefresh.RefreshList;
LRefreshed := True;
end;
if not LRefreshed then
begin
if FBindPosition <> nil then
begin
if Self.DataSource.DataSet.RecNo > 0 then
FBindPosition.EvaluatePosControl; // Needed
end;
FBindListUpdate.UpdateList;
end;
end
else if (FBindPosition <> nil) and Active then
begin
if Self.DataSource.DataSet.RecNo > 0 then
FBindPosition.EvaluatePosControl; // Needed
end;
RecordChanged(nil);
end;
procedure TBindLinkDataLink.DataSetScrolled(ADistance: Integer);
var
LDataLink: TBindLinkDataLink;
begin
LDataLink := Self;
if Active then
if FBindLink <> nil then
begin
if FBindPosition <> nil then
begin
// Must position grid to current record
if LDataLink.DataSource.DataSet.RecNo > 0 then
FBindPosition.EvaluatePosControl;
end
else
RecordChanged(nil);
end
else if FBindPosition <> nil then
if Active then
if LDataLink.DataSource.DataSet.RecNo > 0 then
FBindPosition.EvaluatePosControl;
end;
procedure TBindLinkDataLink.UpdateField;
var
LFieldName: string;
begin
LFieldName := GetFieldName;
if (LFieldName = '') and (FField = nil) then
begin
// No field name
RecordChanged(nil);
end
else
begin
if Active and (LFieldName <> '') then
begin
FField := nil;
SetField(DataSource.DataSet.FieldByName(LFieldName));
end
else
SetField(nil);
end;
end;
function TBindLinkDataLink.GetFieldName: string;
begin
if FBindLink <> nil then
Result := FBindLink.SourceMemberName
else if FBindPosition <> nil then
Result := FBindPosition.SourceMemberName;
if Result = '' then
Result := FFieldName;
end;
function TBindLinkDataLink.IsModified: Boolean;
begin
Result := FModified;
end;
function TBindLinkDataLink.Edit: Boolean;
begin
if CanModify then inherited Edit;
Result := FEditing;
end;
function TBindLinkDataLink.GetCanModify: Boolean;
begin
Result := not ReadOnly and ((Field = nil) or Field.CanModify);
end;
function TBindLinkDataLink.GetField: TField;
begin
Result := FField;
end;
procedure TBindLinkDataLink.Modified;
begin
FModified := True;
end;
procedure TBindLinkDataLink.EditingChanged;
begin
SetEditing(inherited Editing and CanModify);
end;
procedure TBindLinkDataLink.UpdateData;
begin
if FBindLink <> nil then
if not FBindLink.Updating then
begin
FBindLink.BeginUpdate;
try
if FModified then
begin
FBindLink.EvaluateParse('');
FModified := False;
end;
finally
FBindLink.EndUpdate;
end;
end;
end;
procedure TBindLinkDataLink.RecordChanged(Field: TField);
begin
if (Field = nil) or (Field = FField) then
begin
DoDataChange(Self, Field);
FModified := False;
end
else if FField = nil then
begin
DoDataChange(Self, nil);
FModified := False;
end;
end;
procedure TBindLinkDataLink.Reset;
begin
RecordChanged(nil);
end;
// Copied from DBEdit
procedure TBindLinkDataLink.DoDataChange(Sender: TObject; AField: TField);
var
LDataLink: TBindLinkDataLink;
LMemberName: string;
begin
if AField <> nil then
LMemberName := AField.FieldName;
LDataLink := Self;
if FBindLink <> nil then
begin
// if (FBindPosition <> nil) and Active then
// // Must position grid to current record
// if LDataLink.DataSource.DataSet.RecNo > 0 then
// FBindPosition.EvaluatePosControl;
if (not FBindLink.Updating) then
begin
FBindLink.BeginUpdate;
try
if LDataLink.Field <> nil then
begin
if LDataLink.CanModify then // FFocused and FDataLink.CanModify then
FBindLink.EvaluateFormat(LMemberName)
else
begin
FBindLink.EvaluateFormat(LMemberName);
end;
end else
begin
if Active and (RecordCount > 0) then
FBindLink.EvaluateFormat((LMemberName))
else
FBindLink.EvaluateClear((LMemberName))
end;
finally
FBindLink.EndUpdate;
end;
end;
end
// else if FBindPosition <> nil then
// if Active then
// if LDataLink.DataSource.DataSet.RecNo > 0 then
//
// FBindPosition.EvaluatePosControl;
end;
procedure TBindLinkDataLink.SetEditing(Value: Boolean);
begin
if FEditing <> Value then
begin
FEditing := Value;
FModified := False;
//if Assigned(FOnEditingChange) then FOnEditingChange(Self);
end;
end;
procedure TCustomBindScopeDB.AddActiveChanged(LNotify: TNotifyEvent);
begin
FActiveChanged.Add(LNotify);
end;
procedure TCustomBindScopeDB.AddDataSetChanged(LNotify: TNotifyEvent);
begin
FDataSetChanged.Add(LNotify);
end;
procedure TCustomBindScopeDB.AddDataSetScrolled(LNotify: TNotifyDistanceEvent);
begin
FDataSetScrolled.Add(LNotify);
end;
procedure TCustomBindScopeDB.AddEditingChanged(LNotify: TNotifyEvent);
begin
FEditingChanged.Add(LNotify);
end;
procedure TCustomBindScopeDB.AddExpression(AExpression: TBasicBindComponent);
var
LBindLinkDataLink: TBindLinkDataLink;
LBindLink: IBindLink;
LBindPosition: IBindPosition;
begin
inherited;
if Supports(AExpression, IBindLink, LBindLink) then
begin
LBindLinkDataLink := TBindLinkDataLink.Create(LBindLink);
FDataLinks.AddOrSetValue(AExpression,
LBindLinkDataLink);
if Self.DataSource <> nil then
LBindLinkDataLink.DataSource := Self.DataSource;
end
else if Supports(AExpression, IBindPosition, LBindPosition) then
begin
LBindLinkDataLink := TBindLinkDataLink.Create(LBindPosition);
FDataLinks.AddOrSetValue(AExpression,
LBindLinkDataLink);
if Self.DataSource <> nil then
LBindLinkDataLink.DataSource := Self.DataSource;
end;
end;
constructor TCustomBindScopeDB.Create(AOwner: TComponent);
var
LDataLink: TScopeDataLink;
begin
inherited;
LDataLink := TScopeDataLink.Create(Self);
FDataLink := LDataLink;
LDataLink.OnActiveChanged := OnActiveChanged;
LDataLink.OnDataSetChanged := OnDataSetChanged;
LDataLink.OnDataSetScrolled := OnDataSetScrolled;
LDataLink.OnActiveChanged := OnActiveChanged;
LDataLink.OnEditingChanged := OnEditingChanged;
FDataLinks := TObjectDictionary<TBasicBindComponent, TBaseDataLink>.Create([doOwnsValues]);
FActiveChanged := TBindEventList.Create;
FDataSetChanged := TBindEventList.Create;
FEditingChanged := TBindEventList.Create;
FDataSetScrolled := TBindEventList1<Integer>.Create;
end;
procedure TCustomBindScopeDB.Delete;
begin
if CheckDataSet then
FDataSource.DataSet.Delete;
end;
destructor TCustomBindScopeDB.Destroy;
begin
inherited; // Send Notification before free objects
FreeAndNil(FDataLink);
FreeAndNil(FDataLinks);
FreeAndNil(FActiveChanged);
FreeAndNil(FDataSetChanged);
FreeAndNil(FEditingChanged);
FreeAndNil(FDataSetScrolled);
end;
procedure TCustomBindScopeDB.Edit;
begin
if CheckDataSet then
FDataSource.DataSet.Edit;
end;
procedure TCustomBindScopeDB.OnEditingChanged(Sender: TObject);
begin
FEditingChanged.Send(Self);
end;
procedure TCustomBindScopeDB.OnActiveChanged(Sender: TObject);
begin
FActiveChanged.Send(Self);
end;
procedure TCustomBindScopeDB.OnDataSetChanged(Sender: TObject);
begin
FDataSetChanged.Send(Self);
end;
procedure TCustomBindScopeDB.OnDataSetScrolled(Sender: TObject; ADistance: Integer);
begin
FDataSetScrolled.Send(Self, ADistance);
end;
function TCustomBindScopeDB.Edit(ABindComp: TBasicBindComponent): Boolean;
var
LDataLink: TBaseDataLink;
begin
if (FDataLinks <> nil) and FDataLinks.TryGetValue(ABindComp, LDataLink) then
begin
Assert(LDataLink <> nil);
Result := LDataLink.Edit
end
else
Result := False;
end;
function TCustomBindScopeDB.CheckDataSet: Boolean;
begin
Result := (FDataSource <> nil) and (FDataSource.DataSet <> nil);
end;
procedure TCustomBindScopeDB.First;
begin
if CheckDataSet then
FDataSource.DataSet.First;
end;
procedure TCustomBindScopeDB.UpdateRecord(ABindComp: TBasicBindComponent);
var
LDataLink: TBaseDataLink;
begin
if (FDataLinks <> nil) and FDataLinks.TryGetValue(ABindComp, LDataLink) then
begin
Assert(LDataLink <> nil);
LDataLink.UpdateRecord;
end
end;
procedure TCustomBindScopeDB.Reset(ABindComp: TBasicBindComponent);
var
LDataLink: TBaseDataLink;
begin
if (FDataLinks <> nil) and FDataLinks.TryGetValue(ABindComp, LDataLink) then
begin
Assert(LDataLink <> nil);
if LDataLink is TBindLinkDataLink then
TBindLinkDataLink(LDataLink).Reset
end
end;
procedure TCustomBindScopeDB.SetModified(ABindComp: TBasicBindComponent);
var
LDataLink: TBaseDataLink;
begin
if (FDataLinks <> nil) and FDataLinks.TryGetValue(ABindComp, LDataLink) then
begin
Assert(LDataLink <> nil);
if LDataLink is TBindLinkDataLink then
TBindLinkDataLink(LDataLink).Modified
end
end;
procedure TCustomBindScopeDB.ClearModified(ABindComp: TBasicBindComponent);
var
LDataLink: TBaseDataLink;
begin
if (FDataLinks <> nil) and FDataLinks.TryGetValue(ABindComp, LDataLink) then
begin
Assert(LDataLink <> nil);
if LDataLink is TBindLinkDataLink then
TBindLinkDataLink(LDataLink).ClearModified;
end
end;
procedure TCustomBindScopeDB.SetReadOnly(ABindComp: TBasicBindComponent; const Value: Boolean);
var
LDataLink: TBaseDataLink;
begin
if (FDataLinks <> nil) and FDataLinks.TryGetValue(ABindComp, LDataLink) then
begin
Assert(LDataLink <> nil);
if LDataLink is TBindLinkDataLink then
TBindLinkDataLink(LDataLink).ReadOnly := Value;
end
end;
function TCustomBindScopeDB.GetIsModified(ABindComp: TBasicBindComponent): Boolean;
var
LDataLink: TBaseDataLink;
begin
Result := False;
if (FDataLinks <> nil) and FDataLinks.TryGetValue(ABindComp, LDataLink) then
begin
Assert(LDataLink <> nil);
if LDataLink is TBindLinkDataLink then
Result := TBindLinkDataLink(LDataLink).IsModified
end
end;
function TCustomBindScopeDB.GetIsEditing(ABindComp: TBasicBindComponent): Boolean;
var
LDataLink: TBaseDataLink;
begin
Result := False;
if FDataLinks.TryGetValue(ABindComp, LDataLink) then
begin
Assert(LDataLink <> nil);
if LDataLink is TBindLinkDataLink then
Result := TBindLinkDataLink(LDataLink).Editing;
end
end;
procedure TCustomBindScopeDB.Cancel;
begin
if CheckDataSet then
FDataSource.DataSet.Cancel;
end;
function TCustomBindScopeDB.GetCanModify(ABindComp: TBasicBindComponent): Boolean;
var
LDataLink: TBaseDataLink;
begin
Result := False;
if (FDataLinks <> nil) and FDataLinks.TryGetValue(ABindComp, LDataLink) then
begin
Assert(LDataLink <> nil);
if LDataLink is TBindLinkDataLink then
Result := TBindLinkDataLink(LDataLink).CanModify
end
end;
function TCustomBindScopeDB.GetActive: Boolean;
begin
if Assigned(FDataSource) and Assigned(FDataSource.DataSet) then
Result := FDataSource.DataSet.Active and FDataLink.Active
else
Result := FDataLink.Active;
end;
function TCustomBindScopeDB.GetBOF: Boolean;
begin
if CheckDataSet then
Result := FDataSource.DataSet.Bof
else
Result := True;
end;
function TCustomBindScopeDB.GetCanModify: Boolean;
begin
Result := False;
if FDataSource <> nil then
if FDataSource.DataSet <> nil then
Result := FDataSource.DataSet.CanModify;
end;
function TCustomBindScopeDB.GetCurrentRecord(const AMemberName: string): IScope;
begin
if AMemberName <> '' then
Result := GetMemberScope(AMemberName)
else
Result := GetScope;
end;
function TCustomBindScopeDB.GetEditing: Boolean;
begin
Result := FDataLink.Editing;
end;
function TCustomBindScopeDB.GetEnumerator(
const AMemberName: string; ABufferCount: Integer): IScopeRecordEnumerator;
begin
Result := TBindScopeDBEnumerator.Create(Self, AMemberName, ABufferCount);
end;
function TCustomBindScopeDB.GetEOF: Boolean;
begin
if CheckDataSet then
Result := FDataSource.DataSet.Eof
else
Result := True;
end;
function TCustomBindScopeDB.GetSelected: Boolean;
begin
if CheckDataSet then
Result := not (FDataSource.DataSet.Eof and FDataSource.DataSet.Bof)
else
Result := True;
end;
function TCustomBindScopeDB.GetMember(const AMemberName: string): TObject;
begin
Result := nil;
Assert(FDataSource <> nil);
if FDataSource <> nil then
begin
Assert(FDataSource.DataSet <> nil);
if FDataSource.DataSet.Active then
Result := FDataSource.DataSet.FieldByName(AMemberName);
end;
end;
procedure TCustomBindScopeDB.GetMemberNames(AList: TStrings);
begin
if (FDataSource <> nil) and (FDataSource.DataSet <> nil ) then
FDataSource.DataSet.GetFieldNames(AList)
else
AList.Clear;
end;
function TCustomBindScopeDB.GetValue: TObject;
begin
Assert(FDataSource <> nil);
if FDataSource <> nil then
begin
Result := FDataSource.DataSet;
end
else
Result := nil;
end;
procedure TCustomBindScopeDB.Insert;
begin
if CheckDataSet then
FDataSource.DataSet.Insert;
end;
function TCustomBindScopeDB.IsRequired(const AFieldName: string): Boolean;
var
LField: TField;
begin
Result := False;
if CheckDataSet then
begin
LField := FDataSource.DataSet.FieldByName(AFieldName);
if Assigned(LField) then
Result := LField.Required;
end;
end;
function TCustomBindScopeDB.IsValidChar(const AFieldName: string;
const AChar: Char): Boolean;
var
LField: TField;
begin
Result := False;
if CheckDataSet then
begin
LField := FDataSource.DataSet.FieldByName(AFieldName);
if Assigned(LField) then
begin
if AChar = #0 then
// Special case to test if field is read only
Result := LField.CanModify
else
Result := LField.IsValidChar(AChar);
end
end;
end;
procedure TCustomBindScopeDB.Last;
begin
if CheckDataSet then
FDataSource.DataSet.Last;
end;
procedure TCustomBindScopeDB.Next;
begin
if CheckDataSet then
FDataSource.DataSet.Next;
end;
procedure TCustomBindScopeDB.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if Operation = TOperation.opRemove then
begin
if AComponent = FDataSource then
DataSource := nil;
if AComponent is TBasicBindComponent then
if FDataLinks.ContainsKey(TBasicBindComponent(AComponent)) then
FDataLinks.Remove(TBasicBindComponent(AComponent));
end;
end;
procedure TCustomBindScopeDB.Post;
begin
if CheckDataSet then
FDataSource.DataSet.Post;
end;
procedure TCustomBindScopeDB.Refresh;
begin
if CheckDataSet then
FDataSource.DataSet.Refresh;
end;
procedure TCustomBindScopeDB.Prior;
begin
if CheckDataSet then
FDataSource.DataSet.Prior;
end;
procedure TCustomBindScopeDB.RemoveActiveChanged(LNotify: TNotifyEvent);
begin
if Assigned(FActiveChanged) then
FActiveChanged.Remove(LNotify);
end;
procedure TCustomBindScopeDB.RemoveDataSetChanged(LNotify: TNotifyEvent);
begin
if Assigned(FDataSetChanged) then
FDataSetChanged.Remove(LNotify);
end;
procedure TCustomBindScopeDB.RemoveDataSetScrolled(LNotify: TNotifyDistanceEvent);
begin
if Assigned(FDataSetScrolled) then
FDataSetScrolled.Remove(LNotify);
end;
procedure TCustomBindScopeDB.RemoveEditingChanged(LNotify: TNotifyEvent);
begin
if Assigned(FEditingChanged) then
FEditingChanged.Remove(LNotify);
end;
procedure TCustomBindScopeDB.RemoveExpression(AExpression: TBasicBindComponent);
begin
inherited;
if FDataLinks <> nil then
FDataLinks.Remove(AExpression);
end;
procedure TCustomBindScopeDB.SetDataSource(const Value: TDataSource);
var
LLink: TBaseDataLink;
begin
if Value <> FDataSource then
begin
if FDataSource <> nil then
FDataSource.RemoveFreeNotification(Self);
FDataSource := Value;
if FDataSource <> nil then
FDataSource.FreeNotification(Self);
FDataLink.DataSource := Value;
for LLink in FDataLinks.Values do
LLink.DataSource := Value;
end;
end;
procedure TCustomBindScopeDB.SetField(ABindComp: TBasicBindComponent;
const FieldName: string);
var
LDataLink: TBaseDataLink;
begin
if (FDataLinks <> nil) and FDataLinks.TryGetValue(ABindComp, LDataLink) then
begin
Assert(LDataLink <> nil);
if LDataLink is TBindLinkDataLink then
TBindLinkDataLink(LDataLink).SetFieldName(FieldName);
end
end;
{ TScopeDataLink }
procedure TScopeDataLink.ActiveChanged;
begin
inherited;
if Assigned(FOnActiveChanged) then
FOnActiveChanged(Self);
FDBScopeComponent.ActivateExpressions(Self.Active);
end;
constructor TScopeDataLink.Create(ADBScopeComponent: TCustomBindScopeDB);
begin
inherited Create;
FDBScopeComponent := ADBScopeComponent;
end;
procedure TScopeDataLink.DataSetChanged;
begin
inherited;
if Assigned(FOnDataSetChanged) then
FOnDataSetChanged(Self);
end;
procedure TScopeDataLink.DataSetScrolled(Distance: Integer);
begin
if Assigned(FOnDataSetScrolled) then
FOnDataSetScrolled(Self, Distance);
end;
procedure TScopeDataLink.EditingChanged;
begin
inherited;
if Assigned(FOnEditingChanged) then
FOnEditingChanged(Self);
end;
{ TBaseDataLink }
function TBaseDataLink.Edit: Boolean;
begin
Result := inherited Edit;
end;
{ TBindScopeDBEnumerator }
constructor TBindScopeDBEnumerator.Create(ABindScope: TCustomBindScopeDB;
const AMemberName: string; ABufferCount: Integer);
begin
FBindScope := ABindScope;
FMemberName := AMemberName;
FSaveActiveRecord := FBindScope.FDataLink.ActiveRecord;
FNextRecord := FSaveActiveRecord;
if ABufferCount > 0 then
FBindScope.FDataLink.BufferCount := ABufferCount
else
FBindScope.FDataLink.BufferCount := 200; // default to max 200 records in buffer
end;
destructor TBindScopeDBEnumerator.Destroy;
begin
inherited;
FBindScope.FDataLink.ActiveRecord := FSaveActiveRecord;
end;
procedure TBindScopeDBEnumerator.First;
begin
FSaveActiveRecord := FBindScope.FDataLink.ActiveRecord;
if FBindScope.FDataLink.DataSet <> nil then
begin
if FBindScope.FDataLink.ActiveRecord < FBindScope.FDataLink.BufferCount then
FBindScope.FDataLink.ActiveRecord := 0
else if not FBindScope.FDataLink.BOF then
begin
FBindScope.FDataLink.DataSet.First;
FSaveActiveRecord := FBindScope.FDataLink.ActiveRecord;
end;
end;
FNextRecord := FBindScope.FDataLink.ActiveRecord;
end;
function TBindScopeDBEnumerator.GetCurrent: IScope;
begin
if FMemberName <> '' then
Result := FBindScope.GetMemberScope(FMemberName)
else
Result := FBindScope.GetScope;
end;
function TBindScopeDBEnumerator.GetMemberCurrent(const AMemberName: string): IScope;
begin
if AMemberName <> '' then
Result := FBindScope.GetMemberScope(AMemberName)
else
Result := GetCurrent;
end;
function TBindScopeDBEnumerator.GetRecordCount: Integer;
begin
Result := FBindScope.FDataLink.RecordCount;
end;
function TBindScopeDBEnumerator.MoveNext: Boolean;
begin
if FNextRecord < FBindScope.FDataLink.RecordCount then
begin
FBindScope.FDataLink.ActiveRecord := FNextRecord;
FNextRecord := FNextRecord + 1;
Result := True;
end
else
Result := False;
end;
{ TBindDataSetScope }
function TBindDataSetScope.DoLookup(const Name: String): IInterface;
var
DataSet: TDataSet;
begin
Result := nil;
if MappedObject is TDataSet then
begin
DataSet := TDataSet(MappedObject);
if DataSet.FindField(Name) <> nil then
Result := TCustomWrapper.Create(DataSet, DataSet.ClassType, Name, cwtProperty,
function (ParentObject: TObject; const MemberName: String; Args: TArray<TValue>): TValue
begin
Result := TDataSet(ParentObject).FieldByName(MemberName);
end);
end;
end;
type
TDataSetCracker = class(TDataSet)
end;
// Bidi method to constrain a integer value to a valid row number
// RValue uses: ValidRecNo(dataset, integer)
// LValue usage: ValidRecNo(dataset)
function MakeValidRecNo: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
LDataSetValue: IValue;
begin
if Length(Args) < 1 then
raise EEvaluatorError.Create(sArgCount);
LDataSetValue := Args[0];
Result := MakeLocation(TypeInfo(Integer),
function: TValue
var
LRecNo: Integer;
LDataSet: TDataSet;
LRecNoValue: IValue;
begin
if Length(Args) <> 2 then
raise EEvaluatorError.Create(sArgCount);
LRecNo := -1;
if LDataSetValue.GetValue.IsInstanceOf(TDataSet) then
begin
LRecNoValue := Args[1];
LDataSet := TDataSet(LDataSetValue.GetValue.AsObject);
LRecNo := LRecNoValue.GetValue.AsInteger;
// Clip RecNo within valid range
if LRecNo > LDataSet.RecordCount then
LRecNo := LDataSet.RecordCount;
if LRecNo <= 0 then
if LDataSet.RecordCount > 0 then
LRecNo := 1
else
LRecNo := -1;
end;
Result := LRecNo;
end,
procedure(x: TValue)
var
LRecNo: Integer;
LDataSet: TDataSet;
LActiveRecord: Integer;
begin
if Length(Args) <> 1 then
raise EEvaluatorError.Create(sArgCount);
if LDataSetValue.GetValue.IsInstanceOf(TDataSet) then
begin
LDataSet := TDataSet(LDataSetValue.GetValue.AsObject);
LRecNo := x.AsInteger;
if LRecNo > 0 then
begin
LActiveRecord := TDataSetCracker(LDataSet).ActiveRecord;
if LDataSet.RecNo = -1 then
if LRecNo = LActiveRecord + 1 then
// Don't set
Exit;
end;
// Set RecNo within valid range if possible
if LRecNo > LDataSet.RecordCount then
LRecNo := LDataSet.RecordCount;
if LRecNo <= 0 then
if LDataSet.RecordCount > 0 then
LRecNo := 1;
if (LRecNo > 0) and (LRecNo <> LDataSet.RecNo) then
begin
// Must be carefull when set RecNo because this ends editing
LDataSet.RecNo := LRecNo;
end;
end
end);
end);
end;
function MakeActiveRecord: IInvokable;
begin
Result := MakeInvokable(function(Args: TArray<IValue>): IValue
var
LDataSetValue: IValue;
LDataSet: TDataSet;
begin
if Length(Args) <> 1 then
raise EEvaluatorError.Create(Format(sArgCount, [1, Length(Args)]));
LDataSetValue := Args[0];
if LDataSetValue.GetValue.IsInstanceOf(TDataSet) then
begin
LDataSet := TDataSet(LDataSetValue.GetValue.AsObject);
Exit(
TValueWrapper.Create(TDataSetCracker(LDataSet).ActiveRecord));
end
else
Exit(TValueWrapper.Create(TValue.Empty));
end);
end;
const
sValidRecNo = 'DBUtils_ValidRecNo';
sActiveRecord = 'DBUtils_ActiveRecord';
sThisUnit = 'Data.Bind.DBScope';
procedure RegisterMethods;
begin
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeValidRecNo,
sValidRecNo,
sValidRecNo,
sThisUnit,
True,
'', nil)
);
TBindingMethodsFactory.RegisterMethod(
TMethodDescription.Create(
MakeActiveRecord,
sActiveRecord,
sActiveRecord,
sThisUnit,
True,
'', nil)
);
end;
procedure UnregisterMethods;
begin
TBindingMethodsFactory.UnRegisterMethod(sValidRecNo);
TBindingMethodsFactory.UnRegisterMethod(sActiveRecord);
end;
initialization
TBindingScopeFactory.RegisterScope(TDataSet, TBindDataSetScope);
RegisterMethods;
finalization
TBindingScopeFactory.UnregisterScope(TBindDataSetScope);
UnregisterMethods;
end.
|
unit ncaMethodList;
interface
uses
classes;
type
TMethodInfo = class
MethodName : string;
Method : TMethod;
end;
TMethodList = class(TList)
private
protected
function Get(Index: Integer): TMethodInfo;
procedure Put(Index: Integer; Item: TMethodInfo);
public
function assigned(aMethodName: string): boolean;
procedure Clear; override;
procedure New(aMethodName:string; aMethod: TMethod);
function byName(aMethodName:string):TMethod;
property Items[Index: Integer]: TMethodInfo read Get write Put; default;
destructor Destroy; override;
end;
implementation
{ TMethoList }
function TMethodList.byName(aMethodName: string): TMethod;
var
i : integer;
mi : TMethodInfo;
begin
for i:=0 to count-1 do begin
mi := get(i);
if mi.MethodName=aMethodName then begin
result := mi.Method;
exit;
end;
end;
end;
procedure TMethodList.Clear;
var
i : integer;
begin
for i:=count-1 downto 0 do
Get(i).free;
count := 0;
end;
destructor TMethodList.Destroy;
begin
Clear;
inherited;
end;
function TMethodList.Get(Index: Integer): TMethodInfo;
begin
result := inherited Get(Index);
end;
function TMethodList.assigned(aMethodName: string): boolean;
begin
result := byName(aMethodName).Code<>nil;
end;
procedure TMethodList.New(aMethodName: string; aMethod: TMethod);
var
nM : TMethodInfo;
begin
nM := TMethodInfo.create;
nM.MethodName := aMethodName;
nM.Method := aMethod;
inherited add(nM);
end;
procedure TMethodList.Put(Index: Integer; Item: TMethodInfo);
begin
inherited Put(Index, Item);
end;
end.
|
unit maindm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, sqldb, sqlite3conn, db, FileUtil;
type
{ TMainDM }
TMainDM = class(TDataModule)
AttributeDS: TDataSource;
AttributeQuery: TSQLQuery;
Connection: TSQLite3Connection;
ModelDS: TDataSource;
ModelQuery: TSQLQuery;
ProjectDS: TDataSource;
ProjectQuery: TSQLQuery;
Transaction: TSQLTransaction;
procedure AttributeQueryAfterInsert(DataSet: TDataSet);
procedure ModelQueryAfterInsert(DataSet: TDataSet);
procedure ModelQueryAfterScroll(DataSet: TDataSet);
private
procedure OpenAttributeQuery;
procedure OpenModelQuery;
{ private declarations }
public
procedure SaveAllChanges;
procedure ActivateConnectionAndAllQueries;
procedure CloseConnection;
function CreateQuery(ASql: String): TSQLQuery;
end;
var
MainDataModule: TMainDM;
implementation
{$R *.lfm}
{ TMainDM }
procedure TMainDM.ActivateConnectionAndAllQueries;
begin
Connection.Open;
Transaction.Active := True;
ProjectQuery.Active := True;
OpenModelQuery;
OpenAttributeQuery;
end;
procedure TMainDM.CloseConnection;
begin
Connection.Close(true);
end;
procedure TMainDM.SaveAllChanges;
begin
try
if Transaction.Active then
begin
ProjectQuery.ApplyUpdates;
ModelQuery.ApplyUpdates;
AttributeQuery.ApplyUpdates;
Transaction.Commit;
ActivateConnectionAndAllQueries;
end;
except
on E: EDatabaseError do
begin
raise Exception.Create('A database error has occurred. Technical error message: ' + E.Message);
end;
end;
end;
procedure TMainDM.OpenModelQuery;
begin
ModelQuery.Active := False;
ModelQuery.Params.ParamByName('id').AsInteger := ProjectQuery.FieldByName('id').AsInteger;
ModelQuery.Active := True;
end;
procedure TMainDM.OpenAttributeQuery;
begin
AttributeQuery.Active := False;
AttributeQuery.Params.ParamByName('id').AsInteger := ModelQuery.FieldByName('id').AsInteger;
AttributeQuery.Active := True;
end;
procedure TMainDM.ModelQueryAfterScroll(DataSet: TDataSet);
begin
OpenAttributeQuery;
end;
procedure TMainDM.ModelQueryAfterInsert(DataSet: TDataSet);
begin
ModelQuery.FieldByName('projectid').AsInteger := ProjectQuery.FieldByName('id').AsInteger;
end;
procedure TMainDM.AttributeQueryAfterInsert(DataSet: TDataSet);
begin
AttributeQuery.FieldByName('modelid').AsInteger := ModelQuery.FieldByName('id').AsInteger;
AttributeQuery.FieldByName('fieldtype').AsString := 'String';
end;
function TMainDM.CreateQuery(ASql: String): TSQLQuery;
begin
Result := TSQLQuery.Create(nil);
Result.SQL.Add(ASql);
Result.Database := Connection;
Result.Transaction := Transaction;
end;
end.
|
unit Unit7;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Buttons;
type
TForm7 = class(TForm)
Label1: TLabel;
BitBtn1: TBitBtn;
Timer1: TTimer;
Label2: TLabel;
lblCountDown: TLabel;
procedure Timer1Timer(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
const
COUNTDOWN:Integer=5*60;
var
Form7: TForm7;
Elapse: Integer;
implementation
uses Unit1;
{$R *.dfm}
procedure TForm7.Timer1Timer(Sender: TObject);
var
Hour,Second:Integer;
begin
Elapse:=Elapse-1;
if Elapse <= 0 then
begin
Timer1.Enabled:=False;
Form1.CZKEM_A.CancelOperation;
close;
end
else
begin
Hour:=Elapse div 60;
Second:=Elapse - (Hour*60);
lblCountDown.Caption:=IntToStr(Hour)+':'+IntToStr(Second);
end;
end;
procedure TForm7.BitBtn1Click(Sender: TObject);
begin
Form1.CZKEM_A.CancelOperation;
close;
end;
procedure TForm7.FormActivate(Sender: TObject);
var
Hour,Second:Integer;
begin
Timer1.Enabled:=true;
Elapse:=COUNTDOWN;
Hour:=Elapse div 60;
Second:=Elapse - (Hour*60);
lblCountDown.Caption:=IntToStr(Hour)+':'+IntToStr(Second);
end;
end.
|
unit UnitConstants;
interface
const
//About program
PROGRAMNAME = 'PureRAT';
PROGRAMVERSION = 'v6.0';
PROGRAMAUTHOR = 'Wr #!d3';
PROGRAMPASSWORD = PROGRAMNAME + '²³¤¼½¾' + PROGRAMAUTHOR;
//Commands list
ACTIVECONNECTIONS = 'activeconnections';
ACTIVECONNECTIONSCLOSE = 'activeconnectionsclose';
ACTIVECONNECTIONSKILLPROCESS = 'activeconnectionskillprocess';
ACTIVECONNECTIONSLIST = 'activeconnectionslist';
CDDRIVECLOSE = 'cddriveclose';
CDDRIVEOPEN = 'cddriveopen';
CHAT = 'chat';
CHATSTART = 'chatstart';
CHATSTOP = 'chatstop';
CHATTEXT = 'chattext';
CLIENTCLOSE = 'clientclose';
CLIENTNEW = 'clientnew';
CLIENTRENAME = 'clientrename';
CLIENTREMOVE = 'clientremove';
CLIENTRESTART = 'clientrestart';
CLIENTUPDATEFROMFTP = 'clientupdatefromftp';
CLIENTUPDATEFROMLINK = 'clientupdatefromlink';
CLIENTUPDATEFROMLOCAL = 'clientupdatefromlocal';
CLIPBOARD = 'clipboard';
CLIPBOARDCLEAR = 'clipboardclear';
CLIPBOARDFILES = 'clipboardfiles';
CLIPBOARDTEXT = 'clipboardtext';
CLIPBOARDSETTEXT = 'clipboardsettext';
COMPUTERLOGOFF = 'computerlogoff';
COMPUTERREBOOT = 'computerreboot';
COMPUTERSHUTDWON = 'computershutdown';
DELIMITER = #13#10;
DESKTOP = 'desktop';
DESKTOPCAPTURESTART = 'desktopcapturestart';
DESKTOPHIDEICONS = 'desktophideicons';
DESKTOPHIDESYSTEMTRAY = 'desktophidesystemtray';
DESKTOPHIDETASKSBAR = 'desktophidetasksbar';
DESKTOPIMAGE = 'desktopimage';
DESKTOPSETTINGS = 'desktopsettings';
DESKTOPSHOWICONS = 'desktopshowicons';
DESKTOPSHOWSYSTEMTRAY = 'desktopshowsystemtray';
DESKTOPSHOWTASKSBAR = 'desktopshowtasksbar';
DESKTOPTHUMBNAIL = 'desktopthumbnail';
EXECUTESHELLCOMMAND = 'executeshellcommand';
FILESMANAGER = 'filesmanager';
FILESCOPYFILE = 'filescopyfile';
FILESCOPYFOLDER = 'filescopyfolder';
FILESDELETEFILE = 'filesdeletefile';
FILESDELETEFOLDER = 'filesdeletefolder';
FILESDOWNLOADFILE = 'filesdownloadfile';
FILESDRIVESINFOS = 'filesdrivesinfos';
FILESEDITFILE = 'fileseditfile';
FILESEXECUTEFROMFTP = 'filesexecutefromftp';
FILESEXECUTEFROMLINK = 'filesexecutefromlink';
FILESEXECUTEFROMLOCAL = 'filesexecutefromlocal';
FILESEXECUTEHIDEN = 'filesexecutehiden';
FILESEXECUTEVISIBLE = 'filesexecutevisible';
FILESIMAGEPREVIEW = 'filesimagepreview';
FILESLISTDRIVES = 'fileslistdrives';
FILESLISTFILES = 'fileslistfiles';
FILESLISTFOLDERS = 'fileslistfolders';
FILESLISTSHAREDFOLDERS = 'fileslistsharedfolders';
FILESLISTSPECIALSFOLDERS = 'fileslistspecialsfolders';
FILESMOVEFILE = 'filesmovefile';
FILESMOVEFOLDER = 'filesmovefolder';
FILESMULTIDOWNLOAD = 'filesmultidownload';
FILESNEWFOLDER = 'filesnewfolder';
FILESRENAMEFILE = 'filesrenamefile';
FILESRENAMEFOLDER = 'filesrenamefolder';
FILESRESUMEDOWNLOAD = 'filesresumedownload';
FILESSEARCHFILE = 'filessearchfile';
FILESSEARCHIMAGEPREVIEW = 'filessearchimagepreview';
FILESSEARCHRESULTS = 'filessearchresults';
FILESSENDFTP = 'filessendftp';
FILESSTOPSEARCHING = 'filestopsearching';
FILESUPLOADFILEFROMFTP = 'filesuploadfilefromlftp';
FILESUPLOADFILEFROMLINK = 'filesuploadfilefromlink';
FILESUPLOADFILEFROMLOCAL = 'filesuploadfilefromlocal';
FILESVIEWFILE = 'filesviewfile';
FLOODHTTPSTART = 'floodhttpstart';
FLOODHTTPSTOP = 'floodhttpstop';
FLOODUDPSTART = 'floodudpstart';
FLOODUDPSTOP = 'floodudpstop';
FLOODSYNSTART = 'floodsynstart';
FLOODSYNSTOP = 'floodsynstop';
INFOS = 'infos';
INFOSMAIN = 'infosmain';
INFOSREFRESH = 'infosrefresh';
INFOSSYSTEM = 'infossystem';
KEYLOGGER = 'keylogger';
KEYLOGGERDELLOG = 'keyloggerdellog';
KEYLOGGERDELREPO = 'keyloggerdelrepo';
KEYLOGGERGETLOGS = 'keyloggergetlogs';
KEYLOGGERGETREPO = 'keyloggergetrepo';
KEYLOGGERLIVESTART = 'keyloggerlivestart';
KEYLOGGERLIVESTOP = 'keyloggerlivestop';
KEYLOGGERLIVETEXT = 'keyloggerlivetext';
KEYLOGGERREADLOG = 'keyloggerreadlog';
MESSAGESBOX = 'messagesbox';
MICROPHONE = 'microphone';
MICROPHONESTART = 'microphonestart';
MICROPHONESTOP = 'microphonestop';
MICROPHONESTREAM = 'microphonestream';
MOUSELEFTCLICK = 'mouseleftclick';
MOUSELEFTDOUBLECLICK = 'mouseleftdoubleclick';
MOUSEMOVECURSOR = 'mousemovecurosr';
MOUSERIGHTCLICK = 'mouserightclick';
MOUSERIGHTDOUBLECLICK = 'mouserightdoubleclick';
MOUSESWAPBUTTONS = 'mouseswapbuttons';
PASSWORDS = 'passwords';
PASSWORDSBROWSERS = 'passwordsbrowsers';
PASSWORDSWIFI = 'passwordswifi';
PING = 'ping';
PLUGINSCHECK = 'pluginscheck';
PLUGINSUPLOAD = 'pluginsupload';
PORTSCANNERRESULTS = 'portscannerresults';
PORTSCANNERSTART = 'portscannerstart';
PORTSCANNERSTOP = 'portscannerstop';
PORTSNIFFER = 'portsniffer';
PORTSNIFFERINTERFACES = 'portsnifferinterfaces';
PORTSNIFFERRESULTS = 'portsnifferresults';
PORTSNIFFERSTART = 'portsnifferstart';
PORTSNIFFERSTOP = 'portsnifferstop';
PONG = 'pong';
PROCESS = 'process';
PROCESSKILL = 'processkill';
PROCESSLIST = 'processlist';
PROCESSRESUME = 'processresume';
PROCESSSUSPEND = 'processsuspend';
PROGRAMS = 'programs';
PROGRAMSLIST = 'programslist';
PROGRAMSSILENTUNINSTALL = 'programssilentuninstall';
PROGRAMSUNINSTALL = 'programsuninstall';
PROXYSTART = 'proxystart';
PROXYSTOP = 'proxystop';
REGISTRY = 'registry';
REGISTRYADDKEY_VALUE = 'registryaddkey_value';
REGISTRYDELETEKEY_VALUE = 'registrydeletekey_value';
REGISTRYLISTKEYS = 'registrylistkeys';
REGISTRYLISTVALUES = 'registrylistvalues';
REGISTRYRENAMEKEY = 'registryrenamekey';
SERVICES = 'services';
SERVICESEDIT = 'servicesedit';
SERVICESINSTALL = 'servicesinstall';
SERVICESLIST = 'serviceslist';
SERVICESSTART = 'servicesstart';
SERVICESSTOP = 'servicesstop';
SERVICESUNINSTALL = 'servicesuninstall';
SCRIPT = 'script';
SCRIPTVBS = 'scriptvbs';
SHELL = 'shell';
SHELLCOMMAND = 'shellcommand';
SHELLDATAS = 'shelldatas';
SHELLSTART = 'shellstart';
SHELLSTOP = 'shellstop';
TASKSMANAGER = 'tasksmanager';
UPDATEERROR = 'updateerror';
WEBCAM = 'webcam';
WEBCAMCONNECT = 'webcamconnect';
WEBCAMDISCONNECT = 'webcamdisconnect';
WEBCAMIMAGE = 'webcamimage';
WEBCAMSETTINGS = 'webcamsettings';
WINDOWS = 'windows';
WINDOWSCLOSE = 'windowsclose';
WINDOWSDISABLECLOSEBUTTON = 'windowsdisableclosebutton';
WINDOWSHIDE = 'windowshide';
WINDOWSLIST = 'windowslist';
WINDOWSLISTMESSAGESBOX = 'windowslistmessagesbox';
WINDOWSSHAKE = 'windowsshake';
WINDOWSSHOW = 'windowsshow';
WINDOWSTHUMBNAILS = 'windowsthumbnails';
WINDOWSTITLE = 'windowstitle';
implementation
end.
|
// Copyright 2021 Darian Miller, Licensed under Apache-2.0
// SPDX-License-Identifier: Apache-2.0
// More info: www.radprogrammer.com
unit radRTL.TOTP.Tests;
interface
uses
TestFramework;
type
TOTPTest = class(TTestCase)
published
procedure TestRFCVectors;
end;
implementation
uses
radRTL.TOTP,
radRTL.HOTP;
// todo: support SHA256, SHA512 vectors ("TOTP implementations MAY use HMAC-SHA-256 or HMAC-SHA-512 functions")
(*
https://datatracker.ietf.org/doc/html/rfc6238
Appendix B
The test token shared secret uses the ASCII string value
"12345678901234567890". With Time Step X = 30, and the Unix epoch as
the initial value to count time steps, where T0 = 0, the TOTP
algorithm will display the following values for specified modes and
timestamps.
+-------------+--------------+------------------+----------+--------+
| Time (sec) | UTC Time | Value of T (hex) | TOTP | Mode |
+-------------+--------------+------------------+----------+--------+
| 59 | 1970-01-01 | 0000000000000001 | 94287082 | SHA1 |
| | 00:00:59 | | | |
| 59 | 1970-01-01 | 0000000000000001 | 46119246 | SHA256 |
| | 00:00:59 | | | |
| 59 | 1970-01-01 | 0000000000000001 | 90693936 | SHA512 |
| | 00:00:59 | | | |
| 1111111109 | 2005-03-18 | 00000000023523EC | 07081804 | SHA1 |
| | 01:58:29 | | | |
| 1111111109 | 2005-03-18 | 00000000023523EC | 68084774 | SHA256 |
| | 01:58:29 | | | |
| 1111111109 | 2005-03-18 | 00000000023523EC | 25091201 | SHA512 |
| | 01:58:29 | | | |
| 1111111111 | 2005-03-18 | 00000000023523ED | 14050471 | SHA1 |
| | 01:58:31 | | | |
| 1111111111 | 2005-03-18 | 00000000023523ED | 67062674 | SHA256 |
| | 01:58:31 | | | |
| 1111111111 | 2005-03-18 | 00000000023523ED | 99943326 | SHA512 |
| | 01:58:31 | | | |
| 1234567890 | 2009-02-13 | 000000000273EF07 | 89005924 | SHA1 |
| | 23:31:30 | | | |
| 1234567890 | 2009-02-13 | 000000000273EF07 | 91819424 | SHA256 |
| | 23:31:30 | | | |
| 1234567890 | 2009-02-13 | 000000000273EF07 | 93441116 | SHA512 |
| | 23:31:30 | | | |
| 2000000000 | 2033-05-18 | 0000000003F940AA | 69279037 | SHA1 |
| | 03:33:20 | | | |
| 2000000000 | 2033-05-18 | 0000000003F940AA | 90698825 | SHA256 |
| | 03:33:20 | | | |
| 2000000000 | 2033-05-18 | 0000000003F940AA | 38618901 | SHA512 |
| | 03:33:20 | | | |
| 20000000000 | 2603-10-11 | 0000000027BC86AA | 65353130 | SHA1 |
| | 11:33:20 | | | |
| 20000000000 | 2603-10-11 | 0000000027BC86AA | 77737706 | SHA256 |
| | 11:33:20 | | | |
| 20000000000 | 2603-10-11 | 0000000027BC86AA | 47863826 | SHA512 |
| | 11:33:20 | | | |
+-------------+--------------+------------------+----------+--------+
*)
procedure TOTPTest.TestRFCVectors;
const
SECRET = 'GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ'; // TBase32.Encode('12345678901234567890');
INPUT_VALUES: array [0 .. 5] of Int64 = ($1, $23523EC, $23523ED, $273EF07, $3F940AA, $27BC86AA);
EXPECTED_8DIGIT_VALUES: array [0 .. 5] of string = ('94287082', '07081804', '14050471', '89005924', '69279037', '65353130');
EXPECTED_7DIGIT_VALUES: array [0 .. 5] of string = ('4287082', '7081804', '4050471', '9005924', '9279037', '5353130');
EXPECTED_6DIGIT_VALUES: array [0 .. 5] of string = ('287082', '081804', '050471', '005924', '279037', '353130');
var
i:integer;
begin
for i := low(INPUT_VALUES) to high(INPUT_VALUES) do
begin
CheckEquals(EXPECTED_8DIGIT_VALUES[i], TTOTP.GeneratePassword(SECRET, INPUT_VALUES[i], TOTPLength.EightDigits));
CheckEquals(EXPECTED_7DIGIT_VALUES[i], TTOTP.GeneratePassword(SECRET, INPUT_VALUES[i], TOTPLength.SevenDigits));
CheckEquals(EXPECTED_6DIGIT_VALUES[i], TTOTP.GeneratePassword(SECRET, INPUT_VALUES[i], TOTPLength.SixDigits));
end;
end;
initialization
RegisterTest(TOTPTest.Suite);
end.
|
unit fDiagnoses;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
fPCEBase, StdCtrls, CheckLst, ORNet, ExtCtrls, Buttons, uPCE, ORFn,
ComCtrls, fPCEBaseMain, UBAGlobals, UBAConst, UCore, VA508AccessibilityManager,
ORCtrls, StrUtils;
type
TfrmDiagnoses = class(TfrmPCEBaseMain)
cmdDiagPrimary: TButton;
ckbDiagProb: TCheckBox;
procedure cmdDiagPrimaryClick(Sender: TObject);
procedure ckbDiagProbClicked(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnRemoveClick(Sender: TObject);
procedure FormResize(Sender: TObject); override;
procedure lbxSectionClickCheck(Sender: TObject; Index: Integer);
procedure btnOKClick(Sender: TObject); override;
procedure lbSectionClick(Sender: TObject);
procedure GetEncounterDiagnoses;
procedure lbSectionDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure lbxSectionDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure btnOtherClick(Sender: TObject);
private
procedure EnsurePrimaryDiag;
procedure GetSCTforICD(ADiagnosis: TPCEDiag);
procedure UpdateProblem(AplIEN: String; AICDCode: String; ASCTCode: String = '');
function isProblem(diagnosis: TPCEDiag): Boolean;
function isEncounterDx(problem: string): Boolean;
protected
procedure UpdateNewItemStr(var x: string); override;
procedure UpdateControls; override;
public
end;
const
TX_INACTIVE_ICD_CODE = 'This problem references an ICD code that is not active as of the date of this encounter. ' +
'Please update the ICD Diagnosis.';
TX_NONSPEC_ICD_CODE = 'Please enter a more specific ICD Diagnosis for this problem.';
TX_INACTIVE_SCT_CODE = 'This problem references a SNOMED CT code that is not active as of the date of this encounter. ' +
'Please update the SNOMED CT code.';
TX_INACTIVE_ICD_SCT_CODE = 'This problem references BOTH an ICD and a SNOMED CT code that are not active as of the date ' +
'of this encounter. Please update the codes now.';
TX_ICD_LACKS_SCT_CODE = 'Addition of a diagnosis to the problem list requires a SNOMED CT code. Please ' +
'select the SNOMED CT concept which best describes the diagnosis: ';
TX_PROB_LACKS_SCT_CODE = 'You''ve selected to update a problem from the Problem List which now requires a SNOMED CT code. ' +
'Please enter a SNOMED CT equivalent term which best describes the diagnosis: ';
TC_INACTIVE_CODE = 'Problem Contains Inactive Code';
TC_NONSPEC_CODE = 'Problem Contains Non-Specific Code';
TC_I10_LACKS_SCT = 'SNOMED CT Needed for Problem Entry';
TX_REDUNDANT_DX = 'The problem that you''ve selected is already included in the list of diagnoses ' +
'for this encounter. No need to select it again...';
TC_REDUNDANT_DX = 'Redundant Diagnosis: ';
TX_INV_ICD10_DX = 'The selected ICD-10-CM diagnosis cannot be added to an encounter prior to ICD-10 implementation.' + CRLF + CRLF +
'Please select a valid ICD-9-CM diagnosis which best describes the diagnosis.';
TC_INV_ICD10_DX = 'Invalid Selection';
var
frmDiagnoses: TfrmDiagnoses;
dxList : TStringList;
PLUpdated: boolean = False;
implementation
{$R *.DFM}
uses
fEncounterFrame, uConst, UBACore, VA508AccessibilityRouter, fPCELex, rPCE, uProbs, rProbs, rCore, VAUtils;
type
TORCBImgIdx = (iiUnchecked, iiChecked, iiGrayed, iiQMark, iiBlueQMark,
iiDisUnchecked, iiDisChecked, iiDisGrayed, iiDisQMark,
iiFlatUnChecked, iiFlatChecked, iiFlatGrayed,
iiRadioUnchecked, iiRadioChecked, iiRadioDisUnchecked, iiRadioDisChecked);
const
CheckBoxImageResNames: array[TORCBImgIdx] of PChar = (
'ORCB_UNCHECKED', 'ORCB_CHECKED', 'ORCB_GRAYED', 'ORCB_QUESTIONMARK',
'ORCB_BLUEQUESTIONMARK', 'ORCB_DISABLED_UNCHECKED', 'ORCB_DISABLED_CHECKED',
'ORCB_DISABLED_GRAYED', 'ORCB_DISABLED_QUESTIONMARK',
'ORLB_FLAT_UNCHECKED', 'ORLB_FLAT_CHECKED', 'ORLB_FLAT_GRAYED',
'ORCB_RADIO_UNCHECKED', 'ORCB_RADIO_CHECKED',
'ORCB_RADIO_DISABLED_UNCHECKED', 'ORCB_RADIO_DISABLED_CHECKED');
BlackCheckBoxImageResNames: array[TORCBImgIdx] of PChar = (
'BLACK_ORLB_FLAT_UNCHECKED', 'BLACK_ORLB_FLAT_CHECKED', 'BLACK_ORLB_FLAT_GRAYED',
'BLACK_ORCB_QUESTIONMARK', 'BLACK_ORCB_BLUEQUESTIONMARK',
'BLACK_ORCB_DISABLED_UNCHECKED', 'BLACK_ORCB_DISABLED_CHECKED',
'BLACK_ORCB_DISABLED_GRAYED', 'BLACK_ORCB_DISABLED_QUESTIONMARK',
'BLACK_ORLB_FLAT_UNCHECKED', 'BLACK_ORLB_FLAT_CHECKED', 'BLACK_ORLB_FLAT_GRAYED',
'BLACK_ORCB_RADIO_UNCHECKED', 'BLACK_ORCB_RADIO_CHECKED',
'BLACK_ORCB_RADIO_DISABLED_UNCHECKED', 'BLACK_ORCB_RADIO_DISABLED_CHECKED');
PL_ITEMS = 'Problem List Items';
var
ORCBImages: array[TORCBImgIdx, Boolean] of TBitMap;
function GetORCBBitmap(Idx: TORCBImgIdx; BlackMode: boolean): TBitmap;
var
ResName: string;
begin
if (not assigned(ORCBImages[Idx, BlackMode])) then
begin
ORCBImages[Idx, BlackMode] := TBitMap.Create;
if BlackMode then
ResName := BlackCheckBoxImageResNames[Idx]
else
ResName := CheckBoxImageResNames[Idx];
ORCBImages[Idx, BlackMode].LoadFromResourceName(HInstance, ResName);
end;
Result := ORCBImages[Idx, BlackMode];
end;
procedure TfrmDiagnoses.EnsurePrimaryDiag;
var
i: Integer;
Primary: Boolean;
begin
with lstCaptionList do
begin
Primary := False;
for i := 0 to Items.Count - 1 do
if TPCEDiag(Objects[i]).Primary then
Primary := True;
if not Primary and (Items.Count > 0) then
begin
GridIndex := Items.Count - 1;//0; zzzzzzbellc CQ 15836
TPCEDiag(Objects[Items.Count - 1]).Primary := True;
GridChanged;
end;
end;
end;
procedure TfrmDiagnoses.cmdDiagPrimaryClick(Sender: TObject);
var
gi, i: Integer;
ADiagnosis: TPCEDiag;
begin
inherited;
gi := GridIndex;
with lstCaptionList do for i := 0 to Items.Count - 1 do
begin
ADiagnosis := TPCEDiag(Objects[i]);
ADiagnosis.Primary := (gi = i);
end;
GridChanged;
end;
procedure TfrmDiagnoses.ckbDiagProbClicked(Sender: TObject);
var
i: integer;
begin
inherited;
if(NotUpdating) then
begin
for i := 0 to lstCaptionList.Items.Count-1 do
begin
if(lstCaptionList.Items[i].Selected) then
begin
TPCEDiag(lstCaptionList.Objects[i]).AddProb := (ckbDiagProb.Checked) and
(not isProblem(TPCEDiag(lstCaptionList.Objects[i]))) and
(TPCEDiag(lstCaptionList.Objects[i]).Category <> PL_ITEMS);
//TODO: Add check for I10Active
if TPCEDiag(lstCaptionList.Objects[i]).AddProb and
(Piece(Encounter.GetICDVersion, U, 1) = '10D') and
(not ((pos('SCT', TPCEDiag(lstCaptionList.Objects[i]).Narrative) > 0) or
(pos('SNOMED', TPCEDiag(lstCaptionList.Objects[i]).Narrative) > 0))) then
GetSCTforICD(TPCEDiag(lstCaptionList.Objects[i]));
end;
end;
GridChanged;
end;
end;
procedure TfrmDiagnoses.FormCreate(Sender: TObject);
begin
inherited;
FTabName := CT_DiagNm;
FPCEListCodesProc := ListDiagnosisCodes;
FPCEItemClass := TPCEDiag;
FPCECode := 'POV';
FSectionTabCount := 3;
FormResize(Self);
end;
procedure TfrmDiagnoses.btnOtherClick(Sender: TObject);
var
x, Code, SCode, Text, Caption: string;
APCEItem: TPCEItem;
j, SrchCode: integer;
Match: boolean;
begin
ClearGrid;
SrchCode := (Sender as TButton).Tag;
if(SrchCode <= LX_Threshold) then LexiconLookup(Code, SrchCode, 0, False, '');
btnOther.SetFocus;
if Code <> '' then
begin
SCode := Piece(Code, U, 1);
Match := False;
for j := lstCaptionList.Items.Count - 1 downto 0 do
begin
APCEItem := TPCEItem(lstCaptionList.Objects[j]);
if APCEItem.Code = SCode then
begin
// Match := True;
Text := '"' + Piece(Code, U, 2) + '" is already included in the list of selected diagnoses for this encounter. Please select a different diagnosis...';
Caption := 'Duplicate Diagnosis';
InfoBox(Text, Caption, MB_ICONWARNING or MB_OK);
Exit;
end
end;
if not Match then
begin
x := FPCECode + U + Piece(Code, U, 1) + U + U + Piece(Code, U, 2);
if FPCEItemClass = TPCEProc then
SetPiece(x, U, pnumProvider, IntToStr(uProviders.PCEProvider));
UpdateNewItemStr(x);
APCEItem := FPCEItemClass.Create;
APCEItem.SetFromString(x);
GridIndex := lstCaptionList.Add(APCEItem.ItemStr, APCEItem);
end;
end;
UpdateControls;
end;
procedure TfrmDiagnoses.btnRemoveClick(Sender: TObject);
begin
inherited;
Sync2Grid;
EnsurePrimaryDiag;
end;
procedure TfrmDiagnoses.UpdateNewItemStr(var x: string);
begin
inherited;
if lstCaptionList.Items.Count = 0 then
x := x + U + '1'
else
x := x + U + '0';
end;
procedure TfrmDiagnoses.UpdateProblem(AplIEN: String; AICDCode: String; ASCTCode: String = '');
var
AList: TStringList;
ProbRec: TProbRec;
CodeSysStr: String;
DateOfInt: TFMDateTime;
begin
// Update problem list entry with new ICD (& SCT) code(s) (& narrative).
AList := TStringList.create;
try
EditLoad(AplIEN, AList);
ProbRec := TProbRec.create(AList);
ProbRec.PIFN := AplIEN;
if AICDCode <> '' then
begin
ProbRec.Diagnosis.DHCPtoKeyVal(Pieces(AICDCode, U, 1, 2));
CodeSysStr := Piece(AICDCode, U, 4);
if (Pos('10', CodeSysStr) > 0) then
CodeSysStr := '10D^ICD-10-CM'
else
CodeSysStr := 'ICD^ICD-9-CM';
ProbRec.CodeSystem.DHCPtoKeyVal(CodeSysStr);
end;
if ASCTCode <> '' then
begin
ProbRec.SCTConcept.DHCPtoKeyVal(Pieces(ASCTCode, U, 1, 2));
//TODO: need to accommodate changes to Designation Code
ProbRec.Narrative.DHCPtoKeyVal(U + Piece(ASCTCode, U, 3));
ProbRec.SCTDesignation.DHCPtoKeyVal(Piece(ASCTCode, U, 4) + U + Piece(ASCTCode, U, 4));
end;
ProbRec.RespProvider.DHCPtoKeyVal(IntToStr(Encounter.Provider) + u + Encounter.ProviderName);
if Encounter.DateTime = 0 then DateOfInt := FMNow
else DateOfInt := Encounter.DateTime;
ProbRec.CodeDateStr := FormatFMDateTime('mm/dd/yy', DateOfInt);
AList.Clear;
EditSave(ProbRec.PIFN, User.DUZ, User.StationNumber, '1', ProbRec.FilerObject, '', AList);
finally
AList.clear;
end;
end;
function TfrmDiagnoses.isProblem(diagnosis: TPCEDiag): Boolean;
var
i: integer;
p, code, narr, sct: String;
begin
result := false;
for i := 0 to FProblems.Count - 1 do
begin
p := FProblems[i];
code := piece(p, '^', 1);
narr := piece(p, '^', 2);
if (pos('SCT', narr) > 0) or (pos('SNOMED', narr) > 0) then
sct := piece(piece(piece(narr, ')', 1), '(', 2), ' ', 2)
else
sct := '';
narr := TrimRight(piece(narr, '(',1));
if pos(diagnosis.Code, code) > 0 then
begin
result := true;
break;
end
else if (sct <> '') and (pos(sct, diagnosis.Narrative) > 0) then
begin
result := true;
break;
end
else if pos(narr, diagnosis.Narrative) > 0 then
begin
result := true;
break;
end;
end;
end;
function TfrmDiagnoses.isEncounterDx(problem: string): Boolean;
var
i: integer;
dx, code, narr, pCode, pNarrative, sct: String;
function ExtractCode(narr: String; csys: String): String;
var cso: Integer;
begin
if csys = 'SCT' then
begin
cso := 4;
end
else if (csys = 'ICD') and (pos('ICD-10', narr) > 0) then
begin
csys := 'ICD-10-CM';
cso := 10;
end
else
begin
csys := 'ICD-9-CM';
cso := 9;
end;
if (pos(csys, narr) > 0) then
result := Piece(copy(narr, pos(csys, narr) + cso, length(narr)), ')', 1)
else
result := '';
end;
begin
result := false;
pCode := piece(problem, U, 1);
pNarrative := piece(problem, U, 2);
for i := 0 to lstCaptionList.Items.Count - 1 do
begin
dx := lstCaptionList.Strings[i];
narr := piece(dx, U, 3);
code := ExtractCode(narr, 'ICD');
sct := ExtractCode(narr, 'SCT');
if pos(pCode, narr) > 0 then
begin
result := true;
break;
end
else if pos(narr, pNarrative) > 0 then
begin
result := true;
break;
end;
end;
end;
procedure TfrmDiagnoses.UpdateControls;
var
i, j, k, PLItemCount: integer;
OK: boolean;
const
PL_ITEMS = 'Problem List Items';
begin
inherited;
if(NotUpdating) then
begin
BeginUpdate;
try
cmdDiagPrimary.Enabled := (lstCaptionList.SelCount = 1);
OK := (lstCaptionList.SelCount > 0);
PLItemCount := 0;
if OK then
for k := 0 to lstCaptionList.Items.Count - 1 do
begin
if (lstCaptionList.Items[k].Selected) then
begin
if (TPCEDiag(lstCaptionList.Objects[k]).Category = PL_ITEMS) or isProblem(TPCEDiag(lstCaptionList.Objects[k])) then
PLItemCount := PLItemCount + 1;
end;
end;
OK := OK and (PLItemCount < lstCaptionList.SelCount);
ckbDiagProb.Enabled := OK;
if(OK) then
begin
j := 0;
for i := 0 to lstCaptionList.Items.Count-1 do
begin
if(lstCaptionList.Items[i].Selected) and (TPCEDiag(lstCaptionList.Objects[i]).AddProb) then
inc(j);
end;
if(j = 0) then
ckbDiagProb.Checked := FALSE
else
if(j < lstCaptionList.SelCount) then
ckbDiagProb.State := cbGrayed
else
ckbDiagProb.Checked := TRUE;
end
else
ckbDiagProb.Checked := FALSE;
finally
EndUpdate;
end;
end;
end;
procedure TfrmDiagnoses.FormResize(Sender: TObject);
begin
inherited;
FSectionTabs[0] := -(lbxSection.width - LBCheckWidthSpace - (10 * MainFontWidth) - ScrollBarWidth);
FSectionTabs[1] := -FSectionTabs[0]+2;
FSectionTabs[2] := -FSectionTabs[0]+4;
UpdateTabPos;
end;
procedure TfrmDiagnoses.lbxSectionClickCheck(Sender: TObject; Index: Integer);
var
ICDSys, ICDCode, ICDPar, SCTCode, SCTPar, plIEN, msg, SecItem, InputStr, OrigProbStr, I10Description, TmpNarr: String;
function GetSearchString(AString: String): String;
begin
if (Pos('#', AString) > 0) then
Result := TrimLeft(Piece(AString, '#', 2))
else
Result := AString;
end;
begin
if (not FUpdatingGrid) and (lbxSection.Checked[Index]) then
begin
SCTPar := '';
InputStr := '';
OrigProbStr := lbxSection.Items[Index];
if (Piece(lbxSection.Items[Index], U, 4) = '#') or
(Pos('799.9', Piece(lbxSection.Items[Index], U, 1)) > 0) or
(Pos('R69', Piece(lbxSection.Items[Index], U, 1)) > 0) then
begin
if (Piece(lbxSection.Items[Index], U, 4) = '#') then
msg := TX_INACTIVE_ICD_CODE
else
msg := TX_NONSPEC_ICD_CODE;
InputStr := GetSearchString(Piece(lbxSection.Items[Index], U, 2));
LexiconLookup(ICDCode, LX_ICD, 0, True, InputStr, msg);
if (Piece(ICDCode, U, 1) <> '') then
begin
plIEN := Piece(lbxSection.Items[Index], U, 5);
FUpdatingGrid := TRUE;
if Pos('ICD-10', ICDCode) > 0 then ICDSys := '10D' else ICDSys := 'ICD';
lbxSection.Items[Index] := Pieces(ICDCode, U, 1, 2) + U + Piece(ICDCode, U, 1) + U + U + plIEN + U + ICDSys;
lbxSection.Checked[Index] := True;
if plIEN <> '' then
begin
if not (Pos('SCT', Piece(ICDCode, U, 2)) > 0) and (Piece(Encounter.GetICDVersion, U, 1) = '10D') then
begin
//ask for SNOMED CT
I10Description := Piece(ICDCode, U, 2) + ' (' + Piece(ICDCode, U, 4) + #32 + Piece(ICDCode, U, 1) + ')';
LexiconLookup(SCTCode, LX_SCT, 0, True, InputStr, TX_PROB_LACKS_SCT_CODE + CRLF + CRLF + I10Description);
if (Piece(SCTCode, U, 4) <> '') then
begin
SecItem := lbxSection.Items[Index];
if (Pos('SNOMED CT', SCTCode) > 0) then
TmpNarr := ReplaceStr(Piece(SCTCode, U, 2), 'SNOMED CT', 'SCT')
else
TmpNarr := Piece(SCTCode, U, 2);
SetPiece(SecItem, U, 2, TmpNarr);
FUpdatingGrid := TRUE;
lbxSection.Items[Index] := SecItem;
lbxSection.Checked[Index] := True;
if plIEN <> '' then
begin
SCTPar := Piece(SCTCode, U, 4) + U + Piece(SCTCode, U, 4) + U + Piece(SCTCode, U, 2) + U + Piece(SCTCode, U, 3);
end;
FUpdatingGrid := FALSE;
end
else
begin
//Undo previous ICD-10 updates when cancelling out of the SCT update dialog
lbxSection.Items[Index] := OrigProbStr;
lbxSection.Checked[Index] := False;
FUpdatingGrid := False;
exit;
end;
end;
ICDPar := Piece(ICDCode, U, 3) + U + Piece(ICDCode, U, 1) + U + Piece(ICDCode, U, 2) + U + Piece(ICDCode, U, 4);
UpdateProblem(plIEN, ICDPar, SCTPar);
UpdateDiagnosisObj(lbxSection.Items[Index], Index);
PLUpdated := True;
end;
FUpdatingGrid := FALSE;
end
else
begin
lbxSection.Checked[Index] := False;
exit;
end;
end
else if (Piece(lbxSection.Items[Index], U, 4) = '$') then
begin
// correct inactive SCT Code
msg := TX_INACTIVE_SCT_CODE;
LexiconLookup(SCTCode, LX_SCT, 0, True, InputStr, msg);
if (Piece(SCTCode, U, 4) <> '') then
begin
plIEN := Piece(lbxSection.Items[Index], U, 5);
SecItem := lbxSection.Items[Index];
if (Pos('SNOMED CT', SCTCode) > 0) then
TmpNarr := ReplaceStr(Piece(SCTCode, U, 2), 'SNOMED CT', 'SCT')
else
TmpNarr := Piece(SCTCode, U, 2);
SetPiece(SecItem, U, 2, TmpNarr);
FUpdatingGrid := TRUE;
lbxSection.Items[Index] := SecItem;
lbxSection.Checked[Index] := True;
if plIEN <> '' then
begin
SCTPar := Piece(SCTCode, U, 4) + U + Piece(SCTCode, U, 4) + U + Piece(SCTCode, U, 2) + U + Piece(SCTCode, U, 3);
UpdateProblem(plIEN, '', SCTPar);
UpdateDiagnosisObj(lbxSection.Items[Index], Index);
PLUpdated := True;
end;
FUpdatingGrid := FALSE;
end
else
begin
lbxSection.Checked[Index] := False;
exit;
end;
end
else if (Piece(lbxSection.Items[Index], U, 4) = '#$') then
begin
// correct inactive SCT Code
msg := TX_INACTIVE_SCT_CODE;
LexiconLookup(SCTCode, LX_SCT, 0, True, InputStr, msg);
if (Piece(SCTCode, U, 4) = '') then
begin
lbxSection.Checked[Index] := False;
exit;
end;
// correct inactive ICD Code
msg := TX_INACTIVE_ICD_CODE;
LexiconLookup(ICDCode, LX_ICD, 0, True, '', msg);
if (Piece(ICDCode, U, 1) <> '') and (Piece(SCTCode, U, 4) <> '') then
begin
plIEN := Piece(lbxSection.Items[Index], U, 5);
if (Pos('SNOMED CT', SCTCode) > 0) then
TmpNarr := ReplaceStr(Piece(SCTCode, U, 2), 'SNOMED CT', 'SCT')
else
TmpNarr := Piece(SCTCode, U, 2);
SetPiece(ICDCode, U, 2, TmpNarr);
FUpdatingGrid := TRUE;
if Pos('ICD-10', ICDCode) > 0 then ICDSys := '10D' else ICDSys := 'ICD';
lbxSection.Items[Index] := Pieces(ICDCode, U, 1, 2) + U + Piece(ICDCode, U, 1) + U + U + plIEN + U + ICDSys;
lbxSection.Checked[Index] := True;
if plIEN <> '' then
begin
SCTPar := Piece(SCTCode, U, 4) + U + Piece(SCTCode, U, 4) + U + Piece(SCTCode, U, 2) + U + Piece(SCTCode, U, 3);
ICDPar := Piece(ICDCode, U, 3) + U + Piece(ICDCode, U, 1) + U + Piece(ICDCode, U, 2) + U + Piece(ICDCode, U, 4);
UpdateProblem(plIEN, ICDPar, SCTPar);
UpdateDiagnosisObj(lbxSection.Items[Index], Index);
PLUpdated := True;
end;
FUpdatingGrid := FALSE;
end
else
begin
lbxSection.Checked[Index] := False;
exit;
end;
end
else if (Piece(lbSection.Items[lbSection.ItemIndex], U, 2) = PL_ITEMS) and
(Piece(Encounter.GetICDVersion, U, 1) = '10D') and
not (Pos('SCT', Piece(lbxSection.Items[Index], U, 2)) > 0) then
begin
// Problem Lacks SCT Code
msg := TX_PROB_LACKS_SCT_CODE + CRLF + CRLF + Piece(lbxSection.Items[Index], U, 2);
LexiconLookup(SCTCode, LX_SCT, 0, True, InputStr, msg);
if (Piece(SCTCode, U, 4) <> '') then
begin
plIEN := Piece(lbxSection.Items[Index], U, 5);
SecItem := lbxSection.Items[Index];
if (Pos('SNOMED CT', SCTCode) > 0) then
TmpNarr := ReplaceStr(Piece(SCTCode, U, 2), 'SNOMED CT', 'SCT')
else
TmpNarr := Piece(SCTCode, U, 2);
SetPiece(SecItem, U, 2, TmpNarr);
FUpdatingGrid := TRUE;
lbxSection.Items[Index] := SecItem;
lbxSection.Checked[Index] := True;
if plIEN <> '' then
begin
SCTPar := Piece(SCTCode, U, 4) + U + Piece(SCTCode, U, 4) + U + Piece(SCTCode, U, 2) + U + Piece(SCTCode, U, 3);
UpdateProblem(plIEN, '', SCTPar);
UpdateDiagnosisObj(lbxSection.Items[Index], Index);
PLUpdated := True;
end;
FUpdatingGrid := FALSE;
end
else
begin
lbxSection.Checked[Index] := False;
exit;
end;
end
else if (Piece(Encounter.GetICDVersion, U, 1) = 'ICD') and
((Pos('ICD-10', Piece(lbxSection.Items[Index], U, 2)) > 0) or (Piece(lbxSection.Items[Index], U, 6)='10D')) then
begin
// Attempting to add an ICD10 diagnosis code to an ICD9 encounter
InfoBox(TX_INV_ICD10_DX, TC_INV_ICD10_DX, MB_ICONERROR or MB_OK);
lbxSection.Checked[Index] := False;
exit;
end
else if isEncounterDx(lbxSection.Items[Index]) then
begin
InfoBox(TX_REDUNDANT_DX, TC_REDUNDANT_DX + piece(lbxSection.Items[Index], '^',2),
MB_ICONWARNING or MB_OK);
lbxSection.Checked[Index] := False;
exit;
end;
end;
inherited;
EnsurePrimaryDiag;
end;
procedure TfrmDiagnoses.lbxSectionDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
var
Narr, Code: String;
Format, CodeTab, ItemRight, DY: Integer;
ARect, TmpR: TRect;
BMap: TBitMap;
begin
inherited;
Narr := Piece((Control as TORListBox).Items[Index], U, 2);
Code := Piece((Control as TORListBox).Items[Index], U, 3);
CodeTab := StrToInt(Piece(lbxSection.TabPositions, ',', 2));
// draw CheckBoxes
with lbxSection do
begin
if (CheckBoxes) then
begin
case CheckedState[Index] of
cbUnchecked:
begin
if (FlatCheckBoxes) then
BMap := GetORCBBitmap(iiFlatUnChecked, False)
else
BMap := GetORCBBitmap(iiUnchecked, False);
end;
cbChecked:
begin
if (FlatCheckBoxes) then
BMap := GetORCBBitmap(iiFlatChecked, False)
else
BMap := GetORCBBitmap(iiChecked, False);
end;
else // cbGrayed:
begin
if (FlatCheckBoxes) then
BMap := GetORCBBitmap(iiFlatGrayed, False)
else
BMap := GetORCBBitmap(iiGrayed, False);
end;
end;
TmpR := Rect;
TmpR.Right := TmpR.Left;
dec(TmpR.Left, (LBCheckWidthSpace - 5));
DY := ((TmpR.Bottom - TmpR.Top) - BMap.Height) div 2;
Canvas.Draw(TmpR.Left, TmpR.Top + DY, BMap);
end;
end;
// draw the Problem Text
ARect := (Control as TListBox).ItemRect(Index);
ARect.Left := ARect.Left + LBCheckWidthSpace;
ItemRight := ARect.Right;
ARect.Right := CodeTab - 10;
Format := (DT_LEFT or DT_NOPREFIX or DT_WORD_ELLIPSIS);
DrawText((Control as TListBox).Canvas.Handle, PChar(Narr), Length(Narr), ARect, Format);
// now draw ICD codes
ARect.Left := CodeTab;
ARect.Right := ItemRight;
DrawText((Control as TListBox).Canvas.Handle, PChar(Code), Length(Code), ARect, Format);
end;
procedure TfrmDiagnoses.btnOKClick(Sender: TObject);
begin
inherited;
if BILLING_AWARE then
GetEncounterDiagnoses;
if ckbDiagProb.Checked then
PLUpdated := True;
end;
procedure TfrmDiagnoses.lbSectionClick(Sender: TObject);
begin
inherited;
//
end;
procedure TfrmDiagnoses.GetEncounterDiagnoses;
var
i: integer;
dxCode, dxName: string;
ADiagnosis: TPCEItem;
begin
inherited;
UBAGlobals.BAPCEDiagList.Clear;
with lstCaptionList do for i := 0 to Items.Count - 1 do
begin
ADiagnosis := TPCEDiag(Objects[i]);
dxCode := ADiagnosis.Code;
dxName := ADiagnosis.Narrative;
if BAPCEDiagList.Count = 0 then
UBAGlobals.BAPCEDiagList.Add(U + DX_ENCOUNTER_LIST_TXT);
UBAGlobals.BAPCEDiagList.Add(dxCode + U + dxName);
end;
end;
procedure TfrmDiagnoses.GetSCTforICD(ADiagnosis: TPCEDiag);
var
Code, msg, ICDDescription: String;
begin
// look-up SNOMED CT
if ADiagnosis.OldNarrative = '' then
ADiagnosis.OldNarrative := ADiagnosis.Narrative;
if Pos('ICD-10-CM', ADiagnosis.Narrative) > 0 then
ICDDescription := ADiagnosis.Narrative
else
ICDDescription := ADiagnosis.Narrative + ' (' + Piece(Encounter.GetICDVersion, U, 2) + #32 + ADiagnosis.Code + ')';
msg := TX_ICD_LACKS_SCT_CODE + CRLF + CRLF + ICDDescription;
LexiconLookup(Code, LX_SCT, 0, False, '', msg);
if (Code = '') then
begin
ckbDiagProb.Checked := False;
end
else
begin
ADiagnosis.Narrative := Piece(Code, U, 2);
end;
end;
procedure TfrmDiagnoses.lbSectionDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
inherited;
if (control as TListbox).items[index] = DX_PROBLEM_LIST_TXT then
(Control as TListBox).Canvas.Font.Style := [fsBold]
else
if (control as Tlistbox).items[index] = DX_PERSONAL_LIST_TXT then
(Control as TListBox).Canvas.Font.Style := [fsBold]
else
if (control as Tlistbox).items[index] = DX_TODAYS_DX_LIST_TXT then
(Control as TListBox).Canvas.Font.Style := [fsBold]
else
if (control as Tlistbox).items[index] = DX_ENCOUNTER_LIST_TXT then
(Control as TListBox).Canvas.Font.Style := [fsBold]
else
(Control as TListBox).Canvas.Font.Style := [];
(Control as TListBox).Canvas.TextOut(Rect.Left+2, Rect.Top+1, (Control as
TListBox).Items[Index]); {display the text }
end;
initialization
SpecifyFormIsNotADialog(TfrmDiagnoses);
end.
|
unit Laz_And_Controls_Events;
{$mode delphi}
interface
uses
Classes, SysUtils, And_jni, And_jni_Bridge, Laz_And_Controls, PlainWidget, bluetooth, bluetoothclientsocket,
bluetoothserversocket, spinner;
procedure Java_Event_pOnBluetoothEnabled(env: PJNIEnv; this: jobject; Obj: TObject);
procedure Java_Event_pOnBluetoothDisabled(env: PJNIEnv; this: jobject; Obj: TObject);
procedure Java_Event_pOnBluetoothDeviceFound(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString );
procedure Java_Event_pOnBluetoothDiscoveryStarted(env: PJNIEnv; this: jobject; Obj: TObject);
procedure Java_Event_pOnBluetoothDiscoveryFinished(env: PJNIEnv; this: jobject; Obj: TObject; countFoundedDevices: integer; countPairedDevices: integer);
procedure Java_Event_pOnBluetoothDeviceBondStateChanged(env: PJNIEnv; this: jobject; Obj: TObject; state: integer; deviceName: JString; deviceAddress: JString);
procedure Java_Event_pOnBluetoothClientSocketConnected(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString);
procedure Java_Event_pOnBluetoothClientSocketIncomingMessage(env: PJNIEnv; this: jobject; Obj: TObject; messageText: JString);
procedure Java_Event_pOnBluetoothClientSocketWritingMessage(env: PJNIEnv; this: jobject; Obj: TObject);
procedure Java_Event_pOnBluetoothServerSocketConnected(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString);
procedure Java_Event_pOnBluetoothServerSocketIncomingMessage(env: PJNIEnv; this: jobject; Obj: TObject; messageText: JString);
procedure Java_Event_pOnBluetoothServerSocketWritingMessage(env: PJNIEnv; this: jobject; Obj: TObject);
procedure Java_Event_pOnBluetoothServerSocketListen(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString);
procedure Java_Event_pOnBluetoothServerSocketAccept(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString);
procedure Java_Event_pOnSpinnerItemSeleceted(env: PJNIEnv; this: jobject; Obj: TObject; position: integer; caption: JString);
implementation
procedure Java_Event_pOnBluetoothEnabled(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetooth then
begin
jForm(jBluetooth(Obj).Owner).UpdateJNI(gApp);
jBluetooth(Obj).GenEvent_OnBluetoothEnabled(Obj);
end;
end;
procedure Java_Event_pOnBluetoothDisabled(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetooth then
begin
jForm(jBluetooth(Obj).Owner).UpdateJNI(gApp);
jBluetooth(Obj).GenEvent_OnBluetoothDisabled(Obj);
end;
end;
Procedure Java_Event_pOnBluetoothDeviceFound(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString );
var
pasStrName, pasStrAddress: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetooth then
begin
jForm(jBluetooth(Obj).Owner).UpdateJNI(gApp);
pasStrName := '';
if deviceName <> nil then
begin
_jBoolean:= JNI_False;
pasStrName:= string( env^.GetStringUTFChars(Env,deviceName,@_jBoolean) );
end;
pasStrAddress := '';
if deviceAddress <> nil then
begin
_jBoolean := JNI_False;
pasStrAddress:= string( env^.GetStringUTFChars(Env,deviceAddress,@_jBoolean) );
end;
jBluetooth(Obj).GenEvent_OnBluetoothDeviceFound(Obj, pasStrName, pasStrAddress);
end;
end;
procedure Java_Event_pOnBluetoothDiscoveryStarted(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetooth then
begin
jForm(jBluetooth(Obj).Owner).UpdateJNI(gApp);
jBluetooth(Obj).GenEvent_OnBluetoothDiscoveryStarted(Obj);
end;
end;
procedure Java_Event_pOnBluetoothDiscoveryFinished(env: PJNIEnv; this: jobject; Obj: TObject; countFoundedDevices: integer; countPairedDevices: integer);
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetooth then
begin
jForm(jBluetooth(Obj).Owner).UpdateJNI(gApp);
jBluetooth(Obj).GenEvent_OnBluetoothDiscoveryFinished(Obj, countFoundedDevices, countPairedDevices);
end;
end;
procedure Java_Event_pOnBluetoothDeviceBondStateChanged(env: PJNIEnv; this: jobject; Obj: TObject; state: integer; deviceName: JString; deviceAddress: JString);
var
pasStrName, pasStrAddress: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetooth then
begin
jForm(jBluetooth(Obj).Owner).UpdateJNI(gApp);
pasStrName := '';
if deviceName <> nil then
begin
_jBoolean:= JNI_False;
pasStrName:= string( env^.GetStringUTFChars(Env,deviceName,@_jBoolean) );
end;
pasStrAddress := '';
if deviceAddress <> nil then
begin
_jBoolean := JNI_False;
pasStrAddress:= string( env^.GetStringUTFChars(Env,deviceAddress,@_jBoolean) );
end;
jBluetooth(Obj).GenEvent_OnBluetoothDeviceBondStateChanged(Obj, state, pasStrName, pasStrAddress);
end;
end;
procedure Java_Event_pOnBluetoothClientSocketIncomingMessage(env: PJNIEnv; this: jobject; Obj: TObject; messageText: JString);
var
pasStrText: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetoothClientSocket then
begin
jForm(jBluetoothClientSocket(Obj).Owner).UpdateJNI(gApp);
pasStrText := '';
if messageText <> nil then
begin
_jBoolean:= JNI_False;
pasStrText:= string( env^.GetStringUTFChars(Env,messageText,@_jBoolean) );
end;
jBluetoothClientSocket(Obj).GenEvent_OnBluetoothClientSocketIncomingMessage(Obj,pasStrText);
end;
end;
procedure Java_Event_pOnBluetoothClientSocketWritingMessage(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetoothClientSocket then
begin
jForm(jBluetoothClientSocket(Obj).Owner).UpdateJNI(gApp);
jBluetoothClientSocket(Obj).GenEvent_OnBluetoothClientSocketWritingMessage(Obj);;
end;
end;
procedure Java_Event_pOnBluetoothClientSocketConnected(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString);
var
pasStrName, pasStrAddress: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetoothClientSocket then
begin
jForm(jBluetoothClientSocket(Obj).Owner).UpdateJNI(gApp);
pasStrName := '';
if deviceName <> nil then
begin
_jBoolean:= JNI_False;
pasStrName:= string( env^.GetStringUTFChars(Env,deviceName,@_jBoolean) );
end;
pasStrAddress := '';
if deviceAddress <> nil then
begin
_jBoolean := JNI_False;
pasStrAddress:= string( env^.GetStringUTFChars(Env,deviceAddress,@_jBoolean) );
end;
jBluetoothClientSocket(Obj).GenEvent_OnBluetoothClientSocketConnected(Obj, pasStrName, pasStrAddress);
end;
end;
procedure Java_Event_pOnBluetoothServerSocketConnected(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString);
var
pasStrName, pasStrAddress: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetoothServerSocket then
begin
jForm(jBluetoothServerSocket(Obj).Owner).UpdateJNI(gApp);
pasStrName := '';
if deviceName <> nil then
begin
_jBoolean:= JNI_False;
pasStrName:= string( env^.GetStringUTFChars(Env,deviceName,@_jBoolean) );
end;
pasStrAddress := '';
if deviceAddress <> nil then
begin
_jBoolean := JNI_False;
pasStrAddress:= string( env^.GetStringUTFChars(Env,deviceAddress,@_jBoolean) );
end;
jBluetoothServerSocket(Obj).GenEvent_OnBluetoothServerSocketConnected(Obj, pasStrName, pasStrAddress);
end;
end;
procedure Java_Event_pOnBluetoothServerSocketIncomingMessage(env: PJNIEnv; this: jobject; Obj: TObject; messageText: JString);
var
pasStrText: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetoothServerSocket then
begin
jForm(jBluetoothServerSocket(Obj).Owner).UpdateJNI(gApp);
pasStrText := '';
if messageText <> nil then
begin
_jBoolean:= JNI_False;
pasStrText:= string( env^.GetStringUTFChars(Env,messageText,@_jBoolean) );
end;
jBluetoothServerSocket(Obj).GenEvent_OnBluetoothServerSocketIncomingMessage(Obj,pasStrText);
end;
end;
procedure Java_Event_pOnBluetoothServerSocketWritingMessage(env: PJNIEnv; this: jobject; Obj: TObject);
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetoothServerSocket then
begin
jForm(jBluetoothServerSocket(Obj).Owner).UpdateJNI(gApp);
jBluetoothServerSocket(Obj).GenEvent_OnBluetoothServerSocketWritingMessage(Obj);;
end;
end;
procedure Java_Event_pOnBluetoothServerSocketListen(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString);
var
pasStrName, pasStrAddress: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetoothServerSocket then
begin
jForm(jBluetoothServerSocket(Obj).Owner).UpdateJNI(gApp);
pasStrName := '';
if deviceName <> nil then
begin
_jBoolean:= JNI_False;
pasStrName:= string( env^.GetStringUTFChars(Env,deviceName,@_jBoolean) );
end;
pasStrAddress := '';
if deviceAddress <> nil then
begin
_jBoolean := JNI_False;
pasStrAddress:= string( env^.GetStringUTFChars(Env,deviceAddress,@_jBoolean) );
end;
jBluetoothServerSocket(Obj).GenEvent_OnBluetoothServerSocketListen(Obj, pasStrName, pasStrAddress);
end;
end;
procedure Java_Event_pOnBluetoothServerSocketAccept(env: PJNIEnv; this: jobject; Obj: TObject; deviceName: JString; deviceAddress: JString);
var
pasStrName, pasStrAddress: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jBluetoothServerSocket then
begin
jForm(jBluetoothServerSocket(Obj).Owner).UpdateJNI(gApp);
pasStrName := '';
if deviceName <> nil then
begin
_jBoolean:= JNI_False;
pasStrName:= string( env^.GetStringUTFChars(Env,deviceName,@_jBoolean) );
end;
pasStrAddress := '';
if deviceAddress <> nil then
begin
_jBoolean := JNI_False;
pasStrAddress:= string( env^.GetStringUTFChars(Env,deviceAddress,@_jBoolean) );
end;
jBluetoothServerSocket(Obj).GenEvent_OnBluetoothServerSocketAccept(Obj, pasStrName, pasStrAddress);
end;
end;
procedure Java_Event_pOnSpinnerItemSeleceted(env: PJNIEnv; this: jobject; Obj: TObject; position: integer; caption: JString);
var
pasCaption: string;
_jBoolean: JBoolean;
begin
gApp.Jni.jEnv:= env;
gApp.Jni.jThis:= this;
if Obj is jSpinner then
begin
jForm(jSpinner(Obj).Owner).UpdateJNI(gApp);
pasCaption := '';
if caption <> nil then
begin
_jBoolean:= JNI_False;
pasCaption:= string( env^.GetStringUTFChars(Env,caption,@_jBoolean) );
end;
jSpinner(Obj).GenEvent_OnSpinnerItemSeleceted(Obj, pasCaption, position);
end;
end;
end.
|
{: Provides temporary file functions.
Last changed: $Date$
Revision: $Rev$
Author: $Author$
}
unit X2UtTempFile;
interface
function GetAppDataPath(): String;
function GetTempFile(const APrefix: String): String; overload;
function GetTempFile(const APath, AFileName, AExtension: String): String; overload;
function GetTempFile(const APath, AFileName: String): String; overload;
function GetTempAppDataFile(const ASubPath, AFileName, AExtension: String): String; overload;
function GetTempAppDataFile(const ASubPath, AFileName: String): String; overload;
function IsValidFileChar(const AChar: Char): Boolean;
function CheckValidFileName(var AFileName: String; const AReplacement: Char = #0): Boolean;
implementation
uses
ShlObj,
SysUtils,
Windows;
function GetAppDataPath(): String;
var
path: array[0..MAX_PATH] of Char;
begin
FillChar(path, SizeOf(path), #0);
if not SHGetSpecialFolderPath(0, @path, CSIDL_APPDATA, True) then
begin
FillChar(path, SizeOf(path), #0);
GetTempPath(SizeOf(path), @path);
end;
Result := path;
if Length(Result) > 0 then
Result := IncludeTrailingPathDelimiter(Result);
end;
function GetTempFile(const APrefix: String): String; overload;
var
tempPath: array[0..MAX_PATH] of Char;
tempFile: array[0..MAX_PATH] of Char;
begin
FillChar(tempPath, SizeOf(tempPath), #0);
FillChar(tempFile, SizeOf(tempFile), #0);
Windows.GetTempPath(SizeOf(tempPath), @tempPath);
Windows.GetTempFileName(@tempPath, PChar(APrefix), 0, @tempFile);
Result := String(tempFile);
end;
function GetTempFile(const APath, AFileName, AExtension: String): String; overload;
var
iCounter: Integer;
sBase: String;
sExtension: String;
begin
iCounter := 0;
sBase := IncludeTrailingPathDelimiter(APath);
if not ForceDirectories(sBase) then
begin
Result := '';
exit;
end;
sExtension := AExtension;
if (Length(sExtension) > 0) and (AnsiPos('.', sExtension) = 0) then
sExtension := '.' + sExtension;
sBase := sBase + AFileName;
Result := sBase + sExtension;
while FileExists(Result) do
begin
Inc(iCounter);
Result := Format('%s(%d)%s', [sBase, iCounter, sExtension]);
end;
end;
function GetTempFile(const APath, AFileName: String): String; overload;
var
sExt: String;
begin
sExt := ExtractFileExt(AFileName);
Result := GetTempFile(APath, Copy(AFileName, 1, Length(AFileName) - Length(sExt)),
sExt);
end;
function GetTempAppDataFile(const ASubPath, AFileName, AExtension: String): String; overload;
begin
Result := GetTempFile(GetAppDataPath + ASubPath, AFileName, AExtension);
end;
function GetTempAppDataFile(const ASubPath, AFileName: String): String; overload;
var
sExt: String;
begin
sExt := ExtractFileExt(AFileName);
Result := GetTempAppDataFile(ASubPath, Copy(AFileName, 1,
Length(AFileName) - Length(sExt)),
sExt);
end;
function IsValidFileChar(const AChar: Char): Boolean;
begin
Result := not CharInSet(AChar, ['\', '/', ':', '*', '?', '"', '<', '>', '|']);
end;
function CheckValidFileName(var AFileName: String; const AReplacement: Char): Boolean;
var
iPos: Integer;
begin
Result := True;
for iPos := Length(AFileName) downto 1 do
if not IsValidFileChar(AFileName[iPos]) then
begin
Result := False;
if AReplacement = #0 then
Delete(AFileName, iPos, 1)
else
AFileName[iPos] := AReplacement;
end;
end;
end.
|
unit unSuperFastHash;
(*
A Delphi and assembly translation of the SuperFastHash function by
Paul Hsieh (http://www.azillionmonkeys.com/qed/hash.html).
I got the idea for translating it due to borland.public.delphi.language.basm.
See the full discussion at:
http://groups.google.com/group/borland.public.delphi.language.basm/
browse_thread/thread/96482ba4d1d5a016/7745466ab714c3b3
***** 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 SuperFastHash Delphi and BASM translation.
*
* The Initial Developer of the Original Code is
* Davy Landman.
* Portions created by the Initial Developer are Copyright (C) 2007
* 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 ***** *)
interface
{.$define ASMVersion}
function SuperFastHash(AData: pointer; ADataLength: Integer): Cardinal;
function SuperFastHashLargeData(AData: pointer; ADataLength: Integer): Cardinal;
implementation
// Pascal translation of the SuperFastHash function by Paul Hsieh
// more info: http://www.azillionmonkeys.com/qed/hash.html
function SuperFastHash(AData: pointer; ADataLength: Integer): Cardinal;
{$ifndef ASMVersion}
var
TempPart: Cardinal;
RemainingBytes: Integer;
RemainingDWords: Integer;
begin
if not Assigned(AData) or (ADataLength <= 0) then
begin
Result := 0;
Exit;
end;
Result := ADataLength;
RemainingBytes := ADataLength and 3; // mod 4
RemainingDWords := ADataLength shr 2; // div 4
// main loop
while RemainingDWords > 0 do
begin
Result := Result + PWord(AData)^;
// splitting the pointer math keeps the amount of registers pushed at 2
AData := Pointer(Cardinal(AData) + SizeOf(Word));
TempPart := (PWord(AData)^ shl 11) xor Result;
Result := (Result shl 16) xor TempPart;
AData := Pointer(Cardinal(AData) + SizeOf(Word));
Result := Result + (Result shr 11);
dec(RemainingDWords);
end;
// Handle end cases
if RemainingBytes = 3 then
begin
Result := Result + PWord(AData)^;
Result := Result xor (Result shl 16);
AData := Pointer(Cardinal(AData) + SizeOf(Word)); // skip to the last byte
Result := Result xor ((PByte(AData)^ shl 18));
Result := Result + (Result shr 11);
end
else if RemainingBytes = 2 then
begin
Result := Result + PWord(AData)^;
Result := Result xor (Result shl 11);
Result := Result + (Result shr 17);
end
else if RemainingBytes = 1 then
begin
Result := Result + PByte(AData)^;
Result := Result xor (Result shl 10);
Result := Result + (Result shr 1);
end;
// Force "avalanching" of final 127 bits
Result := Result xor (Result shl 3);
Result := Result + (Result shr 5);
Result := Result xor (Result shl 4);
Result := Result + (Result shr 17);
Result := Result xor (Result shl 25);
Result := Result + (Result shr 6);
{$else}
asm
push esi
push edi
test eax, eax // data
jz @Ret // eax is result
xchg edx, eax // swith data and length
test eax, eax // length, and hash
jle @Ret
@Start:
mov edi, eax
mov esi, eax
and edi, 3 // last few bytes
shr esi, 2 // number of DWORD loops
jz @Last3
@Loop:
movzx ecx, word ptr [edx]
add eax, ecx
movzx ecx, word ptr [edx + 2]
shl ecx, 11
xor ecx, eax
shl eax, 16
xor eax, ecx
mov ecx, eax
shr eax, 11
add eax, ecx
add edx, 4
dec esi
jnz @Loop
@Last3:
test edi, edi
jz @Done
dec edi
jz @OneLeft
dec edi
jz @TwoLeft
movzx ecx, word ptr [edx]
add eax, ecx
mov ecx, eax
shl eax, 16
xor eax, ecx
movsx ecx, byte ptr [edx + 2]
shl ecx, 18
xor eax, ecx
mov ecx, eax
shr ecx, 11
add eax, ecx
jmp @Done
@TwoLeft:
movzx ecx, word ptr [edx]
add eax, ecx
mov ecx, eax
shl eax, 11
xor eax, ecx
mov ecx, eax
shr eax, 17
add eax, ecx
jmp @Done
@OneLeft:
movsx ecx, byte ptr [edx]
add eax, ecx
mov ecx, eax
shl eax, 10
xor eax, ecx
mov ecx, eax
shr eax, 1
add eax, ecx
@Done:
// avalanche
mov ecx, eax
shl eax, 3
xor eax, ecx
mov ecx, eax
shr eax, 5
add eax, ecx
mov ecx, eax
shl eax, 4
xor eax, ecx
mov ecx, eax
shr eax, 17
add eax, ecx
mov ecx, eax
shl eax, 25
xor eax, ecx
mov ecx, eax
shr eax, 6
add eax, ecx
@Ret:
pop edi
pop esi
ret
{$endif}
end;
function SuperFastHashLargeData(AData: pointer; ADataLength: Integer): Cardinal;
{$ifndef ASMVersion}
type
TWordArray = array[0..(MaxInt div SizeOf(Word)) - 1] of Word;
PWordArray = ^TWordArray;
var
TempPart: Cardinal;
RemainingBytes: Integer;
RemainingDWords: Integer;
begin
if not Assigned(AData) or (ADataLength <= 0) then
begin
Result := 0;
Exit;
end;
Result := ADataLength;
RemainingBytes := ADataLength and 3;
RemainingDWords := ADataLength shr 2; // div 4
// large loop
while RemainingDWords >= 4 do
begin
Result := Result + PWord(AData)^;
TempPart := (PWordArray(AData)^[1] shl 11) xor Result;
Result := (Result shl 16) xor TempPart;
Result := Result + (Result shr 11);
Result := Result + PWordArray(AData)^[2];
TempPart := (PWordArray(AData)^[3] shl 11) xor Result;
Result := (Result shl 16) xor TempPart;
Result := Result + (Result shr 11);
Result := Result + PWordArray(AData)^[4];
TempPart := (PWordArray(AData)^[5] shl 11) xor Result;
Result := (Result shl 16) xor TempPart;
Result := Result + (Result shr 11);
Result := Result + PWordArray(AData)^[6];
TempPart := (PWordArray(AData)^[7] shl 11) xor Result;
Result := (Result shl 16) xor TempPart;
Result := Result + (Result shr 11);
// update the pointer and the counter
AData := Pointer(Cardinal(AData) + (8 * SizeOf(Word)));
RemainingDWords := RemainingDWords - 4;
end;
// small loop
while RemainingDWords > 0 do
begin
Result := Result + PWord(AData)^;
AData := Pointer(Cardinal(AData) + SizeOf(Word));
TempPart := (PWord(AData)^ shl 11) xor Result;
Result := (Result shl 16) xor TempPart;
AData := Pointer(Cardinal(AData) + SizeOf(Word));
Result := Result + (Result shr 11);
dec(RemainingDWords);
end;
// Handle end cases
if RemainingBytes = 3 then
begin
Result := Result + PWord(AData)^;
Result := Result xor (Result shl 16);
AData := Pointer(Cardinal(AData) + SizeOf(Word)); // skip to the last byte
Result := Result xor ((PByte(AData)^ shl 18));
Result := Result + (Result shr 11);
end
else if RemainingBytes = 2 then
begin
Result := Result + PWord(AData)^;
Result := Result xor (Result shl 11);
Result := Result + (Result shr 17);
end
else if RemainingBytes = 1 then
begin
Result := Result + PByte(AData)^;
Result := Result xor (Result shl 10);
Result := Result + (Result shr 1);
end;
// Force "avalanching" of final 127 bits
Result := Result xor (Result shl 3);
Result := Result + (Result shr 5);
Result := Result xor (Result shl 4);
Result := Result + (Result shr 17);
Result := Result xor (Result shl 25);
Result := Result + (Result shr 6);
{$else}
asm
push esi
push edi
test eax, eax // test for nil pointer
jz @Ret // eax is also result, so save ret here
xchg edx, eax // swith data and length
test eax, eax // length, and hash
jle @Ret
@Start:
mov edi, eax
mov esi, eax
and edi, 3 // last few bytes
shr esi, 2 // number of DWORD loops
jz @Last3
@LargeLoop:
cmp esi,$04
jl @Loop
// first DWORD
movzx ecx, word ptr [edx]
add eax, ecx
movzx ecx, word ptr [edx + 2]
shl ecx, 11
xor ecx, eax
shl eax, 16
xor eax, ecx
mov ecx, eax
shr eax, 11
add eax, ecx
// second DWORD
movzx ecx, word ptr [edx + 4]
add eax, ecx
movzx ecx, word ptr [edx + 6]
shl ecx, 11
xor ecx, eax
shl eax, 16
xor eax, ecx
mov ecx, eax
shr eax, 11
add eax, ecx
// third DWORD
movzx ecx, word ptr [edx + 8]
add eax, ecx
movzx ecx, word ptr [edx + 10]
shl ecx, 11
xor ecx, eax
shl eax, 16
xor eax, ecx
mov ecx, eax
shr eax, 11
add eax, ecx
// fourth DWORD
movzx ecx, word ptr [edx + 12]
add eax, ecx
movzx ecx, word ptr [edx + 14]
shl ecx, 11
xor ecx, eax
shl eax, 16
xor eax, ecx
mov ecx, eax
shr eax, 11
add eax, ecx
add edx, 16
sub esi, 4
jz @Last3
jmp @LargeLoop
@Loop:
movzx ecx, word ptr [edx]
add eax, ecx
movzx ecx, word ptr [edx + 2]
shl ecx, 11
xor ecx, eax
shl eax, 16
xor eax, ecx
mov ecx, eax
shr eax, 11
add eax, ecx
add edx, 4
dec esi
jnz @Loop
@Last3:
test edi, edi
jz @Done
dec edi
jz @OneLeft
dec edi
jz @TwoLeft
movzx ecx, word ptr [edx]
add eax, ecx
mov ecx, eax
shl eax, 16
xor eax, ecx
movsx ecx, byte ptr [edx + 2]
shl ecx, 18
xor eax, ecx
mov ecx, eax
shr ecx, 11
add eax, ecx
jmp @Done
@TwoLeft:
movzx ecx, word ptr [edx]
add eax, ecx
mov ecx, eax
shl eax, 11
xor eax, ecx
mov ecx, eax
shr eax, 17
add eax, ecx
jmp @Done
@OneLeft:
movsx ecx, byte ptr [edx]
add eax, ecx
mov ecx, eax
shl eax, 10
xor eax, ecx
mov ecx, eax
shr eax, 1
add eax, ecx
@Done:
// avalanche
mov ecx, eax
shl eax, 3
xor eax, ecx
mov ecx, eax
shr eax, 5
add eax, ecx
mov ecx, eax
shl eax, 4
xor eax, ecx
mov ecx, eax
shr eax, 17
add eax, ecx
mov ecx, eax
shl eax, 25
xor eax, ecx
mov ecx, eax
shr eax, 6
add eax, ecx
@Ret:
pop edi
pop esi
ret
{$endif}
end;
end.
|
unit ASDTools;
{<|Модуль библиотеки ASDEngine|>}
{<|Дата создания 5.07.07|>}
{<|Автор Adler3D|>}
{<|e-mail : Adler3D@Mail.ru|>}
{<|Дата последнего изменения 5.07.07|>}
interface
uses ASDInterface, ASDClasses;
type
TTools = class(TASDObject, ITools)
public
constructor CreateEx; override;
function InitCalcNPS(WaitTime: Integer = 500): ICalcNPS;
function InitTimer: ITimer;
function InitFileStream(FileName: PChar; Mode: Word = 0): IFileStream;
function InitList: IList;
function InitQuickList: IList;
function InitMemoryStream: IMemoryStream;
function InitMemoryStreamEx(Memory: Pointer; Size: Integer): IMemoryStream;
end;
implementation
uses ASDEng;
{ TASDTools }
constructor TTools.CreateEx;
begin
inherited CreateEx;
end;
function TTools.InitCalcNPS(WaitTime: Integer): ICalcNPS;
begin
Result := TCalcNPS.CreateEx(WaitTime);
end;
function TTools.InitFileStream(FileName: PChar;
Mode: Word): IFileStream;
begin
Result := TFileStream.CreateEx(FileName, Mode);
end;
function TTools.InitList: IList;
begin
Result := TList.CreateEx;
end;
function TTools.InitQuickList: IList;
begin
Result := TQuickList.CreateEx;
end;
function TTools.InitMemoryStream: IMemoryStream;
begin
Result := TMemoryStream.CreateEx;
end;
function TTools.InitMemoryStreamEx(Memory: Pointer; Size: Integer):
IMemoryStream;
begin
Result := TMemoryStream.CreateEx(Memory, Size);
end;
function TTools.InitTimer: ITimer;
begin
Result := TTimer.CreateEx;
end;
end.
|
unit UIConsts;
interface
uses Graphics, SysUtils;
type
TGetStrProc = procedure(const S: string) of object;
TIdentMapEntry = record
Value: Integer;
Name: String;
end;
TColorRec = record
const
SystemColor = $FF000000;
// System Colors (Windows only)
cSCROLLBAR = 0;
cBACKGROUND = 1;
cACTIVECAPTION = 2;
cINACTIVECAPTION = 3;
cMENU = 4;
cWINDOW = 5;
cWINDOWFRAME = 6;
cMENUTEXT = 7;
cWINDOWTEXT = 8;
cCAPTIONTEXT = 9;
cACTIVEBORDER = 10;
cINACTIVEBORDER = 11;
cAPPWORKSPACE = 12;
cHIGHLIGHT = 13;
cHIGHLIGHTTEXT = 14;
cBTNFACE = 15;
cBTNSHADOW = $10;
cGRAYTEXT = 17;
cBTNTEXT = 18;
cINACTIVECAPTIONTEXT = 19;
cBTNHIGHLIGHT = 20;
c3DDKSHADOW = 21;
c3DLIGHT = 22;
cINFOTEXT = 23;
cINFOBK = 24;
cHOTLIGHT = 26;
cGRADIENTACTIVECAPTION = 27;
cGRADIENTINACTIVECAPTION = 28;
cMENUHILIGHT = 29;
cMENUBAR = 30;
cENDCOLORS = cMENUBAR;
cDESKTOP = cBACKGROUND;
c3DFACE = cBTNFACE;
c3DSHADOW = cBTNSHADOW;
c3DHIGHLIGHT = cBTNHIGHLIGHT;
c3DHILIGHT = cBTNHIGHLIGHT;
cBTNHILIGHT = cBTNHIGHLIGHT;
SysScrollBar = TColor(SystemColor or cSCROLLBAR);
SysBackground = TColor(SystemColor or cBACKGROUND);
SysActiveCaption = TColor(SystemColor or cACTIVECAPTION);
SysInactiveCaption = TColor(SystemColor or cINACTIVECAPTION);
SysMenu = TColor(SystemColor or cMENU);
SysWindow = TColor(SystemColor or cWINDOW);
SysWindowFrame = TColor(SystemColor or cWINDOWFRAME);
SysMenuText = TColor(SystemColor or cMENUTEXT);
SysWindowText = TColor(SystemColor or cWINDOWTEXT);
SysCaptionText = TColor(SystemColor or cCAPTIONTEXT);
SysActiveBorder = TColor(SystemColor or cACTIVEBORDER);
SysInactiveBorder = TColor(SystemColor or cINACTIVEBORDER);
SysAppWorkSpace = TColor(SystemColor or cAPPWORKSPACE);
SysHighlight = TColor(SystemColor or cHIGHLIGHT);
SysHighlightText = TColor(SystemColor or cHIGHLIGHTTEXT);
SysBtnFace = TColor(SystemColor or cBTNFACE);
SysBtnShadow = TColor(SystemColor or cBTNSHADOW);
SysGrayText = TColor(SystemColor or cGRAYTEXT);
SysBtnText = TColor(SystemColor or cBTNTEXT);
SysInactiveCaptionText = TColor(SystemColor or cINACTIVECAPTIONTEXT);
SysBtnHighlight = TColor(SystemColor or cBTNHIGHLIGHT);
Sys3DDkShadow = TColor(SystemColor or c3DDKSHADOW);
Sys3DLight = TColor(SystemColor or c3DLIGHT);
SysInfoText = TColor(SystemColor or cINFOTEXT);
SysInfoBk = TColor(SystemColor or cINFOBK);
SysHotLight = TColor(SystemColor or cHOTLIGHT);
SysGradientActiveCaption = TColor(SystemColor or cGRADIENTACTIVECAPTION);
SysGradientInactiveCaption = TColor(SystemColor or cGRADIENTINACTIVECAPTION);
SysMenuHighlight = TColor(SystemColor or cMENUHILIGHT);
SysMenuBar = TColor(SystemColor or cMENUBAR);
SysNone = TColor($1FFFFFFF);
SysDefault = TColor($20000000);
// Actual colors
Aliceblue = TColor($FFF8F0);
Antiquewhite = TColor($D7EBFA);
Aqua = TColor($FFFF00);
Aquamarine = TColor($D4FF7F);
Azure = TColor($FFFFF0);
Beige = TColor($DCF5F5);
Bisque = TColor($C4E4FF);
Black = TColor($000000);
Blanchedalmond = TColor($CDEBFF);
Blue = TColor($FF0000);
Blueviolet = TColor($E22B8A);
Brown = TColor($2A2AA5);
Burlywood = TColor($87B8DE);
Cadetblue = TColor($A09E5F);
Chartreuse = TColor($00FF7F);
Chocolate = TColor($1E69D2);
Coral = TColor($507FFF);
Cornflowerblue = TColor($ED9564);
Cornsilk = TColor($DCF8FF);
Crimson = TColor($3C14DC);
Cyan = TColor($FFFF00);
Darkblue = TColor($8B0000);
Darkcyan = TColor($8B8B00);
Darkgoldenrod = TColor($0B86B8);
Darkgray = TColor($A9A9A9);
Darkgreen = TColor($006400);
Darkgrey = TColor($A9A9A9);
Darkkhaki = TColor($6BB7BD);
Darkmagenta = TColor($8B008B);
Darkolivegreen = TColor($2F6B55);
Darkorange = TColor($008CFF);
Darkorchid = TColor($CC3299);
Darkred = TColor($00008B);
Darksalmon = TColor($7A96E9);
Darkseagreen = TColor($8FBC8F);
Darkslateblue = TColor($8B3D48);
Darkslategray = TColor($4F4F2F);
Darkslategrey = TColor($4F4F2F);
Darkturquoise = TColor($D1CE00);
Darkviolet = TColor($D30094);
Deeppink = TColor($9314FF);
Deepskyblue = TColor($FFBF00);
Dimgray = TColor($696969);
Dimgrey = TColor($696969);
Dodgerblue = TColor($FF901E);
Firebrick = TColor($2222B2);
Floralwhite = TColor($F0FAFF);
Forestgreen = TColor($228B22);
Fuchsia = TColor($FF00FF);
Gainsboro = TColor($DCDCDC);
Ghostwhite = TColor($FFF8F8);
Gold = TColor($00D7FF);
Goldenrod = TColor($20A5DA);
Gray = TColor($808080);
Green = TColor($008000);
Greenyellow = TColor($2FFFAD);
Grey = TColor($808080);
Honeydew = TColor($F0FFF0);
Hotpink = TColor($B469FF);
Indianred = TColor($5C5CCD);
Indigo = TColor($82004B);
Ivory = TColor($F0FFFF);
Khaki = TColor($8CE6F0);
Lavender = TColor($FAE6E6);
Lavenderblush = TColor($F5F0FF);
Lawngreen = TColor($00FC7C);
Lemonchiffon = TColor($CDFAFF);
Lightblue = TColor($E6D8AD);
Lightcoral = TColor($8080F0);
Lightcyan = TColor($FFFFE0);
Lightgoldenrodyellow = TColor($D2FAFA);
Lightgray = TColor($D3D3D3);
Lightgreen = TColor($90EE90);
Lightgrey = TColor($D3D3D3);
Lightpink = TColor($C1B6FF);
Lightsalmon = TColor($7AA0FF);
Lightseagreen = TColor($AAB220);
Lightskyblue = TColor($FACE87);
Lightslategray = TColor($998877);
Lightslategrey = TColor($998877);
Lightsteelblue = TColor($DEC4B0);
Lightyellow = TColor($E0FFFF);
LtGray = TColor($C0C0C0);
MedGray = TColor($A4A0A0);
DkGray = TColor($808080);
MoneyGreen = TColor($C0DCC0);
LegacySkyBlue = TColor($F0CAA6);
Cream = TColor($F0FBFF);
Lime = TColor($00FF00);
Limegreen = TColor($32CD32);
Linen = TColor($E6F0FA);
Magenta = TColor($FF00FF);
Maroon = TColor($000080);
Mediumaquamarine = TColor($AACD66);
Mediumblue = TColor($CD0000);
Mediumorchid = TColor($D355BA);
Mediumpurple = TColor($DB7093);
Mediumseagreen = TColor($71B33C);
Mediumslateblue = TColor($EE687B);
Mediumspringgreen = TColor($9AFA00);
Mediumturquoise = TColor($CCD148);
Mediumvioletred = TColor($8515C7);
Midnightblue = TColor($701919);
Mintcream = TColor($FAFFF5);
Mistyrose = TColor($E1E4FF);
Moccasin = TColor($B5E4FF);
Navajowhite = TColor($ADDEFF);
Navy = TColor($800000);
Oldlace = TColor($E6F5FD);
Olive = TColor($008080);
Olivedrab = TColor($238E6B);
Orange = TColor($00A5FF);
Orangered = TColor($0045FF);
Orchid = TColor($D670DA);
Palegoldenrod = TColor($AAE8EE);
Palegreen = TColor($98FB98);
Paleturquoise = TColor($EEEEAF);
Palevioletred = TColor($9370DB);
Papayawhip = TColor($D5EFFF);
Peachpuff = TColor($B9DAFF);
Peru = TColor($3F85CD);
Pink = TColor($CBC0FF);
Plum = TColor($DDA0DD);
Powderblue = TColor($E6E0B0);
Purple = TColor($800080);
Red = TColor($0000FF);
Rosybrown = TColor($8F8FBC);
Royalblue = TColor($E16941);
Saddlebrown = TColor($13458B);
Salmon = TColor($7280FA);
Sandybrown = TColor($60A4F4);
Seagreen = TColor($578B2E);
Seashell = TColor($EEF5FF);
Sienna = TColor($2D52A0);
Silver = TColor($C0C0C0);
Skyblue = TColor($EBCE87);
Slateblue = TColor($CD5A6A);
Slategray = TColor($908070);
Slategrey = TColor($908070);
Snow = TColor($FAFAFF);
Springgreen = TColor($7FFF00);
Steelblue = TColor($B48246);
Tan = TColor($8CB4D2);
Teal = TColor($808000);
Thistle = TColor($D8BFD8);
Tomato = TColor($4763FF);
Turquoise = TColor($D0E040);
Violet = TColor($EE82EE);
Wheat = TColor($B3DEF5);
White = TColor($FFFFFF);
Whitesmoke = TColor($F5F5F5);
Yellow = TColor($00FFFF);
Yellowgreen = TColor($32CD9A);
Null = TColor($00000000);
class var ColorToRGB: function (Color: TColor): Longint;
{ class operator Implicit(const C: TColor): TColorRec; inline;
class operator Implicit(const C: TColorRec): TColor; inline;
class operator Implicit(const C: TColorRec): Longint; inline;
class operator Explicit(const C: TColorRec): Longint; inline;}
case LongWord of
0:
(Color: TColor);
2:
(HiWord, LoWord: Word);
3:
{$IFDEF BIGENDIAN}
(A, B, G, R: System.Byte);
{$ELSE}
(R, G, B, A: System.Byte);
{$ENDIF}
end;
TColors = TColorRec;
const
Colors: array[0..51] of TIdentMapEntry = (
(Value: TColors.Black; Name: 'clBlack'),
(Value: TColors.Maroon; Name: 'clMaroon'),
(Value: TColors.Green; Name: 'clGreen'),
(Value: TColors.Olive; Name: 'clOlive'),
(Value: TColors.Navy; Name: 'clNavy'),
(Value: TColors.Purple; Name: 'clPurple'),
(Value: TColors.Teal; Name: 'clTeal'),
(Value: TColors.Gray; Name: 'clGray'),
(Value: TColors.Silver; Name: 'clSilver'),
(Value: TColors.Red; Name: 'clRed'),
(Value: TColors.Lime; Name: 'clLime'),
(Value: TColors.Yellow; Name: 'clYellow'),
(Value: TColors.Blue; Name: 'clBlue'),
(Value: TColors.Fuchsia; Name: 'clFuchsia'),
(Value: TColors.Aqua; Name: 'clAqua'),
(Value: TColors.White; Name: 'clWhite'),
(Value: TColors.MoneyGreen; Name: 'clMoneyGreen'),
// Use LegacySkyBlue to maintain consistency in VCL colors
(Value: TColors.LegacySkyBlue; Name: 'clSkyBlue'),
(Value: TColors.Cream; Name: 'clCream'),
(Value: TColors.MedGray; Name: 'clMedGray'),
(Value: TColors.SysActiveBorder; Name: 'clActiveBorder'),
(Value: TColors.SysActiveCaption; Name: 'clActiveCaption'),
(Value: TColors.SysAppWorkSpace; Name: 'clAppWorkSpace'),
(Value: TColors.SysBackground; Name: 'clBackground'),
(Value: TColors.SysBtnFace; Name: 'clBtnFace'),
(Value: TColors.SysBtnHighlight; Name: 'clBtnHighlight'),
(Value: TColors.SysBtnShadow; Name: 'clBtnShadow'),
(Value: TColors.SysBtnText; Name: 'clBtnText'),
(Value: TColors.SysCaptionText; Name: 'clCaptionText'),
(Value: TColors.SysDefault; Name: 'clDefault'),
(Value: TColors.SysGradientActiveCaption; Name: 'clGradientActiveCaption'),
(Value: TColors.SysGradientInactiveCaption; Name: 'clGradientInactiveCaption'),
(Value: TColors.SysGrayText; Name: 'clGrayText'),
(Value: TColors.SysHighlight; Name: 'clHighlight'),
(Value: TColors.SysHighlightText; Name: 'clHighlightText'),
(Value: TColors.SysHotLight; Name: 'clHotLight'),
(Value: TColors.SysInactiveBorder; Name: 'clInactiveBorder'),
(Value: TColors.SysInactiveCaption; Name: 'clInactiveCaption'),
(Value: TColors.SysInactiveCaptionText; Name: 'clInactiveCaptionText'),
(Value: TColors.SysInfoBk; Name: 'clInfoBk'),
(Value: TColors.SysInfoText; Name: 'clInfoText'),
(Value: TColors.SysMenu; Name: 'clMenu'),
(Value: TColors.SysMenuBar; Name: 'clMenuBar'),
(Value: TColors.SysMenuHighlight; Name: 'clMenuHighlight'),
(Value: TColors.SysMenuText; Name: 'clMenuText'),
(Value: TColors.SysNone; Name: 'clNone'),
(Value: TColors.SysScrollBar; Name: 'clScrollBar'),
(Value: TColors.Sys3DDkShadow; Name: 'cl3DDkShadow'),
(Value: TColors.Sys3DLight; Name: 'cl3DLight'),
(Value: TColors.SysWindow; Name: 'clWindow'),
(Value: TColors.SysWindowFrame; Name: 'clWindowFrame'),
(Value: TColors.SysWindowText; Name: 'clWindowText'));
procedure GetColorValues(Proc: TGetStrProc);
function IdentToColor(const Ident: string; var Color: Integer): Boolean;
function IdentToInt(const Ident: string; var Int: Integer; const Map: array of TIdentMapEntry): Boolean;
implementation
procedure GetColorValues(Proc: TGetStrProc);
var
I: Integer;
begin
for I := Low(Colors) to High(Colors) do Proc(Colors[I].Name);
end;
function IdentToColor(const Ident: string; var Color: Integer): Boolean;
begin
Result := IdentToInt(Ident, Color, Colors);
end;
function SameText(const S1, S2: string): Boolean;
begin
if Pointer(S1) = Pointer(S2) then
result := True
else if (Pointer(S1) = nil) or (Pointer(S2) = nil) then
result := False
else
Result := CompareText(S1, S2) = 0;
end;
function IdentToInt(const Ident: string; var Int: Integer; const Map: array of TIdentMapEntry): Boolean;
var
I: Integer;
begin
for I := Low(Map) to High(Map) do
if SameText(Map[I].Name, Ident) then
begin
Result := True;
Int := Map[I].Value;
Exit;
end;
Result := False;
end;
end.
|
unit IWCompFlash;
interface
uses
Classes,
IWControl, IWFileReference, IWTypes, IWHTMLTag;
type
TIWFlashQuality = (fqLow, fqAutoLow, fqAutoHigh, fqMedium, fqHigh, fqBest);
TIWFlashScale = (fsDefault, fsShowAll, fsNoBorder, fsExactFit);
TIWFlashAlign = (faNone, faLeft, faTop, faRight, faBottom);
TIWFlashSAlign = (fsNone, fsLeft, fsTop, fsRight, fsBottom, fsTopLeft, fsTopRight, fsBottomLeft
, fsBottomRight);
TIWCustomFlash = class(TIWControl)
protected
FAlign: TIWFlashAlign;
FAutoPlay: Boolean;
FBGColor: TIWColor;
FEnableMenu: Boolean;
FFlashFile: TIWFileReference;
FLoop: Boolean;
FQuality: TIWFlashQuality;
FSAlign: TIWFlashSAlign;
FScale: TIWFlashScale;
FSWLiveConnect: Boolean;
//
procedure SetFlashFile(const AValue: TIWFileReference);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function RenderHTML: TIWHTMLTag; override;
//@@ Specifies primary alignment.
property Align: TIWFlashAlign read FAlign write FAlign;
//@@ Specifies if the flash movie will begin playing automatically or not.
property AutoPlay: Boolean read FAutoPlay write FAutoPlay;
//@@ Specifies the background color for the flash plugin.
property BGColor: TIWColor read FBGColor write FBGColor;
//@@ Specifies whether or not the flash menu is enabled. Default is clNone.
property EnableMenu: Boolean read FEnableMenu write FEnableMenu;
//@@ Specifies the location of the flash file. This property is required.
property FlashFile: TIWFileReference read FFlashFile write SetFlashFile;
//@@ Specifies if the flash movie will repeat or not. Default is True.
property Loop: Boolean read FLoop write FLoop;
//@@ Specifies the quality used to play the flash movie. See Flash documentation for details.
property Quality: TIWFlashQuality read FQuality write FQuality;
//@@ Specifies secondary alignment.
property SAlign: TIWFlashSAlign read FSAlign write FSAlign;
//@@ Specifies scale.
property Scale: TIWFlashScale read FScale write FScale;
//@@ Specifies if the browser should automatically load Java. If you use JavaScript to interact
//with Flashe, Java must be running for the FSCommand to work.
property SWLiveConnect: Boolean read FSWLiveConnect write FSWLiveConnect;
end;
TIWFlash = class(TIWCustomFlash)
published
property Align;
property AutoPlay;
property BGColor;
property EnableMenu;
property FlashFile;
property Loop;
property Quality;
property SAlign;
property Scale;
property SWLiveConnect;
end;
implementation
uses
{$IFDEF Linux}QGraphics,{$ELSE}Graphics,{$ENDIF}
SysUtils, SWSystem;
{ TIWCustomFlash }
constructor TIWCustomFlash.Create(AOwner: TComponent);
begin
inherited;
FAutoPlay := True;
FBGColor := clNone;
FEnableMenu := True;
FFlashFile := TIWFileReference.Create;
FLoop := True;
FQuality := fqHigh;
Width := 468;
Height := 60;
end;
destructor TIWCustomFlash.Destroy;
begin
FreeAndNil(FFlashFile);
inherited;
end;
function TIWCustomFlash.RenderHTML: TIWHTMLTag;
function QualityText(const AQuality: TIWFlashQuality): string;
begin
case AQuality of
fqLow: Result := 'Low';
fqAutoLow: Result := 'AutoLow';
fqAutoHigh: Result := 'AutoHigh';
fqMedium: Result := 'Medium';
fqHigh: Result := 'High';
fqBest: Result := 'Best';
end;
end;
function AlignText(AAlign: TIWFlashAlign): string;
begin
case AAlign of
faNone: Result := 'None';
faLeft: Result := 'Left';
faTop: Result := 'Top';
faRight: Result := 'Right';
faBottom: Result := 'Bottom';
end;
end;
function SAlignText(ASAlign: TIWFlashSAlign): string;
begin
case ASAlign of
fsNone: Result := 'None';
fsLeft: Result := 'Left';
fsTop: Result := 'Top';
fsRight: Result := 'Right';
fsBottom: Result := 'Bottom';
fsTopLeft: Result := 'TopLeft';
fsTopRight: Result := 'TopRight';
fsBottomLeft: Result := 'BottomLeft';
fsBottomRight: Result := 'BottomRight';
end;
end;
function ScaleText(AScale: TIWFlashScale): string;
begin
case AScale of
fsDefault: Result := 'Default';
fsShowAll: Result := 'ShowAll';
fsNoBorder: Result := 'NoBorder';
fsExactFit: Result := 'ExactFit';
end;
end;
begin
if WebApplication.Browser = brIE then begin
Result := TIWHTMLTag.CreateTag('OBJECT'); try
Result.AddStringParam('ID', HTMLName);
Result.AddStringParam('CLASSID', 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000');
// Width and Height are required for flash.
Result.AddIntegerParam('WIDTH', Width);
Result.AddIntegerParam('HEIGHT', Height);
Result.AddStringParam('CODEBASE', 'http://active.macromedia.com/flash5/cabs/swflash.cab#version=5,0,0,0');
with Result.Contents.AddTag('PARAM') do begin
AddStringParam('NAME', 'MOVIE');
AddStringParam('VALUE', FlashFile.Location(WebApplication.URLBase));
end;
with Result.Contents.AddTag('PARAM') do begin
AddStringParam('NAME', 'PLAY');
AddBoolParam('VALUE', AutoPlay);
end;
with Result.Contents.AddTag('PARAM') do begin
AddStringParam('NAME', 'LOOP');
AddBoolParam('VALUE', Loop);
end;
with Result.Contents.AddTag('PARAM') do begin
AddStringParam('NAME', 'QUALITY');
AddStringParam('VALUE', QualityText(Quality));
end;
with Result.Contents.AddTag('PARAM') do begin
AddStringParam('NAME', 'MENU');
AddBoolParam('VALUE', EnableMenu);
end;
with Result.Contents.AddTag('PARAM') do begin
AddStringParam('NAME', 'BGCOLOR');
AddColor('VALUE', BGColor);
end;
with Result.Contents.AddTag('PARAM') do begin
AddStringParam('NAME', 'ALIGN');
AddStringParam('VALUE', AlignText(Align));
end;
with Result.Contents.AddTag('PARAM') do begin
AddStringParam('NAME', 'SALIGN');
AddStringParam('VALUE', SAlignText(SAlign));
end;
with Result.Contents.AddTag('PARAM') do begin
AddStringParam('NAME', 'SCALE');
AddStringParam('VALUE', ScaleText(Scale));
end;
with Result.Contents.AddTag('PARAM') do begin
AddStringParam('NAME', 'SWLIVECONNECT');
AddBoolParam('VALUE', SWLiveConnect);
end;
except FreeAndNil(Result); raise; end;
end else begin
Result := TIWHTMLTag.CreateTag('EMBED'); try
Result.AddStringParam('NAME', HTMLName);
Result.AddStringParam('SRC', FlashFile.Location(WebApplication.URLBase));
Result.AddIntegerParam('WIDTH', Width);
Result.AddIntegerParam('HEIGHT', Height);
Result.AddBoolParam('PLAY', AutoPlay);
Result.AddBoolParam('LOOP', Loop);
Result.AddStringParam('QUALITY', QualityText(Quality));
Result.AddBoolParam('MENU', EnableMenu);
Result.AddColor('BGCOLOR', BGColor);
Result.AddStringParam('ALIGN', AlignText(Align));
Result.AddStringParam('SALIGN', SAlignText(SAlign));
Result.AddStringParam('SCALE', ScaleText(Scale));
Result.AddBoolParam('SWLIVECONNECT', SWLiveConnect);
Result.AddStringParam('PLUGINSPAGE'
, 'http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash');
Result.Contents.AddText('');
except FreeAndNil(Result); raise; end;
end;
end;
procedure TIWCustomFlash.SetFlashFile(const AValue: TIWFileReference);
begin
FFlashFile.Assign(AValue);
end;
end.
|
unit psc11001;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ExtCtrls, ComCtrls, Db, Tmax_DataSetText,
OnEditBaseCtrl, OnEditStdCtrl, OnEditNumCtl, Grids, DBGrids, OnGrDBGrid,
OnLineLabel, OnInsaCommon, OnEditBtnCtrl, OnTmaxPersonEdit, OnDBGrid, OnEditMemo,
OnScheme, OnShapeLabel, OnFocusButton, Tmax_session,
OnPopupEdit, TmaxFunc, Func, OnEditMdate;
type
TFM_Main = class(TForm)
Panel_Body: TPanel;
SF_Main: TOnSchemeForm;
StatusBar1: TStatusBar;
TMaxSession: TTMaxSession;
TMaxDataSet: TTMaxDataSet;
DataSource1: TDataSource;
P_cprice: TOnNumberEdit;
BT_Save: TOnFocusButton;
P_Condate: TOnDateEdit;
BB_Close: TOnFocusButton;
DbGrid1: TOnGrDbGrid;
TMaxGrid: TTMaxDataSet;
L_Info: TLabel;
BT_Search: TOnFocusButton;
procedure BB_CloseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure BT_SaveClick(Sender: TObject);
procedure DataSource1DataChange(Sender: TObject; Field: TField);
procedure P_CondateChange(Sender: TObject);
procedure P_cpriceKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure BT_SearchClick(Sender: TObject);
private
{ Private declarations }
SqlStr : String;
sEmpno : String;
sKorname : String;
sGrade : String;
vSysDate : String;
ParamSQL : String;
procedure RetrieveData;
public
{ Public declarations }
end;
var
FM_Main: TFM_Main;
implementation
{$R *.DFM}
procedure TFM_Main.BB_CloseClick(Sender: TObject);
begin
Close;
end;
procedure TFM_Main.FormCreate(Sender: TObject);
begin
Self.OnPaint := Nil;
Application.ProcessMessages;
SF_Main.Refresh;
StatusBar1.Panels[1].Text := '종합인사 시스템에 접속 중입니다...';
TMaxSession.EnvFileName := GetHomeDir+'\newhana.env'; //ShowMessage(GetHomeDir);
TMaxSession.LabelName := 'HANAROHPER';
TMaxSession.Connect := False;
TMaxSession.Host := Hinsa_Param(cmdline,10); //'12.4.13.90';
TMaxSession.Port := '9999';
try
TMaxSession.Connect := True;
except
Application.MessageBox(PChar('APP서버 접속 실패'),'에러',mb_ok);
Application.Terminate;
Exit;
end;
//2013.11. Add 파라미터와 비교하여 암호 다르면 접속 막음.
FM_Tmax := TFM_Tmax.Create(Self);
FM_Tmax.T_Session := TMaxSession;
if FM_Tmax.PassWordChk(Hinsa_Param(cmdline,1), Hinsa_Param(cmdline,3)) = 0 then
Application.Terminate;
end;
procedure TFM_Main.FormShow(Sender: TObject);
begin
sEmpno := HInsa_Param(cmdline,1);
sGrade := HInsa_Param(cmdline,3);
StatusBar1.Panels[1].Text := '저장된 자료를 읽고 있습니다. 잠시만 기다려 주십시요..';
FM_Tmax := TFM_Tmax.Create(Self);
FM_Tmax.T_Session := TMaxSession;
vSysDate := FM_Tmax.GetData('sysdate','','');
P_Condate.Text := Hinsa_DisplayDate(vSysDate,'-');
with TMaxDataSet do
begin
ServiceName := 'HINSA_select';
Close;
Sql.Clear;
Sql.Text := 'SELECT groupid, ''field2'', ''field3'', ''field4'',''field5'' '+
' FROM pymenuuser '+
' where empno = '''+ sEmpno +''' ';
ClearFieldInfo;
AddField('field1' , ftString, 100);
AddField('field2' , ftString, 100);
AddField('field3' , ftString, 100);
AddField('field4' , ftString, 100);
AddField('field5' , ftString, 100);
Open;
if ((sEmpno = '0891') or (sEmpno = '0386')) then //스톡옵션 관리자 사번 (조회만 가능토록) 김경호, 하병수
begin
BT_Save.Enabled := False;
ShowMessage('등록 및 수정은 종가관리자(P419 - 최나리)만 가능합니다.');
end
else if (sEmpno <> 'J059') and (Copy(sEmpno,1,1) <> 'D') then //종가관리 담당자 : 종합인사 관리자...
begin
ShowMessage('귀하는 작업 권한이 부족합니다. 프로그램을 종료합니다.');
FM_Main.Close;
end;
TMaxDataSet.Close;
end;
RetrieveData;
DbGrid1.SetFocus;
StatusBar1.Panels[1].Text := '';
end;
procedure TFM_Main.RetrieveData;
var vDate : String;
begin
Application.ProcessMessages;
vDate := RemoveChar(P_Condate.Text,'-');
with TMaxGrid do
begin
ServiceName := 'HINSA_select';
Close;
Sql.Clear;
Sql.Text := 'SELECT Substr(STOCKDATE,1,4)||''-''||Substr(STOCKDATE,5,2)||''-''||Substr(STOCKDATE,7,2), '+
' CPRICE, '+
' Substr(WRITETIME,1,4)||''-''||Substr(WRITETIME,5,2)||''-''||Substr(WRITETIME,7,2)||'' ''|| '+
' Substr(WRITETIME,9,2)||'':''||Substr(WRITETIME,11,2) , '+
' (Select Korname||Empno from Pimpmas Where Empno = WRITEMAN) , '+
' ''field5'' '+
' FROM pstockbas '+
' where Stockdate between To_Char(Add_Months(To_date('''+ vDate +''',''yyyymmdd''),-3),''yyyymmdd'') '+
' and '''+ vDate +''' '+
' Order by Stockdate Desc ';
ClearFieldInfo;
AddField('STOCKDATE', ftString, 100);
AddField('CPRICE' , ftFloat , 100);
AddField('WRITETIME', ftString, 100);
AddField('WRITEMAN' , ftString, 100);
AddField('field5' , ftString, 100);
Open;
TFloatField(FieldByName('CPRICE')).DisplayFormat := '#,##0';
end;
StatusBar1.Panels[1].Text := '조회 완료 [기준일 기준 3개월 내역만 나타납니다.]';
end;
procedure TFM_Main.BT_SaveClick(Sender: TObject);
var
vCnt : Integer;
begin
if MessageDlg(P_Condate.Text + '일 종가를 '+ FloatToStr(p_cprice.Value) +'원으로 저장합니다.',
mtConfirmation, [mbYes, mbNo], 0) <> mrYes then exit;
//ShowMessage(RemoveChar(P_Condate.Text,'-'));
with TMaxDataSet do
begin
ServiceName := 'HINSA_select';
Close;
Sql.Clear;
Sql.Text := 'SELECT count(*), ''field2'', ''field3'', ''field4'',''field5'' '+
' FROM pstockbas '+
' WHERE Stockdate = '''+ RemoveChar(P_Condate.Text,'-') +''' ';
ClearFieldInfo;
AddField('field1' , ftString, 100);
AddField('field2' , ftString, 100);
AddField('field3' , ftString, 100);
AddField('field4' , ftString, 100);
AddField('field5' , ftString, 100);
Open;
vCnt := Fields[0].AsInteger;
end;
if vCnt = 0 then
begin
ParamSQL := 'Insert into pstockbas '+
' values '+
'( '''+ RemoveChar(P_Condate.Text,'-')+''', '+
' '''+ FloatToStr(p_cprice.Value) +''', '+
' TO_CHAR(SYSDATE,''YYYYMMDDHH24MI'') , '+
' '''+ sEmpno +''' )';
end
else
begin
if Copy(RemoveChar(P_Condate.Text,'-'),1,6) <> Copy(vSysDate,1,6) then
begin
ShowMessage('당월에만 종가 수정이 가능합니다. 변경후 작업하시기 바랍니다.');
Exit;
end;
ParamSQL := 'Update pstockbas '+#13+
' Set cprice = '''+ FloatToStr(p_cprice.Value) +''', '+#13+
' writetime = TO_CHAR(SYSDATE,''YYYYMMDDHH24MI''), '+#13+
' writeman = '''+ sEmpno +''' '+#13+
' Where Stockdate = '''+ RemoveChar(P_Condate.Text,'-')+''' ';
end;
TMaxDataSet.Close;
with TMaxDataSet do
begin
ServiceName := 'PSC1040C_dml';
Close;
Sql.Clear;
Sql.Add(ParamSQL); //edit1.text := SQl.text;
if not TMaxDataSet.Execute then
begin
ShowMessage('종가 저장중 에러가 발생했습니다.');
System.Exit;
end;
end;
Application.ProcessMessages;
RetrieveData;
StatusBar1.Panels[1].Text := '종가 저장 완료';
end;
procedure TFM_Main.DataSource1DataChange(Sender: TObject; Field: TField);
begin
P_Condate.Text := TMaxGrid.Fields[0].AsString;
if TMaxGrid.Fields[1].AsString <> '' then
P_cprice.Value := StrToInt(TMaxGrid.Fields[1].AsString);
end;
procedure TFM_Main.P_CondateChange(Sender: TObject);
begin
if Length(Trim(P_Condate.Text)) = 10 then P_cprice.SetFocus;
end;
procedure TFM_Main.P_cpriceKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then BT_Save.SetFocus;
end;
procedure TFM_Main.BT_SearchClick(Sender: TObject);
begin
RetrieveData;
end;
end.
|
unit TechniSatAPI;
{$mode objfpc}{$H+}
{$MACRO ON}
{____________________________________________________________
| _______________________________________________________ |
| | | |
| | Remote API for TechniSat based devices | |
| | (c) 2019 Alexander Feuster (alexander.feuster@web.de) | |
| | http://www.github.com/feuster | |
| |_______________________________________________________| |
|___________________________________________________________}
//define API basics
{$DEFINE APIVERSION:='1.1'}
//{$DEFINE TSAPI_DEBUG}
{___________________________________________________________}
interface
uses
Classes, SysUtils, IdUDPClient, IdStack, IdGlobal, StrUtils, XMLRead, DOM
{$IFDEF LCL}, Forms{$IFDEF TSAPI_DEBUG}, Dialogs{$ENDIF}{$ENDIF}
;
function tsapi_Info_DeviceList(TimeoutMS: Integer): TStringList;
function tsapi_Info_DeviceInformation(URL: String; TimeoutMS: Integer): TStringList;
function tsapi_Info_GetURLByDeviceList(SearchCriteria: String; TimeoutMS: Integer): String;
function tsapi_Info_Authentication(URL: String; PIN: String; TimeoutMS: Integer): Boolean;
function tsapi_Info_KeepAlive(URL: String; TimeoutMS: Integer): Boolean;
function tsapi_rcuButtonRequest(URL: String; PIN: String; ButtonCode: Byte; ButtonState: String; TimeoutMS: Integer): Boolean;
function tsapi_rcuButtonRequestByName(DeviceName: String; PIN: String; ButtonCode: Byte; ButtonState: String; TimeoutMS: Integer): Boolean;
function tsapi_rcuButtonRequestBySerial(Serial: String; PIN: String; ButtonCode: Byte; ButtonState: String; TimeoutMS: Integer): Boolean;
function tsapi_zoomRequest(URL: String; PIN: String; ZoomValue: Integer; TimeoutMS: Integer): Boolean;
function tsapi_mouseMoveRequest(URL: String; PIN: String; deltaX: Integer; deltaY: Integer; TimeoutMS: Integer): Boolean;
function tsapi_mouseScrollRequest(URL: String; PIN: String; deltaS: Integer; TimeoutMS: Integer): Boolean;
function tsapi_mouseClickRequest(URL: String; PIN: String; MouseButton: String; MouseState: String; TimeoutMS: Integer): Boolean;
function tsapi_inputTextRequest(URL: String; PIN: String; InputText: String; Enter: Boolean; TimeoutMS: Integer): Boolean;
function tsapi_BtnCodeByName(ButtonName: String): Byte;
function tsapi_BtnDescByName(ButtonName: String): String;
function tsapi_BtnNameByCode(ButtonCode: Byte): String;
function tsapi_BtnDescByCode(ButtonCode: Byte): String;
type
TButton = record
Code: Byte;
Name: String;
Description: String;
end;
{$IFDEF TSAPI_DEBUG}
var
//storage variable for last debug message
tsapi_Debug_NoShowMessage: Boolean;
tsapi_Debug_Message: String;
{$ENDIF}
const
API_Version: String = APIVERSION;
{$IFDEF TSAPI_DEBUG}
//Debug message strings
STR_Error: String = 'Debug: Error: ';
STR_Info: String = 'Debug: Info: ';
STR_Space: String = ' ';
//Define DEBUG constant
TSAPI_DEBUG: Boolean = true;
{$ELSE}
TSAPI_DEBUG: Boolean = false;
{$ENDIF}
API_License: String = '--------------------------------------------------------------------------------'+#13#10#13#10+
'TechniSat API V'+APIVERSION+' (c) 2019 Alexander Feuster (alexander.feuster@web.de)'+#13#10+
'http://www.github.com/feuster'+#13#10+
'This API is provided "as-is" without any warranties for any data loss,'+#13#10+
'device defects etc. Use at own risk!'+#13#10+
'Free for personal use. Commercial use is prohibited without permission.'+#13#10#13#10+
'--------------------------------------------------------------------------------'+#13#10#13#10+
'Indy BSD License'+#13#10+
#13#10+
'Copyright'+#13#10+
#13#10+
'Portions of this software are Copyright (c) 1993 - 2003, Chad Z. Hower (Kudzu)'+#13#10+
'and the Indy Pit Crew - http://www.IndyProject.org/'+#13#10+
#13#10+
'License'+#13#10+
#13#10+
'Redistribution and use in source and binary forms, with or without modification,'+#13#10+
'are permitted provided that the following conditions are met: Redistributions'+#13#10+
'of source code must retain the above copyright notice, this list of conditions'+#13#10+
'and the following disclaimer.'+#13#10+
#13#10+
'Redistributions in binary form must reproduce the above copyright notice, this'+#13#10+
'list of conditions and the following disclaimer in the documentation, about box'+#13#10+
'and/or other materials provided with the distribution.'+#13#10+
#13#10+
'No personal names or organizations names associated with the Indy project may'+#13#10+
'be used to endorse or promote products derived from this software without'+#13#10+
'specific prior written permission of the specific individual or organization.'+#13#10+
#13#10+
'THIS SOFTWARE IS PROVIDED BY Chad Z. Hower (Kudzu) and the Indy Pit Crew "AS'+#13#10+
'IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE'+#13#10+
'IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE'+#13#10+
'DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY'+#13#10+
'DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES'+#13#10+
'(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;'+#13#10+
'LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON'+#13#10+
'ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT'+#13#10+
'(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS'+#13#10+
'SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.'+#13#10#13#10+
'-------------------------[scroll up for full License]--------------------------'+#13#10#13#10;
tsapi_deviceDiscoveryRequest: String = '<deviceDiscoveryRequest/>';
tsapi_deviceInformationRequest: String = '<deviceInformationRequest/>';
tsapi_keepAliveRequest: String = '<keepAliveRequest/>';
tsapi_keepAliveResponse: String = '<keepAliveResponse/>';
tsapi_ListenerPort: Integer = 8090;
tsapi_TimeoutMS_Max: Integer = 1000;
tsapi_ButtonState_pressed: String = 'pressed';
tsapi_ButtonState_released: String = 'released';
tsapi_ButtonState_hold: String = 'hold';
tsapi_ButtonStates: array[0..2] of String = ('pressed', 'released', 'hold');
tsapi_MouseState_pressed: String = 'pressed';
tsapi_MouseState_released: String = 'released';
tsapi_MouseButtons: array[0..2] of String = ('left', 'middle', 'right');
tsapi_MouseStates: array[0..1] of String = ('pressed', 'released');
tsapi_Buttons: array[0..128] of TButton =
(
(Code: 0; Name: 'BTN_0'; Description: '0'),
(Code: 1; Name: 'BTN_1'; Description: '1'),
(Code: 2; Name: 'BTN_2'; Description: '2'),
(Code: 3; Name: 'BTN_3'; Description: '3'),
(Code: 4; Name: 'BTN_4'; Description: '4'),
(Code: 5; Name: 'BTN_5'; Description: '5'),
(Code: 6; Name: 'BTN_6'; Description: '6'),
(Code: 7; Name: 'BTN_7'; Description: '7'),
(Code: 8; Name: 'BTN_8'; Description: '8'),
(Code: 9; Name: 'BTN_9'; Description: '9'),
(Code: 10; Name: 'BTN_SWITCHDEC'; Description: 'SWITCH DEC'),
(Code: 11; Name: 'BTN_STANDBY'; Description: 'STANDBY'),
(Code: 12; Name: 'BTN_MUTE'; Description: 'MUTE'),
(Code: 13; Name: 'BTN_NOTUSED13'; Description: 'BUTTON 13 NOT USED'),
(Code: 14; Name: 'BTN_LIST'; Description: 'LIST'),
(Code: 15; Name: 'BTN_VOL_UP'; Description: 'VOLUME UP'),
(Code: 16; Name: 'BTN_VOL_DOWN'; Description: 'VOLUME DOWN'),
(Code: 17; Name: 'BTN_HELP'; Description: 'HELP'),
(Code: 18; Name: 'BTN_PROG_UP'; Description: 'PROGRAM UP'),
(Code: 19; Name: 'BTN_PROG_DOWN'; Description: 'PROGRAM DOWN'),
(Code: 20; Name: 'BTN_BACK'; Description: 'BACK'),
(Code: 21; Name: 'BTN_AUDIO'; Description: 'AUDIO'),
(Code: 22; Name: 'BTN_STILL'; Description: 'STILL'),
(Code: 23; Name: 'BTN_EPG'; Description: 'SFI/EPG'),
(Code: 24; Name: 'BTN_EXT'; Description: 'EXT'),
(Code: 25; Name: 'BTN_TXT'; Description: 'TELETEXT'),
(Code: 26; Name: 'BTN_OFF'; Description: 'OFF'),
(Code: 27; Name: 'BTN_TOGGLEIRC'; Description: 'TOGGLE IRC'),
(Code: 28; Name: 'BTN_TVSAT'; Description: 'TV/SAT'),
(Code: 29; Name: 'BTN_INFO'; Description: 'INFO'),
(Code: 30; Name: 'BTN_UP'; Description: 'UP'),
(Code: 31; Name: 'BTN_DOWN'; Description: 'DOWN'),
(Code: 32; Name: 'BTN_MENU'; Description: 'MENU'),
(Code: 33; Name: 'BTN_TVRADIO'; Description: 'TV/RADIO'),
(Code: 34; Name: 'BTN_LEFT'; Description: 'LEFT'),
(Code: 35; Name: 'BTN_RIGHT'; Description: 'RIGHT'),
(Code: 36; Name: 'BTN_OK'; Description: 'OK'),
(Code: 37; Name: 'BTN_RED'; Description: 'RED'),
(Code: 38; Name: 'BTN_GREEN'; Description: 'GREEN'),
(Code: 39; Name: 'BTN_YELLOW'; Description: 'YELLOW'),
(Code: 40; Name: 'BTN_BLUE'; Description: 'BLUE'),
(Code: 41; Name: 'BTN_OPTION'; Description: 'OPTION'),
(Code: 42; Name: 'BTN_SLEEP'; Description: 'SLEEP'),
(Code: 43; Name: 'BTN_REC'; Description: 'RECORD'),
(Code: 44; Name: 'BTN_PIP'; Description: 'PIP/PAP'),
(Code: 45; Name: 'BTN_ZOOM'; Description: 'ZOOM'),
(Code: 46; Name: 'BTN_GENRE'; Description: 'GENRE'),
(Code: 47; Name: 'BTN_HDMI'; Description: 'HDMI'),
(Code: 48; Name: 'BTN_MORE'; Description: 'MORE'),
(Code: 49; Name: 'BTN_REWIND'; Description: 'REWIND'),
(Code: 50; Name: 'BTN_STOP'; Description: 'STOP'),
(Code: 51; Name: 'BTN_PLAYPAUSE'; Description: 'PLAY/PAUSE'),
(Code: 52; Name: 'BTN_WIND'; Description: 'FORWARD WIND'),
(Code: 53; Name: 'BTN_CODESAT1'; Description: 'CODE SAT1'),
(Code: 54; Name: 'BTN_CODESAT2'; Description: 'CODE SAT2'),
(Code: 55; Name: 'BTN_CODETV1'; Description: 'CODE TV1'),
(Code: 56; Name: 'BTN_CODETV2'; Description: 'CODE TV2'),
(Code: 57; Name: 'BTN_CODEVCR1'; Description: 'CODE VCR1'),
(Code: 58; Name: 'BTN_CODEVCR2'; Description: 'CODE VCR2'),
(Code: 59; Name: 'BTN_FREESATBACK';Description: 'FREESAT BACK'),
(Code: 60; Name: 'BTN_AD'; Description: 'AD'),
(Code: 61; Name: 'BTN_SUBTITLE'; Description: 'SUBTITLE'),
(Code: 62; Name: 'BTN_NAV'; Description: 'NAVIGATION'),
(Code: 63; Name: 'BTN_PAGEUP'; Description: 'PAGE UP'),
(Code: 64; Name: 'BTN_PAGEDOWN'; Description: 'PAGE DOWN'),
(Code: 65; Name: 'BTN_PVR'; Description: 'PVR'),
(Code: 66; Name: 'BTN_WWW'; Description: 'WWW'),
(Code: 67; Name: 'BTN_TIMER'; Description: 'TIMER'),
(Code: 68; Name: 'BTN_NOTUSED68'; Description: 'BUTTON 68 NOT USED'),
(Code: 69; Name: 'BTN_NOTUSED69'; Description: 'BUTTON 69 NOT USED'),
(Code: 70; Name: 'BTN_NOTUSED70'; Description: 'BUTTON 70 NOT USED'),
(Code: 71; Name: 'BTN_NOTUSED71'; Description: 'BUTTON 71 NOT USED'),
(Code: 72; Name: 'BTN_NOTUSED72'; Description: 'BUTTON 72 NOT USED'),
(Code: 73; Name: 'BTN_NOTUSED73'; Description: 'BUTTON 73 NOT USED'),
(Code: 74; Name: 'BTN_NOTUSED74'; Description: 'BUTTON 74 NOT USED'),
(Code: 75; Name: 'BTN_NOTUSED75'; Description: 'BUTTON 75 NOT USED'),
(Code: 76; Name: 'BTN_NOTUSED76'; Description: 'BUTTON 76 NOT USED'),
(Code: 77; Name: 'BTN_NOTUSED77'; Description: 'BUTTON 77 NOT USED'),
(Code: 78; Name: 'BTN_NOTUSED78'; Description: 'BUTTON 78 NOT USED'),
(Code: 79; Name: 'BTN_NOTUSED79'; Description: 'BUTTON 79 NOT USED'),
(Code: 80; Name: 'BTN_NOTUSED80'; Description: 'BUTTON 80 NOT USED'),
(Code: 81; Name: 'BTN_NOTUSED80'; Description: 'BUTTON 81 NOT USED'),
(Code: 82; Name: 'BTN_NOTUSED80'; Description: 'BUTTON 82 NOT USED'),
(Code: 83; Name: 'BTN_NOTUSED80'; Description: 'BUTTON 83 NOT USED'),
(Code: 84; Name: 'BTN_NOTUSED80'; Description: 'BUTTON 84 NOT USED'),
(Code: 85; Name: 'BTN_NOTUSED80'; Description: 'BUTTON 85 NOT USED'),
(Code: 86; Name: 'BTN_NOTUSED80'; Description: 'BUTTON 86 NOT USED'),
(Code: 87; Name: 'BTN_NOTUSED80'; Description: 'BUTTON 87 NOT USED'),
(Code: 88; Name: 'BTN_NOTUSED80'; Description: 'BUTTON 88 NOT USED'),
(Code: 89; Name: 'BTN_NOTUSED80'; Description: 'BUTTON 89 NOT USED'),
(Code: 90; Name: 'BTN_NOTUSED90'; Description: 'BUTTON 90 NOT USED'),
(Code: 91; Name: 'BTN_NOTUSED91'; Description: 'BUTTON 91 NOT USED'),
(Code: 92; Name: 'BTN_NOTUSED92'; Description: 'BUTTON 92 NOT USED'),
(Code: 93; Name: 'BTN_NOTUSED93'; Description: 'BUTTON 93 NOT USED'),
(Code: 94; Name: 'BTN_NOTUSED94'; Description: 'BUTTON 94 NOT USED'),
(Code: 95; Name: 'BTN_NOTUSED95'; Description: 'BUTTON 95 NOT USED'),
(Code: 96; Name: 'BTN_NOTUSED96'; Description: 'BUTTON 96 NOT USED'),
(Code: 97; Name: 'BTN_NOTUSED97'; Description: 'BUTTON 97 NOT USED'),
(Code: 98; Name: 'BTN_NOTUSED98'; Description: 'BUTTON 98 NOT USED'),
(Code: 99; Name: 'BTN_NOTUSED99'; Description: 'BUTTON 99 NOT USED'),
(Code: 100; Name: 'BTN_NOTUSED100'; Description: 'BUTTON 100 NOT USED'),
(Code: 101; Name: 'BTN_NOTUSED101'; Description: 'BUTTON 101 NOT USED'),
(Code: 102; Name: 'BTN_NOTUSED102'; Description: 'BUTTON 102 NOT USED'),
(Code: 103; Name: 'BTN_NOTUSED103'; Description: 'BUTTON 103 NOT USED'),
(Code: 104; Name: 'BTN_NOTUSED104'; Description: 'BUTTON 104 NOT USED'),
(Code: 105; Name: 'BTN_NOTUSED105'; Description: 'BUTTON 105 NOT USED'),
(Code: 106; Name: 'BTN_KBDF1'; Description: 'KEYBOARD F1'),
(Code: 107; Name: 'BTN_KBDF2'; Description: 'KEYBOARD F2'),
(Code: 108; Name: 'BTN_KBDF3'; Description: 'KEYBOARD F3'),
(Code: 109; Name: 'BTN_KBDF4'; Description: 'KEYBOARD F4'),
(Code: 110; Name: 'BTN_KBDF5'; Description: 'KEYBOARD F5'),
(Code: 111; Name: 'BTN_KBDF6'; Description: 'KEYBOARD F6'),
(Code: 112; Name: 'BTN_KBDF7'; Description: 'KEYBOARD F7'),
(Code: 113; Name: 'BTN_KBDF8'; Description: 'KEYBOARD F8'),
(Code: 114; Name: 'BTN_KBDF9'; Description: 'KEYBOARD F9'),
(Code: 115; Name: 'BTN_KBDF10'; Description: 'KEYBOARD F10'),
(Code: 116; Name: 'BTN_KBDF11'; Description: 'KEYBOARD F11'),
(Code: 117; Name: 'BTN_KBDF12'; Description: 'KEYBOARD F12'),
(Code: 118; Name: 'BTN_SOFTKEY1'; Description: 'SOFTKEY 1'),
(Code: 119; Name: 'BTN_SOFTKEY2'; Description: 'SOFTKEY 2'),
(Code: 120; Name: 'BTN_SOFTKEY3'; Description: 'SOFTKEY 3'),
(Code: 121; Name: 'BTN_SOFTKEY4'; Description: 'SOFTKEY 4'),
(Code: 122; Name: 'BTN_KBDINFO'; Description: 'KEYBOARD INFO'),
(Code: 123; Name: 'BTN_KBDDOWN'; Description: 'KEYBOARD DOWN'),
(Code: 124; Name: 'BTN_KBDUP'; Description: 'KEYBOARD UP'),
(Code: 125; Name: 'BTN_KBDMODE'; Description: 'KEYBOARD MODE'),
(Code: 126; Name: 'BTN_DOFLASH'; Description: 'DO FLASH RESET'),
(Code: 127; Name: 'BTN_NOTDEFINED'; Description: 'BUTTON NOT DEFINED'),
(Code: 128; Name: 'BTN_INVALID'; Description: 'BUTTON INVALID')
);
implementation
{$IFDEF TSAPI_DEBUG}
procedure DebugPrint(DebugText: String);
//generate debug messages for Console or GUI application
begin
tsapi_Debug_Message:=tsapi_Debug_Message+#13#10+DebugText;
{$IFNDEF LCL}
WriteLn(tsapi_Debug_Message);
{$ELSE}
if fsapi_Debug_NoShowMessage=false then
ShowMessage(tsapi_Debug_Message);
{$ENDIF}
end;
{$ENDIF}
//------------------------------------------------------------------------------
// Helper functions
//------------------------------------------------------------------------------
function tsapi_BtnCodeByName(ButtonName: String): Byte;
//read button code from given button name
var
Counter: Byte;
begin
//set default result to invalid button
Result:=128;
//Check if string is not empty
if ButtonName='' then
exit;
//allow also KEY_ for BTN_
if LeftStr(UpperCase(ButtonName),4)='KEY_' then
ButtonName:=StringReplace(ButtonName, 'KEY_', 'BTN_', [rfReplaceAll, rfIgnoreCase]);
//Check if string starts with BTN_
if LeftStr(UpperCase(ButtonName),4)<>'BTN_' then
exit;
//Read code from array
for Counter:=0 to Length(tsapi_Buttons) do
begin
if tsapi_Buttons[Counter].Name=UpperCase(ButtonName) then
begin
Result:=tsapi_Buttons[Counter].Code;
exit;
end;
end;
end;
function tsapi_BtnDescByName(ButtonName: String): String;
//read button description from given button name
begin
Result:=tsapi_BtnDescByCode(tsapi_BtnCodeByName(ButtonName));
end;
function tsapi_BtnNameByCode(ButtonCode: Byte): String;
//read button name from given button code
begin
//set default result to invalid button
Result:=tsapi_Buttons[128].Name;
//Check if button code is valid
if ButtonCode>128 then
exit;
//Read name from array
Result:=tsapi_Buttons[ButtonCode].Name;
end;
function tsapi_BtnDescByCode(ButtonCode: Byte): String;
//read button description from given button code
begin
//set default result to invalid button
Result:=tsapi_Buttons[128].Description;
//Check if button code is valid
if ButtonCode>128 then
exit;
//Read name from array
Result:=tsapi_Buttons[ButtonCode].Description;
end;
//------------------------------------------------------------------------------
// Info
//------------------------------------------------------------------------------
function tsapi_Info_DeviceList(TimeoutMS: Integer): TStringList;
//List available devices from network
var
Buffer: String;
DeviceList: TStringList;
UDPClient: TIdUDPClient;
UDPPeerPort: Word;
UDPPeerIP: String;
Response: String;
XMLBuffer: TStringStream;
XML: TXMLDocument;
Node: TDOMNode;
begin
try
UDPClient:=TIdUDPClient.Create(nil);
DeviceList:=TStringList.Create;
DeviceList.TextLineBreakStyle:=tlbsCRLF;
DeviceList.Duplicates:=dupIgnore;
DeviceList.SortStyle:=sslAuto;
try
//send discovery request broadcast
UDPClient.BoundIP:=GStack.LocalAddress;
UDPClient.BoundPort:=tsapi_ListenerPort;
UDPClient.Port:=tsapi_ListenerPort;
UDPClient.BroadcastEnabled:=true;
UDPClient.Send('255.255.255.255', tsapi_ListenerPort, tsapi_deviceDiscoveryRequest);
UDPClient.Send('255.255.255.255', tsapi_ListenerPort, tsapi_deviceDiscoveryRequest);
UDPClient.Send('255.255.255.255', tsapi_ListenerPort, tsapi_deviceDiscoveryRequest);
//check for discovery request answers
if TimeoutMS>0 then
UDPClient.ReceiveTimeout:=TimeoutMS
else
UDPClient.ReceiveTimeout:=tsapi_TimeoutMS_Max;
repeat
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Response:=UDPClient.ReceiveString(UDPPeerIP, UDPPeerPort);
//discovery request response received
if (UDPPeerPort<>0) and (GStack.LocalAddress<>UDPPeerIP) then
begin
{$IFDEF TSAPI_DEBUG}{$IFNDEF LCL}
WriteLn(STR_Info,'Response from ',Format('%s:%d', [UDPPeerIP, UDPPeerPort]));
writeln(STR_Info,'tsapi_Info_DeviceList -> RESPONSE BEGIN');
writeln('--------------------------------------------------------------------------------');
Writeln(Response);
writeln('--------------------------------------------------------------------------------');
writeln(STR_Info,'tsapi_Info_DeviceList -> RESPONSE END'+#13#10+#13#10);
{$ENDIF}{$ENDIF}
//extract device infos from response
if AnsiPos('deviceDiscoveryResponse', Response)>0 then
begin
Buffer:=UDPPeerIP+'|';
XMLBuffer:=TStringStream.Create(Trim(Response));
ReadXMLFile(XML, XMLBuffer);
Node:=XML.DocumentElement.ParentNode.FirstChild;
if Node<>NIL then
begin
Buffer:=Buffer+(String(Node.Attributes.GetNamedItem('name').NodeValue))+'|';
Buffer:=Buffer+(String(Node.Attributes.GetNamedItem('type').NodeValue))+'|';
Buffer:=Buffer+(String(Node.Attributes.GetNamedItem('serial').NodeValue))+'|';
Buffer:=Buffer+(String(Node.Attributes.GetNamedItem('version').NodeValue));
end;
if Node<>NIL then Node.Free;
if XML<>NIL then XML.Free;
if XMLBuffer<>NIL then XMLBuffer.Free;
DeviceList.Add(Buffer);
end;
end;
until UDPPeerPort=0;
//sort list
DeviceList.Sort;
finally
UDPClient.Free;
end;
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Result:=DeviceList;
except
on E:Exception do
begin
{$IFDEF FSAPI_DEBUG}E.Message:=STR_Error+'tsapi_Info_DeviceList -> '+E.Message; DebugPrint(E.Message);{$ENDIF}
Result:=DeviceList;
end;
end;
end;
function tsapi_Info_DeviceInformation(URL: String; TimeoutMS: Integer): TStringList;
//List device information
var
DeviceInfo: TStringList;
UDPClient: TIdUDPClient;
UDPPeerPort: Word;
UDPPeerIP: String;
Response: String;
XMLBuffer: TStringStream;
XML: TXMLDocument;
Node: TDOMNode;
Node2: TDOMNode;
Node3: TDOMNode;
Counter: LongWord;
Counter2: LongWord;
Buffer: String;
begin
try
UDPClient:=TIdUDPClient.Create(nil);
DeviceInfo:=TStringList.Create;
DeviceInfo.TextLineBreakStyle:=tlbsCRLF;
DeviceInfo.Duplicates:=dupIgnore;
DeviceInfo.SortStyle:=sslAuto;
//check if URL is available
if URL='' then
begin
Result:=DeviceInfo;
exit;
end;
try
//send device information
UDPClient.BoundIP:=GStack.LocalAddress;
UDPClient.BoundPort:=tsapi_ListenerPort;
UDPClient.Port:=tsapi_ListenerPort;
UDPClient.BroadcastEnabled:=true;
UDPClient.Send(URL, tsapi_ListenerPort, tsapi_deviceInformationRequest);
//check for device information request answers
if TimeoutMS>0 then
UDPClient.ReceiveTimeout:=TimeoutMS
else
UDPClient.ReceiveTimeout:=tsapi_TimeoutMS_Max;
repeat
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Response:=UDPClient.ReceiveString(UDPPeerIP, UDPPeerPort);
//discovery request response received
if (UDPPeerPort<>0) and (GStack.LocalAddress<>UDPPeerIP) then
begin
{$IFDEF TSAPI_DEBUG}{$IFNDEF LCL}
WriteLn(STR_Info,'Response from ',Format('%s:%d', [UDPPeerIP, UDPPeerPort]));
writeln(STR_Info,'tsapi_Info_DeviceInformation -> RESPONSE BEGIN');
writeln('--------------------------------------------------------------------------------');
Writeln(Response);
writeln('--------------------------------------------------------------------------------');
writeln(STR_Info,'tsapi_Info_DeviceInformation -> RESPONSE END'+#13#10+#13#10);
{$ENDIF}{$ENDIF}
//extract device infos from response
if AnsiPos('deviceInformationResponse', Response)>0 then
begin
XMLBuffer:=TStringStream.Create(Trim(Response));
ReadXMLFile(XML, XMLBuffer);
Node:=XML.DocumentElement.ParentNode.FirstChild;
if Node<>NIL then
begin
for Counter:=0 to Node.Attributes.Length-1 do
begin
if String(Node.Attributes.Item[Counter].NodeValue)<>'' then
begin
Buffer:=String(Node.Attributes.Item[Counter].NodeName+'='+Node.Attributes.Item[Counter].NodeValue);
DeviceInfo.Add(Trim(Buffer));
end;
end;
//extract additional information like capabilities
for Counter:=0 to Node.GetChildNodes.Count-1 do
begin
Node2:=Node.GetChildNodes.Item[Counter];
if String(Node2.NodeName)<>'' then
begin
for Counter2:=0 to Node2.GetChildNodes.Count-1 do
begin
Buffer:=String(Node2.NodeName+':'+Node2.GetChildNodes.Item[Counter2].NodeName+Node2.GetChildNodes.Item[Counter2].NodeValue);
Node3:=Node2.GetChildNodes.Item[Counter2].FirstChild;
if Node3<>NIL then
begin
if String(Node3.NodeValue)<>'' then
Buffer:=Buffer+'='+String(Node3.NodeValue);
end;
DeviceInfo.Add(Trim(Buffer));
end;
end;
end;
end;
//clean up variables
if Node<>NIL then Node.Free;
if Node2<>NIL then Node2.Free;
if Node3<>NIL then Node3.Free;
if XML<>NIL then XML.Free;
if XMLBuffer<>NIL then XMLBuffer.Free;
end;
end;
until UDPPeerPort=0;
//sort list
DeviceInfo.Sort;
finally
UDPClient.Free;
end;
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Result:=DeviceInfo;
except
on E:Exception do
begin
{$IFDEF FSAPI_DEBUG}E.Message:=STR_Error+'tsapi_Info_DeviceInformation -> '+E.Message; DebugPrint(E.Message);{$ENDIF}
Result:=DeviceInfo;
end;
end;
end;
function tsapi_Info_Authentication(URL: String; PIN: String; TimeoutMS: Integer): Boolean;
//Device authentication with PIN
var
Authentication: Boolean;
UDPClient: TIdUDPClient;
UDPPeerPort: Word;
UDPPeerIP: String;
Response: String;
XMLBuffer: TStringStream;
XML: TXMLDocument;
Node: TDOMNode;
begin
try
UDPClient:=TIdUDPClient.Create(nil);
Authentication:=false;
//check if URL is available
if URL='' then
begin
Result:=Authentication;
exit;
end;
//check if PIN is available, if not try fallback to default value
if PIN='' then PIN:='0000';
try
//send authentication request
UDPClient.BoundIP:=GStack.LocalAddress;
UDPClient.BoundPort:=tsapi_ListenerPort;
UDPClient.Port:=tsapi_ListenerPort;
UDPClient.BroadcastEnabled:=true;
UDPClient.Send(URL, tsapi_ListenerPort, '<authenticationRequest pin="'+PIN+'"/>');
//check authentication request answer
if TimeoutMS>0 then
UDPClient.ReceiveTimeout:=TimeoutMS
else
UDPClient.ReceiveTimeout:=tsapi_TimeoutMS_Max;
repeat
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Response:=UDPClient.ReceiveString(UDPPeerIP, UDPPeerPort);
//discovery request response received
if (UDPPeerPort<>0) and (GStack.LocalAddress<>UDPPeerIP) then
begin
{$IFDEF TSAPI_DEBUG}{$IFNDEF LCL}
WriteLn(STR_Info,'Response from ',Format('%s:%d', [UDPPeerIP, UDPPeerPort]));
writeln(STR_Info,'tsapi_Info_Authentication -> RESPONSE BEGIN');
writeln('--------------------------------------------------------------------------------');
Writeln(Response);
writeln('--------------------------------------------------------------------------------');
writeln(STR_Info,'tsapi_Info_Authentication -> RESPONSE END'+#13#10+#13#10);
{$ENDIF}{$ENDIF}
//check authentication response
if AnsiPos('authenticationResponse', Response)>0 then
begin
XMLBuffer:=TStringStream.Create(Trim(Response));
ReadXMLFile(XML, XMLBuffer);
Node:=XML.DocumentElement.ParentNode.FirstChild;
if Node<>NIL then
begin
if UpperCase((String(Node.Attributes.GetNamedItem('result').NodeValue)))='SUCCESS' then
Authentication:=true
else
Authentication:=false;
end;
if Node<>NIL then Node.Free;
if XML<>NIL then XML.Free;
if XMLBuffer<>NIL then XMLBuffer.Free;
end;
end;
until UDPPeerPort=0;
finally
UDPClient.Free;
end;
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Result:=Authentication;
except
on E:Exception do
begin
{$IFDEF FSAPI_DEBUG}E.Message:=STR_Error+'tsapi_Info_Authentication -> '+E.Message; DebugPrint(E.Message);{$ENDIF}
Result:=false;
end;
end;
end;
function tsapi_Info_KeepAlive(URL: String; TimeoutMS: Integer): Boolean;
//Device keep alive check
var
KeepAlive: Boolean;
UDPClient: TIdUDPClient;
UDPPeerPort: Word;
UDPPeerIP: String;
Response: String;
begin
try
UDPClient:=TIdUDPClient.Create(nil);
KeepAlive:=false;
//check if URL is available
if URL='' then
begin
Result:=KeepAlive;
exit;
end;
try
//send keep alive request
UDPClient.BoundIP:=GStack.LocalAddress;
UDPClient.BoundPort:=tsapi_ListenerPort;
UDPClient.Port:=tsapi_ListenerPort;
UDPClient.BroadcastEnabled:=true;
UDPClient.Send(URL, tsapi_ListenerPort, tsapi_keepAliveRequest);
//check keep alive request answer
if TimeoutMS>0 then
UDPClient.ReceiveTimeout:=TimeoutMS
else
UDPClient.ReceiveTimeout:=tsapi_TimeoutMS_Max;
repeat
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Response:=UDPClient.ReceiveString(UDPPeerIP, UDPPeerPort);
//keep alive request response received
if (UDPPeerPort<>0) and (GStack.LocalAddress<>UDPPeerIP) then
begin
{$IFDEF TSAPI_DEBUG}{$IFNDEF LCL}
WriteLn(STR_Info,'Response from ',Format('%s:%d', [UDPPeerIP, UDPPeerPort]));
writeln(STR_Info,'tsapi_Info_KeepAlive -> RESPONSE BEGIN');
writeln('--------------------------------------------------------------------------------');
Writeln(Response);
writeln('--------------------------------------------------------------------------------');
writeln(STR_Info,'tsapi_Info_KeepAlive -> RESPONSE END'+#13#10+#13#10);
{$ENDIF}{$ENDIF}
//check keep alive response
if AnsiPos(tsapi_keepAliveResponse, Response)>0 then
KeepAlive:=true
else
KeepAlive:=false;
end;
until UDPPeerPort=0;
finally
UDPClient.Free;
end;
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Result:=KeepAlive;
except
on E:Exception do
begin
{$IFDEF FSAPI_DEBUG}E.Message:=STR_Error+'tsapi_Info_KeepAlive -> '+E.Message; DebugPrint(E.Message);{$ENDIF}
Result:=false;
end;
end;
end;
//------------------------------------------------------------------------------
// Button Request
//------------------------------------------------------------------------------
function tsapi_rcuButtonRequest(URL: String; PIN: String; ButtonCode: Byte; ButtonState: String; TimeoutMS: Integer): Boolean;
//Device button request
var
rcuBtnRequest: Boolean;
UDPClient: TIdUDPClient;
UDPPeerPort: Word;
UDPPeerIP: String;
Response: String;
begin
try
UDPClient:=TIdUDPClient.Create(nil);
rcuBtnRequest:=false;
//check if URL and button code is available and not invalid
if (URL='') or (ButtonCode>Length(tsapi_Buttons)-1) then
begin
Result:=rcuBtnRequest;
exit;
end;
//check if ButtonState is correct
if AnsiIndexText(ButtonState, tsapi_ButtonStates)<0 then
ButtonState:=tsapi_ButtonStates[0];
try
//check if device reacts on keep alive request
if tsapi_Info_KeepAlive(URL, TimeoutMS)=false then
begin
//keep alive failed so try to authenticate
if tsapi_Info_Authentication(URL, PIN, TimeoutMS)=false then
begin
//Authentication failed also therefore button request can not be send
Result:=rcuBtnRequest;
exit;
end;
end;
//send rcu button request
UDPClient.BoundIP:=GStack.LocalAddress;
UDPClient.BoundPort:=tsapi_ListenerPort;
UDPClient.Port:=tsapi_ListenerPort;
UDPClient.BroadcastEnabled:=true;
UDPClient.Send(URL, tsapi_ListenerPort, '<rcuButtonRequest code="'+IntToStr(ButtonCode)+'" state="'+ButtonState+'"/>');
//check keep alive request answer
if TimeoutMS>0 then
UDPClient.ReceiveTimeout:=TimeoutMS
else
UDPClient.ReceiveTimeout:=tsapi_TimeoutMS_Max;
repeat
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Response:=UDPClient.ReceiveString(UDPPeerIP, UDPPeerPort);
//keep rcu button request response received
if (UDPPeerPort<>0) and (GStack.LocalAddress<>UDPPeerIP) then
begin
{$IFDEF TSAPI_DEBUG}{$IFNDEF LCL}
WriteLn(STR_Info,'Response from ',Format('%s:%d', [UDPPeerIP, UDPPeerPort]));
writeln(STR_Info,'tsapi_rcuButtonRequest -> RESPONSE BEGIN');
writeln('--------------------------------------------------------------------------------');
Writeln(Response);
writeln('--------------------------------------------------------------------------------');
writeln(STR_Info,'tsapi_rcuButtonRequest -> RESPONSE END'+#13#10+#13#10);
{$ENDIF}{$ENDIF}
//check button request response if available
if Response<>'' then
begin
if AnsiPos('rcuButtonRequest', Response)>0 then
rcuBtnRequest:=true
else
rcuBtnRequest:=false;
end
else
rcuBtnRequest:=true;
end
else
rcuBtnRequest:=true;
until UDPPeerPort=0;
finally
UDPClient.Free;
end;
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Result:=rcuBtnRequest;
except
on E:Exception do
begin
{$IFDEF FSAPI_DEBUG}E.Message:=STR_Error+'tsapi_rcuButtonRequest -> '+E.Message; DebugPrint(E.Message);{$ENDIF}
Result:=false;
end;
end;
end;
function tsapi_Info_GetURLByDeviceList(SearchCriteria: String; TimeoutMS: Integer): String;
//retrieve URL from device list by a given search criteria
var
DeviceList: TStringList;
Counter: Integer;
Buffer: String;
begin
try
Buffer:='';
//check if search criteria is not empty
if SearchCriteria='' then
begin
Result:=Buffer;
exit;
end;
//read device list
DeviceList:=TStringList.Create;
DeviceList.TextLineBreakStyle:=tlbsCRLF;
DeviceList.Duplicates:=dupIgnore;
DeviceList.SortStyle:=sslAuto;
DeviceList:=tsapi_Info_DeviceList(TimeoutMS);
if DeviceList.Count=0 then
begin
if DeviceList<>NIL then DeviceList.Free;
exit;
end;
//search device URL
for Counter:=0 to DeviceList.Count-1 do
begin
if (UpperCase(SearchCriteria)=Uppercase(DeviceList.Strings[Counter].Split('|')[1])) or (UpperCase(SearchCriteria)=Uppercase(DeviceList.Strings[Counter].Split('|')[2])) or (UpperCase(SearchCriteria)=Uppercase(DeviceList.Strings[Counter].Split('|')[3])) then
begin
Buffer:=DeviceList.Strings[Counter].Split('|')[0];
end;
end;
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Result:=Buffer;
if DeviceList<>NIL then DeviceList.Free;
except
on E:Exception do
begin
{$IFDEF FSAPI_DEBUG}E.Message:=STR_Error+'tsapi_Info_GetURLByDeviceList -> '+E.Message; DebugPrint(E.Message);{$ENDIF}
Result:='';
end;
end;
end;
function tsapi_rcuButtonRequestByName(DeviceName: String; PIN: String; ButtonCode: Byte; ButtonState: String; TimeoutMS: Integer): Boolean;
//Device button request with device name
var
rcuBtnRequest: Boolean;
URL: String;
begin
try
rcuBtnRequest:=false;
//check if device name is not empty
if DeviceName='' then
begin
Result:=rcuBtnRequest;
exit;
end;
//retrieve device URL by name
URL:=tsapi_Info_GetURLByDeviceList(DeviceName,TimeoutMS);
//start now button request with found URL
if URL<>'' then
begin
writeln(URL);
rcuBtnRequest:=tsapi_rcuButtonRequest(URL, PIN, ButtonCode, ButtonState, TimeoutMS);
end;
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Result:=rcuBtnRequest;
except
on E:Exception do
begin
{$IFDEF FSAPI_DEBUG}E.Message:=STR_Error+'tsapi_rcuButtonRequestByName -> '+E.Message; DebugPrint(E.Message);{$ENDIF}
Result:=false;
end;
end;
end;
function tsapi_rcuButtonRequestBySerial(Serial: String; PIN: String; ButtonCode: Byte; ButtonState: String; TimeoutMS: Integer): Boolean;
//Device button request with serial
var
rcuBtnRequest: Boolean;
URL: String;
begin
try
rcuBtnRequest:=false;
//check if serial is not empty
if Serial='' then
begin
Result:=rcuBtnRequest;
exit;
end;
//retrieve device URL by serial
URL:=tsapi_Info_GetURLByDeviceList(Serial,TimeoutMS);
//start now button request with found URL
if URL<>'' then
begin
writeln(URL);
rcuBtnRequest:=tsapi_rcuButtonRequest(URL, PIN, ButtonCode, ButtonState, TimeoutMS);
end;
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Result:=rcuBtnRequest;
except
on E:Exception do
begin
{$IFDEF FSAPI_DEBUG}E.Message:=STR_Error+'tsapi_rcuButtonRequestBySerial -> '+E.Message; DebugPrint(E.Message);{$ENDIF}
Result:=false;
end;
end;
end;
//------------------------------------------------------------------------------
// Zoom Request
//------------------------------------------------------------------------------
function tsapi_zoomRequest(URL: String; PIN: String; ZoomValue: Integer; TimeoutMS: Integer): Boolean;
//Device zoom request
var
ZoomRequest: Boolean;
UDPClient: TIdUDPClient;
begin
try
UDPClient:=TIdUDPClient.Create(nil);
ZoomRequest:=false;
//check if URL and zoom value is available and not invalid
if (URL='') or (ZoomValue=0) then
begin
Result:=ZoomRequest;
exit;
end;
try
//check if device reacts on keep alive request
if tsapi_Info_KeepAlive(URL, TimeoutMS)=false then
begin
//keep alive failed so try to authenticate
if tsapi_Info_Authentication(URL, PIN, TimeoutMS)=false then
begin
//Authentication failed also therefore request can not be send
Result:=ZoomRequest;
exit;
end;
end;
//send zoom request (there will be no response from the device)
UDPClient.BoundIP:=GStack.LocalAddress;
UDPClient.BoundPort:=tsapi_ListenerPort;
UDPClient.Port:=tsapi_ListenerPort;
UDPClient.BroadcastEnabled:=true;
UDPClient.Send(URL, tsapi_ListenerPort, '<zoomRequest zoom="'+IntToStr(ZoomValue)+'"/>');
ZoomRequest:=true;
finally
UDPClient.Free;
end;
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Result:=ZoomRequest;
except
on E:Exception do
begin
{$IFDEF FSAPI_DEBUG}E.Message:=STR_Error+'tsapi_zoomRequest -> '+E.Message; DebugPrint(E.Message);{$ENDIF}
Result:=false;
end;
end;
end;
//------------------------------------------------------------------------------
// Mouse Requests
//------------------------------------------------------------------------------
function tsapi_mouseMoveRequest(URL: String; PIN: String; deltaX: Integer; deltaY: Integer; TimeoutMS: Integer): Boolean;
//Mouse move request
var
MouseRequest: Boolean;
UDPClient: TIdUDPClient;
begin
try
UDPClient:=TIdUDPClient.Create(nil);
MouseRequest:=false;
//check if URL is available
if URL='' then
begin
Result:=MouseRequest;
exit;
end;
try
//check if device reacts on keep alive request
if tsapi_Info_KeepAlive(URL, TimeoutMS)=false then
begin
//keep alive failed so try to authenticate
if tsapi_Info_Authentication(URL, PIN, TimeoutMS)=false then
begin
//Authentication failed also therefore request can not be send
Result:=MouseRequest;
exit;
end;
end;
//send mouse move request (there will be no response from the device)
UDPClient.BoundIP:=GStack.LocalAddress;
UDPClient.BoundPort:=tsapi_ListenerPort;
UDPClient.Port:=tsapi_ListenerPort;
UDPClient.BroadcastEnabled:=true;
UDPClient.Send(URL, tsapi_ListenerPort, '<mouseMoveRequest deltaX="'+IntToStr(deltaX)+'" deltaY="'+IntToStr(deltaY)+'"/>');
MouseRequest:=true;
finally
UDPClient.Free;
end;
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Result:=MouseRequest;
except
on E:Exception do
begin
{$IFDEF FSAPI_DEBUG}E.Message:=STR_Error+'tsapi_mouseMoveRequest -> '+E.Message; DebugPrint(E.Message);{$ENDIF}
Result:=false;
end;
end;
end;
function tsapi_mouseScrollRequest(URL: String; PIN: String; deltaS: Integer; TimeoutMS: Integer): Boolean;
//Mouse move request
var
MouseRequest: Boolean;
UDPClient: TIdUDPClient;
begin
try
UDPClient:=TIdUDPClient.Create(nil);
MouseRequest:=false;
//check if URL is available
if URL='' then
begin
Result:=MouseRequest;
exit;
end;
try
//check if device reacts on keep alive request
if tsapi_Info_KeepAlive(URL, TimeoutMS)=false then
begin
//keep alive failed so try to authenticate
if tsapi_Info_Authentication(URL, PIN, TimeoutMS)=false then
begin
//Authentication failed also therefore request can not be send
Result:=MouseRequest;
exit;
end;
end;
//send mouse move request (there will be no response from the device)
UDPClient.BoundIP:=GStack.LocalAddress;
UDPClient.BoundPort:=tsapi_ListenerPort;
UDPClient.Port:=tsapi_ListenerPort;
UDPClient.BroadcastEnabled:=true;
UDPClient.Send(URL, tsapi_ListenerPort, '<mouseScrollRequest deltaS="'+IntToStr(deltaS)+'"/>');
MouseRequest:=true;
finally
UDPClient.Free;
end;
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Result:=MouseRequest;
except
on E:Exception do
begin
{$IFDEF FSAPI_DEBUG}E.Message:=STR_Error+'tsapi_mouseScrollRequest -> '+E.Message; DebugPrint(E.Message);{$ENDIF}
Result:=false;
end;
end;
end;
function tsapi_mouseClickRequest(URL: String; PIN: String; MouseButton: String; MouseState: String; TimeoutMS: Integer): Boolean;
//Mouse move request
var
MouseRequest: Boolean;
UDPClient: TIdUDPClient;
begin
try
UDPClient:=TIdUDPClient.Create(nil);
MouseRequest:=false;
//check if URL and button code is available and not invalid
if URL='' then
begin
Result:=MouseRequest;
exit;
end;
//check if MouseButton is correct
if AnsiIndexText(MouseButton, tsapi_MouseButtons)<0 then
MouseButton:=tsapi_MouseButtons[0];
//check if MouseState is correct
if AnsiIndexText(MouseState, tsapi_MouseStates)<0 then
MouseState:=tsapi_MouseStates[0];
//check if URL is available
if URL='' then
begin
Result:=MouseRequest;
exit;
end;
try
//check if device reacts on keep alive request
if tsapi_Info_KeepAlive(URL, TimeoutMS)=false then
begin
//keep alive failed so try to authenticate
if tsapi_Info_Authentication(URL, PIN, TimeoutMS)=false then
begin
//Authentication failed also therefore request can not be send
Result:=MouseRequest;
exit;
end;
end;
//send mouse button click request (there will be no response from the device)
UDPClient.BoundIP:=GStack.LocalAddress;
UDPClient.BoundPort:=tsapi_ListenerPort;
UDPClient.Port:=tsapi_ListenerPort;
UDPClient.BroadcastEnabled:=true;
UDPClient.Send(URL, tsapi_ListenerPort, '<mouseButtonRequest button="'+MouseButton+'" state="'+MouseState+'"/>');
MouseRequest:=true;
finally
UDPClient.Free;
end;
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Result:=MouseRequest;
except
on E:Exception do
begin
{$IFDEF FSAPI_DEBUG}E.Message:=STR_Error+'tsapi_mouseClickRequest -> '+E.Message; DebugPrint(E.Message);{$ENDIF}
Result:=false;
end;
end;
end;
//------------------------------------------------------------------------------
// Input Text Request
//------------------------------------------------------------------------------
function tsapi_inputTextRequest(URL: String; PIN: String; InputText: String; Enter: Boolean; TimeoutMS: Integer): Boolean;
//Input character request
var
InputTextRequest: Boolean;
UDPClient: TIdUDPClient;
begin
try
UDPClient:=TIdUDPClient.Create(nil);
InputTextRequest:=false;
//check if URL is available
if (URL='') then
begin
Result:=InputTextRequest;
exit;
end;
try
//check if device reacts on keep alive request
if tsapi_Info_KeepAlive(URL, TimeoutMS)=false then
begin
//keep alive failed so try to authenticate
if tsapi_Info_Authentication(URL, PIN, TimeoutMS)=false then
begin
//Authentication failed also therefore request can not be send
Result:=InputTextRequest;
exit;
end;
end;
if Enter=true then
InputText:='<inputTextRequest enter="true"><![CDATA['+InputText+']]></inputTextRequest>'
else
InputText:='<inputTextRequest enter="false"><![CDATA['+InputText+']]></inputTextRequest>';
//send input character request (there will be no response from the device)
UDPClient.BoundIP:=GStack.LocalAddress;
UDPClient.BoundPort:=tsapi_ListenerPort;
UDPClient.Port:=tsapi_ListenerPort;
UDPClient.BroadcastEnabled:=true;
UDPClient.Send(URL, tsapi_ListenerPort, InputText, IndyTextEncoding(encUTF8));
InputTextRequest:=true;
finally
UDPClient.Free;
end;
{$IFDEF LCL}Application.ProcessMessages;{$ENDIF}
Result:=InputTextRequest;
except
on E:Exception do
begin
{$IFDEF FSAPI_DEBUG}E.Message:=STR_Error+'tsapi_inputTextRequest -> '+E.Message; DebugPrint(E.Message);{$ENDIF}
Result:=false;
end;
end;
end;
end.
|
unit Frame.NodeTree;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, VirtualTrees,
GMGlobals, Generics.Collections, BaseNodeReader, Vcl.Menus, GMConst, ActiveX, Vcl.ImgList,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxScrollBox,
dxSkinsCore, cxLabel, cxTextEdit, cxMaskEdit, cxSplitter, cxColorComboBox, cxMemo, cxProgressBar,
cxDropDownEdit, cxCalendar, dxSkinscxPCPainter, dxBarBuiltInMenu, cxPC, cxTimeEdit, cxRadioGroup,
cxGroupBox, cxSpinEdit, cxCheckBox, cxButtonEdit, cxButtons, cxCheckListBox, cxListBox, cxListView,
cxImage, dxSkinOffice2010Silver;
type
TfrmNodeTree = class(TFrame)
Tree: TVirtualStringTree;
Panel1: TcxGroupBox;
pmNodeTree: TPopupMenu;
miAdd: TMenuItem;
miDelete: TMenuItem;
miExpandAll: TMenuItem;
miSeparator1: TMenuItem;
pmTree: TPopupMenu;
N1: TMenuItem;
ilNodeTree: TImageList;
procedure TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: string);
procedure TreeExpanding(Sender: TBaseVirtualTree; Node: PVirtualNode; var Allowed: Boolean);
procedure TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
procedure miAddClick(Sender: TObject);
procedure TreeEditing(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; var Allowed: Boolean);
procedure TreeNewText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; NewText: string);
procedure TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure miDeleteClick(Sender: TObject);
procedure TreeDragDrop(Sender: TBaseVirtualTree; Source: TObject; DataObject: IDataObject; Formats: TFormatArray;
Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode);
procedure TreeDragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState; Pt: TPoint;
Mode: TDropMode; var Effect: Integer; var Accept: Boolean);
procedure miExpandAllClick(Sender: TObject);
procedure pmNodeTreePopup(Sender: TObject);
procedure N1Click(Sender: TObject);
procedure TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean;
var ImageIndex: Integer);
private
{ Private declarations }
FCheckBoxLevels: SetOfInt;
reader: TBaseNodeReader;
FReadOnly: bool;
procedure AddLoadedChildren(Node: PVirtualNode);
procedure DelCurrentNode;
function AddNode(vnd: PVTNodeData): PVirtualNode;
procedure SetReadOnly(const Value: bool);
procedure ActivateCheckBoxes_CycleProc(nd: PVirtualNode; CycleObject: pointer);
public
{ Public declarations }
procedure AfterConstruction(); override;
destructor Destroy; override;
property ReadOnly: bool read FReadOnly write SetReadOnly;
procedure Load(bWithInit: bool; readerClass: TBaseNodeReaderClass);
procedure LoadAllTree();
procedure ActivateCheckBoxes(CheckBoxLevels: SetOfInt);
function IsChannelSelected(): bool;
function SelectedObject(): TObject;
end;
implementation
{$R *.dfm}
uses VT_Utils, GMDBClasses;
procedure TfrmNodeTree.AfterConstruction;
begin
inherited;
Tree.NodeDataSize := SizeOf(TVTNodeData);
reader := nil;
end;
destructor TfrmNodeTree.Destroy;
begin
if reader <> nil then
reader.Free();
inherited;
end;
function TfrmNodeTree.IsChannelSelected: bool;
var v: PVTNodeData;
nd: PVirtualNode;
begin
Result := false;
nd := Tree.FocusedNode;
if nd = nil then Exit;
v := Tree.GetNodeData(nd);
Result := v.ID_Prm > 0;
end;
procedure TfrmNodeTree.ActivateCheckBoxes_CycleProc(nd: PVirtualNode; CycleObject: pointer);
var v: PVTNodeData;
begin
v := Tree.GetNodeData(nd);
if v.Obj is TGMNodeChannel then
begin
if NODE_LEVEL_PARAM in FCheckBoxLevels then
Tree.CheckType[nd] := ctCheckBox;
end
else
begin
if NODE_LEVEL_OBJECT in FCheckBoxLevels then
Tree.CheckType[nd] := ctCheckBox;
end
end;
procedure TfrmNodeTree.ActivateCheckBoxes(CheckBoxLevels: SetOfInt);
begin
FCheckBoxLevels := CheckBoxLevels;
CycleTree(Tree.RootNode, ActivateCheckBoxes_CycleProc, nil);
end;
procedure TfrmNodeTree.AddLoadedChildren(Node: PVirtualNode);
var v: TVTNodeData;
p: PVTNodeData;
nd: PVirtualNode;
begin
for v in reader.ReadResult do
begin
nd := Tree.AddChild(Node);
Include(nd.States, vsInitialized);
Tree.HasChildren[nd] := v.ID_Prm <= 0; // каналы не имеют потомков
p := Tree.GetNodeData(nd);
p^ := v;
end;
end;
procedure TfrmNodeTree.Load(bWithInit: bool; readerClass: TBaseNodeReaderClass);
begin
if bWithInit then
Tree.Clear();
if Reader <> nil then
reader.Free();
reader := readerClass.Create();
reader.ReadChildren(0);
AddLoadedChildren(nil);
end;
procedure TfrmNodeTree.LoadAllTree;
begin
Tree.FullExpand();
Tree.FullCollapse();
end;
function TfrmNodeTree.AddNode(vnd: PVTNodeData): PVirtualNode;
var ndp: PVirtualNode;
idp: int;
v: PVTNodeData;
begin
ndp := Tree.FocusedNode;
idp := 0;
if ndp <> nil then
begin
v := Tree.GetNodeData(ndp);
idp := v.ID_Obj;
end;
reader.AddNew(idp, vnd);
Result := Tree.AddChild(ndp);
v := Tree.GetNodeData(Result);
v^ := vnd^;
if ndp <> nil then
Tree.Expanded[ndp] := true;
SelectNode(Result);
end;
procedure TfrmNodeTree.miAddClick(Sender: TObject);
var v: TVTNodeData;
begin
InitVND(@v);
v.sTxt := 'Новый узел';
v.ObjType := NODE_TYPE_NODE;
AddNode(@v);
end;
procedure TfrmNodeTree.miDeleteClick(Sender: TObject);
begin
DelCurrentNode();
end;
procedure TfrmNodeTree.miExpandAllClick(Sender: TObject);
begin
Tree.FullExpand(Tree.FocusedNode);
end;
procedure TfrmNodeTree.N1Click(Sender: TObject);
begin
Tree.FullExpand(Tree.FocusedNode);
end;
procedure TfrmNodeTree.pmNodeTreePopup(Sender: TObject);
begin
miAdd.Visible := not FReadOnly;
miDelete.Visible := not FReadOnly;
miSeparator1.Visible := not FReadOnly;
end;
function TfrmNodeTree.SelectedObject: TObject;
begin
Result := nil;
if Tree.FocusedNode <> nil then
Result := PVTNodeData(Tree.GetNodeData(Tree.FocusedNode)).Obj;
end;
procedure TfrmNodeTree.SetReadOnly(const Value: bool);
begin
FReadOnly := Value;
Panel1.Visible := FReadOnly;
end;
procedure TfrmNodeTree.TreeDragDrop(Sender: TBaseVirtualTree; Source: TObject; DataObject: IDataObject;
Formats: TFormatArray; Shift: TShiftState; Pt: TPoint; var Effect: Integer; Mode: TDropMode);
var vSrc: PVTNodeData;
vNew: TVTNodeData;
srcTree: TVirtualStringTree;
HitInfo: THitInfo;
begin
Tree.GetHitTestInfoAt(Pt.X, Pt.Y, false, HitInfo);
if (HitInfo.HitNode = nil) or not (hiOnItem in HitInfo.HitPositions) then Exit;
srcTree := TVirtualStringTree(Source);
vSrc := srcTree.GetNodeData(srcTree.FocusedNode);
InitVND(@vNew);
vNew.sTxt := vSrc.sTxt;
vNew.BaseChn := vSrc.ID_Prm;
vNew.ID_PT := vSrc.ID_PT;
SelectNode(HitInfo.HitNode);
AddNode(@vNew);
end;
procedure TfrmNodeTree.TreeDragOver(Sender: TBaseVirtualTree; Source: TObject; Shift: TShiftState; State: TDragState;
Pt: TPoint; Mode: TDropMode; var Effect: Integer; var Accept: Boolean);
var v: PVTNodeData;
srcTree: TVirtualStringTree;
HitInfo: THitInfo;
begin
Accept := (Mode = dmOnNode)
and (Source is TVirtualStringTree)
and (TVirtualStringTree(Source).NodeDataSize = sizeOf(TVTNodeData));
if not Accept then Exit;
srcTree := TVirtualStringTree(Source);
v := srcTree.GetNodeData(srcTree.FocusedNode);
Accept := (v.ID_Prm > 0);
if not Accept then Exit;
Tree.GetHitTestInfoAt(Pt.X, Pt.Y, false, HitInfo);
Accept := HitInfo.HitNode <> nil;
if not Accept then Exit;
v := Tree.GetNodeData(HitInfo.HitNode);
Accept := v.ID_Prm <= 0; // Это пока будет единственный метод добавки каналов к узлам
end;
procedure TfrmNodeTree.TreeEditing(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex;
var Allowed: Boolean);
var v: PVTNodeData;
begin
v := Tree.GetNodeData(Node);
Allowed := not ReadOnly and (v.ID_Prm <= 0);
end;
procedure TfrmNodeTree.TreeExpanding(Sender: TBaseVirtualTree; Node: PVirtualNode; var Allowed: Boolean);
var v: PVTNodeData;
begin
if Tree.HasChildren[Node] and (Node.FirstChild = nil) then
begin
v := Tree.GetNodeData(Node);
reader.ReadChildren(v.ID_Obj);
AddLoadedChildren(Node);
end;
end;
procedure TfrmNodeTree.TreeFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
var v: PVTNodeData;
begin
v := Tree.GetNodeData(Node);
Finalize(v^);
end;
procedure TfrmNodeTree.TreeGetImageIndex(Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex; var Ghosted: Boolean;
var ImageIndex: Integer);
var v: PVTNodeData;
begin
ImageIndex := -1;
if Kind in [ikNormal, ikSelected] then
begin
v := Tree.GetNodeData(Node);
if v.ID_Prm > 0 then
ImageIndex := 1
else
if v.ObjType < ilNodeTree.Count - 2 then
ImageIndex := v.ObjType + 2
else
ImageIndex := 0;
end;
end;
procedure TfrmNodeTree.TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex;
TextType: TVSTTextType; var CellText: string);
var v: PVTNodeData;
begin
v := Tree.GetNodeData(Node);
CellText := v.sTxt;
end;
procedure TfrmNodeTree.DelCurrentNode();
var v: PVTNodeData;
nd: PVirtualNode;
begin
nd := Tree.FocusedNode;
if nd = nil then Exit;
v := Tree.GetNodeData(nd);
reader.Delete(v);
DelNodeAndSelectNextSibling(nd);
end;
procedure TfrmNodeTree.TreeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_DELETE then
DelCurrentNode();
end;
procedure TfrmNodeTree.TreeNewText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; NewText: string);
var v: PVTNodeData;
begin
v := Tree.GetNodeData(Node);
v.sTxt := NewText;
reader.NewCaption(v);
end;
end.
|
unit BrickCamp.Repositories.IProduct;
interface
uses
System.JSON,
BrickCamp.Model.TProduct;
type
IProductRepository = interface(IInterface)
['{0AE577BE-875B-4C1D-B4D7-717F20B73480}']
function GetOne(const Id: Integer): TProduct;
function GetList: TJSONArray;
procedure Insert(const Product: TProduct);
procedure Update(const Product: TProduct);
procedure Delete(const Id: Integer);
end;
implementation
end.
|
{******************************************}
{ TeeChart Map Series }
{ Copyright (c) 2000-2004 by David Berneda }
{ All Rights Reserved }
{******************************************}
unit TeeMapSeries;
{$I TeeDefs.inc}
interface
Uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, Types,
{$ELSE}
Graphics,
{$IFDEF D6}
Types,
{$ENDIF}
{$ENDIF}
TeEngine, TeCanvas, TeeProcs, TeeSurfa;
type
TTeePolygon=class;
TPolygonSeries=class(TChartSeries)
protected
Procedure DrawLegendShape(ValueIndex:Integer; Const Rect:TRect); override;
Procedure NotifyValue(ValueEvent:TValueEvent; ValueIndex:Integer); override;
procedure PrepareLegendCanvas(ValueIndex:Integer; Var BackColor:TColor;
Var BrushStyle:TBrushStyle); override;
Procedure SetActive(Value:Boolean); override;
Procedure SetSeriesColor(AColor:TColor); override;
public
Procedure FillSampleValues(NumValues:Integer); override;
Function Polygon:TTeePolygon;
end;
TMapSeries=class;
TTeePolygon=class(TCollectionItem)
private
FClosed : Boolean;
FGradient : TChartGradient;
FParentBrush : Boolean;
FParentPen : Boolean;
FPoints : TPolygonSeries;
FTransparency: TTeeTransparency;
IPoints : TPointArray;
{$IFDEF CLR}
procedure CanvasChanged(Sender: TObject);
{$ENDIF}
function GetBrush: TChartBrush;
function GetColor: TColor;
function GetGradient: TChartGradient;
function GetPen: TChartPen;
Function GetText:String;
function GetZ: Double;
procedure SetBrush(const Value: TChartBrush);
procedure SetClosed(const Value: Boolean);
procedure SetColor(const Value: TColor);
procedure SetGradient(const Value: TChartGradient);
procedure SetParentBrush(const Value: Boolean);
procedure SetParentPen(const Value: Boolean);
procedure SetPen(const Value: TChartPen);
Procedure SetText(Const Value:String);
procedure SetTransparency(const Value: TTeeTransparency);
procedure SetZ(const Value: Double);
//Function ZPosition:Double;
public
ParentSeries : TMapSeries;
Constructor Create(Collection:TCollection); override;
Destructor Destroy; override;
Function AddXY(Const Point:TFloatPoint):Integer; overload;
Function AddXY(Const X,Y:Double):Integer; overload;
Procedure Draw(ACanvas:TCanvas3D; ValueIndex:Integer);
Function GetPoints:TPointArray;
Function Visible:Boolean;
Function Bounds:TRect; // 7.0
property Points:TPolygonSeries read FPoints;
published
property Brush:TChartBrush read GetBrush write SetBrush;
property Closed:Boolean read FClosed write SetClosed default True;
property Color:TColor read GetColor write SetColor default clWhite;
property Gradient:TChartGradient read GetGradient write SetGradient;
property ParentBrush:Boolean read FParentBrush write SetParentBrush default True;
property ParentPen:Boolean read FParentPen write SetParentPen default True;
property Pen:TChartPen read GetPen write SetPen;
property Text:String read GetText write SetText;
property Transparency:TTeeTransparency read FTransparency write SetTransparency default 0; // 7.0
property Z:Double read GetZ write SetZ;
end;
TTeePolygonList=class(TOwnedCollection)
private
Procedure Delete(Start,Quantity:Integer); overload;
Function Get(Index:Integer):TTeePolygon;
Procedure Put(Index:Integer; Const Value:TTeePolygon);
function GetByName(const AName: String): TTeePolygon;
public
Function Add:TTeePolygon;
Function Owner:TMapSeries;
property Polygon[Index:Integer]:TTeePolygon read Get write Put; default;
property ByName[const AName:String]:TTeePolygon read GetByName; // 7.0
end;
TMapSeries=class(TCustom3DPaletteSeries)
private
FShapes : TTeePolygonList;
I3DList : Array of TTeePolygon;
Function CompareOrder(a,b:Integer):Integer;
Function GetPolygon(Index:Integer):TTeePolygon; // 7.0
procedure SetShapes(const Value: TTeePolygonList);
Procedure SwapPolygon(a,b:Integer);
protected
Procedure AddSampleValues(NumValues:Integer; OnlyMandatory:Boolean=False); override;
Procedure CalcHorizMargins(Var LeftMargin,RightMargin:Integer); override;
Procedure CalcVerticalMargins(Var TopMargin,BottomMargin:Integer); override;
class procedure CreateSubGallery(AddSubChart: TChartSubGalleryProc); override;
Procedure DrawAllValues; override;
Procedure DrawMark( ValueIndex:Integer; Const St:String;
APosition:TSeriesMarkPosition); override;
Procedure DrawValue(ValueIndex:Integer); override;
Procedure GalleryChanged3D(Is3D:Boolean); override;
class Function GetEditorClass:String; override;
procedure PrepareForGallery(IsEnabled:Boolean); override;
class procedure SetSubGallery(ASeries: TChartSeries; Index: Integer); override;
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
Procedure Clear; override;
Function Clicked(x,y:Integer):Integer; override;
Procedure Delete(ValueIndex:Integer); overload; override;
Procedure Delete(Start,Quantity:Integer; RemoveGap:Boolean=False); overload; override;
Function MaxXValue:Double; override;
Function MaxYValue:Double; override;
Function MinXValue:Double; override;
Function MinYValue:Double; override;
Function NumSampleValues:Integer; override;
procedure SwapValueIndex(a,b:Integer); override;
property Polygon[Index:Integer]:TTeePolygon read GetPolygon; default; // 7.0
published
{ Published declarations }
property Active;
property ColorSource;
property Cursor;
property HorizAxis;
property Marks;
property ParentChart;
property DataSource;
property PercentFormat;
property SeriesColor;
property ShowInLegend;
property Title;
property ValueFormat;
property VertAxis;
property XLabelsSource;
property Brush;
property EndColor;
property MidColor;
property LegendEvery;
property Pen;
property PaletteMin;
property PaletteStep;
property PaletteSteps;
property Shapes:TTeePolygonList read FShapes write SetShapes stored False;
property StartColor;
property UseColorRange;
property UsePalette;
property UsePaletteMin;
property TimesZOrder;
property XValues;
property YValues;
property ZValues;
{ events }
property AfterDrawValues;
property BeforeDrawValues;
property OnAfterAdd;
property OnBeforeAdd;
property OnClearValues;
property OnClick;
property OnDblClick;
property OnGetColor;
property OnGetMarkText;
property OnMouseEnter;
property OnMouseLeave;
end;
implementation
Uses Math,
{$IFDEF CLR}
Variants,
{$ENDIF}
TeeConst, TeeProCo, Chart;
{$IFNDEF CLR}
type
TSeriesAccess=class(TCustomChartElement);
{$ENDIF}
{ TTeePolygon }
constructor TTeePolygon.Create(Collection: TCollection);
begin
inherited;
ParentSeries:=TTeePolygonList(Collection).Owner as TMapSeries;
FClosed:=True;
FPoints:=TPolygonSeries.Create(nil); // 7.0
FPoints.Tag:={$IFDEF CLR}Variant{$ELSE}Integer{$ENDIF}(Self);
FPoints.XValues.Order:=loNone;
FPoints.ShowInLegend:=False;
FParentPen:=True;
FParentBrush:=True;
ParentSeries.AddXY(0,0);
end;
Destructor TTeePolygon.Destroy;
begin
IPoints:=nil;
FPoints.Free;
FGradient.Free;
inherited;
end;
function TTeePolygon.AddXY(const Point:TFloatPoint): Integer;
begin
result:=FPoints.AddXY(Point.X,Point.Y);
end;
function TTeePolygon.AddXY(const X,Y: Double): Integer;
begin
result:=FPoints.AddXY(X,Y);
end;
{ return the array of Points in screen (pixel) coordinates }
Function TTeePolygon.GetPoints:TPointArray;
var t : Integer;
tmpHoriz : TChartAxis;
tmpVert : TChartAxis;
tmpX : TChartValues;
tmpY : TChartValues;
begin
SetLength(IPoints,FPoints.Count);
result:=IPoints;
tmpHoriz:=ParentSeries.GetHorizAxis;
tmpVert:=ParentSeries.GetVertAxis;
tmpX:=FPoints.XValues.Value;
tmpY:=FPoints.YValues.Value;
for t:=0 to FPoints.Count-1 do
begin
result[t].X:=tmpHoriz.CalcPosValue(tmpX[t]);
result[t].Y:=tmpVert.CalcPosValue(tmpY[t]);
end;
end;
// Returns True if the polygon contains points that lie inside
// the chart "ChartRect" (the visible chart area).
Function TTeePolygon.Visible:Boolean;
// optimized version of InteresectRect
function ContainsRect(R1:TRect; const R2:TRect): Boolean;
begin
if R2.Left > R1.Left then R1.Left := R2.Left;
if R2.Right < R1.Right then R1.Right := R2.Right;
if R2.Top > R1.Top then R1.Top := R2.Top;
if R2.Bottom < R1.Bottom then R1.Bottom := R2.Bottom;
result := not ((R1.Right < R1.Left) or (R1.Bottom < R1.Top));
end;
var tmpR : TRect;
tmpChart : TCustomAxisPanel;
begin
tmpChart:=ParentSeries.ParentChart;
result:=not tmpChart.ClipPoints;
if not result then
begin
with ParentSeries.GetHorizAxis do
begin
tmpR.Left:=CalcPosValue(FPoints.XValues.MinValue);
tmpR.Right:=CalcPosValue(FPoints.XValues.MaxValue);
end;
with ParentSeries.GetVertAxis do
begin
tmpR.Top:=CalcPosValue(FPoints.YValues.MaxValue);
tmpR.Bottom:=CalcPosValue(FPoints.YValues.MinValue);
end;
result:=ContainsRect(tmpChart.ChartRect, tmpR);
end;
end;
{ draw the polygon... }
procedure TTeePolygon.Draw(ACanvas: TCanvas3D; ValueIndex:Integer);
Var tmpZ : Integer;
tmpIs3D : Boolean;
tmpBlend : TTeeBlend;
tmpR : TRect;
begin
if FPoints.Active and (FPoints.Count>0) and Visible then
begin
// set pen and brush...
if ParentPen then ACanvas.AssignVisiblePen(ParentSeries.Pen)
else ACanvas.AssignVisiblePen(Self.Pen);
if ParentBrush then ACanvas.AssignBrush(ParentSeries.Brush,ParentSeries.ValueColor[ValueIndex])
else ACanvas.AssignBrush(Self.Brush,ParentSeries.ValueColor[ValueIndex]);
GetPoints;
tmpIs3D:=ParentSeries.ParentChart.View3D;
// Calculate "Z" depth position
if tmpIs3D then tmpZ:=ParentSeries.CalcZPos(Index)
else tmpZ:=0;
if Transparency>0 then
begin
tmpR:=PolygonBounds(IPoints);
tmpBlend:=ACanvas.BeginBlending(ACanvas.RectFromRectZ(tmpR,tmpZ),Transparency)
end
else
tmpBlend:=nil;
// Fill background with gradient...
if Assigned(Self.FGradient) and Self.FGradient.Visible
and ParentSeries.ParentChart.CanClip then
begin
Self.Gradient.Draw(ACanvas,IPoints,tmpZ,tmpIs3D);
ACanvas.Brush.Style:=bsClear;
end;
// Draw the shape...
with ACanvas do
if tmpIs3D then
begin
if Self.Closed then
PolygonWithZ(IPoints,tmpZ)
else
{$IFDEF D5}
Polyline(IPoints,tmpZ);
{$ELSE}
Polyline(IPoints); // D4: Pending
{$ENDIF}
end
else
begin
if Self.Closed then
Polygon(IPoints)
else
Polyline(IPoints);
end;
if Assigned(tmpBlend) then
ACanvas.EndBlending(tmpBlend);
end;
end;
function TTeePolygon.GetBrush: TChartBrush;
begin
result:=FPoints.Brush;
end;
function TTeePolygon.GetColor: TColor;
begin
result:=ParentSeries.ValueColor[Index];
end;
function TTeePolygon.GetPen: TChartPen;
begin
result:=FPoints.Pen;
end;
procedure TTeePolygon.SetBrush(const Value: TChartBrush);
begin
FPoints.Brush:=Value;
end;
procedure TTeePolygon.SetColor(const Value: TColor);
begin
Points.SeriesColor:=Value;
end;
procedure TTeePolygon.SetClosed(const Value: Boolean);
begin
ParentSeries.SetBooleanProperty(FClosed,Value);
end;
Function TTeePolygon.GetGradient: TChartGradient;
begin
if not Assigned(FGradient) then
FGradient:=TChartGradient.Create({$IFNDEF CLR}TSeriesAccess(ParentSeries).{$ENDIF}CanvasChanged);
result:=FGradient;
end;
procedure TTeePolygon.SetGradient(const Value: TChartGradient);
begin
if Assigned(Value) then
Gradient.Assign(Value)
else
FreeAndNil(FGradient);
end;
procedure TTeePolygon.SetPen(const Value: TChartPen);
begin
FPoints.Pen:=Value;
end;
procedure TTeePolygon.SetZ(const Value: Double);
begin
ParentSeries.ZValues.Value[Index]:=Value;
ParentSeries.Repaint;
end;
function TTeePolygon.GetZ: Double;
begin
result:=ParentSeries.ZValues.Value[Index];
end;
function TTeePolygon.GetText: String;
begin
result:=ParentSeries.Labels[Index];
end;
procedure TTeePolygon.SetText(const Value: String);
begin
ParentSeries.Labels[Index]:=Value;
end;
procedure TTeePolygon.SetParentBrush(const Value: Boolean);
begin
ParentSeries.SetBooleanProperty(FParentBrush,Value);
end;
procedure TTeePolygon.SetParentPen(const Value: Boolean);
begin
ParentSeries.SetBooleanProperty(FParentPen,Value);
end;
(*
function TTeePolygon.ZPosition:Integer;
var x : Integer;
y : Integer;
P : TPoint;
tmpZ : Integer;
begin
result:=0;
With ParentSeries do
if FPoints.Count>0 then
begin
X:=GetHorizAxis.CalcPosValue(FPoints.XValues.Value[0]);
Y:=GetVertAxis.CalcPosValue(FPoints.YValues.Value[0]);
tmpZ:=ParentSeries.CalcZPos(0);
P:=ParentSeries.ParentChart.Canvas.Calculate3DPosition(TeePoint(x,y),tmpZ);
end;
end;
*)
function TTeePolygon.Bounds: TRect; // 7.0
begin
result:=PolygonBounds(GetPoints);
end;
{$IFDEF CLR}
procedure TTeePolygon.CanvasChanged(Sender: TObject);
begin
ParentSeries.Repaint;
end;
{$ENDIF}
procedure TTeePolygon.SetTransparency(const Value: TTeeTransparency);
begin
if FTransparency<>Value then
begin
FTransparency:=Value;
ParentSeries.Repaint;
end;
end;
{ TTeePolygonList }
type TComponentAccess=class(TComponent);
function TTeePolygonList.Add: TTeePolygon;
{$IFNDEF CLR}
var p : TPolygonSeries;
{$ENDIF}
begin
result:=inherited Add as TTeePolygon;
{$IFNDEF CLR}
p:=result.Points;
TComponentAccess(p).SetDesigning(False);
{$ENDIF}
end;
procedure TTeePolygonList.Delete(Start, Quantity: Integer);
var t: Integer;
begin
for t:=1 to Quantity do Items[Start].Free;
end;
function TTeePolygonList.Get(Index: Integer): TTeePolygon;
begin
result:=TTeePolygon(Items[Index]);
end;
function TTeePolygonList.GetByName(const AName: String): TTeePolygon;
var t : Integer;
tmp : String;
begin
result:=nil;
tmp:=UpperCase(AName);
for t:=0 to Count-1 do
if UpperCase(Polygon[t].Text)=tmp then
begin
result:=Polygon[t];
break;
end;
end;
function TTeePolygonList.Owner: TMapSeries;
begin
result:=TMapSeries(GetOwner);
end;
procedure TTeePolygonList.Put(Index: Integer; const Value: TTeePolygon);
begin
Items[Index]:=Value;
end;
{ TMapSeries }
Constructor TMapSeries.Create(AOwner: TComponent);
begin
inherited;
FShapes:=TTeePolygonList.Create(Self,TTeePolygon);
CalcVisiblePoints:=False;
YMandatory:=False;
MandatoryValueList:=ZValues;
end;
Destructor TMapSeries.Destroy;
begin
FreeAndNil(FShapes);
inherited;
end;
procedure TMapSeries.DrawValue(ValueIndex: Integer);
begin
if Shapes.Count>ValueIndex then
Shapes[ValueIndex].Draw(ParentChart.Canvas,ValueIndex);
end;
Procedure TMapSeries.Delete(ValueIndex:Integer);
begin
inherited;
if Assigned(FShapes) then Shapes[ValueIndex].Free;
end;
Procedure TMapSeries.Delete(Start,Quantity:Integer; RemoveGap:Boolean=False);
begin
inherited;
if Assigned(FShapes) then FShapes.Delete(Start,Quantity);
end;
function TMapSeries.MaxXValue: Double;
var t : Integer;
begin
if Shapes.Count=0 then result:=0
else
begin
result:=Shapes[0].FPoints.MaxXValue;
for t:=1 to Shapes.Count-1 do
result:=Math.Max(result,Shapes[t].FPoints.MaxXValue);
end;
end;
function TMapSeries.MaxYValue: Double;
var t : Integer;
begin
if Shapes.Count=0 then result:=0
else
begin
result:=Shapes[0].FPoints.MaxYValue;
for t:=1 to Shapes.Count-1 do
result:=Math.Max(result,Shapes[t].FPoints.MaxYValue);
end;
end;
function TMapSeries.MinXValue: Double;
var t : Integer;
begin
if Shapes.Count=0 then result:=0
else
begin
result:=Shapes[0].FPoints.MinXValue;
for t:=1 to Shapes.Count-1 do
result:=Math.Min(result,Shapes[t].FPoints.MinXValue);
end;
end;
function TMapSeries.MinYValue: Double;
var t : Integer;
begin
if Shapes.Count=0 then result:=0
else
begin
result:=Shapes[0].FPoints.MinYValue;
for t:=1 to Shapes.Count-1 do
result:=Math.Min(result,Shapes[t].FPoints.MinYValue);
end;
end;
procedure TMapSeries.PrepareForGallery(IsEnabled:Boolean);
var t : Integer;
begin
inherited;
if not IsEnabled then
for t:=0 to Count-1 do Shapes[t].Color:=clSilver;
end;
procedure TMapSeries.SwapValueIndex(a,b:Integer);
begin
inherited;
Shapes[a].Index:=b;
Repaint;
end;
procedure TMapSeries.SetShapes(const Value: TTeePolygonList);
begin
FShapes.Assign(Value);
end;
procedure TMapSeries.CalcHorizMargins(var LeftMargin,
RightMargin: Integer);
begin
inherited;
if Pen.Visible then
begin
Inc(LeftMargin,Pen.Width);
Inc(RightMargin,Pen.Width);
end;
end;
procedure TMapSeries.CalcVerticalMargins(var TopMargin,
BottomMargin: Integer);
begin
inherited;
Inc(BottomMargin);
if Pen.Visible then
begin
Inc(TopMargin,Pen.Width);
Inc(BottomMargin,Pen.Width);
end;
end;
Function TMapSeries.NumSampleValues;
begin
result:=12;
end;
procedure TMapSeries.AddSampleValues(NumValues: Integer; OnlyMandatory:Boolean=False);
Procedure AddShape(Const X,Y:Array of Integer; Const AText:String);
var t : Integer;
tmpX : Integer;
tmpY : Integer;
begin
if Count>NumSampleValues then
begin
tmpX:=RandomValue(NumSampleValues);
tmpY:=RandomValue(NumSampleValues);
end
else
begin
tmpX:=0;
tmpY:=0;
end;
With Shapes.Add do
begin
for t:=Low(X) to High(X) do
AddXY(tmpX+X[t],tmpY+Y[t]);
// Color:=AColor; 7.0 removed
Text:=AText;
Z:=RandomValue(1000)/1000.0;
end;
end;
Const AX:Array[0..13] of Integer=(1,3,4,4,5,5,6,6,4,3,2,1,2,2);
AY:Array[0..13] of Integer=(7,5,5,7,8,9,10,11,11,12,12,11,10,8);
BX:Array[0..8] of Integer=(5,7,8,8,7,6,5,4,4);
BY:Array[0..8] of Integer=(4,4,5,6,7,7,8,7,5);
CX:Array[0..15] of Integer=(9,10,11,11,12,9,8,7,6,6,5,5,6,7,8,8);
CY:Array[0..15] of Integer=(5,6,6,7,8,11,11,12,11,10,9,8,7,7,6,5);
DX:Array[0..7] of Integer=(12,14,15,14,13,12,11,11);
DY:Array[0..7] of Integer=(5,5,6,7,7,8,7,6);
EX:Array[0..10] of Integer=(4,6,7,7,6,6,5,4,3,3,2);
EY:Array[0..10] of Integer=(11,11,12,13,14,15,16,16,15,14,13);
FX:Array[0..11] of Integer=(7,8,9,11,10,8,7,6,5,5,6,6);
FY:Array[0..11] of Integer=(13,14,14,16,17,17,18,18,17,16,15,14);
GX:Array[0..11] of Integer=(10,12,12,14,13,11,9,8,7,7,8,9);
GY:Array[0..11] of Integer=(10,12,13,15,16,16,14,14,13,12,11,11);
HX:Array[0..9] of Integer=(17,19,18,18,17,15,14,13,15,16);
HY:Array[0..9] of Integer=(11,13,14,16,17,15,15,14,12,12);
IX:Array[0..14] of Integer=(15,16,17,16,15,14,14,13,12,11,10,11,12,13,14);
IY:Array[0..14] of Integer=(6,6,7,8,8,9,10,11,12,11,10,9,8,7,7);
JX:Array[0..11] of Integer=(15,16,16,17,17,16,15,13,12,12,14,14);
JY:Array[0..11] of Integer=(8,8,9,10,11,12,12,14,13,12,10,9);
KX:Array[0..9] of Integer=(17,19,20,20,19,17,16,16,17,16);
KY:Array[0..9] of Integer=(5,5,6,8,8,10,9,8,7,6);
LX:Array[0..6] of Integer=(19,20,21,21,19,17,17);
LY:Array[0..6] of Integer=(8,8,9,11,13,11,10);
var t : Integer;
begin
for t:=0 to NumValues-1 do
case t mod NumSampleValues of
0: AddShape(AX,AY,'A');
1: AddShape(BX,BY,'B');
2: AddShape(CX,CY,'C');
3: AddShape(DX,DY,'D');
4: AddShape(EX,EY,'E');
5: AddShape(FX,FY,'F');
6: AddShape(GX,GY,'G');
7: AddShape(HX,HY,'H');
8: AddShape(IX,IY,'I');
9: AddShape(JX,JY,'J');
10: AddShape(KX,KY,'K');
11: AddShape(LX,LY,'L');
end;
end;
function TMapSeries.Clicked(x, y: Integer): Integer;
var tmpClip : Boolean;
tmpRect : TRect;
function IsShapeVisible(Shape:TPolygonSeries):Boolean;
var tmp : Integer;
tmp2 : Integer;
begin
if tmpClip then
begin
with GetHorizAxis do
begin
tmp:=CalcPosValue(Shape.XValues.MinValue);
if (tmp<tmpRect.Left) or (tmp>tmpRect.Right) then
begin
tmp2:=CalcPosValue(Shape.XValues.MaxValue);
if (tmp2<tmpRect.Left) or
((tmp2>tmpRect.Right) and (tmp>tmpRect.Right)) then
begin
result:=False;
Exit;
end;
end;
end;
with GetVertAxis do
begin
tmp:=CalcPosValue(Shape.YValues.MaxValue);
if (tmp<tmpRect.Top) or (tmp>tmpRect.Bottom) then
begin
tmp2:=CalcPosValue(Shape.YValues.MinValue);
result:=( (tmp2>=tmpRect.Top) and (tmp2<=tmpRect.Bottom) ) or
( (tmp2>tmpRect.Bottom) and (tmp<tmpRect.Top) );
end
else result:=True;
end;
end
else result:=True;
end;
var t : Integer;
tmpX : Integer;
tmpY : Integer;
tmpChart : TCustomAxisPanel;
tmpshape : TTeePolygon;
begin
result:=TeeNoPointClicked;
tmpChart:=ParentChart;
if Assigned(tmpChart) then
begin
tmpClip:=tmpChart.ClipPoints;
tmpRect:=tmpChart.ChartRect;
for t:=0 to Shapes.Count-1 do
begin
tmpShape:=Shapes[t];
if IsShapeVisible(tmpShape.FPoints) then
begin
tmpX:=X;
tmpY:=Y;
tmpChart.Canvas.Calculate2DPosition(tmpX,tmpY,CalcZPos(t));
if PointInPolygon(TeePoint(tmpX,tmpY),tmpShape.GetPoints) then
begin
result:=t;
break;
end;
end;
end;
end;
end;
procedure TMapSeries.DrawMark(ValueIndex: Integer; const St: String;
APosition: TSeriesMarkPosition);
begin
if Shapes.Count>ValueIndex then
begin
with Shapes[ValueIndex].Bounds do
begin
APosition.LeftTop.X:=((Right+Left) div 2)-(APosition.Width div 2);
APosition.LeftTop.Y:=((Top+Bottom) div 2)-(APosition.Height div 2);
end;
// Marks.ZPosition:=CalcZPos(ValueIndex); 7.0 already done in inherited
end;
inherited;
end;
class function TMapSeries.GetEditorClass: String;
begin
result:='TMapSeriesEditor';
end;
procedure TMapSeries.Clear;
begin
inherited;
if Assigned(Shapes) then Shapes.Clear;
end;
class procedure TMapSeries.CreateSubGallery(
AddSubChart: TChartSubGalleryProc);
begin
inherited;
AddSubChart(TeeMsg_Colors);
end;
class procedure TMapSeries.SetSubGallery(ASeries: TChartSeries;
Index: Integer);
begin
with TMapSeries(ASeries) do
Case Index of
2: ColorEachPoint:=True;
else inherited;
end
end;
procedure TMapSeries.GalleryChanged3D(Is3D: Boolean);
begin { 5.02 }
if Is3D then inherited
else ParentChart.View3D:=False;
end;
Function TMapSeries.CompareOrder(a,b:Integer):Integer;
var tmpA : Double;
tmpB : Double;
begin
tmpA:=I3DList[a].Z; //ZPosition;
tmpB:=I3DList[b].Z; //ZPosition;
if tmpA>tmpB then result:=1
else
if tmpA<tmpB then result:=-1
else
result:=0;
end;
Function TMapSeries.GetPolygon(Index:Integer):TTeePolygon; // 7.0
begin
result:=FShapes[Index];
end;
Procedure TMapSeries.SwapPolygon(a,b:Integer);
var tmp : TTeePolygon;
begin
tmp:=I3DList[b];
I3DList[b]:=I3DList[a];
I3DList[a]:=tmp;
end;
procedure TMapSeries.DrawAllValues;
Procedure DrawAllSorted;
var t : Integer;
tmpCount : Integer;
begin
tmpCount:=Shapes.Count;
if tmpCount>0 then
begin
SetLength(I3DList,tmpCount);
try
for t:=0 to tmpCount-1 do I3DList[t]:=Shapes.Get(t);
TeeSort(0,tmpCount-1,CompareOrder,SwapPolygon);
for t:=tmpCount-1 downto 0 do
I3DList[t].Draw(ParentChart.Canvas,I3DList[t].Index);
finally
I3DList:=nil;
end;
end;
end;
begin
if ParentChart.View3D then DrawAllSorted
else inherited;
end;
{ TPolygonSeries }
procedure TPolygonSeries.NotifyValue(ValueEvent: TValueEvent;
ValueIndex: Integer);
begin
inherited;
Polygon.ParentSeries.Repaint;
end;
procedure TPolygonSeries.SetActive(Value: Boolean);
begin
inherited;
Polygon.ParentSeries.Repaint;
end;
Function TPolygonSeries.Polygon:TTeePolygon;
begin
{$IFDEF CLR}
result:=TTeePolygon(TObject(Tag));
{$ELSE}
result:=TTeePolygon(Tag);
{$ENDIF}
end;
procedure TPolygonSeries.SetSeriesColor(AColor: TColor);
begin
inherited;
// Prevent changing color when caller is Chart.PaintSeriesLegend
if not Assigned(ParentChart) then
Polygon.ParentSeries.ValueColor[Polygon.Index]:=AColor;
end;
procedure TPolygonSeries.PrepareLegendCanvas(ValueIndex:Integer; Var BackColor:TColor;
Var BrushStyle:TBrushStyle);
begin
inherited;
with Polygon do { 5.02 }
begin
ParentSeries.DoBeforeDrawChart;
if (not Assigned(FGradient)) or (not Gradient.Visible) then
ParentChart.Canvas.Brush.Color:=Color;
end;
end;
procedure TPolygonSeries.DrawLegendShape(ValueIndex: Integer;
const Rect: TRect);
begin
if Assigned(Polygon.FGradient) then
with Polygon.Gradient do { 5.02 }
if Visible then Draw(ParentChart.Canvas,Rect)
else inherited
else
inherited;
end;
procedure TPolygonSeries.FillSampleValues(NumValues: Integer);
begin { do nothing, sample values are provided by Owner Map Series }
end;
initialization
RegisterTeeSeries( TMapSeries, {$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryMap,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryExtended,1);
finalization
UnRegisterTeeSeries([TMapSeries]);
end.
|
{$mode objfpc}{$H+}{$J-}
uses SysUtils, Generics.Collections;
type
TApple = class
Name: string;
end;
TAppleDictionary = specialize TDictionary<string, TApple>;
var
Apples: TAppleDictionary;
A, FoundA: TApple;
ApplePair: TAppleDictionary.TDictionaryPair;
AppleKey: string;
begin
Apples := TAppleDictionary.Create;
try
A := TApple.Create;
A.Name := 'моє яблуко';
Apples.AddOrSetValue('яблучний ключ 1', A);
if Apples.TryGetValue('яблучний ключ 1', FoundA) then
Writeln('Знайдено яблуко під ключем "яблучний ключ 1" з назвою: ' +
FoundA.Name);
for AppleKey in Apples.Keys do
Writeln('Знайдено яблучний ключ: ' + AppleKey);
for A in Apples.Values do
Writeln('Знайдено яблучне значення: ' + A.Name);
for ApplePair in Apples do
Writeln('Знайдено яблучні ключ->значення: ' +
ApplePair.Key + '->' + ApplePair.Value.Name);
{ Рядок нижче також працює, але його можна використовувати
лише для встановлення *існуючого* ключа словника.
Замість цього зазвичай використовуйте AddOrSetValue,
щоб установити або додати новий ключ, якщо це необхідно. }
// Apples['яблучний ключ 1'] := ... ;
Apples.Remove('яблучний ключ 1');
{ Зверніть увагу, що TDictionary не володіє елементами,
вам потрібно звільнити їх самостійно.
Ми могли б використовувати TObjectDictionary,
щоб мати автоматичний механізм власності. }
A.Free;
finally FreeAndNil(Apples) end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
Redis.Commons, Redis.Client, Redis.NetLib.INDY, Redis.Values
;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Edit1: TEdit;
Edit2: TEdit;
Button6: TButton;
LabeledEdit1: TLabeledEdit;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
private
FCon: IRedisClient;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
Self.FCon := TRedisClient.Create();
Self.FCon.Connect;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
oValue : TRedisString;
begin
oValue := Self.FCon.GET(Self.LabeledEdit1.Text);
if oValue.IsNull then
raise Exception.Create('Não há valor!');
Self.Edit1.Text := oValue.Value;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
Self.FCon.&SET(Self.LabeledEdit1.Text,Self.Edit2.Text);
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
Self.FCon.DEL([Self.LabeledEdit1.Text]);
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
Self.FCon.EXPIRE(Self.LabeledEdit1.Text, 10);
end;
procedure TForm1.Button6Click(Sender: TObject);
var
bRet: Boolean;
begin
bRet := Self.FCon.EXISTS(Self.LabeledEdit1.Text);
if not bRet then
ShowMessage('A CHAVE NÃO EXISTE!')
else
ShowMessage('A CHAVE EXISTE');
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ Web server application components }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
// Parse a multipart form data request which may contain
// uploaded files. use ReqMulti to register this parser.
unit Web.ReqMulti;
{$WARN IMPLICIT_STRING_CAST OFF}
interface
uses System.SysUtils, System.Classes, System.Masks, System.Generics.Collections, Web.HTTPApp,
Web.ReqFiles, Web.HTTPParse;
type
{ TMultipartContentParser }
TMultipartContentParser = class(TAbstractContentParser)
private
FContentFields: TStrings;
FFiles: TWebRequestFiles;
FContentBuffer: TBytes;
protected
function GetContentFields: TStrings; override;
function GetFiles: TAbstractWebRequestFiles; override;
procedure ExtractContentTypeFields(Strings: TStrings);
procedure ParseMultiPartContent;
procedure ParseMultiPart(APart: PByte; ASize: Integer);
procedure BufferContent;
procedure ParseMultipartHeaders(Parser: THTTPParser; AContent: PByte;
AContentLength: Integer);
procedure ExtractMultipartContentFields;
public
destructor Destroy; override;
class function CanParse(AWebRequest: TWebRequest): Boolean; override;
end;
implementation
uses Web.WebConst, Web.BrkrConst;
const
sMultiPartFormData = 'multipart/form-data';
function IsMultipartForm(ARequest: TWebRequest): Boolean;
begin
Result := StrLIComp(PChar(ARequest.ContentType), PChar(sMultiPartFormData),
Length(sMultiPartFormData)) = 0;
end;
{ TMultipartContentParser }
destructor TMultipartContentParser.Destroy;
begin
FContentFields.Free;
FFiles.Free;
inherited Destroy;
end;
procedure TMultipartContentParser.BufferContent;
begin
if (WebRequest.ContentLength > 0) and (Length(FContentBuffer) = 0) then
begin
WebRequest.ReadTotalContent;
FContentBuffer := WebRequest.RawContent;
end;
end;
procedure TMultipartContentParser.ExtractMultipartContentFields;
begin
if WebRequest.ContentLength > 0 then
begin
BufferContent;
ParseMultiPartContent;
end;
end;
procedure TMultipartContentParser.ExtractContentTypeFields(Strings: TStrings);
begin
ExtractHeaderFields([';'], [' '], WebRequest.ContentType, Strings, False, True);
end;
procedure TMultipartContentParser.ParseMultiPartContent;
function IndexOfPattern(const ABoundary: TBytes; const ABuffer: TBytes; AOffset: Integer): Integer; overload;
var
I, LIterCnt, L, J: Integer;
begin
L := Length(ABoundary);
{ Calculate the number of possible iterations. Not valid if AOffset < 1. }
LIterCnt := Length(ABuffer) - AOffset - L + 1;
{ Only continue if the number of iterations is positive or zero (there is space to check) }
if (AOffset >= 0) and (LIterCnt >= 0) and (L > 0) then
begin
for I := 0 to LIterCnt do
begin
J := 0;
while (J >= 0) and (J < L) do
begin
if ABuffer[I + J + AOffset] = ABoundary[J] then
Inc(J)
else
J := -1;
end;
if J >= L then
Exit(I + AOffset);
end;
end;
Result := -1;
end;
type
TMultipartBoundaries = array of Integer;
function FindBoundaries(const Boundary: TBytes): TMultipartBoundaries;
var
P1: Integer;
Boundaries: TMultipartBoundaries;
Count: Integer;
begin
Count := 0;
P1 := IndexOfPattern(Boundary, FContentBuffer, 0);
while P1 >= 0 do
begin
Inc(Count);
SetLength(Boundaries, Count);
Boundaries[Count-1] := P1;
P1 := IndexOfPattern(Boundary, FContentBuffer, P1 + Length(Boundary));
end;
Result := Boundaries;
end;
var
ContentTypeFields: TStrings;
Boundaries: TMultipartBoundaries;
Temp: string;
Boundary: TBytes;
I: Integer;
P: Integer;
begin
SetLength(Boundaries, 0);
ContentTypeFields := TStringList.Create;
try
ExtractContentTypeFields(ContentTypeFields);
Temp := ContentTypeFields.Values['boundary'];
if Temp <> '' then
begin
Temp := '--' + Temp;
Boundary := TEncoding.ASCII.GetBytes(Temp);
end;
finally
ContentTypeFields.Free;
end;
if Length(Boundary) = 0 then
Exit;
Boundaries := FindBoundaries(Boundary);
for I := Low(Boundaries) to High(Boundaries)-1 do
begin
P := Boundaries[I] + Length(Boundary) + 2;
ParseMultiPart(@FContentBuffer[P], Boundaries[I+1] - P);
end;
end;
procedure TMultipartContentParser.ParseMultipartHeaders(Parser: THTTPParser;
AContent: PByte; AContentLength: Integer);
var
PartContentType: string;
PartFileName: string;
PartName: string;
ContentDisposition: string;
procedure SkipLine;
begin
Parser.CopyToEOL;
Parser.SkipEOL;
end;
function TrimLeft(const S: UTF8String): UTF8String;
var
I, L: Integer;
begin
L := Length(S);
I := 1;
while (I <= L) and (S[I] <= ' ') do Inc(I);
Result := Copy(S, I, Maxint);
end;
procedure ParseContentType;
begin
with Parser do
begin
NextToken;
if Token = ':' then NextToken;
if PartContentType = '' then
PartContentType := TrimLeft(CopyToEOL)
else CopyToEOL;
NextToken;
end;
end;
procedure ExtractContentDispositionFields;
var
S: UTF8String;
Strings: TStrings;
begin
S := ContentDisposition;
Strings := TStringList.Create;
try
ExtractHeaderFields([';'], [' '], S, Strings, True, True);
PartName := Strings.Values['name'];
PartFileName := Strings.Values['filename'];
finally
Strings.Free;
end;
end;
procedure ParseContentDisposition;
begin
with Parser do
begin
NextToken;
if Token = ':' then NextToken;
if ContentDisposition = '' then
ContentDisposition := TrimLeft(CopyToEOL)
else CopyToEOL;
NextToken;
ExtractContentDispositionFields;
end;
end;
var
Temp: UTF8String;
begin
while Parser.Token <> toEOF do with Parser do
begin
case Token of
toContentType: ParseContentType;
toContentDisposition: ParseContentDisposition;
toEOL: Break; // At content
else
SkipLine;
end;
end;
if PartName <> '' then
begin
if PartFileName <> '' then
begin
// Note. Filename is not added as content field
// FContentFields.Add(PartName + '=' + PartFileName);
if FFiles = nil then
FFiles := TWebRequestFiles.Create;
FFiles.Add(PartName, PartFileName, PartContentType,
AContent, AContentLength-2); // Exclude the cr/lf pair
end
else if PartContentType = '' then
begin
Temp := '';
if AContentLength > 0 then
begin
Assert(AContentLength >= 2);
Temp := TEncoding.UTF8.GetString(BytesOf(AContent, AContentLength-2), 0, AContentLength-2);
end;
FContentFields.Add(PartName + '=' + Temp);
end
end;
end;
procedure TMultipartContentParser.ParseMultiPart(APart: PByte; ASize: Integer);
function StrPos(const Str1, Str2: PUTF8Char): PUTF8Char;
var
MatchStart, LStr1, LStr2: PUTF8Char;
begin
Result := nil;
if (Str1^ = #0) or (Str2^ = #0) then
Exit;
MatchStart := Str1;
while MatchStart^<> #0 do
begin
if MatchStart^ = Str2^ then
begin
LStr1 := MatchStart+1;
LStr2 := Str2+1;
while True do
begin
if LStr2^ = #0 then
Exit(MatchStart);
if (LStr1^ <> LStr2^) or (LStr1^ = #0) then
Break;
Inc(LStr1);
Inc(LStr2);
end;
end;
Inc(MatchStart);
end;
end;
var
PEndHeader: PUTF8Char;
S: TStream;
HeaderLen: Integer;
Parser: THTTPParser;
begin
PEndHeader := StrPos(PUTF8Char(APart), #13#10#13#10);
if PEndHeader <> nil then
begin
HeaderLen := PEndHeader-APart+4;
S := TWebRequestFileStream.Create(APart, HeaderLen);
try
Parser := THTTPParser.Create(S);
try
ParseMultiPartHeaders(Parser, APart + HeaderLen, ASize - HeaderLen);
finally
Parser.Free;
end;
finally
S.Free;
end;
end;
end;
function TMultipartContentParser.GetContentFields: TStrings;
begin
if FContentFields = nil then
begin
FContentFields := TStringList.Create;
if IsMultiPartForm(WebRequest) then
ExtractMultipartContentFields
else
WebRequest.ExtractContentFields(FContentFields);
end;
Result := FContentFields;
end;
function TMultipartContentParser.GetFiles: TAbstractWebRequestFiles;
begin
GetContentFields;
if FFiles = nil then
FFiles := TWebRequestFiles.Create;
Result := FFiles;
end;
class function TMultipartContentParser.CanParse(
AWebRequest: TWebRequest): Boolean;
begin
Result := IsMultipartForm(AWebRequest);
end;
initialization
RegisterContentParser(TMultipartContentParser);
end.
|
unit Code02.Clarc1984.DaylightTimeZone;
interface
uses
System.json;
{
@theme: Delphi Challenge
@subject: #02 Daylight Time Zone
@author: Bogdan Polak
@date: 2020-05-16 21:00
}
{
Zadaniem jest wydobycie z treści strony https://www.timeanddate.com/
informacji o tym czy w podanej strefie czasowej wykonuje się przesuniecie
czasu podstawowego (zimowego) na czas letni. Daylight Saving Time
Funkcja:
* IsDaylightSaving - powinna sprawdzić to dla podanego roku (year) i dla podanego obszaru (area).
Jeśli przesuniecie czasu jest aktywne to funkcje:
* GetDaylightStart
* GetDaylightEnd
powinny zwrócić informacje w jakim dniu i o jakiej godzinie następuje przesuniecie czasu.
Dla przykładu przy danych:
- area: poland/warsaw
- year: 2015
Powinna zostać wywołana strona:
https://www.timeanddate.com/time/change/poland/warsaw?year=2015
i na podstawie analizy treści strony WWW należy zwrócić podane wyżej wyniki
Aby nie powtarzać wielokrotnego pobierania danych dla tych samych stron
należy przechować poprzednie wyniki, aby nie pobierać wielokrotnie tych
samych danych.
Uwaga!
Wymagane jest użycie `TMyHttpGet.GetWebsiteContent` do pobrania zawartości strony
Przykład wywołania:
aHtmlPageContent := TMyHttpGet.GetWebsiteContent(‘http://delphi.pl/’);
}
type
TJsonParam = (jpDTS, jpStart, jpEnd);
function IsDaylightSaving(const area: string; year: Word): boolean;
function GetDaylightStart(const area: string; year: Word): TDateTime;
function GetDaylightEnd(const area: string; year: Word): TDateTime;
function MakeValidUrl(const area: string; year: Word): string;
function GetPageContent(const area: string; year: Word): string;
procedure SaveDataToRecords(const area: string; year: Word);
function DataInRecords(const data: string): TJSONObject;
function JsonFromDB: TJSONObject;
function PageStringToDateTime(const date: string; year: Word): TDateTime;
function GetDaylightParamFromRecord(const area: string; year: Word; param: TJsonParam): Variant;
implementation
uses
System.SysUtils,
System.IOUtils,
System.DateUtils,
System.StrUtils,
Code02.HttpGet;
const
cUrlStr = 'https://www.timeanddate.com/time/change/%s?year=%d';
cNotDTSdiv = '<div class="alert warning">';
cDBfile = 'DBrecords.json';
cJsonDTS = 'DTS';
cJsonStart = 'start';
cJsonEnd = 'end';
function GetDaylightParamFromRecord(const area: string; year: Word; param: TJsonParam): Variant;
var
lJsonObj: TJSONObject;
begin
SaveDataToRecords(area, year);
lJsonObj := DataInRecords(area + year.ToString);
if Assigned(lJsonObj) then
begin
lJsonObj := JsonFromDB;
case param of
jpDTS : Result := lJsonObj.GetValue<Boolean>(area + year.ToString + '[0].' + cJsonDTS);
jpStart : Result := UnixToDateTime(lJsonObj.GetValue<Integer>(area + year.ToString + '[0].' + cJsonStart));
jpEnd : Result := UnixToDateTime(lJsonObj.GetValue<Integer>(area + year.ToString + '[0].' + cJsonEnd));
end;
end;
end;
function PageStringToDateTime(const date: string; year: word): TDateTime;
var
lDateParts: TArray<string>;
lMonth, lDay, lHour, lMinute: word;
lFs: TFormatSettings;
begin
lFs := TFormatSettings.Create('en-US');
lDateParts := SplitString(date, ' ');
lMonth := IndexText(lDateParts[2], lFs.LongMonthNames) + 1;
lDay := lDateParts[1].ToInteger;
lHour := StrToInt(Copy(lDateParts[3], 1, 2));
lMinute := StrToInt(Copy(lDateParts[3], 4, 2));
Result := EncodeDateTime(year, lMonth, lDay, lHour, lMinute, 0, 0);
end;
function JsonFromDB: TJSONObject;
begin
Result := TJSONObject.Create;
if FileExists(cDBfile) then
Result := TJSONObject(TJSONObject.ParseJSONValue(TFile.ReadAllText(cDBfile)));
end;
function DataInRecords(const data: string): TJSONObject;
var
lJsonObj: TJSONObject;
begin
lJsonObj := JsonFromDB;
Result := TJSONObject(lJsonObj.FindValue(data));
lJsonObj.Free;
end;
procedure SaveDataToRecords(const area: string; year: word);
var
lJsonObj, lJsonData: TJSONObject;
lJsonArray: TJSONArray;
lPageContent: string;
lvalDTS: boolean;
lStartDate, lEndDate: Integer;
lStartPos, lEndPos: Integer;
lTmpDatesStr: string;
lStartDateStr, lEndDateStr: string;
begin
lJsonObj := DataInRecords(area + year.ToString);
if lJsonObj = nil then
begin
lPageContent := GetPageContent(area, year);
lStartPos := Pos('</td></tr><tr ><th>' + year.ToString + '</th><td>', lPageContent);
lStartPos := lStartPos + 32;
lEndPos := Pos('</td></tr>', lPageContent, lStartPos);
if (lStartPos < lEndPos) and (lEndPos > 1) then
begin
lTmpDatesStr := Copy(lPageContent, lStartPos, lEndPos - lStartPos);
lTmpDatesStr := StringReplace(lTmpDatesStr, ',', '', [rfReplaceAll]);
if (lTmpDatesStr[1] <> '<') then
begin
lStartPos := Pos('</td><td>', lTmpDatesStr);
lStartPos := lStartPos + 9;
lEndPos := Pos('>', lTmpDatesStr, lStartPos);
lStartDateStr := Copy(lTmpDatesStr, 1, lStartPos - 10);
if lEndPos = 0 then
Delete(lTmpDatesStr, 1, Pos('>', lTmpDatesStr))
else
Delete(lTmpDatesStr, 1, lEndPos);
end
else
begin
lStartPos := Pos('>', lTmpDatesStr);
lEndPos := Pos('</', lTmpDatesStr, lStartPos);
if (lStartPos < lEndPos) then
Delete(lTmpDatesStr, 1, lStartPos);
lStartPos := Pos('</', lTmpDatesStr);
lEndPos := Pos('<td>', lTmpDatesStr, lStartPos);
lStartDateStr := Copy(lTmpDatesStr, 1, lStartPos - 1);
Delete(lTmpDatesStr, 1, lEndPos + 3);
end;
lEndDateStr := lTmpDatesStr;
end;
lvalDTS := Pos(cNotDTSdiv, lPageContent) = 0;
if lStartDateStr.IsEmpty then
lStartDate := 0
else
lStartDate := DateTimeToUnix(PageStringToDateTime(lStartDateStr, year));
if lEndDateStr.IsEmpty then
lEndDate := 0
else
lEndDate := DateTimeToUnix(PageStringToDateTime(lEndDateStr, year));
lJsonData := TJSONObject.Create;
try
lJsonData.AddPair(cJsonStart, lStartDate.ToString);
lJsonData.AddPair(cJsonEnd, lEndDate.ToString);
lJsonData.AddPair(cJsonDTS, lvalDTS.ToString);
lJsonArray := TJSONArray.Create;
lJsonArray.Add(lJsonData);
lJsonObj := JsonFromDB;
lJsonObj.AddPair(area + year.ToString, lJsonArray);
TFile.WriteAllText(cDBfile, lJsonObj.ToString);
finally
lJsonObj.Free;
end;
end;
end;
function GetPageContent(const area: string; year: word): string;
begin
Result := TMyHttpGet.GetWebsiteContent(MakeValidUrl(area, year));
end;
function MakeValidUrl(const area: string; year: word): string;
begin
Result := Format(cUrlStr, [area, year]);
end;
function IsDaylightSaving(const area: string; year: word): Boolean;
begin
Result := GetDaylightParamFromRecord(area, year, jpDTS);
end;
function GetDaylightStart(const area: string; year: word): TDateTime;
begin
Result := GetDaylightParamFromRecord(area, year, jpStart);
end;
function GetDaylightEnd(const area: string; year: word): TDateTime;
begin
Result := GetDaylightParamFromRecord(area, year, jpEnd);
end;
initialization
begin
DeleteFile(cDBfile);
end;
end.
|
unit uHttpDownloader;
interface
uses
Windows, Messages, SysUtils, Variants, Classes,
IdBaseComponent, IdComponent,
IdTCPConnection, IdTCPClient, IdHTTP, IdURI,
math, uFileBlockStream;
Const
_1seg = 1/24/3600;
_500ms = 1/24/3600/2;
type
THttpDownloaderProgress = procedure (Sender: TObject; aPosition, aSize: int64; aPercent, aVel: double; aTimeLeft: TDateTime; aMayUpdate:boolean) of Object;
THttpDownloader = class(TComponent)
private
IdHTTP1: TIdHTTP;
FHost : string;
FURLpath : string;
FFilename : string;
FdnFolder : string;
FDelay : integer;
FOnProgress : THttpDownloaderProgress;
FIniTime : TDateTime;
FVelInst : double;
FVel1 : double;
FVel2 : double;
FVel3 : double;
FLastTime : TDateTime;
FLastUpdate : TDateTime;
FLastBytes : int64;
fs : TFileBlockStream;
procedure SetdnFolder (adnFolder : string);
procedure BufferEvent(Sender: TObject; var Buffer; Count: Longint; isLast:boolean);
{ Private declarations }
public
property Delay : integer read FDelay write FDelay;
property Host : string read FHost write FHost;
property URLpath : string read FURLpath write FURLpath;
property Filename : string read FFilename write FFilename;
property dnFolder : string read FdnFolder write SetdnFolder;
property OnProgress : THttpDownloaderProgress
read FOnProgress write FOnProgress;
function Download:boolean;
procedure Cancel;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{ Public declarations }
end;
implementation
constructor THttpDownloader.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
IdHTTP1 := TIdHTTP.Create(nil);
IdHTTP1.ConnectTimeout := 5000;
IdHTTP1.ReadTimeout := 30000;
end;
destructor THttpDownloader.Destroy;
begin
IdHTTP1.Free;
inherited Destroy;
end;
procedure THttpDownloader.SetdnFolder (adnFolder: string);
begin
if adnFolder<>FdnFolder then begin
FdnFolder := adnFolder;
forcedirectories (FdnFolder);
end;
end;
procedure THttpDownloader.Cancel;
begin
IdHTTP1.Disconnect;
end;
function THttpDownloader.Download:boolean;
var
err : boolean;
cl : integer;
procedure cleanup;
begin
fs.Free;
if err and (fileexists(FdnFolder+FFilename)) then
deletefile(FdnFolder+FFilename);
end;
begin
cl:=0;
err := true;
FLastTime :=0;
FLastUpdate :=0;
FLastBytes :=0;
FVel1 := 0;
FVel2 := 0;
FVel3 := 0;
if fileexists(FdnFolder+FFilename) then
deletefile(FdnFolder+FFilename);
fs := TFileBlockStream.Create(FdnFolder+FFilename, fmCreate );
fs.WriteBlockSize := $7FFF;
fs.OnWriteBuffer := BufferEvent;
IdHTTP1.Disconnect;
IdHTTP1.Host := FHost;
try
IdHTTP1.head(TIdURI.PathEncode(FURLpath+FFilename));
fs.WriteBlockSize := $7FFF;// * 10;
FIniTime := now;
IdHTTP1.get(TIdURI.PathEncode(FURLpath+FFilename), fs);
if IdHTTP1.Response.HasContentLength then
cl := IdHTTP1.Response.ContentLength;
err:=( cl>0)and(cl<>fs.size);
result:=( cl>0)and(cl=fs.size);
except
on e:exception do begin
cleanup;
raise;
end;
end;
cleanup;
IdHTTP1.Disconnect;
end;
procedure THttpDownloader.BufferEvent(Sender: TObject; var Buffer; Count: Longint; isLast:boolean);
var
TimeLeft: TDateTime;
MayUpdate : boolean;
velMedia : double;
begin
TimeLeft := 0;
velMedia := 0;
MayUpdate := false;
if now-FLastTime>0 then begin
FVelInst := (fs.Position - FLastBytes) / ((now-FLastTime)*24*3600);
if FVel1 = 0 then FVel1 := FVelInst;
if FVel2 = 0 then FVel1 := FVelInst;
if FVel3 = 0 then FVel1 := FVelInst;
FVel3 := FVel2;
FVel2 := FVel1;
FVel1 := FVelInst;
velMedia := (FVel1 + FVel2 + FVel3)/3;
try
TimeLeft := ( (fs.Size - fs.Position) / velMedia / 24 / 3600 ) + _1seg; ;
except
TimeLeft := 0;
end;
MayUpdate := (now-FLastUpdate) > _500ms ;
if MayUpdate then
FLastUpdate := 0;
if velMedia<10 then
IdHTTP1.ReadTimeout := 60000
else
if velMedia<25 then
IdHTTP1.ReadTimeout := 45000
else
IdHTTP1.ReadTimeout := 30000;
end;
if assigned(FOnProgress) then
FOnProgress(Self, fs.Position, fs.Size, (fs.Position/fs.Size)*100,
velMedia, TimeLeft, MayUpdate);
FLastTime := now;
FLastBytes := fs.Position;
if FDelay>0 then
sleep(FDelay);
end;
end.
|
unit TestMapReduce;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, SysUtils, MapReduce;
type
// Test methods for class TMapReduce
TestTMapReduce = class(TTestCase)
private
procedure ForEachAddTriangle(var X: string; const I: Integer; var Done: Boolean);
procedure ForEachLAddTriangle(var X: string);
function Map(const X: string; const I: Integer): string;
function MapL(const X: string): string;
function FilterLengthMoreThan1(const X: string; const I: Integer): Boolean;
function FilterLLengthMoreThan1(const X: string): Boolean;
function PredicateEndsWithTriangle(const X: string): Boolean;
function Reduce(const Accumulator: string; const X: string; const I: Integer): string;
function ReduceL(const Accumulator: string; const X: string): string;
function MapTo(const X: string; const I: Integer): string;
function MapToL(const X: string): string;
function ReduceTo(const Accumulator: string; const X: string; const I: Integer): string;
function ReduceToL(const Accumulator: string; const X: string): string;
function MapToIntegerL(const X: string): Integer;
function ReduceIntegersL(const Accumulator: Integer; const X: Integer): Integer;
function ReduceToIntegerL(const Accumulator: Integer; const X: string): Integer;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestForEachArrChange;
procedure TestForEachArrChange1;
procedure TestForEachArrChange2;
procedure TestForEachArrChange3;
procedure TestForEach;
procedure TestForEach1;
procedure TestForEach2;
procedure TestForEach3;
procedure TestForEach4;
procedure TestForEach5;
procedure TestMap;
procedure TestFilter;
procedure TestReduce;
procedure TestMapToInteger;
procedure TestReduceToInteger;
end;
implementation
uses System.Generics.Collections, System.Types;
type
TTestCaseList = class
class function Create: TList<string>;
end;
const
c_std_arr: TStringDynArray = ['1', '22', '333', '4444'];
c_tarray: TArray<string> = ['1', '22', '333', '4444'];
{ TTestCaseList }
class function TTestCaseList.Create: TList<string>;
var
ResultList: TList<string>;
begin
ResultList := TList<string>.Create;
TMapReduce<string>.ForEach(c_std_arr,
procedure(const X: string)
begin
ResultList.Add(X);
end);
Result := ResultList;
end;
{ TestTMapReduce }
function TestTMapReduce.FilterLengthMoreThan1(const X: string; const I: Integer): Boolean;
begin
if X.Length > 1 then
Result := True
else
Result := False;
end;
function TestTMapReduce.FilterLLengthMoreThan1(const X: string): Boolean;
begin
if X.Length > 1 then
Result := True
else
Result := False;
end;
procedure TestTMapReduce.ForEachAddTriangle(var X: string; const I: Integer; var Done: Boolean);
begin
X := X + StringOfChar('▲', I + 1);
Done := False;
end;
procedure TestTMapReduce.ForEachLAddTriangle(var X: string);
begin
X := X + '▲';
end;
function TestTMapReduce.Map(const X: string; const I: Integer): string;
begin
Result := X + StringOfChar('▲', I + 1);
end;
function TestTMapReduce.MapL(const X: string): string;
begin
Result := X + '▲';
end;
function TestTMapReduce.MapTo(const X: string; const I: Integer): string;
begin
Result := X + StringOfChar('▲', I + 1);
end;
function TestTMapReduce.MapToL(const X: string): string;
begin
Result := X + '▲';
end;
function TestTMapReduce.PredicateEndsWithTriangle(const X: string): Boolean;
begin
Result := X.EndsWith('▲');
end;
function TestTMapReduce.Reduce(const Accumulator, X: string; const I: Integer): string;
begin
Result := Accumulator + sLineBreak + X + StringOfChar('▲', I + 1);
end;
function TestTMapReduce.ReduceL(const Accumulator, X: string): string;
begin
Result := Accumulator + sLineBreak + X;
end;
function TestTMapReduce.ReduceTo(const Accumulator, X: string; const I: Integer): string;
begin
Result := Accumulator + sLineBreak + X + StringOfChar('▲', I + 1);
end;
function TestTMapReduce.ReduceToL(const Accumulator, X: string): string;
begin
Result := Accumulator + sLineBreak + X;
end;
function TestTMapReduce.MapToIntegerL(const X: string): Integer;
begin
Result := X.ToInteger;
end;
function TestTMapReduce.ReduceIntegersL(const Accumulator, X: Integer): Integer;
begin
Result := Accumulator + X;
end;
function TestTMapReduce.ReduceToIntegerL(const Accumulator: Integer; const X: string): Integer;
begin
Result := Accumulator + X.ToInteger;
end;
procedure TestTMapReduce.SetUp;
begin
end;
procedure TestTMapReduce.TearDown;
begin
end;
procedure TestTMapReduce.TestForEachArrChange;
var
Source: TArray<string>;
begin
// Setup method call parameters
Source := Copy(c_tarray);
// Testing
TMapReduce<string>.ForEachArrChange(Source, ForEachAddTriangle);
// Validate method results
CheckTrue(TMapReduce<string>.Every(Source, PredicateEndsWithTriangle));
end;
procedure TestTMapReduce.TestForEachArrChange1;
var
Source: TStringDynArray;
begin
// Setup method call parameters
Source := Copy(c_std_arr);
// Testing
TMapReduce<string>.ForEachArrChange(Source, ForEachAddTriangle);
// Validate method results
CheckTrue(TMapReduce<string>.Every(Source, PredicateEndsWithTriangle));
end;
procedure TestTMapReduce.TestForEachArrChange2;
var
Source: TArray<string>;
begin
// Setup method call parameters
Source := Copy(c_tarray);
// Testing
TMapReduce<string>.ForEachArrChange(Source, ForEachLAddTriangle);
// Validate method results
CheckTrue(TMapReduce<string>.Every(Source, PredicateEndsWithTriangle));
end;
procedure TestTMapReduce.TestForEachArrChange3;
var
Source: TStringDynArray;
begin
// Setup method call parameters
Source := Copy(c_std_arr);
// Testing
TMapReduce<string>.ForEachArrChange(Source, ForEachLAddTriangle);
// Validate method results
CheckTrue(TMapReduce<string>.Every(Source, PredicateEndsWithTriangle));
end;
procedure TestTMapReduce.TestFilter;
begin
CheckTrue(Length(TMapReduce<string>.Filter(c_std_arr, FilterLengthMoreThan1))
= Length(c_std_arr) - 1);
end;
procedure TestTMapReduce.TestMap;
begin
CheckTrue(TMapReduce<string>.Every(TMapReduce<string>.Map(c_std_arr, Map),
PredicateEndsWithTriangle));
end;
procedure TestTMapReduce.TestMapToInteger;
begin
CheckTrue(TMapReduce<Integer>.Reduce(TMapReduce<string, Integer>.Map(c_std_arr, MapToIntegerL),
ReduceIntegersL) = 4800);
end;
procedure TestTMapReduce.TestReduce;
var
ResultValue: string;
begin
ResultValue := TMapReduce<string>.Reduce(c_tarray, Reduce);
CheckTrue(Length(ResultValue.Split([sLineBreak])) = Length(c_std_arr));
end;
procedure TestTMapReduce.TestReduceToInteger;
begin
CheckTrue(TMapReduce<string, Integer>.Reduce(c_std_arr, 0, ReduceToIntegerL) = 4800);
end;
procedure TestTMapReduce.TestForEach;
var
Source: TList<string>;
LoopCount: Integer;
begin
// Setup method call parameters
Source := TTestCaseList.Create;
try
LoopCount := 0;
// Testing
TMapReduce<string>.ForEach(Source,
procedure(const X: string; const I: Integer; var Done: Boolean)
begin
if I = high(c_tarray) then
Done := True
else
begin
Done := False;
Inc(LoopCount);
end;
end);
finally
FreeAndNil(Source);
end;
// Validate method results
CheckTrue(LoopCount = Length(c_std_arr) - 1);
end;
procedure TestTMapReduce.TestForEach1;
var
LoopCount: Integer;
begin
// Setup method call parameters
LoopCount := 0;
// Testing
TMapReduce<string>.ForEach(c_tarray,
procedure(const X: string; const I: Integer; var Done: Boolean)
begin
if I = high(c_tarray) then
Done := True
else
begin
Done := False;
Inc(LoopCount);
end;
end);
// Validate method results
CheckTrue(LoopCount = Length(c_tarray) - 1);
end;
procedure TestTMapReduce.TestForEach2;
var
LoopCount: Integer;
begin
// Setup method call parameters
LoopCount := 0;
// Testing
TMapReduce<string>.ForEach(c_std_arr,
procedure(const X: string; const I: Integer; var Done: Boolean)
begin
if I = high(c_std_arr) then
Done := True
else
begin
Done := False;
Inc(LoopCount);
end;
end);
// Validate method results
CheckTrue(LoopCount = Length(c_std_arr) - 1);
end;
procedure TestTMapReduce.TestForEach3;
var
Source: TList<string>;
LoopCount: Integer;
begin
// Setup method call parameters
Source := TTestCaseList.Create;
try
LoopCount := 0;
// Testing
TMapReduce<string>.ForEach(Source,
procedure(const X: string)
begin
Inc(LoopCount);
end);
finally
FreeAndNil(Source);
end;
// Validate method results
CheckTrue(LoopCount = Length(c_std_arr));
end;
procedure TestTMapReduce.TestForEach4;
var
LoopCount: Integer;
begin
// Setup method call parameters
LoopCount := 0;
// Testing
TMapReduce<string>.ForEach(c_tarray,
procedure(const X: string)
begin
Inc(LoopCount);
end);
// Validate method results
CheckTrue(LoopCount = Length(c_tarray));
end;
procedure TestTMapReduce.TestForEach5;
var
LoopCount: Integer;
begin
// Setup method call parameters
LoopCount := 0;
// Testing
TMapReduce<string>.ForEach(c_std_arr,
procedure(const X: string)
begin
Inc(LoopCount);
end);
// Validate method results
CheckTrue(LoopCount = Length(c_std_arr));
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTMapReduce.Suite);
end.
|
unit Kafka.FMX.Form.Main;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, System.Actions, System.DateUtils, System.SyncObjs,
System.Generics.Collections, System.Rtti,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.ActnList, FMX.Memo.Types, FMX.ScrollBox,
FMX.Edit, FMX.EditBox, FMX.SpinBox, FMX.Memo, FMX.Layouts,
FMX.Grid.Style, FMX.Grid,
Kafka.Lib,
Kafka.Factory,
Kafka.Interfaces,
Kafka.Helper,
Kafka.Types,
Kafka.FMX.Helper;
type
TLogEntryRec = record
Sender: String;
Value: String;
Timestamp: TDateTime;
end;
TfrmKafkaDemo = class(TForm)
ActionList1: TActionList;
tmrUpdate: TTimer;
GridPanelLayout1: TGridPanelLayout;
GroupBox3: TGroupBox;
Layout1: TLayout;
Label1: TLabel;
edtKafkaServer: TEdit;
actNewProducer: TAction;
actNewConsumer: TAction;
Button2: TButton;
Button1: TButton;
Options: TGroupBox;
GroupBox1: TGroupBox;
grdCallbacks: TGrid;
colType: TStringColumn;
colValue: TStringColumn;
grdDebugLog: TGrid;
colTimestamp: TStringColumn;
colLogText: TStringColumn;
colCallbackTimestamp: TStringColumn;
colDebugType: TStringColumn;
procedure tmrUpdateTimer(Sender: TObject);
procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure edtKafkaServerChange(Sender: TObject);
procedure edtTopicChange(Sender: TObject);
procedure actNewProducerExecute(Sender: TObject);
procedure actNewConsumerExecute(Sender: TObject);
procedure grdCallbackLogGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue);
procedure grdDebugLogGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue);
private
FStringEncoding: TEncoding;
FKafkaConsumer: IKafkaConsumer;
FCallbackLog: TList<TLogEntryRec>;
FDebugLog: TList<TLogEntryRec>;
procedure OnLog(const Values: TStrings);
procedure UpdateStatus;
procedure DestroyClasses;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
frmKafkaDemo: TfrmKafkaDemo;
implementation
{$R *.fmx}
uses
Kafka.FMX.Form.Producer,
Kafka.FMX.Form.Consumer;
{ TfrmKafkaDemo }
procedure TfrmKafkaDemo.OnLog(const Values: TStrings);
var
i: Integer;
LogEntryRec: TLogEntryRec;
List: TList<TLogEntryRec>;
begin
for i := 0 to pred(Values.Count) do
begin
LogEntryRec.Timestamp := now;
LogEntryRec.Value := Values[i];
LogEntryRec.Sender := KafkaLogTypeDescriptions[TKafkaLogType(Values.Objects[i])];
if TKafkaLogType(Values.Objects[i]) in [kltProducer, kltConsumer] then
begin
List := FCallbackLog;
end
else
begin
List := FDebugLog;
end;
List.Add(LogEntryRec);
end;
while FCallbackLog.Count > TFMXHelper.MAX_LOG_LINES do
begin
FCallbackLog.Delete(0);
end;
while FDebugLog.Count > TFMXHelper.MAX_LOG_LINES do
begin
FDebugLog.Delete(0);
end;
TFMXHelper.SetGridRowCount(grdCallbacks, FCallbackLog.Count);
TFMXHelper.SetGridRowCount(grdDebugLog, FDebugLog.Count);
end;
procedure TfrmKafkaDemo.actNewConsumerExecute(Sender: TObject);
begin
with TfrmConsume.Create(Self) do
begin
Execute(edtKafkaServer.Text);
end;
end;
procedure TfrmKafkaDemo.actNewProducerExecute(Sender: TObject);
begin
with TfrmProduce.Create(Self) do
begin
Execute(edtKafkaServer.Text);
end;
end;
procedure TfrmKafkaDemo.ActionList1Update(Action: TBasicAction; var Handled: Boolean);
begin
Handled := True;
end;
constructor TfrmKafkaDemo.Create(AOwner: TComponent);
begin
inherited;
TKafkaHelper.OnLog := OnLog;
FStringEncoding := TEncoding.UTF8;
FCallbackLog := TList<TLogEntryRec>.Create;
FDebugLog := TList<TLogEntryRec>.Create;
UpdateStatus;
end;
procedure TfrmKafkaDemo.edtKafkaServerChange(Sender: TObject);
begin
DestroyClasses;
end;
procedure TfrmKafkaDemo.edtTopicChange(Sender: TObject);
begin
FKafkaConsumer := nil;
end;
destructor TfrmKafkaDemo.Destroy;
begin
FreeAndNil(FCallbackLog);
FreeAndNil(FDebugLog);
inherited;
end;
procedure TfrmKafkaDemo.DestroyClasses;
begin
FKafkaConsumer := nil;
end;
procedure TfrmKafkaDemo.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
DestroyClasses;
// Wait for all the threads to terminate
sleep(1000);
end;
procedure TfrmKafkaDemo.grdCallbackLogGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue);
begin
case ACol of
0: Value := TKafkaUtils.DateTimeToStrMS(FCallbackLog[ARow].Timestamp);
1: Value := FCallbackLog[ARow].Sender;
2: Value := FCallbackLog[ARow].Value;
end;
end;
procedure TfrmKafkaDemo.grdDebugLogGetValue(Sender: TObject; const ACol, ARow: Integer; var Value: TValue);
begin
case ACol of
0: Value := TKafkaUtils.DateTimeToStrMS(FDebugLog[ARow].Timestamp);
1: Value := FDebugLog[ARow].Sender;
2: Value := FDebugLog[ARow].Value;
end;
end;
procedure TfrmKafkaDemo.tmrUpdateTimer(Sender: TObject);
begin
UpdateStatus;
end;
procedure TfrmKafkaDemo.UpdateStatus;
begin
TKafkaHelper.FlushLogs;
end;
end.
|
unit ASDLog;
{<|Модуль библиотеки ASDEngine|>}
{<|Дата создания 31.05.07|>}
{<|Автор Adler3D|>}
{<|e-mail : Adler3D@Mail.ru|>}
{<|Дата последнего изменения 31.05.07|>}
interface
uses
Windows, ASDUtils, ASDType,
ASDInterface;
type
TLog = class(TASDObject, ILog)
private
FTimeStamp: Boolean; // Time Stamp
FActiveFlush: Boolean; // Active Flush
FStream: IFileStream;
FSec: ITimer;
FLineCount: Integer;
procedure AddToFile(S: string);
procedure NextLine(Time: Integer; Sender, Msg: string; ID: string = '');
public
constructor CreateEx; override;
function Create(FileName: PChar): Boolean;
procedure Print(Sender: IASDObject; Text: PChar);
function Msg(Caption, Text: PChar; ID: Cardinal): Integer;
procedure TimeStamp(Active: Boolean);
procedure Flush(Active: Boolean);
procedure Free;
procedure UnLoad; override;
end;
implementation
uses
ASDEng;
constructor TLog.CreateEx;
begin
inherited CreateEx;
FTimeStamp := True;
FActiveFlush := False;
end;
function TLog.Create(FileName: PChar): Boolean;
const
C_H1: string = '<html><head><title>';
C_H2: string = '</title>'#13#10;
C_H3: string =
'<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">'#13#10
+ '<style type="text/css">'#13#10'<!--body {background-color: #000000;}' +
'body,td,th {color: #FFFFFF;font-family: Courier New, Courier, mono;}' +
'tr#sel {background-color: #666666;} td#c1{width: 70px;text-align: right;}' +
'td#c2 {text-align: center;width: 100px;}td#rs {background-color: #333333;width: 1px;}'+
'-->'#13#10'</style></head><body>'#13#10 +
'<table cellSpacing="1" cellPadding="0" width="100%" border="1" bgcolor="#FF9900"><tr><td>'#13#10
+ '<table id="out" width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="#000000">'#13#10;
begin
if FSec = nil then
begin
FSec := Tools.InitTimer;
FSec.Start;
end;
Free;
FStream := Tools.InitFileStream(FileName, fmCreate);
Result := FStream.Valid;
FLineCount := 0;
if Result then
begin
AddToFile(C_H1 + ENG_NAME + '[' + FileName + ']' + C_H2 + C_H3);
NextLine(-1, '', '<b>"' + ENG_NAME + ' ' + ENG_VER + '" log start</b>',
'sel');
end;
end;
procedure TLog.Print(Sender: IASDObject; Text: PChar);
var
S: string;
Zeit: Integer;
begin
if FStream.Valid then
begin
if FTimeStamp then
begin
FSec.Stop;
Zeit := Round(FSec.Time);
FSec.Start;
end;
if Sender <> nil then
begin
S := Sender.ASDName;
if S[1] = 'T' then
S := Copy(S, 2, Length(S) - 1);
end;
NextLine(Zeit, S, Text);
if FActiveFlush then
begin
//FStream
end;
end;
end;
function TLog.Msg(Caption, Text: PChar; ID: Cardinal): Integer;
begin
Result := MessageBox(Window.Handle, Text, Caption, ID);
end;
procedure TLog.TimeStamp(Active: Boolean);
begin
FTimeStamp := Active;
end;
procedure TLog.Flush(Active: Boolean);
begin
FActiveFlush := Active;
end;
procedure TLog.Free;
const
C_End: string = '</table></table></body></html>'#13#10;
begin
if FStream = nil then
Exit;
AddToFile(C_End);
FStream.UnLoad;
FStream := nil;
end;
procedure TLog.UnLoad;
begin
FSec.UnLoad;
Print(nil, PChar('ASDAllOBJ = ' + IntToStr(ASDAllOBJ)));
Print(nil, PChar('ASDCountOBJ = ' + IntToStr(ASDCountOBJ)));
NextLine(-1, '', '<b>"' + ENG_NAME + ' ' + ENG_VER + '" log close</b>',
'sel');
Free;
inherited UnLoad;
end;
procedure TLog.AddToFile(S: string);
begin
FStream.Write(S[1], Length(S));
end;
procedure TLog.NextLine(Time: Integer; Sender, Msg: string; ID: string);
const
C_Space: string = ' ';
function F(Teg, ID, Atr, S: string): string;
begin
if S = '' then
S := C_Space;
if ID <> '' then
Result := '<' + Teg + ' id="' + ID + '"' + Atr + '>' + S + '</' + Teg + '>'
else
Result := '<' + Teg + ' ' + Atr + '>' + S + '</' + Teg + '>';
end;
var
RS, V_Time: string;
begin
Inc(FLineCount);
if Sender = '' then
Sender := C_Space;
if Msg = '' then
Msg := C_Space;
V_Time := '';
if Time <> -1 then
V_Time := IntToStr(Time);
RS := '';
if FLineCount = 1 then
begin
RS := F('td', 'rs', 'rowspan="9500"', '');
end;
AddToFile(F('tr', ID, '', F('td', 'c1', '', V_Time) + RS +
F('td', 'c2', '', Sender) + RS + F('td', '', '', Msg)));
end;
end.
|
unit PeriodicPublishObj;
interface
uses
Windows, System.Classes, System.SysUtils,
Winapi.Messages, Vcl.Dialogs, System.UITypes, System.StrUtils,
Vcl.Forms, Vcl.ExtCtrls, CodeSiteLogging;
type
TPublishProc = procedure(topic, payload: string; QoS: Integer; Retain: Boolean) of object;
TBUBFuncsType = (pbfRandom, pbfSinus, pbfTriangle, pbfSquare);
type
TPeriodicPublishObj = class(TTimer)
private
F_topic: String;
F_paylod: STring;
F_QoS: Integer;
F_retain: Boolean;
F_function: Integer; // Номер функции
F_max: single; // Максимум выходной величины
F_min: single; // Минимум выходной величины
F_periodicity: Integer;
F_sample_cnt: Integer; // Счетчик отсчетов
F_publishproc: TPublishProc;
F_offs: Integer;
procedure SetPayload(Value: String);
protected
procedure EventHandler(Sender: TObject);
public
procedure SetPackData(topicv, payloadv: string; QoSv: Integer; Retainv: Boolean);
procedure SetFunction(func: Integer; minv, maxv: single; periodicityv, offsv: Integer);
constructor Create(AOwner: TComponent; timeout: Integer; publishproc: TPublishProc);
destructor Destroy; override;
published
property topic: String read F_topic write F_topic;
property payload: String read F_paylod write SetPayload;
property QoS: Integer read F_QoS write F_QoS default 0;
property Retain: Boolean read F_retain write F_retain default False;
end;
implementation
constructor TPeriodicPublishObj.Create(AOwner: TComponent; timeout: Integer; publishproc: TPublishProc);
begin
inherited Create(AOwner);
Enabled := False;
Interval := timeout;
OnTimer := EventHandler;
F_publishproc := publishproc;
end;
procedure TPeriodicPublishObj.SetPackData(topicv, payloadv: string; QoSv: Integer; Retainv: Boolean);
begin
F_topic := topicv;
F_QoS := QoSv;
F_retain := Retainv;
payload := payloadv;
end;
procedure TPeriodicPublishObj.SetFunction(func: Integer; minv, maxv: single; periodicityv, offsv: Integer);
begin
F_function := func;
F_max := maxv;
F_min := minv;
F_periodicity := periodicityv;
F_offs := offsv;
end;
procedure TPeriodicPublishObj.SetPayload(Value: String);
begin
F_paylod := Value;
end;
procedure TPeriodicPublishObj.EventHandler(Sender: TObject);
var
v: single;
vstr: String;
begin
try
case TBUBFuncsType(F_function) of
pbfRandom:
v := Random * (F_max - F_min) + F_min;
pbfSinus:
v := ((sin(((F_sample_cnt + F_offs)mod F_periodicity) * 2 * 3.141592653 / F_periodicity) + 1) / 2) * (F_max - F_min) + F_min;
pbfTriangle:
v := 0;
pbfSquare:
v := 0;
else
v := 0;
end;
except
v := 0;
end;
// Ищем и заменяем а Paylod патерн переменной на саму переменню
try
vstr := format(F_paylod, [v]);
except
vstr := F_paylod;
end;
if Assigned(F_publishproc) then
F_publishproc(F_topic, vstr, F_QoS, F_retain);
Inc(F_sample_cnt);
end;
destructor TPeriodicPublishObj.Destroy;
begin
Enabled := False;
inherited Destroy;
end;
end.
|
{ Fonctions de chaines pour Mister Patate }
unit MrpStr;
interface
{ Convertit une valeur en chaine }
function Str (Valeur: LongInt; NbrChiffre: Byte): String;
{ Convertit une valeur en chaine en laissant des espaces }
function StrE (Valeur: LongInt; NbrChiffre: Byte): String;
{ Convertit une chaine en valeur }
function Val (S: String): LongInt;
{ Convertit une valeur en chaine hexad‚cimale }
function StrHexa (Valeur: LongInt; NbrChiffre: Byte): String;
{ Convertit une valeur en chaine hexad‚cimale }
function ValHexa (S: String): Word;
{ Convertit un pointer en SSSS:OOOO }
function PtrToStr(P: Pointer): String;
{ Cr‚e une chaine du mˆme charactŠre }
function StrChar (Charact: Char; Nb: Word): String;
{ Cr‚e une chaine de 80 espaces avec un texte au milieu }
function CenterText (Txt: String): String;
{ Renvoie 'OUI' si Bool = True et 'NON' si Bool = False }
function StrOk (Bool: Boolean): String;
{ Nombre de nombre de chiffre d'un nombre }
function Len (Nombre: Word): Byte;
{ Convertit une chaine en minuscule }
function StrLower (S: String): String;
{ Renvoie la moiti‚ d'une chaine }
function StrPart1 (S: String): String;
function StrPart2 (S: String): String;
implementation
function Str; assembler;
asm
DB $66; XOR DX,DX
MOV DX,10
DB $66; MOV SI,DX
LES DI,@Result { ES:DI -> Chaine de destination }
XOR AH,AH
MOV AL,NbrChiffre { Si NbrChiffre <> 0, on prend le nombre }
OR AL,AL { de chiffre indiqu‚es }
JNZ @CHiffreIndique
DB 66h
MOV AX,Valeur.Word
XOR CX,CX
INC DI
TEST Valeur.Word[2],8000h { Si la valeur est < 0 }
JZ @@3 { la chaine commence par '-' }
MOV ES:Byte[DI],'-'
INC DI
DB 66h
NEG AX
@@3: XOR DX,DX
DB 66h
DIV SI
ADD DL,'0'
MOV ES:[DI],DL
INC DI
INC CL
DB 66h
OR AX,AX
JNZ @@3
LES DI,@Result
MOV ES:[DI],CL
MOV SI,DI
ADD SI,CX
INC DI
CMP ES:Byte[DI],'-'
JNE @@7
INC ES:Byte[DI-1]
INC DI
INC SI
@@7: SHR CX,1
OR CX,CX
JZ @@4
@@5: MOV AL,ES:[DI]
XCHG AL,ES:[SI]
STOSB
DEC SI
LOOP @@5
JMP @@4
@ChiffreIndique:
STOSB
TEST Valeur.Word[2],8000h
JZ @@6
MOV ES:Byte[DI],'-'
INC ES:Byte[DI-1]
INC DI
DB 66h
NEG Valeur.Word
@@6: ADD DI,AX
DEC DI
MOV CX,AX
DB 66h
MOV AX,Valeur.Word
@@1: XOR DX,DX
DB 66h
DIV SI
ADD DL,"0"
MOV ES:[DI],DL
DEC DI
LOOP @@1
@@4:
end;
function StrE; assembler;
asm
DB $66; XOR DX,DX
MOV DX,10
DB $66; MOV SI,DX
LES DI,@Result
XOR AH,AH
MOV AL,NbrChiffre
STOSB
TEST Valeur.Word[2],8000h
JZ @@6
MOV ES:Byte[DI],'-'
INC ES:Byte[DI-1]
INC DI
DB 66h
NEG Valeur.Word
@@6: ADD DI,AX
DEC DI
MOV CX,AX
DB 66h
MOV AX,Valeur.Word
@@1: XOR DX,DX
DB 66h
DIV SI
ADD DL,"0"
MOV ES:[DI],DL
DEC DI
DB $66; OR AX,AX
JZ @@2
LOOP @@1
JMP @@4
@@2: DEC CX
JZ @@4
MOV AL,' '
STD
REP STOSB
CLD
@@4:
end;
function Val; assembler;
asm
XOR DX,DX
XOR AX,AX
PUSH DS
LDS SI,S
LODSB
MOV CL,AL
XOR CH,CH
OR AL,AL
JZ @@1
DB 66h
XOR AX,AX
DB 66h
XOR BX,BX
DB 66h
XOR DI,DI
MOV DI,10
CMP DS:Byte[SI],'-'
JNE @@2
INC SI
DEC CX
@@2: MOV BL,DS:[SI]
INC SI
SUB BL,'0'
DB 66h
MUL DI
DB 66h
ADD AX,BX
DB 66h
LOOP @@2
LDS SI,S
CMP DS:Byte[SI+1],'-'
JNE @@3
DB 66h
NEG AX
@@3: MOV BX,AX
DB 66h
SHR AX,16
MOV DX,AX
MOV AX,BX
@@1: POP DS
end;
function StrHexa; assembler;
asm
DB 66h
MOV DX,Valeur.Word
LES DI,@Result
XOR AH,AH
MOV AL,NbrChiffre
OR AL,AL
JNZ @@2
INC DI
XOR BH,BH
XOR CX,CX
@@3: INC CL
MOV AL,DL
AND AL,15
CMP AL,9
JA @@6
ADD AL,'0'
JMP @@7
@@6: ADD AL,'A' - 10
@@7: STOSB
DB 66h
SHR DX,4
DB 66h
OR DX,DX
JNZ @@3
LES DI,@Result
MOV ES:[DI],CL
MOV SI,DI
ADD SI,CX
INC DI
SHR CX,1
OR CX,CX
JZ @@4
@@5: MOV AL,ES:[DI]
XCHG AL,ES:[SI]
STOSB
DEC SI
LOOP @@5
JMP @@4
@@2: STOSB
ADD DI,AX
DEC DI
STD
MOV CL,AL
XOR CH,CH
XOR BH,BH
@@1: MOV AL,DL
AND AL,15
CMP AL,9
JA @@8
ADD AL,'0'
JMP @@9
@@8: ADD AL,'A' - 10
@@9: STOSB
DB 66h
SHR DX,4
LOOP @@1
CLD
@@4:
end;
function ValHexa; assembler;
asm
XOR DX,DX
XOR AX,AX
PUSH DS
LDS SI,S
LODSB
MOV DI,AX
OR AL,AL
JZ @@1
DB 66h
XOR BX,BX
DB 66h
XOR AX,AX
ADD SI,DI
DEC SI
STD
XOR CL,CL
@@2: LODSB
CMP AL,'9'
JA @@3
SUB AL,'0'
JMP @@4
@@3: SUB AL,'A' - 10
@@4: DB 66h
SHL AX,CL
DB 66h
OR BX,AX
DB 66h
XOR AX,AX
ADD CL,4
DEC DI
JNZ @@2
CLD
MOV AX,BX
DB 66h
SHR BX,16
MOV DX,BX
@@1: POP DS
end;
function PtrToStr;
begin
PtrToStr := StrHexa (LongInt (P) shr 16, 4) + ':' + StrHexa (LongInt (P) and $FFFF, 4);
end;
function StrChar; assembler;
asm
LES DI,@Result { ES:DI -> Chaine de destination }
MOV AX,Nb
STOSB
MOV CX,AX
MOV AL,Charact
REP STOSB
end;
function CenterText; assembler;
asm
LES DI,@Result { ES:DI -> Chaine de destination }
MOV AL,80
STOSB { Length (CenterText) = 80 }
DB 66h
MOV AX," "
DW " " { EAX = 4 esapces }
MOV CX,20
DB 66h
REP STOSW { Remplit la chaine d'espace }
SUB DI,40 { Met DI au milieu de la chaine }
PUSH DS
LDS SI,Txt { DS:SI -> Texte … centrer }
LODSB { Longueur du texte }
XOR AH,AH
MOV CX,AX
SHR AX,1
SUB DI,AX { DI = 40 - Length (Txt) / 2 }
REP MOVSB
POP DS
end;
function StrOk; assembler;
asm
LES DI,@Result
TEST [Bool],255
JZ @Non
DB 66h
MOV AX,"O" * 256 + 3
DW "IU"
JMP @Fin
@Non: DB 66h
MOV AX,"N" * 256 + 3
DW "NO"
@Fin: DB 66h
STOSW
end;
function Len; assembler;
asm
MOV AX,WORD[Nombre]
XOR DX,DX
XOR CL,CL
MOV BX,10
@LoopLen:
XOR DX,DX
DIV BX
INC CL
OR AX,AX
JNZ @LoopLen
MOV AL,CL
end;
function StrLower; assembler;
asm
PUSH DS
LDS SI,[S]
LES DI,@Result
LODSB
STOSB
MOV CL,AL
XOR CH,CH
@LoopStr:
LODSB
CMP AL,'A'
JB @PutChar
CMP AL,'Z'
JA @PutChar
OR AL,32
@PutChar:
STOSB
LOOP @LoopStr
POP DS
end;
function StrPart1;
var
Middle, Pos: Byte;
begin
Middle := Length (S) shr 1;
Pos := 0;
repeat
if S[Middle-Pos] = ' ' then begin
StrPart1 := Copy (S, 1, Middle - Pos - 1);
exit;
end;
if S[Middle+Pos] = ' ' then begin
StrPart1 := Copy (S, 1, Middle + Pos - 1);
exit;
end;
inc (Pos);
until false;
end;
function StrPart2;
var
Middle, Pos: Byte;
begin
Middle := Length (S) shr 1;
Pos := 0;
repeat
if S[Middle-Pos] = ' ' then begin
StrPart2 := Copy (S, Middle - Pos + 1, Length (S) - (Middle - Pos));
exit;
end;
if S[Middle+Pos] = ' ' then begin
StrPart2 := Copy (S, Middle + Pos + 1, Length (S) - (Middle + Pos));
exit;
end;
inc (Pos);
until false;
end;
end.
|
unit BigInt;
interface
uses
System.SysUtils;
const
numlen = 102;
{
везде в циклах используются переменные типа integer,
если numlen > maxint, нужно использовать переменные типа word
}
type
number = array [1..numlen] of byte;
{
переменной а типа number представлено число SUM a[i]*10^(i-l)
Обнуление
}
procedure set0(var n: number);
procedure setN(var n : number; short : Int64);
function len(var n : number) : integer;
procedure show(var n : number);
procedure showf(var f:TextFile; var n : number);
procedure addShort(var n : number; short : integer);
procedure mulShort(var n : number; short : Int64);
procedure divShort(var n : number; divisor : integer; var rem : integer);
procedure add(var nl, n2 : number);
procedure substract(var n1, n2 : number);
procedure mul(nl, n2 : number; var n3 : number);
function cmp(var nl, n2 : number) : integer;
procedure incn(var n: number);
function toString(var n : number): String;
procedure reverse(var n: number; leng: Byte);
procedure readFromFileOne(var f: TextFile; var n1: number);
procedure readFromFile(var f: TextFile; var n1, n2: number);
function Sq(var n: number): number;
function copy(var n:number):number;
function toExtended(var n: number): Extended;
function BIntVariance(var n: number): longInt;
implementation
procedure set0(var n: number);
var
i : integer;
begin
for i := 1 to numlen do
n[i] := 0;
end;
{296 Приложение Б. Процедуры длинной арифметики
Занесение короткого числа
}
procedure setN(var n : number; short : Int64);
var
i : integer;
begin
set0(n);
i := 1;
while short > 0 do begin
n[i] := short mod 10;
short := short div 10;
inc(i);
end;
end;
{Получение длины числа
Если число представляет ноль, длина 1.
}
function len(var n : number) : integer;
var
i : integer;
begin
for i := numlen downto 1 do
if n[i] <> 0 then begin
len := i;
exit;
end;
len := 1;
end;
{Вывод числа и перевод строки
}
procedure show(var n : number);
var
i : integer;
begin
for i := len(n) downto 1 do
write(n[i]);
//writeln;
end;
{Процедуры длинной арифметики 297
Добавление короткого числа
}
procedure showf(var f:TextFile; var n : number);
var
i : integer;
begin
for i := len(n) downto 1 do
write(f, n[i]);
//writeln;
end;
procedure addShort(var n : number; short : integer);
var
i : integer;
begin
i := 1;
while short > 0 do begin
short := short + n[i];
n[i] := short mod 10;
short := short div 10;
inc(i);
end;
end;
{Умножение на короткое число
}
procedure mulShort(var n : number; short : Int64);
var
i, carry : integer;
begin
carry := 0;
for i := 1 to numlen do begin
carry := carry + n[i] * short;
n[i] := carry mod 10;
carry := carry div 10;
end;
if carry <> 0 then {диагностика переполнения}
halt(1);
end;
{Деление на короткое число и получение остатка
}
procedure divShort(var n : number; divisor : integer; var rem : integer);
var
i : integer;
begin
rem := 0;
for i := numlen downto 1 do begin
rem := rem * 10 + n[i];
n[i] := rem div divisor;
//298 Приложение Б, Процедуры длинной арифметики
rem := rem mod divisor;
end;
end;
{Добавление длинного числа
}
procedure add(var nl, n2 : number);
var
i, саггу : integer;
begin
саггу := 0;
for i := 1 to numlen do begin
саггу := саггу + nl[i] + n2[i];
nl[i] := саггу mod 10;
саггу := саггу div 10;
end;
if саггу <> 0 then {диагностика переполнения}
halt(1);
end;{
Умножение длинных чисел
}
procedure mul(nl, n2 : number; var n3 : number);
var
il, i2, i3, lenl, len2, саггу : integer;
begin
set0(n3);
lenl := len(nl);
len2 := len(n2);
for il := 1 to lenl do
for i2 := 1 to len2 do begin
i3 := il + i2 - 1;
саггу := nl[il] * n2[i2];
while саггу > 0 do begin
саггу := саггу + n3[i3];
n3[i3] := саггу mod 10;
саггу := саггу div 10;
inc(i3);
end;
end;
end;
//Процедуры длинной арифметики 299
{
Сравнение чисел
если nl < n2. выдает -1
если nl = n2, выдает 0
если nl >'n2. выдает 1
}
function cmp(var nl, n2 : number) : integer;
var
i : integer;
begin
for i := numlen downto 1 do begin
if nl[i] < n2[i] then begin
cmp := -1;
exit;
end;
if nl[i] > n2[i] then begin
cmp := 1;
exit;
end;
end;
cmp := 0;
end;
procedure incn(var n: number);
begin
addShort(n, 1);
end;
function toString(var n : number): String;
var
i: integer;
begin
Result := '';
for i := len(n) downto 1 do
Result := Result + IntToStr(n[i]);
end;
function copy(var n:number):number;
var
i: integer;
begin
set0(Result);
for i := len(n) downto 1 do
Result[i] := n[i];
end;
procedure reverse(var n: number; leng: Byte);
var
i, temp: Byte;
begin
for i := 1 to leng shr 1 do begin
temp := n[i];
n[i] := n[leng + 1 - i];
n[leng + 1 - i] := temp;
end;
end;
procedure readFromFileOne(var f: TextFile; var n1: number);
var
s: String;
i, j, l1: Byte;
e: Integer;
begin
Readln(f, s);
set0(n1);
l1 := 0;
for i := 1 to Length(s) do begin
Val(s[i], j, E);
if (E = 0) then begin
n1[i] := j;
Inc(l1);
end
else
break;
end;
reverse(n1, l1);
end;
procedure readFromFile(var f: TextFile; var n1, n2: number);
var
s: String;
i, j, k, l1, l2: Byte;
e: Integer;
begin
Readln(f, s);
set0(n1);
set0(n2);
l1 := 0;
for i := 1 to Length(s) do begin
Val(s[i], j, E);
if (E = 0) then begin
n1[i] := j;
Inc(l1);
end
else
break;
end;
l2 := 0;
for k := l1 + 2 to Length(s) do begin
Val(s[k], j, E);
if (E = 0) then begin
n2[k - i] := j;
Inc(l2);
end
else
break;
end;
reverse(n1, l1);
reverse(n2, l2);
end;
function Sq(var n: number): number;
begin
mul(n, n, Result);
end;
function SqrCeil(var n: number): number;
var
b, c: number;
begin
setn(b, 1);
set0(c);
//repeat
//substract(n, b);
//add(b, 2);
//incn(c);
//until ;
//return c
end;
procedure substract(var n1, n2 : number);
var
i, {саггу,} carry : integer;
begin
//саггу := 0;
carry := 0;
for i := 1 to numlen do begin
if n1[i] + carry >= n2[i] then begin
n1[i] := n1[i] + carry - n2[i];
carry := 0;
end
else begin
n1[i] := 10 + n1[i] + carry - n2[i];
carry := -1;
end;
//саггу := саггу + nl[i] + n2[i];
//nl[i] := саггу mod 10;
//саггу := саггу div 10;
end;
//if саггу <> 0 then {диагностика переполнения}
// halt(1);
end;
function toExtended(var n: number): Extended;
var
i: integer;
begin
Result := 1;
for i := len(n) downto 1 do
Result := Result * 10 + n[i];
end;
function BIntVariance(var n: number): longInt;
var
i: integer;
begin
Result := 0;
for i := len(n) downto 1 do
Result := Result + Sqr(n[i]);
end;
end.
|
UNIT StudentUnit;
INTERFACE
USES PersonUnit;
TYPE
Student = ^StudentObj;
StudentObj = OBJECT(PersonObj)
PUBLIC
CONSTRUCTOR Init(name: STRING);
CONSTRUCTOR Init2(name: STRING; mood: MoodType);
DESTRUCTOR Done;
END; (* PERSON *)
IMPLEMENTATION
FUNCTION MoodTypeToString(mood: MoodType): STRING;
BEGIN (* MoodTypeToString *)
CASE (mood) OF
happy: MoodTypeToString := 'happy';
excited: MoodTypeToString := 'excited';
funny: MoodTypeToString := 'funny';
angry: MoodTypeToString := 'angry';
tired: MoodTypeToString := 'tired';
END;
END; (* MoodTypeToString *)
CONSTRUCTOR StudentObj.Init(name: STRING);
BEGIN (* CONSTRUCTOR *)
self.name := name;
age := 18;
mood := happy;
END; (* CONSTRUCTOR *)
CONSTRUCTOR StudentObj.Init2(name: STRING; mood: MoodType);
BEGIN (* CONSTRUCTOR *)
self.name := name;
age := 0;
self.mood := mood;
END; (* CONSTRUCTOR *)
DESTRUCTOR StudentObj.Done;
BEGIN (* DESTRUCTOR *)
END; (* DESTRUCTOR *)
BEGIN (* PersonUnit *)
END. (* PersonUnit *)
|
{-Test prog Blowfish encr/decr speed, we 11.2004}
program t_bspeed;
{$i STD.INC}
{$ifdef APPCONS}
{$apptype console}
{$endif}
{$ifndef FPC}
{$N+}
{$endif}
{$ifdef X_Opt}
{$x+}
{$endif}
uses
{$ifdef WINCRT}
wincrt,
{$endif}
BF_Base, hrtimer;
const
LOOPS = 100;
var
ctx: TBFContext;
key: array[0..31] of byte;
ct : TBFBlock;
pt : TBFBlock;
{---------------------------------------------------------------------------}
procedure RandFill(var block; size: word);
var
ba: array[1..$F000] of byte absolute block;
i: word;
begin
for i:=1 to size do ba[i] := random(256);
end;
{---------------------------------------------------------------------------}
function EncrCycles(kbits: word): longint;
var
i: integer;
cyc0, cyc1, cyc2: comp;
t1,t2,c1,c2: longint;
begin
RandFill(key, sizeof(key));
RandFill(pt, sizeof(pt));
i := BF_Init(Key, kbits div 8, ctx);
if i<>0 then begin
writeln('Error BF_Init');
halt;
end;
BF_Encrypt(ctx, pt, ct);
c1 := MaxLongint;
c2 := MaxLongint;
for i:=1 to LOOPS do begin
RandFill(pt, sizeof(pt));
ReadTSC(cyc0);
BF_Encrypt(ctx, pt, ct);
ReadTSC(cyc1);
BF_Encrypt(ctx, ct, ct);
BF_Encrypt(ctx, ct, ct);
BF_Encrypt(ctx, ct, ct);
BF_Encrypt(ctx, ct, ct);
BF_Encrypt(ctx, ct, ct);
ReadTSC(cyc2);
t2 := round(cyc2-cyc1);
t1 := round(cyc1-cyc0);
if t1<c1 then c1 := t1;
if t2<c2 then c2 := t2;
end;
EncrCycles := (c2-c1+1) shr 2;
end;
{---------------------------------------------------------------------------}
function DecrCycles(kbits: word): longint;
var
i: integer;
cyc0, cyc1, cyc2: comp;
t1,t2,c1,c2: longint;
begin
RandFill(key, sizeof(key));
RandFill(pt, sizeof(pt));
i := BF_Init(Key, kbits div 8, ctx);
if i<>0 then begin
writeln('Error BF_Init_Decr');
halt;
end;
BF_Decrypt(ctx, pt, ct);
c1 := MaxLongint;
c2 := MaxLongint;
for i:=1 to LOOPS do begin
RandFill(pt, sizeof(pt));
ReadTSC(cyc0);
BF_Decrypt(ctx, pt, ct);
ReadTSC(cyc1);
BF_Decrypt(ctx, ct, ct);
BF_Decrypt(ctx, ct, ct);
BF_Decrypt(ctx, ct, ct);
BF_Decrypt(ctx, ct, ct);
BF_Decrypt(ctx, ct, ct);
ReadTSC(cyc2);
t2 := round(cyc2-cyc1);
t1 := round(cyc1-cyc0);
if t1<c1 then c1 := t1;
if t2<c2 then c2 := t2;
end;
DecrCycles := (c2-c1+1) shr 2;
end;
{---------------------------------------------------------------------------}
function KeyCycles(kbits: word): longint;
var
i,j: integer;
cyc0, cyc1, cyc2: comp;
t1,t2,c1,c2: longint;
keybytes : word;
begin
keybytes := kbits div 8;
RandFill(key, sizeof(key));
RandFill(pt, sizeof(pt));
c1 := MaxLongint;
c2 := MaxLongint;
j := BF_Init(Key, KeyBytes, ctx);
if j<>0 then begin
writeln('Error BF_Initr');
halt;
end;
for i:=1 to LOOPS do begin
RandFill(key, sizeof(key));
ReadTSC(cyc0);
{$ifndef X_Opt} j := {$endif} BF_Init(Key, KeyBytes, ctx);
ReadTSC(cyc1);
{$ifndef X_Opt} j := {$endif} BF_Init(Key, KeyBytes, ctx);
{$ifndef X_Opt} j := {$endif} BF_Init(Key, KeyBytes, ctx);
{$ifndef X_Opt} j := {$endif} BF_Init(Key, KeyBytes, ctx);
{$ifndef X_Opt} j := {$endif} BF_Init(Key, KeyBytes, ctx);
{$ifndef X_Opt} j := {$endif} BF_Init(Key, KeyBytes, ctx);
ReadTSC(cyc2);
t2 := round(cyc2-cyc1);
t1 := round(cyc1-cyc0);
if t1<c1 then c1 := t1;
if t2<c2 then c2 := t2;
end;
KeyCycles := (c2-c1+1) shr 2;
end;
var
k: word;
ec,dc,kc : array[2..4] of longint;
avg: longint;
MB,sec: double;
begin
writeln('BF Encr/Decr cycles (c) W.Ehrhardt 2004');
writeln('KeyBit EncCyc DecCyc InitCyc');
for k:=4 downto 2 do begin
ec[k] := EncrCycles(k*64);
dc[k] := DecrCycles(k*64);
kc[k] := KeyCycles(k*64);
end;
avg := 0;
for k:=4 downto 2 do begin
avg := avg + ec[k] + dc[k];
writeln(k*64:6, ec[k]:8, dc[k]:8, kc[k]:10);
end;
MB := sizeof(TBFBlock)/1E6;
sec := avg/6.0/CPUFrequency;
writeln('Avg Cyc: ', avg/6.0:5:0, ' MB/s: ',MB/sec:7:2);
end.
|
unit MapParallel;
interface
uses
System.SysUtils, System.Generics.Collections;
type
TIndexed<T> = record
private
FIndex: Integer;
FValue: T;
public
constructor Create(AIndex: Integer; AValue: T);
end;
TListWriter<T> = class
public
class procedure AddToThreadList(AItem: T; AThreadList: TThreadList<T>); static;
end;
TMapParallel<T> = class
strict private
type
TForEachRef = reference to procedure(var X: T; const I: Integer; var Done: Boolean);
TMapRef = reference to function(const X: T; const I: Integer): T;
TFilterRef = reference to function(const X: T; const I: Integer): Boolean;
TPredicateRef = reference to function(const X: T): Boolean;
TReduceRef = reference to function(const Accumulator: T; const X: T; const I: Integer): T;
TIndexed = TIndexed<T>;
TListWriter = TListWriter<TIndexed>;
public
class function Map(const Source: TArray<T>; const Lambda: TMapRef): TArray<T>; static;
class function Filter(const Source: TArray<T>; const Lambda: TFilterRef): TArray<T>; static;
class function Every(const Source: TArray<T>; const Lambda: TPredicateRef): Boolean; static;
class function Some(const Source: TArray<T>; const Lambda: TPredicateRef): Boolean; static;
end;
TMapParallel<T, R> = class(TMapParallel<T>)
strict private
type
TMapToRef = reference to function(const X: T; const I: Integer): R;
TIndexed = TIndexed<R>;
TListWriter = TListWriter<TIndexed>;
public
class function Map(const Source: TArray<T>; const Lambda: TMapToRef): TArray<R>; static;
end;
implementation
uses System.Threading, System.SyncObjs, System.Classes, System.Generics.Defaults;
constructor TIndexed<T>.Create(AIndex: Integer; AValue: T);
begin
FIndex := AIndex;
FValue := AValue;
end;
class procedure TListWriter<T>.AddToThreadList(AItem: T; AThreadList: TThreadList<T>);
begin
AThreadList.LockList;
try
AThreadList.Add(AItem);
finally
AThreadList.UnlockList;
end;
end;
class function TMapParallel<T>.Map(const Source: TArray<T>; const Lambda: TMapRef): TArray<T>;
{$INCLUDE Map}
class function TMapParallel<T, R>.Map(const Source: TArray<T>; const Lambda: TMapToRef): TArray<R>;
{$INCLUDE Map}
class function TMapParallel<T>.Filter(const Source: TArray<T>; const Lambda: TFilterRef): TArray<T>;
var
ThreadList: TThreadList<TIndexed>;
FinalList: TList<TIndexed>;
Comparison: TComparison<TIndexed>;
TmpIndexedRecord: TIndexed;
begin
Result := [];
// Thread-safe unordered storage
ThreadList := TThreadList<TIndexed>.Create;
try
ThreadList.Duplicates := dupAccept;
// do the job
TParallel.For(low(Source), high(Source),
procedure(AIndex: Integer; ALoopState: TParallel.TLoopState)
begin
// add item to the ThreadList
if Lambda(Source[AIndex], AIndex) then
TListWriter.AddToThreadList(TIndexed.Create(AIndex, Source[AIndex]), ThreadList);
end);
// not-thread-safe ordered storage
FinalList := ThreadList.LockList;
try
// specify the comparer
Comparison := function(const Left: TIndexed; const Right: TIndexed): Integer
begin
Result := TComparer<Integer>.Default.Compare(Left.FIndex, Right.FIndex);
end;
// sort list by the comparer
FinalList.Sort(TComparer<TIndexed>.Construct(Comparison));
// put list items to the result array
for TmpIndexedRecord in FinalList do
Result := Result + [TmpIndexedRecord.FValue];
finally
ThreadList.UnlockList;
end;
finally
FreeAndNil(ThreadList);
end;
end;
class function TMapParallel<T>.Every(const Source: TArray<T>; const Lambda: TPredicateRef): Boolean;
var
ResultValue: Integer;
begin
ResultValue := 1;
TParallel.For(low(Source), high(Source),
procedure(AIndex: Integer; ALoopState: TParallel.TLoopState)
begin
if not Lambda(Source[AIndex]) then
begin
TInterlocked.Exchange(ResultValue, 0);
ALoopState.Break;
end;
end);
Result := ResultValue.ToBoolean;
end;
class function TMapParallel<T>.Some(const Source: TArray<T>; const Lambda: TPredicateRef): Boolean;
var
ResultValue: Integer;
begin
ResultValue := 0;
TParallel.For(low(Source), high(Source),
procedure(AIndex: Integer; ALoopState: TParallel.TLoopState)
begin
if Lambda(Source[AIndex]) then
begin
TInterlocked.Exchange(ResultValue, 1);
ALoopState.Break;
end;
end);
Result := ResultValue.ToBoolean;
end;
end.
|
unit ParametroUsuarioDataUn;
interface
uses
SysUtils, Classes, FMTBcd, DB, Provider, osSQLDataSetProvider, SqlExpr,
osCustomDataSetProvider, osUtils, osSQLDataSet;
type
TParametroUsuarioData = class(TDataModule)
MasterDataSet: TosSQLDataset;
MasterProvider: TosSQLDataSetProvider;
MasterDataSetIDPARAMETROUSUARIO: TIntegerField;
MasterDataSetNOMEPARAMETRO: TStringField;
MasterDataSetDESCRICAO: TStringField;
MasterDataSetCONTEUDO: TStringField;
MasterDataSetTIPODADO: TStringField;
private
public
procedure Validate(PDataSet: TDataSet);
end;
var
ParametroUsuarioData: TParametroUsuarioData;
implementation
uses osErrorHandler, SQLMainData;
{$R *.dfm}
procedure TParametroUsuarioData.Validate(PDataSet: TDataSet);
var
sTipoDado : string;
sConteudo : string;
{
i : integer;
d : double;
}
begin
with PDataSet, HError do
begin
Clear;
CheckEmpty(FieldByName('NomeParametro'));
WarningEmpty(FieldByName('Descricao'));
sTipoDado := FieldByName('TipoDado').AsString;
if IsEmpty(sTipoDado) then
Add('Falta informar o Tipo de Dado')
else if sTipoDado[1] in ['C', 'I', 'V', 'M', 'D'] then
begin
sConteudo := FieldByName('Conteudo').AsString;
CheckEmpty(sConteudo, 'Conteudo');
try
if sTipoDado = 'I' then
{i :=} StrToInt(sConteudo)
else if sTipoDado = 'V' then
{d :=} StrToFloat(sConteudo);
except
Add('Conte˙do incompatÝvel com o tipo de dado');
end;
end
else
Add('Tipo de dado deve ser: I = inteiro, V = valor, M = memorando ou D = data');
Check;
end;
end;
initialization
OSRegisterClass(TParametroUsuarioData);
end.
|
unit uEditorLspSettings;
{$mode objfpc}{$H+}
interface
uses
Classes, Graphics, SysUtils, Forms,
SynEdit, SynEditMiscClasses, SynEditMarkupBracket, SynEditMarks,
LCSynEdit, SynLCHighlighter;
const
MAX_NIVEL_IDENTACAO = 10;
resourcestring
rsUnknown = 'Desconhecido';
rsDescNivelIdentacao = 'Nivel %s';
type
TLCIdiomaEditor = (ieLCPtBr, ieLCEs);
Const
LCIdiomasEditor = [Low(TLCIdiomaEditor)..High(TLCIdiomaEditor)];
LCI18nIdiomasEditor: array[TLCIdiomaEditor] of string = ('pt_br', 'es');
type
{ TLCNiveisIdentacaoConfig }
TLCNiveisIdentacaoConfig = class(TCollectionItem)
private
fAtributos : TSynSelectedColor;
fDefaultValues : Boolean;
function GetDescription: String;
function GetNivel : Integer;
protected
function GetDisplayName: string; override;
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
property Description:String read GetDescription;
published
property Atributos:TSynSelectedColor read fAtributos write fAtributos;
property DefaultValues:Boolean read fDefaultValues write fDefaultValues;
property Nivel:Integer read GetNivel;
end;
{ TLCElementoSintaxe }
TLCElementoSintaxe = class(TCollectionItem)
private
fAtributos : TSynLCAttributeSettings;
fDescription : String;
fKind : TLCTokenKind;
fDefaultValues : Boolean;
protected
function GetDisplayName: string; override;
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
published
property DefaultValues:Boolean read fDefaultValues write fDefaultValues;
property Description:String read fDescription write fDescription;
property Kind:TLCTokenKind read fKind write fKind;
property Atributos:TSynLCAttributeSettings read fAtributos write fAtributos;
end;
{ TModuloVetorh }
TModuloVetorh = class(TCollectionItem)
private
FArqExc : TStrings;
fPastaBase : String;
FSigla : TLCSiglaModuloVetorh;
protected
function GetDisplayName: string; override;
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
published
property PastaBase:String read fPastaBase write fPastaBase;
property Sigla:TLCSiglaModuloVetorh read FSigla write FSigla;
property ArquivosExcluidos:TStrings read FArqExc;
end;
{ TMRUBookmark }
TMRUBookmark = class(TCollectionItem)
private
FBookmarkNum : integer;
FColumn : integer;
FImageIndex : integer;
FLine : integer;
FPriority : integer;
FVisible : boolean;
published
property BookmarkNumber: integer read FBookmarkNum write fBookmarkNum;
property Column: integer read FColumn write FColumn;
property ImageIndex: integer read FImageIndex write FImageIndex;
property Line: integer read FLine write FLine;
property Priority: integer read FPriority write FPriority;
property Visible: boolean read FVisible write FVisible;
end;
{ TMRUFile }
TMRUFile = class(TCollectionItem)
private
FBookmarks : TCollection;
FFixed : Boolean;
fLastTimeOpened: TDateTime;
FLeft: integer;
FTop: Integer;
FPath: String;
FName: String;
FCaret: TPoint;
protected
function GetDisplayName: string; override;
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
procedure GetFromSynEdit(aSynEd:TSynEdit; aSaveBookmarks:Boolean);
procedure SetToSynEdit(aSynEd:TSynEdit);
procedure SetPathName(value:String);
function GetPathName:String;
published
property Path:String read FPath write FPath;
property Name:String read FName write FName;
property Top:Integer read FTop write FTop;
property Left:integer read FLeft write FLeft;
property CaretX:integer read FCaret.x write FCaret.x;
property CaretY:integer read FCaret.y write FCaret.y;
property LastTimeOpened:TDateTime read fLastTimeOpened write fLastTimeOpened;
property Bookmarks:TCollection read FBookmarks;
property Fixed:Boolean read FFixed write FFixed;
end;
{ TSessionFile }
TSessionFile = class(TCollectionItem)
private
FActive : Boolean;
FFileName : String;
protected
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
published
property FileName:String read FFileName write FFileName;
property Active:Boolean read FActive write FActive default false;
end;
{ TGutterPartSettings }
TGutterPartSettings = class(TPersistent)
private
fAutoSize: Boolean;
fMarkupInfo: TSynSelectedColor;
fVisible: Boolean;
fWidth: Integer;
protected
public
constructor Create; virtual;
destructor Destroy; override;
published
property Visible:Boolean read fVisible write fVisible;
property AutoSize:Boolean read fAutoSize write fAutoSize;
property Width:Integer read fWidth write fWidth;
property MarkupInfo:TSynSelectedColor read fMarkupInfo write fMarkupInfo;
end;
{ TLineNumberGutterSettings }
TLineNumberGutterSettings = class(TGutterPartSettings)
private
fDigitCount: integer;
fLeadingZeros: Boolean;
fShowOnlyLineNumbersMultiplesOf: Integer;
fZeroStart: Boolean;
protected
public
constructor Create; override;
destructor Destroy; override;
published
property LeadingZeros:Boolean read fLeadingZeros write fLeadingZeros;
property DigitCount:integer read fDigitCount write fDigitCount;
property ShowOnlyLineNumbersMultiplesOf:Integer read fShowOnlyLineNumbersMultiplesOf write fShowOnlyLineNumbersMultiplesOf;
property ZeroStart:Boolean read fZeroStart write fZeroStart;
end;
{ TChangesPartGutterSettings }
TChangesPartGutterSettings = class(TGutterPartSettings)
private
fModifiedColor: TColor;
fSavedColor: TColor;
protected
public
constructor Create; override;
destructor Destroy; override;
published
property ModifiedColor:TColor read fModifiedColor write fModifiedColor;
property SavedColor:TColor read fSavedColor write fSavedColor;
end;
{ TGutterSettings }
TGutterSettings = class(TPersistent)
private
fAutoSize: Boolean;
fChangesPart: TChangesPartGutterSettings;
fCodeFoldPart: TGutterPartSettings;
fColor: TColor;
fLineNumberPart: TLineNumberGutterSettings;
fSeparatorPart: TGutterPartSettings;
fVisible: Boolean;
fWidth: Integer;
protected
public
constructor Create;
destructor Destroy; override;
published
property Visible:Boolean read fVisible write fVisible;
property AutoSize:Boolean read fAutoSize write fAutoSize;
property Width:Integer read fWidth write fWidth;
property Color:TColor read fColor write fColor;
property ChangesPart:TChangesPartGutterSettings read fChangesPart write fChangesPart;
property LineNumberPart:TLineNumberGutterSettings read fLineNumberPart write fLineNumberPart;
property SeparatorPart:TGutterPartSettings read fSeparatorPart write fSeparatorPart;
property CodeFoldPart:TGutterPartSettings read fCodeFoldPart write fCodeFoldPart;
end;
{ TMarkupHighlightAllCaretSettings }
TMarkupHighlightAllCaretSettings = class(TPersistent)
private
FFullWord : Boolean;
FFullWordMaxLen : Integer;
fMarkupInfo : TSynSelectedColor;
FTrim : Boolean;
FWaitTime : Integer;
protected
public
constructor Create;
destructor Destroy; override;
published
property MarkupInfo: TSynSelectedColor read fMarkupInfo write fMarkupInfo;
property WaitTime: Integer read FWaitTime write FWaitTime;
property Trim: Boolean read FTrim write FTrim;
property FullWord: Boolean read FFullWord write FFullWord;
property FullWordMaxLen: Integer read FFullWordMaxLen write FFullWordMaxLen;
end;
{ TEditorSettings }
TEditorSettings = class(TPersistent)
private
fCoresPadraoNivelIdentacao: array of TColor;
fActiveLine: TSynSelectedColor;
fBracketHighlightStyle: TSynEditBracketHighlightStyle;
fBracketMatchColor: TSynSelectedColor;
fElementosSintaxe : TCollection;
fFontName: String;
fFontQuality: TFontQuality;
fFontSize: Integer;
fGutter: TGutterSettings;
fLineErrorColor : TSynSelectedColor;
fMarkupHighlightAllCaret : TMarkupHighlightAllCaretSettings;
fMaxUndo: Integer;
fMouseLinkColor: TSynSelectedColor;
fNiveisIdentacao: TCollection;
FOptions: TSynEditorOptions;
FOptions2: TSynEditorOptions2;
fRightEdge: Integer;
fRightEdgeColor: TColor;
fTabWidth : Integer;
fWantTabs: Boolean;
protected
public
constructor Create;
destructor Destroy; override;
function GetCorPadraoNivelIdentacao(pNivel:Integer):TColor;
published
property ActiveLine: TSynSelectedColor read fActiveLine write fActiveLine;
property BracketHighlightStyle: TSynEditBracketHighlightStyle read fBracketHighlightStyle write fBracketHighlightStyle;
property BracketMatchColor: TSynSelectedColor read fBracketMatchColor write fBracketMatchColor;
property FontName:String read fFontName write fFontName;
property FontSize:Integer read fFontSize write fFontSize;
property FontQuality: TFontQuality read fFontQuality write fFontQuality;
property Gutter:TGutterSettings read fGutter write fGutter;
property LineErrorColor:TSynSelectedColor read fLineErrorColor write fLineErrorColor;
property MaxUndo:Integer read fMaxUndo write fMaxUndo;
property MouseLinkColor: TSynSelectedColor read fMouseLinkColor write fMouseLinkColor;
property WantTabs:Boolean read fWantTabs write fWantTabs;
property RightEdge:Integer read fRightEdge write fRightEdge;
property RightEdgeColor:TColor read fRightEdgeColor write fRightEdgeColor;
property TabWidth:Integer read fTabWidth write fTabWidth;
property Options: TSynEditorOptions read FOptions write FOptions;
property Options2: TSynEditorOptions2 read FOptions2 write FOptions2;
property MarkupHighlightAllCaret:TMarkupHighlightAllCaretSettings read fMarkupHighlightAllCaret write fMarkupHighlightAllCaret;
property ElementosSintaxe:TCollection read fElementosSintaxe;
property NiveisIdentacao:TCollection read fNiveisIdentacao;
end;
{ TEditorLspSettings }
TEditorLspSettings = class(TPersistent)
private
fCreateEmptyFile : boolean;
fEditor: TEditorSettings;
FEnabledAutoSaveFile : Boolean;
fHeight: Integer;
fIdioma: TLCIdiomaEditor;
FIntervalAutoSaveFile : Integer;
fLeft: Integer;
fListOfCommandsIndex : Integer;
fListOfCommandsWidth : Integer;
FMakeBackupFiles : boolean;
fMaximized: boolean;
fMaxMruFilesStored: integer;
fModulosVetorh : TCollection;
fMruFiles:TCollection;
fAskBeforeExit: boolean;
FNumberOfBackupFilesToPreserve : Integer;
fPathAppRoot : String;
fPathConfig : String;
FPathToBackupFiles : String;
fSaveBookmarksWhenCloseFile : boolean;
FSaveSession : Boolean;
fSessionFiles : TCollection;
fShowListOfCommands : Boolean;
fTop: Integer;
fWidth: Integer;
fFiltros:TStrings;
fPathBase:String;
fShowExplorer:boolean;
fExplorerWidth:Integer;
procedure SetIntervalAutoSaveFile(AValue : Integer);
procedure SetMaxMruFilesStored(AValue: integer);
procedure SetNumberOfBackupFilesToPreserve(AValue : Integer);
public
constructor Create;
destructor Destroy; override;
procedure SaveToFile(fileName:String);
procedure LoadFromFile(fileName:String);
procedure UpdateSettingsByEditor(SynEd: TSynEdit);
procedure AddMruFiles(fileName:String; SynEd: TSynEdit);
function getMruFile(index:Integer):TMRUFile;
function getMruFile(aFileName:String):TMRUFile;
function getIdiomaI18n:String;
// Internal Configurations
property PathAppRoot:String read fPathAppRoot write fPathAppRoot;
property PathConfig:String read fPathConfig write fPathConfig;
published
// App propertys
property Idioma:TLCIdiomaEditor read fIdioma write fIdioma;
property AskBeforeExit:boolean read fAskBeforeExit write fAskBeforeExit;
property CreateEmptyFile: boolean read fCreateEmptyFile write fCreateEmptyFile;
// Explorer options
property Filters:TStrings read fFiltros;
property PathBase:String read fPathBase write fPathBase;
property ShowExplorer: Boolean read fShowExplorer write fShowExplorer;
property ExplorerWidth: Integer read fExplorerWidth write fExplorerWidth;
// List of Commands Properties
property ShowListOfCommands: Boolean read fShowListOfCommands write fShowListOfCommands;
property ListOfCommandsWidth: Integer read fListOfCommandsWidth write fListOfCommandsWidth;
property ListOfCommandsIndex: Integer read fListOfCommandsIndex write fListOfCommandsIndex;
// Windows propertys
property Top:Integer read fTop write fTop;
property Left:Integer read fLeft write fLeft;
property Width:Integer read fWidth write fWidth;
property Height:Integer read fHeight write fHeight;
property Maximized:boolean read fMaximized write fMaximized;
// Last open files
property MaxMruFilesStored:integer read fMaxMruFilesStored write SetMaxMruFilesStored;
property MruFiles:TCollection read fMruFiles;
property SaveBookmarksWhenCloseFile:boolean read fSaveBookmarksWhenCloseFile write fSaveBookmarksWhenCloseFile default true;
// Backup files
property MakeBackupFiles:boolean read FMakeBackupFiles write FMakeBackupFiles default true;
property PathToBackupFiles:String read FPathToBackupFiles write FPathToBackupFiles;
property NumberOfBackupFilesToPreserve:Integer read FNumberOfBackupFilesToPreserve write SetNumberOfBackupFilesToPreserve;
// session files
property SaveSession:Boolean read FSaveSession write FSaveSession default false;
property SessionFiles:TCollection read fSessionFiles;
// Auto Save
property EnabledAutoSaveFile:Boolean read FEnabledAutoSaveFile write FEnabledAutoSaveFile default true;
property IntervalAutoSaveFile:Integer read FIntervalAutoSaveFile write SetIntervalAutoSaveFile default 5; // in minutes
// Editor
property Editor:TEditorSettings read fEditor write fEditor;
// Diversas
property ModulosVetorh:TCollection read fModulosVetorh;
end;
implementation
uses
fpjsonrtti, fpjson, jsonparser,
SynEditTypes, SynEditMarkupHighAll, LazFileUtils;
{ TLCNiveisIdentacaoConfig }
function TLCNiveisIdentacaoConfig.GetDescription: String;
begin
Result := Format(rsDescNivelIdentacao, [FormatFloat('#,#00', Nivel+1)]);
end;
function TLCNiveisIdentacaoConfig.GetNivel : Integer;
begin
Result := Index;
end;
function TLCNiveisIdentacaoConfig.GetDisplayName: string;
begin
Result:= Description;
end;
constructor TLCNiveisIdentacaoConfig.Create(ACollection: TCollection);
begin
inherited Create(ACollection);
fAtributos := TSynSelectedColor.Create;
end;
destructor TLCNiveisIdentacaoConfig.Destroy;
begin
FreeAndNil(fAtributos);
inherited Destroy;
end;
{ TLCElementoSintaxe }
function TLCElementoSintaxe.GetDisplayName : string;
begin
Result := fDescription;
end;
constructor TLCElementoSintaxe.Create(ACollection : TCollection);
begin
inherited Create(ACollection);
fDefaultValues:= True;
fKind := tLCUnknown;
fDescription := rsUnknown;
fAtributos := TSynLCAttributeSettings.Create;
end;
destructor TLCElementoSintaxe.Destroy;
begin
FreeAndNil(fAtributos);
inherited Destroy;
end;
{ TModuloVetorh }
function TModuloVetorh.GetDisplayName : string;
begin
Result := AbreviaturaModuloVetorh[FSigla];
end;
constructor TModuloVetorh.Create(ACollection : TCollection);
begin
inherited Create(ACollection);
FSigla := smvNone;
FArqExc := TStringList.Create;
fPastaBase := '';
end;
destructor TModuloVetorh.Destroy;
begin
FreeAndNil(FArqExc);
inherited Destroy;
end;
{ TMarkupHighlightAllCaretSettings }
constructor TMarkupHighlightAllCaretSettings.Create;
begin
inherited Create;
fMarkupInfo := TSynSelectedColor.Create;
fMarkupInfo.Background := $00EEEEEE;
fMarkupInfo.FrameColor:= clNone;
fMarkupInfo.Foreground := clNone;
FFullWord := true;
FWaitTime := 2000;
FFullWordMaxLen := 0;
FTrim := True;
end;
destructor TMarkupHighlightAllCaretSettings.Destroy;
begin
FreeAndNil(fMarkupInfo);
inherited Destroy;
end;
{ TSessionFile }
constructor TSessionFile.Create(ACollection : TCollection);
begin
inherited Create(ACollection);
FActive := False;
FFileName := '';
end;
destructor TSessionFile.Destroy;
begin
inherited Destroy;
end;
{ TChangesPartGutterSettings }
constructor TChangesPartGutterSettings.Create;
begin
inherited Create;
fModifiedColor:= $0000E9FC;
fSavedColor:= clLime;
end;
destructor TChangesPartGutterSettings.Destroy;
begin
inherited Destroy;
end;
{ TLineNumberGutterSettings }
constructor TLineNumberGutterSettings.Create;
begin
inherited Create;
fDigitCount:= 3;
fLeadingZeros:=true;
fShowOnlyLineNumbersMultiplesOf:=5;
fZeroStart:= false;
MarkupInfo.Background:=12615680;
MarkupInfo.Foreground:=clLtGray;
end;
destructor TLineNumberGutterSettings.Destroy;
begin
inherited Destroy;
end;
{ TGutterPartSettings }
constructor TGutterPartSettings.Create;
begin
inherited Create;
fMarkupInfo:=TSynSelectedColor.Create;
fAutoSize:= true;
fVisible:= true;
fWidth:= 30;
end;
destructor TGutterPartSettings.Destroy;
begin
FreeAndNil(fMarkupInfo);
inherited Destroy;
end;
{ TGutterSettings }
constructor TGutterSettings.Create;
begin
inherited Create;
fLineNumberPart:= TLineNumberGutterSettings.Create;
fSeparatorPart:= TGutterPartSettings.Create;
fCodeFoldPart:= TGutterPartSettings.Create;
fChangesPart:= TChangesPartGutterSettings.Create;
fAutoSize:= true;
fColor:= 12615680;
fVisible:= true;
fWidth:= 30;
fLineNumberPart.Visible:=true;
fLineNumberPart.ShowOnlyLineNumbersMultiplesOf:=1;
fLineNumberPart.AutoSize:=true;
fLineNumberPart.DigitCount:=3;
fLineNumberPart.MarkupInfo.Background:=12615680;
fLineNumberPart.MarkupInfo.Foreground:=clLtGray;
fLineNumberPart.MarkupInfo.Style:=[];
fLineNumberPart.LeadingZeros:=true;
fLineNumberPart.ZeroStart:=false;
fChangesPart.AutoSize:=false;
fChangesPart.Width:=2;
fChangesPart.ModifiedColor:=$0000E9FC;
fChangesPart.SavedColor:=clLime;
fSeparatorPart.AutoSize:=false;
fSeparatorPart.Width:=2;
fSeparatorPart.MarkupInfo.Background:=12615680;
fCodeFoldPart.MarkupInfo.Background:=clBtnFace;
end;
destructor TGutterSettings.Destroy;
begin
FreeAndNil(fLineNumberPart);
FreeAndNil(fSeparatorPart);
FreeAndNil(fCodeFoldPart);
FreeAndNil(fChangesPart);
inherited Destroy;
end;
{ TEditorSettings }
constructor TEditorSettings.Create;
begin
SetLength(fCoresPadraoNivelIdentacao, MAX_NIVEL_IDENTACAO);
fCoresPadraoNivelIdentacao[0] := clRed;
fCoresPadraoNivelIdentacao[1] := $0098F7; //orange
fCoresPadraoNivelIdentacao[2] := $22CC40; //green
fCoresPadraoNivelIdentacao[3] := $CCCC00; //cyan
fCoresPadraoNivelIdentacao[4] := $FF682A; //blue
fCoresPadraoNivelIdentacao[5] := $CF00C4; //purple
fCoresPadraoNivelIdentacao[6] := $C08000;
fCoresPadraoNivelIdentacao[7] := $408080;
fCoresPadraoNivelIdentacao[8] := $400080;
fCoresPadraoNivelIdentacao[9] := $808040;
inherited Create;
fGutter:= TGutterSettings.create;
fActiveLine := TSynSelectedColor.Create;
fMouseLinkColor := TSynSelectedColor.Create;
fMarkupHighlightAllCaret := TMarkupHighlightAllCaretSettings.Create;
fElementosSintaxe := TCollection.Create(TLCElementoSintaxe);
fLineErrorColor := TSynSelectedColor.Create;
fNiveisIdentacao := TCollection.Create(TLCNiveisIdentacaoConfig);
fOptions := [eoAltSetsColumnMode
,eoAutoIndent
,eoBracketHighlight
,eoGroupUndo
,eoScrollPastEol
,eoSmartTabs
,eoTabIndent
,eoTabsToSpaces
,eoTrimTrailingSpaces
,eoDragDropEditing
,eoEnhanceHomeKey
];
fOptions2 := [eoFoldedCopyPaste,
eoOverwriteBlock
];
fBracketHighlightStyle:= sbhsBoth;
fBracketMatchColor:= TSynSelectedColor.Create;
fBracketMatchColor.Background := clRed;
fBracketMatchColor.Foreground := clWhite;
// Linha Ativa
fActiveLine.Background := $00FFF7E6;
fActiveLine.Foreground := clNone;
fActiveLine.FrameColor := $00FFC753;
fActiveLine.FrameStyle := slsDashed;
fActiveLine.FrameEdges := sfeAround;
// Mouse Link
fActiveLine.Background := clNone;
fActiveLine.Foreground := clNone;
fMouseLinkColor.Style := [fsUnderline];
// Linha com Erro
fLineErrorColor.Background := $00E5E5E5;
fLineErrorColor.Foreground := clNone;
fLineErrorColor.FrameColor := clRed;
fLineErrorColor.FrameStyle := slsDashed;
fLineErrorColor.FrameEdges := sfeAround;
fFontName := 'Courier New';
fFontSize := 10;
fFontQuality := fqCleartype;
fMaxUndo := 1024;
fWantTabs := true;
fTabWidth := 2;
fRightEdge := 80;
fRightEdgeColor := clLtGray;
end;
destructor TEditorSettings.Destroy;
begin
FreeAndNil(fActiveLine);
FreeAndNil(fMouseLinkColor);
FreeAndNil(fBracketMatchColor);
FreeAndNil(fGutter);
FreeAndNil(fMarkupHighlightAllCaret);
FreeAndNil(fElementosSintaxe);
FreeAndNil(fLineErrorColor);
FreeAndNil(fNiveisIdentacao);
inherited Destroy;
end;
function TEditorSettings.GetCorPadraoNivelIdentacao(pNivel : Integer) : TColor;
begin
Result := clNone;
if (pNivel >= 0)
and (pNivel <= High(fCoresPadraoNivelIdentacao)) then
begin
Result := fCoresPadraoNivelIdentacao[pNivel];
end;
end;
{ TEditorLspSettings }
procedure TEditorLspSettings.SetMaxMruFilesStored(AValue: integer);
begin
if fMaxMruFilesStored = AValue then
begin
Exit;
end;
// O Limite permitido é 16, pois foi o máximo previsto no editor
if AValue > 16 then
begin
AValue := 16;
end;
fMaxMruFilesStored := AValue;
// Se a quantidade armazenada de arquivo for superior ao novo limite, eliminar os mais antigos
While (MruFiles.Count > fMaxMruFilesStored) do
begin
MruFiles.Delete(MruFiles.Count - 1);
end;
end;
procedure TEditorLspSettings.SetIntervalAutoSaveFile(AValue : Integer);
begin
if FIntervalAutoSaveFile = AValue then
begin
Exit;
end;
if AValue < 1 then
begin
AValue := 1;
end;
FIntervalAutoSaveFile := AValue;
end;
procedure TEditorLspSettings.SetNumberOfBackupFilesToPreserve(AValue : Integer);
begin
if FNumberOfBackupFilesToPreserve = AValue then
begin
Exit;
end;
if AValue < 1 then
begin
AValue := 1;
end
else
if AValue > 999 then
begin
AValue := 999;
end;
FNumberOfBackupFilesToPreserve := AValue;
end;
constructor TEditorLspSettings.Create;
begin
fMruFiles := TCollection.Create(TMRUFile);
fSessionFiles := TCollection.Create(TSessionFile);
fModulosVetorh := TCollection.Create(TModuloVetorh);
fEditor := TEditorSettings.Create;
fIdioma := ieLCPtBr;
fMaxMruFilesStored := 16;
fHeight := 400;
fLeft := 0;
fMaximized:= true;
fAskBeforeExit:= false;
fTop:= 0;
fWidth:= 400;
fPathAppRoot := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName));
fPathConfig := IncludeTrailingPathDelimiter(fPathAppRoot + 'config');
fFiltros := TStringList.Create;
fPathBase := 'c:\';
fShowExplorer := true;
fExplorerWidth := 170;
fCreateEmptyFile := true;
fSaveBookmarksWhenCloseFile := true;
fSaveSession:= false;
fShowListOfCommands:= false;
fListOfCommandsWidth := 250;
fListOfCommandsIndex := 0;
FPathToBackupFiles := IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName) + 'bkp');
FMakeBackupFiles := true;
FNumberOfBackupFilesToPreserve := 999;
FEnabledAutoSaveFile := true;
FIntervalAutoSaveFile := 5;
end;
destructor TEditorLspSettings.Destroy;
begin
FreeAndNil(fMruFiles);
FreeAndNil(fSessionFiles);
FreeAndNil(fModulosVetorh);
FreeAndNil(fEditor);
FreeAndNil(fFiltros);
inherited Destroy;
end;
procedure TEditorLspSettings.SaveToFile(fileName: String);
var
Streamer:TJSONStreamer;
JData : TJSONData;
Arq:TStrings;
i:integer;
elemento: TLCElementoSintaxe;
begin
i := fEditor.ElementosSintaxe.Count-1;
while i >= 0 do
begin
elemento := TLCElementoSintaxe(fEditor.ElementosSintaxe.Items[i]);
if elemento.kind in [tLCUnknown, tLCEol] then
begin
fEditor.ElementosSintaxe.Delete(i);
end;
Dec(i);
end;
Arq := TStringList.Create;
Streamer := TJSONStreamer.Create(nil);
Streamer.Options := Streamer.Options + [jsoTStringsAsArray];
JData := GetJSON(Streamer.ObjectToJSONString(Self));
Arq.Text := Jdata.FormatJSON(DefaultFormat,2);
Arq.SaveToFile(fileName);
arq.Destroy;
JData.Destroy;
Streamer.Destroy;
end;
procedure TEditorLspSettings.LoadFromFile(fileName: String);
var
DeStreamer:TJSONDeStreamer;
arq:TStrings;
i:integer;
oMru: TMRUFile;
bAdicionar:Boolean;
Modulo:TModuloVetorh;
Sigla: TLCSiglaModuloVetorh;
kind: TLCTokenKind;
elemento: TLCElementoSintaxe;
nivel: TLCNiveisIdentacaoConfig;
begin
if FileExistsUTF8(fileName) then
begin
arq := TStringList.Create;
DeStreamer := TJSONDeStreamer.Create(nil);
try
arq.LoadFromFile(fileName);
DeStreamer.JSONToObject(arq.Text, self);
finally
arq.Destroy;
DeStreamer.Destroy;
end;
end;
if fFiltros.Count = 0 then
begin
fFiltros.Add('*.txt');
fFiltros.Add('*.sql');
fFiltros.Add('*.log');
fFiltros.Add('*.bat');
end;
// Verificar se os arquivos da lista MRU existem, caso não existam o mesmo deverá ser eliminado da lista
i := MruFiles.Count-1;
while i >= 0 do
begin
oMru := TMRUFile(MruFiles.Items[i]);
if (FileExistsUTF8(oMru.GetPathName) = false) then
begin
MruFiles.Delete(i);
end;
Dec(i);
end;
// Verificar se o limite Arquivos da lista foi atingido, se sim, apagar o mais antigo
while MruFiles.Count > MaxMruFilesStored do
begin
MruFiles.Delete(MruFiles.Count -1);
end;
// Criar as configurações para os modulos que não estão gravados ainda
for sigla in TLCSiglaModuloVetorh do
begin
bAdicionar := true;
for i := 0 to Pred(fModulosVetorh.Count) do
begin
if TModuloVetorh(fModulosVetorh.Items[i]).Sigla = sigla then
begin
bAdicionar := false;
break;
end;
end;
if not (sigla in [smvNone])
and (bAdicionar = true) then
begin
Modulo := TModuloVetorh.Create(fModulosVetorh);
Modulo.Sigla := sigla;
end;
end;
// Criar os elementos ainda não gravados
for kind in TLCTokenKind do
begin
//TLCTokenKind = (tLCAttributeName, tLCComment, tLCDataType, tLCIdentifier, tLCKey, tLCNull, tLCNumber,
// tLCReservedWord, tLCSpace, tLCString, tLCSymbol, tLCUnknown, tLCVariable, tLCEol);
if not (kind in [tLCNull, tLCUnknown, tLCEol]) then
begin
bAdicionar := true;
for i := 0 to Pred(fEditor.ElementosSintaxe.Count) do
begin
if TLCElementoSintaxe(fEditor.ElementosSintaxe.Items[i]).Kind = kind then
begin
if TLCElementoSintaxe(fEditor.ElementosSintaxe.Items[i]).Description <> DescricaoTiposToken[Kind] then
begin
TLCElementoSintaxe(fEditor.ElementosSintaxe.Items[i]).Description := DescricaoTiposToken[Kind];
end;
bAdicionar := false;
break;
end;
end;
if bAdicionar = true then
begin
elemento := TLCElementoSintaxe.Create(fEditor.ElementosSintaxe);
elemento.Kind := kind;
elemento.Description := DescricaoTiposToken[Kind];
end;
end;
end;
if MAX_NIVEL_IDENTACAO > Editor.NiveisIdentacao.Count then
begin
for i:= 0 to MAX_NIVEL_IDENTACAO-1 do
begin
if i >= Editor.NiveisIdentacao.Count then
begin
Nivel := TLCNiveisIdentacaoConfig.Create(Editor.NiveisIdentacao);
Nivel.DefaultValues := true;
Nivel.Atributos.Foreground := Editor.GetCorPadraoNivelIdentacao(i);
end;
end;
end;
if not (fIdioma in LCIdiomasEditor) then
begin
fIdioma := ieLCPtBr;
end;
end;
procedure TEditorLspSettings.UpdateSettingsByEditor(SynEd: TSynEdit);
var
fSynMarkHAllCaret:TSynEditMarkupHighlightAllCaret;
Elemento: TLCElementoSintaxe;
i: integer;
begin
// Editor
Editor.WantTabs := SynEd.WantTabs;
Editor.MaxUndo := SynEd.MaxUndo;
Editor.RightEdge := SynEd.RightEdge;
Editor.RightEdgeColor := SynEd.RightEdgeColor;
Editor.BracketHighlightStyle := SynEd.BracketHighlightStyle;
Editor.BracketMatchColor.Assign(SynEd.BracketMatchColor);
Editor.Options := SynEd.Options;
Editor.Options2 := SynEd.Options2;
// Linha ativa
Editor.ActiveLine.Assign(SynEd.LineHighlightColor);
// Font
Editor.FontName := SynEd.Font.Name;
Editor.FontSize := SynEd.Font.Size;
Editor.FontQuality := SynEd.Font.Quality;
// Gutter
Editor.Gutter.Visible := SynEd.Gutter.Visible;
Editor.Gutter.AutoSize := SynEd.Gutter.AutoSize;
Editor.Gutter.Width := SynEd.Gutter.Width;
Editor.Gutter.Color := SynEd.Gutter.Color;
// Número das linhas do Gutter
Editor.Gutter.LineNumberPart.Visible := SynEd.Gutter.LineNumberPart(0).Visible;
Editor.Gutter.LineNumberPart.ShowOnlyLineNumbersMultiplesOf:= SynEd.Gutter.LineNumberPart(0).ShowOnlyLineNumbersMultiplesOf;
Editor.Gutter.LineNumberPart.AutoSize := SynEd.Gutter.LineNumberPart(0).AutoSize;
Editor.Gutter.LineNumberPart.DigitCount := SynEd.Gutter.LineNumberPart(0).DigitCount;
Editor.Gutter.LineNumberPart.MarkupInfo.Assign(SynEd.Gutter.LineNumberPart(0).MarkupInfo);
Editor.Gutter.LineNumberPart.LeadingZeros := SynEd.Gutter.LineNumberPart(0).LeadingZeros;
Editor.Gutter.LineNumberPart.ZeroStart := SynEd.Gutter.LineNumberPart(0).ZeroStart;
Editor.Gutter.ChangesPart.AutoSize := SynEd.Gutter.ChangesPart(0).AutoSize;
Editor.Gutter.ChangesPart.Width := SynEd.Gutter.ChangesPart(0).Width;
Editor.Gutter.ChangesPart.ModifiedColor := SynEd.Gutter.ChangesPart(0).ModifiedColor;
Editor.Gutter.ChangesPart.SavedColor := SynEd.Gutter.ChangesPart(0).SavedColor;
Editor.Gutter.SeparatorPart.AutoSize := SynEd.Gutter.SeparatorPart(0).AutoSize;
Editor.Gutter.SeparatorPart.Width := SynEd.Gutter.SeparatorPart(0).Width;
Editor.Gutter.SeparatorPart.MarkupInfo.Assign(SynEd.Gutter.SeparatorPart(0).MarkupInfo);
Editor.Gutter.CodeFoldPart.MarkupInfo.Assign(SynEd.Gutter.CodeFoldPart(0).MarkupInfo);
fSynMarkHAllCaret := TSynEditMarkupHighlightAllCaret(SynEd.MarkupByClass[TSynEditMarkupHighlightAllCaret]);
if assigned(fSynMarkHAllCaret) then
begin
Editor.MarkupHighlightAllCaret.MarkupInfo.Assign(fSynMarkHAllCaret.MarkupInfo);
Editor.MarkupHighlightAllCaret.Trim := fSynMarkHAllCaret.Trim;
Editor.MarkupHighlightAllCaret.FullWord := fSynMarkHAllCaret.FullWord;
Editor.MarkupHighlightAllCaret.WaitTime := fSynMarkHAllCaret.WaitTime;
Editor.MarkupHighlightAllCaret.FullWordMaxLen := fSynMarkHAllCaret.FullWordMaxLen;
end;
For i:= 0 to Editor.ElementosSintaxe.count - 1 do
begin
Elemento := TLCElementoSintaxe(Editor.ElementosSintaxe.Items[i]);
case Elemento.Kind of
tLCAttributeName: Elemento.Atributos.Assign(TSynLCHighlighter(SynEd.Highlighter).Settings.SettingsToAttributeName);
tLCComment: Elemento.Atributos.Assign(TSynLCHighlighter(SynEd.Highlighter).Settings.SettingsToComment);
tLCDataType: Elemento.Atributos.Assign(TSynLCHighlighter(SynEd.Highlighter).Settings.SettingsToDataType);
tLCIdentifier: Elemento.Atributos.Assign(TSynLCHighlighter(SynEd.Highlighter).Settings.SettingsToIdentifier);
tLCKey: Elemento.Atributos.Assign(TSynLCHighlighter(SynEd.Highlighter).Settings.SettingsToKey);
tLCNumber: Elemento.Atributos.Assign(TSynLCHighlighter(SynEd.Highlighter).Settings.SettingsToNumber);
tLCReservedWord: Elemento.Atributos.Assign(TSynLCHighlighter(SynEd.Highlighter).Settings.SettingsToReservedWord);
tLCSpace: Elemento.Atributos.Assign(TSynLCHighlighter(SynEd.Highlighter).Settings.SettingsToSpace);
tLCString: Elemento.Atributos.Assign(TSynLCHighlighter(SynEd.Highlighter).Settings.SettingsToString);
tLCSymbol: Elemento.Atributos.Assign(TSynLCHighlighter(SynEd.Highlighter).Settings.SettingsToSymbol);
tLCVariable: Elemento.Atributos.Assign(TSynLCHighlighter(SynEd.Highlighter).Settings.SettingsToVariable);
end;
end;
end;
procedure TEditorLspSettings.AddMruFiles(fileName: String; SynEd: TSynEdit);
var
i : Integer;
Mru: TMRUFile;
begin
if FileExistsUTF8(fileName) = false then
begin
exit;
end;
// Verificar se o arquivo já faz parte da lista
for i := 0 to Pred(MruFiles.Count) do
begin
if AnsiUpperCase(TMRUFile(MruFiles.Items[i]).GetPathName) = AnsiUpperCase(FileName) then
begin
getMruFile(i).GetFromSynEdit(SynEd, SaveBookmarksWhenCloseFile);
getMruFile(i).LastTimeOpened := now;
MruFiles.Items[i].Index := 0;
exit;
end;
end;
// Adicionar o arquivo na lista
mru := TMRUFile(MruFiles.Insert(0));
Mru.GetFromSynEdit(SynEd, SaveBookmarksWhenCloseFile);
Mru.SetPathName(FileName);
Mru.LastTimeOpened := now;
// Verificar se o limite Arquivos da lista foi atingido, se sim, apagar o mais antigo
while MruFiles.Count > MaxMruFilesStored do
begin
MruFiles.Delete(MruFiles.Count -1);
end;
end;
function TEditorLspSettings.getMruFile(index: Integer): TMRUFile;
begin
Result := TMRUFile(Self.MruFiles.Items[index]);
end;
function TEditorLspSettings.getMruFile(aFileName : String) : TMRUFile;
var
i : integer;
begin
result := nil;
For i:=0 to Self.MruFiles.Count - 1 do
begin
if (aFileName = TMRUFile(Self.MruFiles.Items[i]).GetPathName) then
begin
result := TMRUFile(Self.MruFiles.Items[i]);
exit;
end;
end;
end;
function TEditorLspSettings.getIdiomaI18n : String;
begin
Result := LCI18nIdiomasEditor[ieLCPtBr];
if (fIdioma in (LCIdiomasEditor - [ieLCPtBr])) then
begin
Result := LCI18nIdiomasEditor[fIdioma];
end;
end;
{ TMRUFile }
function TMRUFile.GetDisplayName : string;
begin
Result := GetPathName;
end;
constructor TMRUFile.Create(ACollection : TCollection);
begin
inherited Create(ACollection);
fBookmarks := TCollection.Create(TMRUBookmark);
FFixed := false;
FTop := 0;
FLeft := 0;
FCaret.X := 0;
FCaret.Y := 0;
FPath := '';
FName := '';
end;
destructor TMRUFile.Destroy;
begin
FreeAndNil(fBookmarks);
inherited Destroy;
end;
procedure TMRUFile.GetFromSynEdit(aSynEd : TSynEdit; aSaveBookmarks : Boolean);
var
i : integer;
oMRUBookmark : TMRUBookmark;
begin
FTop := aSynEd.TopLine;
FLeft := aSynEd.LeftChar;
FCaret.X := aSynEd.CaretX;
FCaret.Y := aSynEd.CaretY;
fBookmarks.Clear;
if aSaveBookmarks = true then
begin
For i:= 0 to aSynEd.Marks.Count - 1 do
begin
oMRUBookmark := TMRUBookmark(fBookmarks.Add);
oMRUBookmark.BookmarkNumber := aSynEd.Marks[i].BookmarkNumber;
oMRUBookmark.Column := aSynEd.Marks[i].Column;
oMRUBookmark.ImageIndex := aSynEd.Marks[i].ImageIndex;
oMRUBookmark.Line := aSynEd.Marks[i].Line;
oMRUBookmark.Priority := aSynEd.Marks[i].Priority;
oMRUBookmark.Visible := aSynEd.Marks[i].Visible;
end;
end;
end;
procedure TMRUFile.SetToSynEdit(aSynEd: TSynEdit);
var
i : integer;
oMRUBookmark : TMRUBookmark;
oMark : TSynEditMark;
begin
aSynEd.TopLine := FTop;
aSynEd.LeftChar := FLeft;
aSynEd.CaretX := FCaret.X;
aSynEd.CaretY := FCaret.Y;
for i:= 0 to fBookmarks.Count - 1 do
begin
oMRUBookmark := TMRUBookmark(fBookmarks.Items[i]);
if aSynEd.IsBookmark(oMRUBookmark.BookmarkNumber) = false then
begin
oMark := TSynEditMark.Create(aSynEd);
oMark.BookmarkNumber := oMRUBookmark.BookmarkNumber;
oMark.ImageIndex := oMRUBookmark.ImageIndex;
oMark.Column := oMRUBookmark.Column;
oMark.Line := oMRUBookmark.Line;
oMark.Priority := oMRUBookmark.Priority;
oMark.Visible := oMRUBookmark.Visible;
aSynEd.Marks.Add(oMark);
end;
end;
end;
procedure TMRUFile.SetPathName(value: String);
begin
FName := ExtractFileName(value);
FPath := ExtractFilePath(value);
end;
function TMRUFile.GetPathName: String;
begin
Result := FPath + FName;
end;
end.
|
unit DelphiAdapter;
interface
type TAdapter = class
procedure addDatum(aDatum: Pointer); virtual; stdcall; abstract;
procedure startServer; virtual; stdcall; abstract;
function startServerThread(): Boolean; virtual; stdcall; abstract;
procedure sendChangedData; virtual; stdcall; abstract;
procedure flush; virtual; stdcall; abstract;
procedure timestamp; virtual; stdcall; abstract;
procedure unavailable; virtual; stdcall; abstract;
procedure stopServer; virtual; stdcall; abstract;
procedure free; virtual; stdcall; abstract;
end;
function NewAdapter(aPort: integer): TAdapter; cdecl;
type TEvent = class
function getDatum() : Pointer; virtual; stdcall; abstract;
procedure setValue(aValue: PChar); virtual; stdcall; abstract;
function getValue() : PChar; virtual; stdcall; abstract;
procedure free(); virtual; stdcall; abstract;
end;
function NewEvent(aName: PChar): TEvent; cdecl;
type TSample = class
function getDatum() : Pointer; virtual; stdcall; abstract;
procedure setValue(aValue: Double); virtual; stdcall; abstract;
function getValue() : Double; virtual; stdcall; abstract;
procedure free(); virtual; stdcall; abstract;
end;
function NewSample(aName: PChar): TSample; cdecl;
type
TExecutionState = (
ExecutionState_UNAVAILABLE,
ExecutionState_READY,
ExecutionState_INTERRUPTED,
ExecutionState_STOPPED,
ExecutionState_ACTIVE);
TExecution = class
function getDatum() : Pointer; virtual; stdcall; abstract;
procedure setValue(aValue: TExecutionState); virtual; stdcall; abstract;
function getValue() : TExecutionState; virtual; stdcall; abstract;
procedure free(); virtual; stdcall; abstract;
end;
function NewExecution(aName: PChar): TExecution; cdecl;
type
TControllerModes = (
ControllerMode_UNAVAILABLE,
ControllerMode_AUTOMATIC,
ControllerMode_MANUAL,
ControllerMode_MANUAL_DATA_INPUT,
ControllerMode_SEMI_AUTOMATIC);
TControllerMode = class
function getDatum() : Pointer; virtual; stdcall; abstract;
procedure setValue(aValue: TControllerModes); virtual; stdcall; abstract;
function getValue() : TControllerModes; virtual; stdcall; abstract;
procedure free(); virtual; stdcall; abstract;
end;
function NewControllerMode(aName: PChar): TControllerMode; cdecl;
type
TRotationDirection = (
Direction_UNAVAILABLE,
Direction_CLOCKWISE,
Direction_COUNTER_CLOCKWISE);
TDirection = class
function getDatum() : Pointer; virtual; stdcall; abstract;
procedure setValue(aValue: TRotationDirection); virtual; stdcall; abstract;
function getValue() : TRotationDirection; virtual; stdcall; abstract;
procedure free(); virtual; stdcall; abstract;
end;
function NewDirection(aName: PChar): TDirection; cdecl;
type
TEStop = (
EmergencyStop_UNAVAILABLE,
EmergencyStop_TRIGGERED,
EmergencyStop_ARMED);
TEmergencyStop = class
function getDatum() : Pointer; virtual; stdcall; abstract;
procedure setValue(aValue: TEStop); virtual; stdcall; abstract;
function getValue() : TEStop; virtual; stdcall; abstract;
procedure free(); virtual; stdcall; abstract;
end;
function NewEmergencyStop(aName: PChar): TEmergencyStop; cdecl;
type
TCoupling = (
AxisCoupling_UNAVAILABLE,
AxisCoupling_TANDEM,
AxisCoupling_SYNCHRONOUS,
AxisCoupling_MASTER,
AxisCoupling_SLAVE
);
TAxisCoupling = class
function getDatum() : Pointer; virtual; stdcall; abstract;
procedure setValue(aValue: TCoupling); virtual; stdcall; abstract;
function getValue() : TCoupling; virtual; stdcall; abstract;
procedure free(); virtual; stdcall; abstract;
end;
function NewAxisCoupling(aName: PChar): TAxisCoupling; cdecl;
type
TDoorStates = (
DoorState_UNAVAILABLE,
DoorState_OPEN,
DoorState_CLOSED);
TDoorState = class
function getDatum() : Pointer; virtual; stdcall; abstract;
procedure setValue(aValue: TDoorStates); virtual; stdcall; abstract;
function getValue() : TDoorStates; virtual; stdcall; abstract;
procedure free(); virtual; stdcall; abstract;
end;
function NewDoorState(aName: PChar): TDoorState; cdecl;
type
TPathModes = (
PathMode_UNAVAILABLE,
PathMode_INDEPENDENT,
PathMode_SYNCHRONOUS,
PathMode_MIRROR);
TPathMode = class
function getDatum() : Pointer; virtual; stdcall; abstract;
procedure setValue(aValue: TPathModes); virtual; stdcall; abstract;
function getValue() : TPathModes; virtual; stdcall; abstract;
procedure free(); virtual; stdcall; abstract;
end;
function NewPathMode(aName: PChar): TPathMode; cdecl;
type
TRotaryModes = (
RotaryMode_UNAVAILABLE,
RotaryMode_SPINDLE,
RotaryMode_INDEX,
RotaryMode_CONTOUR);
TRotaryMode = class
function getDatum() : Pointer; virtual; stdcall; abstract;
procedure setValue(aValue: TRotaryModes); virtual; stdcall; abstract;
function getValue() : TRotaryModes; virtual; stdcall; abstract;
procedure free(); virtual; stdcall; abstract;
end;
function NewRotaryMode(aName: PChar): TRotaryMode; cdecl;
type
TConditionLevels = (
Condition_UNAVAILABLE,
Condition_NORMAL,
Condition_WARNING,
Condition_FAULT);
TCondition = class
function getDatum() : Pointer; virtual; stdcall; abstract;
procedure setValue(aLevel: TConditionLevels; aText: PChar; aCode: PChar;
aQualifier: PChar; aSeverity: PChar); virtual; stdcall; abstract;
procedure free(); virtual; stdcall; abstract;
end;
function NewCondition(aName: PChar): TCondition; cdecl;
type
TMessage = class
function getDatum() : Pointer; virtual; stdcall; abstract;
procedure setValue(aText: PChar; aCode: PChar); virtual; stdcall; abstract;
procedure free(); virtual; stdcall; abstract;
end;
function NewMessage(aName: PChar): TMessage; cdecl;
type
TAvailability = class
function getDatum() : Pointer; virtual; stdcall; abstract;
procedure available(); virtual; stdcall; abstract;
procedure unavailable(); virtual; stdcall; abstract;
procedure free(); virtual; stdcall; abstract;
end;
function NewAvailability(aName: PChar): TAvailability; cdecl;
implementation
function NewAdapter(aPort: integer): TAdapter; external 'DelphiAdapter.dll';
function NewEvent(aName: PChar): TEvent; external 'DelphiAdapter.dll';
function NewSample(aName: PChar): TSample; external 'DelphiAdapter.dll';
function NewExecution(aName: PChar): TExecution; external 'DelphiAdapter.dll';
function NewControllerMode(aName: PChar): TControllerMode; external 'DelphiAdapter.dll';
function NewDirection(aName: PChar): TDirection; external 'DelphiAdapter.dll';
function NewEmergencyStop(aName: PChar): TEmergencyStop; external 'DelphiAdapter.dll';
function NewAxisCoupling(aName: PChar): TAxisCoupling; external 'DelphiAdapter.dll';
function NewDoorState(aName: PChar): TDoorState; external 'DelphiAdapter.dll';
function NewPathMode(aName: PChar): TPathMode; external 'DelphiAdapter.dll';
function NewRotaryMode(aName: PChar): TRotaryMode; external 'DelphiAdapter.dll';
function NewCondition(aName: PChar): TCondition; external 'DelphiAdapter.dll';
function NewMessage(aName: PChar): TMessage; external 'DelphiAdapter.dll';
function NewAvailability(aName: PChar): TAvailability; external 'DelphiAdapter.dll';
end.
|
unit uPrintException;
interface
uses
sysutils;
type
eNexPrinterNotFound = class(exception)
PrinterName: string;
constructor Create(const aPrinterName: string);
end;
eNexTipoImpressaoNotFound = class(exception)
TipoImpressao: string;
constructor Create(const aTipoImpressao: string);
end;
eNexIDTipoImpressaoNotFound = class(exception)
idTipoImpressao: integer;
constructor Create(const aIdTipoImpressao: integer);
end;
eNexUnzipError = class(exception)
fileName: string;
constructor Create(const afileName: string);
end;
eNexDownloadError = class(exception)
fileName, aMessage: string;
constructor Create(const afileName, eMsg: string);
end;
eNexDownloadMd5Error = class(exception)
fileName, aMessage: string;
constructor Create(const afileName: string);
end;
implementation
{ eNexPrinterNotFound }
constructor eNexPrinterNotFound.Create(const aPrinterName: string);
begin
inherited create('Erro abrindo impressora '+aPrinterName);
PrinterName := APrinterName;
end;
{ eInfo8ImpressionTypeNotFound }
constructor eNexTipoImpressaoNotFound.Create(const aTipoImpressao: string);
begin
inherited create('Tipo de impressão não localizado '+aTipoImpressao);
TipoImpressao := aTipoImpressao;
end;
{ eNexIDTipoImpressaoNotFound }
constructor eNexIDTipoImpressaoNotFound.Create(const aIdTipoImpressao: integer);
begin
inherited create('Tipo de impressão não localizado id: '+inttostr(aIdTipoImpressao));
idTipoImpressao := aIdTipoImpressao;
end;
{ eNexUnzipError }
constructor eNexUnzipError.Create(const afileName: string);
begin
inherited create('Erro descompactando arquivo '+afileName);
fileName := afileName;
end;
{ eNexDownloadError }
constructor eNexDownloadError.Create(const afileName, eMsg: string);
begin
inherited create('Erro descarregando arquivo '+afileName + ': ' +eMsg);
fileName := afileName;
aMessage := eMsg;
end;
{ eNexDownloadMd5Error }
constructor eNexDownloadMd5Error.Create(const afileName: string);
begin
inherited create('Erro de MD5 do arquivo descarregado: '+afileName);
fileName := afileName;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : GLSRGBE<p>
<b>History : </b><font size=-1><ul>
<li>17/11/14 - PW - Renamed from RGBE.pas to GLSRGBE.pas
<li>15/06/10 - Yar - Fixes for Linux x64
<li>20/01/10 - Yar - Creation
</ul><p>
}
unit GLSRGBE;
interface
{$I GLScene.inc}
uses
Classes, SysUtils,
//GLS
GLVectorTypes, GLVectorGeometry, GLCrossPlatform;
procedure Float2rgbe(var RGBE: TVector4b; const Red, Green, Blue: Single);
procedure Rgbe2float(var Red, Green, Blue: Single; const RGBE: TVector4b);
procedure LoadRLEpixels(Stream: TStream; Dst: PSingle;
Scanline_width, Num_scanlines: Integer);
procedure LoadRGBEpixels(Stream: TStream; Dst: PSingle; Numpixels: Integer);
implementation
type
ERGBEexception = class(Exception);
{ Extract exponent and mantissa from X }
procedure Frexp(X: Extended; var Mantissa: Extended; var Exponent: Integer);
{ Mantissa ptr in EAX, Exponent ptr in EDX }
{$IFDEF GLS_NO_ASM}
begin
Exponent := 0;
if (X <> 0) then
if (Abs(X) < 0.5) then
repeat
X := X * 2;
Dec(Exponent);
until (Abs(X) >= 0.5)
else
while (Abs(X) >= 1) do
begin
X := X / 2;
Inc(Exponent);
end;
Mantissa := X;
{$ELSE}
asm
FLD X
PUSH EAX
MOV dword ptr [edx], 0 { if X = 0, return 0 }
FTST
FSTSW AX
FWAIT
SAHF
JZ @@Done
FXTRACT // ST(1) = exponent, (pushed) ST = fraction
FXCH
// The FXTRACT instruction normalizes the fraction 1 bit higher than
// wanted for the definition of frexp() so we need to tweak the result
// by scaling the fraction down and incrementing the exponent.
FISTP dword ptr [edx]
FLD1
FCHS
FXCH
FSCALE // scale fraction
INC dword ptr [edx] // exponent biased to match
FSTP ST(1) // discard -1, leave fraction as TOS
@@Done:
POP EAX
FSTP tbyte ptr [eax]
FWAIT
{$ENDIF}
end;
function Ldexp(X: Extended; const P: Integer): Extended;
{$IFDEF GLS_NO_ASM}
begin
Ldexp := X * Intpower(2.0, P);
{$ELSE}
{ Result := X * (2^P) }
asm
PUSH EAX
FILD dword ptr [ESP]
FLD X
FSCALE
POP EAX
FSTP ST(1)
FWAIT
{$ENDIF}
end;
// standard conversion from float pixels to rgbe pixels
procedure Float2rgbe(var RGBE: TVector4b; const Red, Green, Blue: Single);
var
V, M: Extended;
E: Integer;
begin
V := Red;
if (Green > V) then
V := Green;
if (Blue > V) then
V := Blue;
if (V < 1E-32) then
begin
RGBE.V[0] := 0;
RGBE.V[1] := 0;
RGBE.V[2] := 0;
RGBE.V[3] := 0;
end
else
begin
FrExp(V, M, E);
M := M * 256 / V;
RGBE.V[0] := Floor(Red * V);
RGBE.V[1] := Floor(Green * V);
RGBE.V[2] := Floor(Blue * V);
RGBE.V[3] := Floor(E + 128);
end;
end;
// standard conversion from rgbe to float pixels
// note: Ward uses ldexp(col+0.5,exp-(128+8)). However we wanted pixels
// in the range [0,1] to map back into the range [0,1].
procedure Rgbe2float(var Red, Green, Blue: Single; const RGBE: TVector4b);
var
F: Single;
begin
if RGBE.V[3] <> 0 then // nonzero pixel
begin
F := Ldexp(1.0, RGBE.V[3] - (128 + 8));
Red := RGBE.V[0] * F;
Green := RGBE.V[1] * F;
Blue := RGBE.V[2] * F;
end
else
begin
Red := 0;
Green := 0;
Blue := 0;
end;
end;
procedure LoadRLEpixels(Stream: TStream; Dst: PSingle;
Scanline_width, Num_scanlines: Integer);
var
RgbeTemp: TVector4b;
Buf: TVector2b;
Rf, Gf, Bf: Single;
Scanline_buffer: PByteArray;
Ptr, Ptr_end: PByte;
I: Integer;
Count: Cardinal;
begin
if (Scanline_width < 8) or (Scanline_width > $7FFF) then
begin
// run length encoding is not allowed so read flat
LoadRGBEPixels(Stream, Dst, Scanline_width * Num_scanlines);
Exit;
end;
Scanline_buffer := nil;
while Num_scanlines > 0 do
begin
Stream.Read(RgbeTemp, SizeOf(TVector4b));
if (RgbeTemp.V[0] <> 2) or (RgbeTemp.V[1] <> 2) or
(RgbeTemp.V[2] and $80 <> 0) then
begin
// this file is not run length encoded
Rgbe2float(Rf, Gf, Bf, RgbeTemp);
Dst^ := Rf;
Inc(Dst);
Dst^ := Gf;
Inc(Dst);
Dst^ := Bf;
Inc(Dst);
if Assigned(Scanline_buffer) then
FreeMem(Scanline_buffer);
LoadRGBEpixels(Stream, Dst, Scanline_width * Num_scanlines - 1);
Exit;
end;
if ((Integer(RgbeTemp.V[2]) shl 8) or RgbeTemp.V[3]) <> Scanline_width
then
begin
if Assigned(Scanline_buffer) then
FreeMem(Scanline_buffer);
raise ERGBEexception.Create('Wrong scanline width.');
end;
if not Assigned(Scanline_buffer) then
ReallocMem(Scanline_buffer, 4 * Scanline_width);
Ptr := PByte(Scanline_buffer);
// read each of the four channels for the scanline into the buffer
for I := 0 to 3 do
begin
Ptr_end := @Scanline_buffer[(I + 1) * Scanline_width];
while PtrUInt(Ptr) < PtrUInt(Ptr_end) do
begin
Stream.Read(Buf, SizeOf(TVector2b));
if Buf.V[0] > 128 then
begin // a run of the same value
Count := Buf.V[0] - 128;
if (Count = 0) or (Count > PtrUInt(Ptr_end) - PtrUInt(Ptr)) then
begin
FreeMem(Scanline_buffer);
raise ERGBEexception.Create('Bad HDR scanline data.');
end;
while Count > 0 do
begin
Ptr^ := Buf.V[1];
Dec(Count);
Inc(Ptr);
end;
end
else
begin // a non-run
Count := Buf.V[0];
if (Count = 0) or (Count > PtrUInt(Ptr_end) - PtrUInt(Ptr)) then
begin
FreeMem(Scanline_buffer);
raise ERGBEexception.Create('Bad HDR scanline data.');
end;
Ptr^ := Buf.V[1];
Dec(Count);
Inc(Ptr);
if Count > 0 then
Stream.Read(Ptr^, Count);
Inc(Ptr, Count);
end;
end;
end;
// now convert data from buffer into floats
for I := 0 to Scanline_width - 1 do
begin
RgbeTemp.V[0] := Scanline_buffer[I];
RgbeTemp.V[1] := Scanline_buffer[I + Scanline_width];
RgbeTemp.V[2] := Scanline_buffer[I + 2 * Scanline_width];
RgbeTemp.V[3] := Scanline_buffer[I + 3 * Scanline_width];
Rgbe2float(Rf, Gf, Bf, RgbeTemp);
Dst^ := Rf;
Inc(Dst);
Dst^ := Gf;
Inc(Dst);
Dst^ := Bf;
Inc(Dst);
end;
Dec(Num_scanlines);
end;
if Assigned(Scanline_buffer) then
FreeMem(Scanline_buffer);
end;
procedure LoadRGBEpixels(Stream: TStream; Dst: PSingle; Numpixels: Integer);
var
RgbeTemp: TVector4b;
Rf, Gf, Bf: Single;
begin
while Numpixels > 0 do
begin
Stream.Read(RgbeTemp, SizeOf(TVector4b));
Rgbe2float(Rf, Gf, Bf, RgbeTemp);
Dst^ := Rf;
Inc(Dst);
Dst^ := Gf;
Inc(Dst);
Dst^ := Bf;
Inc(Dst);
Dec(Numpixels);
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit ExpertsProjectCreators;
interface
uses ToolsApi, ExpertsBaseCreators, ExpertsIntf, SysUtils, ExpertsProject;
type
TExpertsProjectCreator = class(TCreator, IOTACreator, IOTAProjectCreator, IOTAProjectCreator80, IOTAProjectCreator160, IOTAProjectCreator190)
private
FExpertsProject: IExpertsProjectAccessor;
FPersonality: string;
property Personality: string read FPersonality;
function InternalGetPlatforms(const OSFamily: TOSFamilySet): TArray<string>;
{ IOTACreator }
function GetCreatorType: string;
{ IOTAProjectCreator80 }
function GetProjectPersonality: string;
{ IOTAProjectCreator }
function GetFileName: string;
function GetOptionFileName: string;
function GetShowSource: Boolean;
procedure NewDefaultModule;
function NewOptionSource(const ProjectName: string): IOTAFile;
procedure NewProjectResource(const Project: IOTAProject);
function NewProjectSource(const ProjectName: string): IOTAFile;
{ IOTAProjectCreator50 }
procedure NewDefaultProjectModule(const Project: IOTAProject);
{ IOTACreator }
function GetUnnamed: Boolean;
{ IOTAProjectCreator160 }
function GetFrameworkType: string;
function GetPlatformTypes: TOSFamilySet;
function GetPlatforms: TArray<string>;
function GetPreferredPlatform: string;
procedure SetInitialOptions(const NewProject: IOTAProject);
{ IOTAProjectCreator190 }
function GetSupportedPlatforms: TArray<string>;
function GetSupportedPlatformTypes: TOSFamilySet;
public
constructor Create(const APersonality: string; const AExpertsProject: IExpertsProjectAccessor);
end;
implementation
uses PlatformAPI, System.Classes, BCCStrs;
{ TProjectCreator }
constructor TExpertsProjectCreator.Create(const APersonality: string; const AExpertsProject: IExpertsProjectAccessor);
begin
FPersonality := APersonality;
FExpertsProject := AExpertsProject;
end;
function TExpertsProjectCreator.GetCreatorType: string;
begin
Result := FExpertsProject.GetCreatorType;
end;
//function DefaultProjectFile(const APersonality: string; const ADirectory: string): string;
// function ValidProjectName(var AFileName: string): Boolean;
// var
// LBaseName: string;
// I: Integer;
// begin
// Result := False;
// LBaseName := ChangeFileExt(AFileName, '');
// if (Length(LBaseName) > 0) then
// begin
// Result := True;
// for I := 1 to Length(LBaseName) do
// if not (CharInSet(LBaseName[I], ['0'..'9','A'..'Z','a'..'z','_'])) then
// LBaseName[I] := '_';
// AFileName := ChangeFileExt(LBaseName, ExtractFileExt(AFileName));
// end;
// end;
//var
// LTemplate: string;
// I: Integer;
// LExt: string;
//begin
// if APersonality = sCBuilderPersonality then
// LExt := '.cpp'
// else
// LExt := '.dpr';
//
// Result := ChangeFileExt(ExtractFileName(ExcludeTrailingPathDelimiter(ADirectory)), LExt);
// if ValidProjectName(Result) and not FileExists(IncludeTrailingPathDelimiter(ADirectory) + Result) then
// Exit;
// LTemplate := 'Project%d' + LExt;
// I := 1;
// repeat
// Result := Format(LTemplate, [I]);
// Inc(I);
// until not FileExists(IncludeTrailingPathDelimiter(ADirectory) + Result);
//end;
//function DefaultProjectDirectory: string;
//var
// LTemplate: string;
// I: Integer;
//begin
// LTemplate := IncludeTrailingPathDelimiter((BorlandIDEServices as IOTAServices).GetStartupDirectory) +
// sProjectDirTemplate;
// I := 1;
// repeat
// Result := Format(LTemplate, [I]);
// Inc(I);
// until not DirectoryExists(Result);
//end;
function TExpertsProjectCreator.GetFileName: string;
var
LSuffix: string;
LFileName: string;
LDirectory: string;
begin
Result := '';
LDirectory := FExpertsProject.GetDirectory;
LFileName := FExpertsProject.GetFileName;
// For cpppackages always generate a file name. The default name generated by the IDE has the wrong extension
if (LDirectory <> '') or (LFileName <> '') or SameText(GetCreatorType, 'cpppackage') then
begin
if LFileName <> '' then
begin
if Personality = sCBuilderPersonality then
LFileName := ChangeFileExt(LFileName, '.cpp')
else
LFileName := ChangeFileExt(LFileName, '.dpr');
end;
if LDirectory = '' then
begin
LDirectory := (BorlandIDEServices as IOTAServices).GetStartupDirectory;
end;
Result := GetNewModuleFileName('Project', LDirectory,
LFileName, False, LSuffix, '.bdsproj;.dproj;.dpr;.dpk;.cbproj')
end;
end;
function TExpertsProjectCreator.GetFrameworkType: string;
begin
Result := FExpertsProject.GetFrameWorkType;
end;
function TExpertsProjectCreator.GetOptionFileName: string;
begin
Result := '';
end;
function TExpertsProjectCreator.InternalGetPlatforms(
const OSFamily: TOSFamilySet): TArray<string>;
begin
if osfLinux in OSFamily then
Result := TArray<string>.Create(cWin32Platform, cWin64Platform, cLinux64Platform)
else
Result := TArray<string>.Create(cWin32Platform, cWin64Platform);
end;
function TExpertsProjectCreator.GetPlatforms: TArray<string>;
begin
Result := InternalGetPlatforms(GetPlatformTypes);
end;
function TExpertsProjectCreator.GetSupportedPlatforms: TArray<string>;
begin
Result := InternalGetPlatforms(GetSupportedPlatformTypes);
end;
function TExpertsProjectCreator.GetPlatformTypes: TOSFamilySet;
begin
Result := FExpertsProject.GetPlatformTypes;
end;
function TExpertsProjectCreator.GetSupportedPlatformTypes: TOSFamilySet;
var
LProjectAccessor: IExpertsProjectAccessor190;
begin
Result := [osfWindows];
if Supports(FExpertsProject, IExpertsProjectAccessor190, LProjectAccessor) then
Result := LProjectAccessor.GetProjectPlatformTypes
end;
function TExpertsProjectCreator.GetPreferredPlatform: string;
begin
Result := GetPlatforms[0];
end;
function TExpertsProjectCreator.GetProjectPersonality: string;
begin
Result := Personality;
end;
function TExpertsProjectCreator.GetShowSource: Boolean;
begin
Result := True;
end;
function TExpertsProjectCreator.GetUnnamed: Boolean;
begin
Result := FExpertsProject.GetUnnamed;
end;
procedure TExpertsProjectCreator.NewDefaultModule;
begin
FExpertsProject.NewDefaultModule;
end;
procedure TExpertsProjectCreator.NewDefaultProjectModule(const Project: IOTAProject);
begin
NewDefaultModule;
end;
function TExpertsProjectCreator.NewOptionSource(const ProjectName: string): IOTAFile;
begin
Result := nil;
end;
procedure TExpertsProjectCreator.NewProjectResource(const Project: IOTAProject);
begin
{ do nothing here }
end;
function TExpertsProjectCreator.NewProjectSource(const ProjectName: string): IOTAFile;
begin
Result := FExpertsProject.NewProjectSource(ProjectName);
end;
procedure TExpertsProjectCreator.SetInitialOptions(
const NewProject: IOTAProject);
var
POC: IOTAProjectOptionsConfigurations;
ModuleInfo: IOTAModuleInfo;
i: integer;
begin
if Personality = sCBuilderPersonality then
begin
// Look for default pch file and set initial options
if Supports(NewProject.ProjectOptions, IOTAProjectOptionsConfigurations, POC) then
begin
for i:=0 to NewProject.GetModuleCount -1 do
begin
ModuleInfo := NewProject.GetModule(i);
if ExtractFileExt(ModuleInfo.FileName) = '.h' then
begin
POC.BaseConfiguration.PlatformConfiguration[cWin64Platform][BCCStrs.sPCHName_Clang] := ExtractFileName(ModuleInfo.FileName);
ModuleInfo.BuildAction := sbaPCHCompile;
end;
end;
end;
end;
end;
end.
|
//////////////////////////////////////////////////
// Universal Data Access Components
// Copyright © 1998-2020 Devart. All right reserved.
// ReportBuilder support
// Based on Digital Metaphors Corporation's demos
//////////////////////////////////////////////////
unit daUniDAC;
interface
uses
SysUtils, // System.SysUtils
Classes, // System.Classes
DB, // Data.DB
Uni,
ppTypes,
ppUtils,
ppDB,
ppDBPipe,
ppClasUt,
daDB,
daDataView,
daQueryDataView;
type
{Universal Data Access Components (UniDAC) DataView Classes:
1. UniDAC TDataSet descendants
- TDataSets that can be children of a DataView.
- Override the HasParent method of TComponent to return True
- Must be registerd with the Delphi IDE using the RegisterNoIcon procedure
a. TdaChildUniDACQuery - TUniQuery descendant that can be a child of a DataView
b. TdaChildUniDACTable - TUniTable descendant that can be a child of a DataView
b. TdaChildUniDACStoredProc - TUniStoredProc descendant that can be a child of a DataView
3. TdaUniDACSession
- descendant of TppSession
- implements GetDatabaseNames, GetTableNames, etc.
4. TdaUniDACDataSet
- descendant of TppDataSet
- implements GetFieldNames for SQL
5. TdaUniDACQueryDataView
- descendant of TppQueryDataView
- uses the above classes to create the required
Query -> DataSource -> Pipeline -> Report connection
- uses the TdaSQL object built by the QueryWizard to assign
SQL to the TUniDACQuery etc.
}
{ TdaChildUniDACQuery }
{$IFDEF VER230}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TdaChildUniDACQuery = class(TUniQuery)
public
function HasParent: Boolean; override;
end; {class, TdaChildUniDACQuery}
{ TdaChildUniDACTable }
{$IFDEF VER230}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TdaChildUniDACTable = class(TUniTable)
public
function HasParent: Boolean; override;
end; {class, TdaChildUniDACTable}
{ TdaChildUniDACStoredProc }
{$IFDEF VER230}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TdaChildUniDACStoredProc = class(TUniStoredProc)
public
function HasParent: Boolean; override;
end; {class, TdaChildUniDACStoredProc}
{ TdaUniDACSession }
{$IFDEF VER230}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TdaUniDACSession = class(TdaSession)
private
protected
function GetDefaultDatabase(const aDatabaseName: String): TComponent; override;
procedure GetTableNamesForConnection(const aConnection: TUniConnection; aList: TStrings); virtual;
function IsNamedDatabase(const aDatabaseName: String; aDatabase: TComponent): Boolean; override;
public
class function ClassDescription: String; override;
class function DataSetClass: TdaDataSetClass; override;
class function DatabaseClass: TComponentClass; override;
class function GetDefaultUniDACConnection: TUniConnection;
class function GetUniDatabaseType(aUniDacConnection: TUniConnection): TppDatabaseType;
procedure GetDatabaseNames(aList: TStrings); override;
function GetDatabaseType(const aDatabaseName: String): TppDatabaseType; override;
procedure GetTableNames(const aDatabaseName: String; aList: TStrings); override;
function ValidDatabaseTypes: TppDatabaseTypes; override;
end; {class, TdaUniDACSession}
{ TdaUniDACDataSet }
{$IFDEF VER230}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TdaUniDACDataSet = class(TdaDataSet)
private
FQuery: TUniQuery;
FConnection: TUniConnection;
function GetQuery: TUniQuery;
protected
procedure BuildFieldList; override;
function GetActive: Boolean; override;
procedure SetActive(Value: Boolean); override;
procedure SetDatabase(aDatabase: TComponent); override;
procedure SetDataName(const aDataName: String); override;
property Query: TUniQuery read GetQuery;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
class function ClassDescription: String; override;
procedure GetFieldNamesForSQL(aList: TStrings; aSQL: TStrings); override;
procedure GetFieldsForSQL(aList: TList; aSQL: TStrings); override;
end; {class, TdaUniDACDataSet}
{ TdaUniDACQueryDataView }
{$IFDEF VER230}
[ComponentPlatformsAttribute(pidWin32 or pidWin64)]
{$ENDIF}
TdaUniDACQueryDataView = class(TdaQueryDataView)
private
FDataSource: TppChildDataSource;
FQuery: TdaChildUniDACQuery;
protected
procedure SQLChanged; override;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
class function SessionClass: TClass; override;
procedure Init; override;
procedure ConnectPipelinesToData; override;
published
property DataSource: TppChildDataSource read FDataSource;
end; {class, TdaUniDACQueryDataView}
{Delphi design time registration}
procedure Register;
implementation
const
cDefaultConnection = 'DefaultUniDACConnection';
var
uUniDACConnection: TUniConnection;
{******************************************************************************
*
** R E G I S T E R
*
{******************************************************************************}
procedure Register;
begin
{UniDAC DataAccess Components}
RegisterNoIcon([TdaChildUniDACQuery, TdaChildUniDACTable, TdaChildUniDACStoredProc]);
{UniDAC DataViews}
RegisterNoIcon([TdaUniDACQueryDataView]);
end;
{******************************************************************************
*
** C H I L D U N I D A C D A T A A C C E S S C O M P O N E N T S
*
{******************************************************************************}
{------------------------------------------------------------------------------}
{ TdaChildUniDACQuery.HasParent }
function TdaChildUniDACQuery.HasParent: Boolean;
begin
Result := True;
end; {function, HasParent}
{------------------------------------------------------------------------------}
{ TdaChildUniDACTable.HasParent }
function TdaChildUniDACTable.HasParent: Boolean;
begin
Result := True;
end; {function, HasParent}
{------------------------------------------------------------------------------}
{ TdaChildUniDACStoredProc.HasParent }
function TdaChildUniDACStoredProc.HasParent: Boolean;
begin
Result := True;
end; {function, HasParent}
{******************************************************************************
*
** U N I D A C S E S S I O N
*
{******************************************************************************}
{------------------------------------------------------------------------------}
{ TdaUniDACSession.ClassDescription }
class function TdaUniDACSession.ClassDescription: String;
begin
Result := 'UniDACSession';
end; {class function, ClassDescription}
{------------------------------------------------------------------------------}
{ TdaUniDACSession.DataSetClass }
class function TdaUniDACSession.DataSetClass: TdaDataSetClass;
begin
Result := TdaUniDACDataSet;
end; {class function, DataSetClass}
{------------------------------------------------------------------------------}
{ TdaUniDACSession.DatabaseClass }
class function TdaUniDACSession.DatabaseClass: TComponentClass;
begin
Result := TUniConnection;
end;
class function TdaUniDACSession.GetDefaultUniDACConnection: TUniConnection;
begin
{create the default Connection, if needed}
if (uUniDACConnection = nil) then
begin
uUniDACConnection := TUniConnection.Create(nil);
uUniDACConnection.Name := cDefaultConnection;
end;
Result := uUniDACConnection;
end;
class function TdaUniDacSession.GetUniDatabaseType(aUniDacConnection: TUniConnection): TppDatabaseType;
begin
if aUniDacConnection.ProviderName='SQL Server' then
Result := dtMSSQLServer
else if aUniDacConnection.ProviderName='Oracle' then
Result := dtOracle
else if aUniDacConnection.ProviderName='MySQL' then
Result := dtMySQL
else if aUniDacConnection.ProviderName='InterBase' then
Result := dtInterBase
else if aUniDacConnection.ProviderName='PostgreSQL' then
Result := dtPostgreSQL
else
Result := dtOther;
end; {procedure, GetDatabaseType}
{------------------------------------------------------------------------------}
{ TdaUniDACSession.GetDatabaseType }
function TdaUniDACSession.GetDatabaseType(const aDatabaseName: String): TppDatabaseType;
var
aUniDacConnection: TUniConnection;
begin
aUniDacConnection := GetDefaultUniDacConnection;
Result := GetUniDatabaseType(aUniDacConnection);
end; {procedure, GetDatabaseType}
{------------------------------------------------------------------------------}
{ TdaUniDACSession.GetDatabaseNames }
procedure TdaUniDACSession.GetDatabaseNames(aList: TStrings);
begin
{call inherited to build list of available TADOConnection components}
inherited GetDatabaseNames(aList);
{could add hard-coded connection strings here, or could
read from an .ini file }
end; {procedure, GetDatabaseNames}
{------------------------------------------------------------------------------}
{ TdaUniDACSession.GetDefaultDatabase }
function TdaUniDACSession.GetDefaultDatabase(const aDatabaseName: String): TComponent;
var
lConnection: TUniConnection;
begin
lConnection := GetDefaultUniDACConnection;
if (lConnection.Server <> aDatabaseName) then
begin
if lConnection.Connected then
lConnection.Connected := False;
lConnection.Server := aDatabaseName;
end;
Result := lConnection;
end; {function, GetDefaultDatabase}
{------------------------------------------------------------------------------}
{ TdaUniDACSession.GetTableNames }
procedure TdaUniDACSession.GetTableNames(const aDatabaseName: String; aList: TStrings);
var
lConnection: TUniConnection;
begin
{get the connection}
lConnection := TUniConnection(GetDatabaseForName(aDatabaseName));
{connection must be active to get table names}
if not lConnection.Connected then
lConnection.Connected := True;
GetTableNamesForConnection(lConnection, aList);
end;
{------------------------------------------------------------------------------}
{ TdaUniDACSession.GetTableNamesForConnection }
procedure TdaUniDACSession.GetTableNamesForConnection(const aConnection: TUniConnection; aList: TStrings);
var
lNameField: TField;
lMetaData: TUniMetadata;
begin
aList.BeginUpdate;
lMetaData := TUniMetadata.Create(nil);
try
lMetaData.Connection := aConnection;
lMetaData.MetaDatakind := 'Tables';
// get table names
lMetaData.Restrictions.Values['TABLE_TYPE'] := 'TABLE';
lMetaData.Open;
lNameField := lMetaData.FieldByName('TABLE_NAME') as TStringField;
while not lMetaData.Eof do
begin
aList.Add(lNameField.Value);
lMetaData.Next
end;
lMetaData.Close;
// get view names
lMetaData.Restrictions.Values['TABLE_TYPE'] := 'VIEW';
lMetaData.Open;
lNameField := lMetaData.FieldByName('TABLE_NAME') as TStringField;
while not lMetaData.Eof do
begin
aList.Add(lNameField.Value);
lMetaData.Next
end;
finally
lMetaData.Free;
aList.EndUpdate;
end;
end;
{------------------------------------------------------------------------------}
{ TdaUniDACSession.IsNamedDatabase }
function TdaUniDACSession.IsNamedDatabase(const aDatabaseName: String; aDatabase: TComponent): Boolean;
begin
Result := (AnsiCompareText(aDatabase.Name, aDatabaseName) = 0) or
(AnsiCompareText(TUniConnection(aDatabase).Server, aDatabaseName) = 0);
end; {function, IsNamedDatabase}
{------------------------------------------------------------------------------}
{ TdaUniDACSession.ValidDatabaseTypes }
function TdaUniDACSession.ValidDatabaseTypes: TppDatabaseTypes;
begin
Result := [dtMSSQLServer, dtOracle, dtMySQL, dtInterBase, dtPostgreSQL, dtOther];
end; {function, ValidDatabaseTypes}
{******************************************************************************
*
** U N I D A C D A T A S E T
*
{******************************************************************************}
{------------------------------------------------------------------------------}
{ TdaUniDACDataSet.Create }
constructor TdaUniDACDataSet.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
FQuery := nil;
end; {constructor, Create}
{------------------------------------------------------------------------------}
{ TdaUniDACDataSet.Destroy }
destructor TdaUniDACDataSet.Destroy;
begin
FQuery.Free;
inherited Destroy;
end; {destructor, Destroy}
{------------------------------------------------------------------------------}
{ TdaUniDACDataSet.ClassDescription }
class function TdaUniDACDataSet.ClassDescription: String;
begin
Result := 'UniDACDataSet';
end; {class function, ClassDescription}
{------------------------------------------------------------------------------}
{ TdaUniDACDataSet.GetActive }
function TdaUniDACDataSet.GetActive: Boolean;
begin
Result := GetQuery.Active
end; {function, GetActive}
{------------------------------------------------------------------------------}
{ TdaUniDACDataSet.SetActive }
procedure TdaUniDACDataSet.SetActive(Value: Boolean);
begin
GetQuery.Active := Value;
end; {procedure, SetActive}
{------------------------------------------------------------------------------}
{ TdaUniDACDataSet.GetQuery }
function TdaUniDACDataSet.GetQuery: TUniQuery;
begin
{create UniDACDataSet, if needed}
if (FQuery = nil) then
FQuery := TUniQuery.Create(Self);
Result := FQuery;
end; {procedure, GetQuery}
{------------------------------------------------------------------------------}
{ TdaUniDACDataSet.SetDatabase }
procedure TdaUniDACDataSet.SetDatabase(aDatabase: TComponent);
begin
inherited SetDatabase(aDatabase);
{table cannot be active to set database property}
if GetQuery.Active then
FQuery.Active := False;
FConnection := TUniConnection(aDatabase);
{get UniDAC Connection for name}
FQuery.Connection := FConnection;
end; {procedure, SetDatabaseName}
{------------------------------------------------------------------------------}
{ TdaUniDACDataSet.SetDataName }
procedure TdaUniDACDataSet.SetDataName(const aDataName: String);
begin
inherited SetDataName(aDataName);
{dataset cannot be active to set data name}
if GetQuery.Active then
FQuery.Active := False;
{construct an SQL statment that returns an empty result set,
this is used to get the field information }
FQuery.SQL.Text := 'SELECT * FROM ' + aDataName +
' WHERE ''c'' <> ''c'' ';
end; {procedure, SetDataName}
{------------------------------------------------------------------------------}
{ TdaUniDACDataSet.BuildFieldList }
procedure TdaUniDACDataSet.BuildFieldList;
var
liIndex: Integer;
lQueryField: TField;
lField: TppField;
begin
inherited BuildFieldList;
{set table to active}
if not(GetQuery.Active) then
FQuery.Active := True;
{create TppField objects for each field in the table}
for liIndex := 0 to FQuery.FieldCount - 1 do begin
lQueryField := FQuery.Fields[liIndex];
lField := TppField.Create(nil);
lField.TableName := DataName;
lField.FieldName := lQueryField.FieldName;
lField.DataType := ppConvertFieldType(lQueryField.DataType);
AddField(lField);
end;
end; {function, BuildFieldList}
{------------------------------------------------------------------------------}
{ TdaUniDACDataSet.GetFieldNamesForSQL }
procedure TdaUniDACDataSet.GetFieldNamesForSQL(aList: TStrings; aSQL: TStrings);
var
lQuery: TUniQuery;
begin
aList.Clear;
{create a temporary query}
lQuery := TUniQuery.Create(Self);
{set the database and SQL properties}
lQuery.Connection := FConnection;
lQuery.SQL := aSQL;
{get the field names}
lQuery.GetFieldNames(aList);
lQuery.Free;
end; {procedure, GetFieldNamesForSQL}
{------------------------------------------------------------------------------}
{ TdaUniDACDataSet.GetFieldsForSQL }
procedure TdaUniDACDataSet.GetFieldsForSQL(aList: TList; aSQL: TStrings);
var
lQuery: TUniQuery;
lQueryField: TField;
lField: TppField;
liIndex: Integer;
begin
aList.Clear;
{create a temporary query}
lQuery := TUniQuery.Create(Self);
{assign databae and SQL properties}
lQuery.Connection := FConnection;
lQuery.SQL := aSQL;
{set query to active}
lQuery.Active := True;
{create a TppField object for each field in the query}
for liIndex := 0 to lQuery.FieldCount - 1 do begin
lQueryField := lQuery.Fields[liIndex];
lField := TppField.Create(nil);
lField.FieldName := lQueryField.FieldName;
lField.DataType := ppConvertFieldType(lQueryField.DataType);
aList.Add(lField);
end;
lQuery.Free;
end; {procedure, GetFieldsForSQL}
{******************************************************************************
*
** U N I D A C Q U E R Y D A T A V I E W
*
{******************************************************************************}
{------------------------------------------------------------------------------}
{ TdaUniDACQueryDataView.Create }
constructor TdaUniDACQueryDataView.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
{notes: 1. must use ChildQuery, ChildDataSource, ChildPipeline etc.
2. use Self as owner for Query, DataSource etc.
3. do NOT assign a Name }
FQuery := TdaChildUniDACQuery.Create(Self);
FDataSource := TppChildDataSource.Create(Self);
FDataSource.DataSet := FQuery;
end; {constructor, Create}
{------------------------------------------------------------------------------}
{ TdaUniDACQueryDataView.Destroy }
destructor TdaUniDACQueryDataView.Destroy;
begin
FDataSource.Free;
FQuery.Free;
inherited Destroy;
end; {destructor, Destroy}
{------------------------------------------------------------------------------}
{ TdaUniDACQueryDataView.SessionClass }
class function TdaUniDACQueryDataView.SessionClass: TClass;
begin
Result := TdaUniDACSession;
end; {class function, SessionClass}
{------------------------------------------------------------------------------}
{ TdaUniDACQueryDataView.ConnectPipelinesToData }
procedure TdaUniDACQueryDataView.ConnectPipelinesToData;
begin
if DataPipelineCount = 0 then Exit;
{need to reconnect here}
TppDBPipeline(DataPipelines[0]).DataSource := FDataSource;
end; {procedure, ConnectPipelinesToData}
{------------------------------------------------------------------------------}
{ TdaUniDACQueryDataView.Init }
procedure TdaUniDACQueryDataView.Init;
var
lDataPipeline: TppChildDBPipeline;
begin
inherited Init;
if DataPipelineCount > 0 then Exit;
{note: DataView's owner must own the DataPipeline }
lDataPipeline := TppChildDBPipeline(ppComponentCreate(Self, TppChildDBPipeline));
lDataPipeline.DataSource := FDataSource;
lDataPipeline.AutoCreateFields := False;
{add DataPipeline to the dataview }
lDataPipeline.DataView := Self;
end; {procedure, Init}
{------------------------------------------------------------------------------}
{ TdaUniDACQueryDataView.SQLChanged }
procedure TdaUniDACQueryDataView.SQLChanged;
var
lDatabase: TComponent;
begin
if FQuery.Active then
FQuery.Close;
lDatabase := Session.GetDatabaseForName(SQL.DatabaseName);
if (lDatabase = nil) then
raise EDataError.Create('TdaUniDACQueryDataView.SQLChanged: No MSConnection object found, ' + SQL.DatabaseName);
FQuery.Connection := TUniConnection(lDatabase);
FQuery.SQL := SQL.MagicSQLText;
end; {procedure, SQLChanged}
initialization
{register the UniDAC descendant classes}
RegisterClasses([TdaChildUniDACQuery, TdaChildUniDACTable, TdaChildUniDACStoredProc]);
{register DADE descendant session, dataset, dataview}
daRegisterSession(TdaUniDACSession);
daRegisterDataSet(TdaUniDACDataSet);
daRegisterDataView(TdaUniDACQueryDataView);
{initialize internal reference variables}
uUniDACConnection := nil;
finalization
{free the default connection object}
uUniDACConnection.Free;
{unregister the UniDAC descendant classes}
UnRegisterClasses([TdaChildUniDACQuery, TdaChildUniDACTable, TdaChildUniDACStoredProc]);
{unregister DADE descendant the session, dataset, dataview}
daUnRegisterSession(TdaUniDACSession);
daUnRegisterDataSet(TdaUniDACDataSet);
daUnRegisterDataView(TdaUniDACQueryDataView);
end.
|
// Mini Sistema para calculr la Transformada de Fourier de una Imagen
// mediante el método de la FFT-2D
//
// Autor. Manuel Martin Ortiz
// FCC - BUAP
//
// Curso de "Procesamiento Digital de Imágenes"
//
// Ultima Revisión : 6 noviembre 2007
// Versión : 0.0.3
unit UFourier;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, Menus, ExtDlgs, ToolWin, ComCtrls, StdCtrls, Math, UFTipos, JPEG,
ImgList, Buttons, UBase;
type
TFFourier = class(TForm)
MainMenu1: TMainMenu;
OpenPD: TOpenPictureDialog;
Archivo1: TMenuItem;
Transformada1: TMenuItem;
Filtros1: TMenuItem;
Abrir1: TMenuItem;
Salvar1: TMenuItem;
Directa1: TMenuItem;
Inversa1: TMenuItem;
PasaBaja1: TMenuItem;
PasaAlta1: TMenuItem;
PasaBanda1: TMenuItem;
N1: TMenuItem;
Salida1: TMenuItem;
Panel1: TPanel;
ScrollBox1: TScrollBox;
ScrollBox2: TScrollBox;
ScrollBox3: TScrollBox;
Image1: TImage;
Image2: TImage;
Image3: TImage;
SB1: TStatusBar;
SavePictureDialog1: TSavePictureDialog;
DF1: TMenuItem;
Salvar2: TMenuItem;
Abrir2: TMenuItem;
SalvarImTF1: TMenuItem;
OpenD_TDF: TOpenDialog;
SaveD_TDF: TSaveDialog;
Panel2: TPanel;
Label5: TLabel;
TrackBar2: TTrackBar;
Label7: TLabel;
CoolBar1: TCoolBar;
ToolBar1: TToolBar;
ToolBar2: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
ToolButton7: TToolButton;
ToolButton8: TToolButton;
ToolButton9: TToolButton;
ToolButton10: TToolButton;
ToolButton11: TToolButton;
ToolButton12: TToolButton;
ToolButton13: TToolButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label6: TLabel;
TrackBar1: TTrackBar;
Label4: TLabel;
Bevel1: TBevel;
ImageList1: TImageList;
ToolButton14: TToolButton;
ToolButton6: TToolButton;
ToolButton15: TToolButton;
ToolButton16: TToolButton;
ToolButton17: TToolButton;
h1Butterworth1: TMenuItem;
Panel3: TPanel;
ToolButton18: TToolButton;
ComboBox1: TComboBox;
SpeedButton1: TSpeedButton;
Label8: TLabel;
Panel4: TPanel;
Button1: TButton;
Button2: TButton;
TrackBar3: TTrackBar;
Label9: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Panel5: TPanel;
Panel6: TPanel;
Panel7: TPanel;
Panel8: TPanel;
Label10: TLabel;
RadioButton1: TRadioButton;
RadioButton2: TRadioButton;
Button3: TButton;
Button4: TButton;
Button5: TButton;
Button6: TButton;
TrackBar4: TTrackBar;
Label15: TLabel;
Patrones1: TMenuItem;
CheckBox1: TCheckBox;
RuidoPeriodico1: TMenuItem;
BitBtn1: TBitBtn;
procedure Image2MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure RuidoPeriodico1Click(Sender: TObject);
procedure Patrones1Click(Sender: TObject);
procedure Propiedades1Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure TrackBar4Change(Sender: TObject);
procedure Image3MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Image2MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Abrir1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Salida1Click(Sender: TObject);
procedure Directa1Click(Sender: TObject);
procedure Inversa1Click(Sender: TObject);
procedure PasaBaja1Click(Sender: TObject);
procedure Salvar2Click(Sender: TObject);
procedure Abrir2Click(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure SalvarImTF1Click(Sender: TObject);
procedure Salvar1Click(Sender: TObject);
procedure TrackBar1Change(Sender: TObject);
procedure TrackBar2Change(Sender: TObject);
procedure PasaAlta1Click(Sender: TObject);
procedure PasaBanda1Click(Sender: TObject);
procedure ToolButton6Click(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure TrackBar3Change(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
BM : TBitMap;
jBM : TJPegImage;
nom,ext : string;
ta : char;
Nx,Ny : integer;
Mx,My : integer;
pf : TPixelFormat;
mat0,
mat1 : Bmatrix2D;
matcd,
matci : TComplexmatrix;
Bimag,
Btdf,
Btdfi : boolean;
gamma : real;
xc,yc : integer;
procedure Conv (B : TBitMap ;
var mat : Bmatrix2D ;
Nx,Ny : integer ); overload;
procedure Conv (mat : Bmatrix2D ;
var B : TBitMap ;
Nx,Ny : integer ); overload;
// procedure ConvGris (var B :TBitMap);
procedure TDFInversa(filtro : TFil);
procedure MuestraTDF( v : Tvista; p : integer = 1);
procedure AjustaLimites;
procedure FButterworth(Sender : TObject; k : byte);
public
{ Public declarations }
p_ruido : byte;
MT : MatImg;
procedure Elimina_ruido();
end;
var
FFourier: TFFourier;
implementation
uses UFourierBase, UFPatron, UFCapZonas;
{$R *.DFM}
// Usar imagen en el main
procedure TFFourier.BitBtn1Click(Sender: TObject);
begin
BMP2Mat(Image3.Picture.Bitmap, MT);
end;
// Evento Onshow, agregamos la imagen de trabajo
procedure TFFourier.FormShow(Sender: TObject);
var
j : integer;
bim : boolean;
begin
// Tenemos la matriz de trabajo copiada, la asignamos al Bitmap
Mat2BMP(MT, BM);
BM.PixelFormat := pf24bit;
// Realizamos el proceso de apertura
bim := true;
ta := 'b';
Nx := BM.Width;
Ny := BM.Height;
SB1.Panels[1].text := IntToStr(Nx)+'x'+IntToStr(Ny);
pf := BM.PixelFormat;
if pf = pf24bit then begin
// completa columnas y renglones a múltiplos de 2^n
j := 2;
while ((Nx div j) > 0 ) do j := 2*j;
if (Nx = (j div 2)) then j := j div 2;
Mx := j;
j := 2;
while ((Ny div j) > 0 ) do j := 2*j;
if (Ny = (j div 2)) then j := j div 2;
My := j;
// centro de las imágenes ajustadas
xc := Mx div 2;
yc := My div 2;
// reporta nuevas dimensiones
SB1.Panels[3].text := IntToStr(Mx)+'x'+IntToStr(My);
// Convierte y muestra Imagen en tonos de gris
//ConvGris(BM);
// pasa el BitMap a su forma matricial
SetLength(Mat0,Mx,My);
Conv(BM,Mat0,Mx,My);
// Muestra imagen con bordes negros en caso que haya crecido
Conv(Mat0,BM,Mx,My);
// Muestra Imagen de entrada
Image1.Picture.Assign(BM);
// Oculta opciones
Salvar1.Visible := false;
Filtros1.Visible := false;
Inversa1.Visible := false;
ToolBar2.Visible := false;
// Muestra opciones
Transformada1.Visible := true;
Directa1.Visible := true;
ToolButton7.visible := true;
Panel2.Visible := false;
Patrones1.Visible := true;
RuidoPeriodico1.Visible := false;
// Imagen cargada
Bimag := true;
end
else ShowMessage('Profundidad en bits no soportada para el Proceso...SIC');
end;
// Asumimos que la imagen esta en tonos de gris,
// se toma el canal rojo como base
// Convierte Bitmap en Matriz
procedure TFFourier.Conv(B :TBitMap; var mat : Bmatrix2D; Nx,Ny : integer);
var
i,j,k : integer;
p : PByteArray;
kx,ky,
sx,sy : integer;
begin
kx := MIN(Nx, B.Width);
ky := MIN(Ny, B.Height);
sx := (Nx-kx) shr 1;
sy := (Ny-ky) shr 1;
// limpia la matriz
for j := 0 to Ny-1 do
for i := 0 to Nx-1 do
mat[i,j] := 0;
// Llena la matriz con los datos de la imagen
for j := 0 to ky-1 do begin
p := B.ScanLine[j];
for i := 0 to kx-1 do begin
k := 3*i;
mat[i+sx,j+sy] := p[k];
end;
end;
end;
// Convierte matriz en Bitmap
procedure TFFourier.Conv (mat : Bmatrix2D ; var B :TBitMap; Nx,Ny : integer);
var
i,j,k,q,c : integer;
// p : PByteArray;
pix : byte;
ton : integer;
begin
Nx := MAX(Nx,B.Width);
Ny := MAX(Ny,B.Height);
B.Width := Nx;
B.Height := Ny;
// SetLength(mat,Nx,Ny); // aguas
for j := 0 to Ny-1 do begin
// p := B.ScanLine[j];
for i := 0 to Nx-1 do begin
// k := 3*i;
pix := ajusta255(mat[i,j]);
B.Canvas.Pixels[i,j] := RGB(pix,pix,pix);
// for q := 0 to 2 do p[k+q] := pix;
end;
end;
end;
// Convierte a Grises
{procedure TFFourier.ConvGris(var B :TBitMap);
var
i,j,k,s : integer;
p : PByteArray;
kx,ky : integer;
begin
kx := B.Width;
ky := B.Height;
for j := 0 to ky-1 do begin
p := B.ScanLine[j];
for i := 0 to kx-1 do begin
k := 3*i;
s := (p[k]+p[k+1]+p[k+2]) div 3;
p[k] := s;
p[k+1] := s;
p[k+2] := s;
end;
end;
end;
{ ------------------------- Vistas de la TDF ------------------------------- }
// Reflejo de la selección del parámetro k para Ln(k*z+1)
procedure TFFourier.TrackBar3Change(Sender: TObject);
begin
label9.Caption := 'k = '+IntToSTr(TrackBar3.Position);
end;
procedure TFFourier.TrackBar4Change(Sender: TObject);
var
p,q : integer;
begin
p := TrackBar4.Position;
q := p+1;
Label15.caption := '1/'+ IntToStr(q);
gamma := 1/q;
end;
// Muestra la TDF
procedure TFFourier.MuestraTDF( v : Tvista; p : integer);
var
Bx,Rx,By,Ry: integer;
begin
// Convierte Matcd a su forma escalar real
MatrizEsc(Matcd,mat1,Mx,My,v,p);
// Dimensionamos el BitMap de Salida / panel 2
BM.Width := Mx;
BM.Height := My;
BM.PixelFormat := pf24bit;
// Limpiamos la zona
BM.canvas.brush.Color:= clwhite;
BM.canvas.pen.Color:= clwhite;
BM.Canvas.Rectangle(0,0,Mx-1,My-1);
// Convertimos la matriz a un BitMap
Conv (mat1,BM,Mx,My);
// Mostramos en el Image2
Image2.Picture.Assign(BM);
// centra el espectro en el scrollBox
Bx := ScrollBox2.Width - ScrollBox2.HorzScrollBar.ButtonSize div 2;
Rx := ScrollBox2.HorzScrollBar.Range;
if Rx > Bx then ScrollBox2.HorzScrollBar.Position := (Rx-Bx) div 2;
By := ScrollBox2.Width - ScrollBox2.VertScrollBar.ButtonSize div 2;
Ry := ScrollBox2.VertScrollBar.Range;
if Ry > By then ScrollBox2.VertScrollBar.Position := (Ry-By) div 2;
end;
// Ln(z+1)
procedure TFFourier.Button1Click(Sender: TObject);
begin
MuestraTDF(VLn);
end;
// Ln(k*z+1)
procedure TFFourier.Button2Click(Sender: TObject);
var
k : integer;
begin
// Lee el parámetro k
k := TrackBar3.Position;
MuestraTDF(VLnk,k);
end;
// Negativo de la Imagen Reconstruida
procedure TFFourier.Button3Click(Sender: TObject);
var
x,y : integer;
begin
if btdfi then begin
for y := 0 to My-1 do
for x := 0 to Mx - 1 do
mat1[x][y] := 255 - mat1[x][y];
Conv (mat1,BM,Mx,My);
Image3.Picture.Assign(BM);
end;
end;
// Aclarado SIN la Imagen Reconstruida
procedure TFFourier.Button4Click(Sender: TObject);
var
x,y,p : integer;
C1,t : Real;
TD : array[0..255] of byte;
begin
if btdfi then begin
// Llenamos LUT
C1 := PI/(2*255);
for x := 0 to 255 do begin
t := 255*sin(C1*x);
TD[x] := round(t) and $FF;
end;
// Aplicamos LUT
for y := 0 to My-1 do
for x := 0 to Mx - 1 do begin
p := mat1[x][y];
mat1[x][y] := TD[p];
end;
Conv (mat1,BM,Mx,My);
Image3.Picture.Assign(BM);
end;
end;
// Aclarado Log(Z+1) -- Rango Dinámico Simple
procedure TFFourier.Button5Click(Sender: TObject);
var
x,y,p : integer;
C1,t : real;
TD : array[0..255] of byte;
begin
if Btdfi then begin
C1 := 255/LnXP1(255);
// Llenamos LUT
for x := 0 to 255 do begin
t := C1*LnXP1(x);
TD[x] := round(t) and $FF;
end;
// Aplicamos LUT
for y := 0 to My-1 do
for x := 0 to Mx - 1 do begin
p := mat1[x][y];
mat1[x][y] := TD[p];
end;
Conv (mat1,BM,Mx,My);
Image3.Picture.Assign(BM);
end;
end;
// Corrección Gamma de aclarado 1/2 - 1/8
procedure TFFourier.Button6Click(Sender: TObject);
var
x,y,p : integer;
t : real;
TD : array[0..255] of byte;
begin
if Btdfi then begin
// Llenamos LUT
for x := 0 to 255 do begin
t := 255*power(x/255,gamma);
TD[x] := round(t) and $FF;
end;
// Aplicamos LUT
for y := 0 to My-1 do
for x := 0 to Mx - 1 do begin
p := mat1[x][y];
mat1[x][y] := TD[p];
end;
Conv (mat1,BM,Mx,My);
Image3.Picture.Assign(BM);
end;
end;
// -----------------------------------------------------------------
// Procedimientos de la interfase
// -----------------------------------------------------------------
procedure TFFourier.FormCreate(Sender: TObject);
begin
BM := TBitMap.Create;
jBM := TjpegImage.Create;
Salvar1.Visible := false;
Transformada1.Visible := false;
Filtros1.Visible := false;
Salvar2.Visible := false;
SalvarImTF1.Visible := false;
Patrones1.Visible := false;
RuidoPeriodico1.Visible := false;
Panel2.Hide;
Panel3.Hide;
Panel4.Hide;
CoolBar1.Bands[1].Visible := false;
ToolButton7.visible := false;
Bimag := false;
Btdf := false;
Btdfi := false;
gamma := 1/2;
p_ruido := 1;
end;
// Salida del programa
procedure TFFourier.Salida1Click(Sender: TObject);
begin
Close;
end;
// Abre imagen para su procesamiento
procedure TFFourier.Abrir1Click(Sender: TObject);
var
j : integer;
bim : boolean;
begin
if OpenPD.Execute then begin
nom := OpenPD.FileName;
ext := ExtractFileExt(nom);
bim := false;
if CompareStr(LowerCase(ext),'.jpg') = 0 then begin
jBM.LoadFromFile(nom);
BM.Assign(jBM);
bim := true;
ta := 'j';
end;
if (CompareStr(LowerCase(ext),'.bmp') = 0) then begin
BM.LoadFromFile(nom);
bim := true;
ta := 'b';
end;
if bim then begin
Nx := BM.Width;
Ny := BM.Height;
SB1.Panels[1].text := IntToStr(Nx)+'x'+IntToStr(Ny);
pf := BM.PixelFormat;
if pf = pf24bit then begin
// completa columnas y renglones a múltiplos de 2^n
j := 2;
while ((Nx div j) > 0 ) do j := 2*j;
if (Nx = (j div 2)) then j := j div 2;
Mx := j;
j := 2;
while ((Ny div j) > 0 ) do j := 2*j;
if (Ny = (j div 2)) then j := j div 2;
My := j;
// centro de las imágenes ajustadas
xc := Mx div 2;
yc := My div 2;
// reporta nuevas dimensiones
SB1.Panels[3].text := IntToStr(Mx)+'x'+IntToStr(My);
// Convierte y muestra Imagen en tonos de gris
//ConvGris(BM);
// pasa el BitMap a su forma matricial
SetLength(Mat0,Mx,My);
Conv(BM,Mat0,Mx,My);
// Muestra imagen con bordes negros en caso que haya crecido
Conv(Mat0,BM,Mx,My);
// Muestra Imagen de entrada
Image1.Picture.Assign(BM);
// Oculta opciones
Salvar1.Visible := false;
Filtros1.Visible := false;
Inversa1.Visible := false;
ToolBar2.Visible := false;
// Muestra opciones
Transformada1.Visible := true;
Directa1.Visible := true;
ToolButton7.visible := true;
Panel2.Visible := false;
Patrones1.Visible := true;
RuidoPeriodico1.Visible := false;
// Imagen cargada
Bimag := true;
end
else ShowMessage('Profundidad en bits no soportada para el Proceso...SIC');
end
else ShowMessage('Formato no soportado...SIC');
end;
end;
// Salva Matriz con la TDF de la imagen procesada
procedure TFFourier.Salvar2Click(Sender: TObject);
var
id : file of real;
Ny : integer;
rr,rMx,rMy : real;
nomt : String;
i,j : integer;
begin
if SaveD_TDF.Execute then begin
nomt := SaveD_TDF.FileName;
AssignFile(id,nomt);
rewrite(id);
// control del header
rr := 2*PI;
write(id,rr);
rMx := Mx+0.0;
rMy := My+0.0;
write(id,rMx,rMy);
Ny := My div 2 ;
for i := 0 to Mx-1 do
for j := 0 to Ny do
write(id,Matcd[i][j].r, Matcd[i][j].i);
closeFile(id);
end;
end;
// Abre Matriz con la TDF de una imagen
procedure TFFourier.Abrir2Click(Sender: TObject);
var
id : file of real;
rr,rc,rMx,rMy : real;
nomt : String;
i,j,Ny,i1,j1 : integer;
begin
if OpenD_TDF.Execute then begin
nomt := OpenD_TDF.FileName;
AssignFile(id,nomt);
reset(id);
// control del header
rr := 2*PI;
read(id,rc);
if (rc <> rr) then begin
ShowMessage('Archivo con TDF corrupto ... SIC');
closeFile(id);
exit;
end;
// lectura de datos
read(id,rMx,rMy);
Mx := trunc(rMx);
My := trunc(rMy);
// dimensiona matriz Compleja con la TDF
SetLength(Matcd,Mx,My);
Ny := My div 2;
for i := 0 to Mx-1 do
for j := 0 to Ny do
read(id,Matcd[i][j].r,Matcd[i][j].i);
closeFile(id);
// Completa la matriz por las simetrias
// de almacenamiento en cada dirección
// banda izquierda inferior
for j := 1 to Ny-1 do begin
j1 := My - j;
Matcd[0][j1].r := Matcd[0][j].r;
Matcd[0][j1].i := -Matcd[0][j].i; // conjugado
end;
// parte inferior
for j := 1 to Ny-1 do begin
j1 := My - j;
for i := 1 to Mx-1 do begin
i1 := Mx - i;
Matcd[i1][j1].r := Matcd[i][j].r;
Matcd[i1][j1].i := -Matcd[i][j].i; // conjugado
end;
end;
// dimensiona el resto de matrices de trabajo
SetLength(Mat1 ,Mx,My);
SetLength(Matci,Mx,My);
// Reporta resultados en la interfase
SB1.Panels[1].text := IntToStr(Mx)+'x'+IntToStr(My);
SB1.Panels[3].text := IntToStr(Mx)+'x'+IntToStr(My);
// Muestra la imagen de la TDF
MuestraTDF(VLn);
// Ajusta barras para el filtrado
AjustaLimites;
// Muestra opciones
Transformada1.Visible := true;
Inversa1.Visible := true;
Filtros1.Visible := true;
Salvar2.Visible := true;
SalvarImTF1.Visible := true;
AjustaLimites;
Panel2.Show;
Panel4.Show;
CoolBar1.Bands[1].Visible := true;
// oculta opciones
Directa1.Visible := false;
end;
end;
// Salva Imagen de la TDF
procedure TFFourier.SalvarImTF1Click(Sender: TObject);
var
nom : String;
bb : boolean;
begin
SavePictureDialog1.Title := 'Salvar Imagen de la TDF';
if SavePictureDialog1.Execute then begin
nom := SavePictureDialog1.FileName;
bb := true;
if FileExists(nom) then
if MessageDlg('Desea Reescribir el Archivo ' + nom +' ?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes
then bb := true
else bb := false;
if bb then Image2.Picture.SaveToFile(nom);
end;
end;
// Salva Imagen Filtrada
procedure TFFourier.Salvar1Click(Sender: TObject);
var
nom : String;
bb : boolean;
begin
SavePictureDialog1.Title := 'Salvar Imagen Filtrada';
if SavePictureDialog1.Execute then begin
nom := SavePictureDialog1.FileName;
bb := true;
if FileExists(nom) then
if MessageDlg('Desea Reescribir el Archivo ' + nom +' ?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes
then bb := true
else bb := false;
if bb then Image3.Picture.SaveToFile(nom);
end;
end;
{ ---------------------------- |.......................| -------------------- }
{ ---------------------------- | FFT Directa e Inversa | -------------------- }
{ ---------------------------- |.......................| -------------------- }
// ---------------------------- FFT Directa ---------------------------------
procedure TFFourier.Directa1Click(Sender: TObject);
var
t1,t2 : TDateTime;
tt1,tt2 : TTimeStamp;
h1,h2,hh : real;
begin
// TDF Evaluada
Btdf := true;
// Recalcula tamaño de la imagen cargada por si se abrió una TDF
// En el Image1 está la imagen a procesar
Mx := Image1.Width;
My := Image1.Height;
// dimensionamiento de matrices de salida para visualización y procesamiento
setLength(Mat1 ,Mx,My);
setLength(Matcd,Mx,My);
setLength(Matci,Mx,My);
CopyMat(Mat0,Mat1,Mx,My);
// Construye matriz compleja
MatrizCompleja(Mat1,Matcd,Mx,My);
// Reorganiza la matriz de datos para centrar la TDF
ReOrdena(Matcd,Mx,My);
// Toma la hora actual
t1 := Now;
// Evalua la transformada directa de Fourier de la imagen
FFT2D(Matcd,Mx,My,1);
t2 := Now;
tt1 := DateTimeToTimeStamp(t1);
tt2 := DateTimeToTimeStamp(t2);
h1 := tt1.Time;
h2 := tt2.Time;
hh := (h2 - h1)/1000.0;
SB1.Panels[5].text := FloatToStr(hh)+' seg' ;
// Muestra la imagen de la TDF
MuestraTDF(VLn);
// muestra opciones
Inversa1.Visible := true;
Filtros1.Visible := true;
Salvar2.Visible := true;
SalvarImTF1.Visible := true;
AjustaLimites;
Panel2.Show;
Panel4.Show;
CoolBar1.Bands[1].Visible := true;
end;
// --------------------------- FFT Inversa ---------------------------------
procedure TFFourier.TDFInversa(Filtro : TFil);
var
t1,t2 : TDateTime;
tt1,tt2 : TTimeStamp;
h1,h2,hh : real;
potencia : Tpot;
begin
t1 := Now;
// Evalua la transformada inversa de Fourier de la imagen
// Copia Matriz con la TDF de Matcd a Matci
setLength(Matci,Mx,My);
if Filtro = FNull then CopyMat(Matcd,Matci,Mx,My);
FFT2D(Matci,Mx,My,-1);
t2 := Now;
tt1 := DateTimeToTimeStamp(t1);
tt2 := DateTimeToTimeStamp(t2);
h1 := tt1.Time;
h2 := tt2.Time;
hh := (h2 - h1)/1000.0;
SB1.Panels[7].text := FloatToStr(hh)+' seg';
// Grafica la image resultante en el tercer panel
// elige forma de calcular la Mat. real
potencia := PCompleja;
if RadioButton2.Checked then potencia := PReal;
MatrizNor(Matci, mat1, Mx,My, potencia);
if potencia = Preal then ReOrdena(mat1,Mx,My);
BM.Width := Mx;
BM.Height := My;
BM.PixelFormat := pf24bit;
BM.canvas.brush.Color:= clwhite;
BM.canvas.pen.Color:= clwhite;
BM.Canvas.Rectangle(0,0,Mx-1,My-1);
Conv (mat1,BM,Mx,My);
Image3.Picture.Assign(BM);
Salvar1.Visible := true;
Btdfi := true;
end;
// inversa simple
procedure TFFourier.Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
dentro : boolean;
begin
if Bimag then begin
dentro := (X>=0) and (X<=Mx) and (Y>=0) and (Y<=My);
if dentro
then Panel5.Caption := Format('( %d , %d )',[X,Y])
else Panel5.Caption := '(X,Y)';
end;
end;
procedure TFFourier.Image2MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
PP : real;
dentro : boolean;
begin
if Btdf then begin
dentro := (X>=0) and (X<=Mx) and (Y>=0) and (Y<=My);
if dentro then begin
PP := sqr(matcd[X][Y].r) + sqr(matcd[X][Y].i);
if CheckBox1.Checked then begin
X := X-xc;
Y := yc-Y;
end;
Panel6.Caption := Format('(%d , %d) : %10.6f',[X,Y,PP]);
end
else Panel6.Caption := '(X,Y) : P';
end;
end;
procedure TFFourier.Image2MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbright then begin
FFCapZonas.StringGrid1.Cells[1,p_ruido] := IntToStr(X);
FFCapZonas.StringGrid1.Cells[2,p_ruido] := IntToStr(Y);
FFCapZonas.StringGrid1.Cells[3,p_ruido] := '1';
FFCapZonas.StringGrid1.Cells[4,p_ruido] := 'S';
inc(p_ruido);
if (p_ruido>FFCapZonas.StringGrid1.RowCount)
then p_ruido:=FFCapZonas.StringGrid1.RowCount;
end;
end;
procedure TFFourier.Image3MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
dentro : boolean;
TT : byte;
begin
if Btdfi then begin
dentro := (X>=0) and (X<=Mx) and (Y>=0) and (Y<=My);
if dentro then begin
TT := mat1[X][Y];
Panel7.Caption := Format('(%d , %d) : %d',[X,Y,TT]);
end
else Panel6.Caption := '(X,Y) : P';
end;
end;
procedure TFFourier.Inversa1Click(Sender: TObject);
begin
TDFInversa(FNull);
end;
{ --------------------------- FILTROS --------------------------------------- }
// Ajusta Limites de los TrackBar
procedure TFFourier.AjustaLimites;
var
hip : integer;
begin
hip := trunc (sqrt(sqr(Mx/2)+sqr(My/2)));
TrackBar1.Max := hip;
TrackBar2.Max := hip;
TrackBar1.Position := 2;
TrackBar2.Position := hip;
Label6.Caption := '2:'+IntTostr(hip);
Label7.Caption := IntToStr(hip)+':'+IntTostr(hip);
end;
// Cambio en TrackBar1
procedure TFFourier.TrackBar1Change(Sender: TObject);
var
li,ls : integer;
begin
li := TrackBar1.position;
ls := TrackBar2.position;
if li >= ls then begin
li := ls-1;
TrackBar1.position := li;
end;
Label6.Caption := IntToStr(li)+':'+IntToStr(TrackBar1.max);
end;
// Cambio en TrackBar2
procedure TFFourier.TrackBar2Change(Sender: TObject);
var
li,ls : integer;
begin
li := TrackBar1.position;
ls := TrackBar2.position;
if ls <= li then begin
ls := li+1;
TrackBar2.position := ls;
end;
Label7.Caption := IntToStr(ls)+':'+IntToStr(TrackBar2.max);
end;
{ ------------------------- FILTROS --------------------------- }
// Filtro Pasa Baja
procedure TFFourier.PasaBaja1Click(Sender: TObject);
var
i,j,cx,cy,tt : integer;
R2 : real;
H : RMatrix2D;
begin
SetLength(H,Mx,My);
R2 := sqr(TrackBar1.Position);
cx := Mx shr 1;
cy := My shr 1;
for j := 0 to pred(My) do begin
tt := sqr(j-cy);
for i := 0 to pred(Mx) do
if (sqr(i-cx) + tt) <= R2
then H[i][j] := 1.0
else H[i][j] := 0.0;
end;
for j := 0 to pred(My) do
for i := 0 to pred(Mx) do
Matci[i][j] := ComplexProd(Matcd[i][j],H[i][j]);
Salvar1.Visible := true;
TDFInversa(FPBaja);
end;
// Filtro Pasa Alta
procedure TFFourier.PasaAlta1Click(Sender: TObject);
var
i,j,cx,cy,tt : integer;
R2 : real;
H : RMatrix2D;
begin
SetLength(H,Mx,My);
R2 := sqr(TrackBar2.Position);
cx := Mx shr 1;
cy := My shr 1;
for j := 0 to pred(My) do begin
tt := sqr(j-cy);
for i := 0 to pred(Mx) do
if (sqr(i-cx) + tt) < R2
then H[i][j] := 0.0
else H[i][j] := 1.0;
end;
for j := 0 to pred(My) do
for i := 0 to pred(Mx) do
Matci[i][j] := ComplexProd(Matcd[i][j],H[i][j]);
Salvar1.Visible := true;
TDFInversa(FPAlta);
end;
// Filtro Pasa Banda
procedure TFFourier.PasaBanda1Click(Sender: TObject);
var
i,j,cx,cy,tt : integer;
R12,R22,R : real;
H : RMatrix2D;
begin
SetLength(H,Mx,My);
R12 := sqr(TrackBar1.Position);
R22 := sqr(TrackBar2.Position);
cx := Mx shr 1;
cy := My shr 1;
for j := 0 to pred(My) do begin
tt := sqr(j-cy);
for i := 0 to pred(Mx) do begin
R := sqr(i-cx) + tt;
if ( R >= R12 ) and (R <= R22)
then H[i][j] := 1.0
else H[i][j] := 0.0;
end;
end;
for j := 0 to pred(My) do
for i := 0 to pred(Mx) do
Matci[i][j] := ComplexProd(Matcd[i][j],H[i][j]);
Salvar1.Visible := true;
TDFInversa(FPBanda);
end;
// Elimina Ruido en base a una serie de puntos
procedure TFFourier.Elimina_ruido();
var
i,j : integer;
H : RMatrix2D;
k : byte;
ss : string;
lonss,err : integer;
op : char;
xk,yk,Lk : integer;
ii,jj : integer;
begin
// Dimensionamos Máscara
SetLength(H,Mx,My);
// Llenamos la máscara con 1's
for j := 0 to pred(My) do
for i := 0 to pred(Mx) do
H[i][j] := 1.0;
// Recogemos puntos a eliminar
for k := 1 to FFCapZonas.StringGrid1.RowCount - 1 do begin
ss := LowerCase(FFCapZonas.StringGrid1.Cells[4,k]);
lonss := length(ss);
if (lonss <> 0) then begin
op:= ss[1];
if (op='s') then begin
val(FFCapZonas.StringGrid1.Cells[1,k],xk,err);
if (err<>0) then continue;
val(FFCapZonas.StringGrid1.Cells[2,k],yk,err);
if (err<>0) then continue;
val(FFCapZonas.StringGrid1.Cells[3,k],Lk,err);
if (err<>0) then continue;
for j := -Lk to Lk do begin
jj := yk + j;
for i := -Lk to Lk do begin
ii := xk+i;
H[ii][jj] := 0;
end;
end;
end;
end;
end;
for j := 0 to pred(My) do
for i := 0 to pred(Mx) do
Matci[i][j] := ComplexProd(Matcd[i][j],H[i][j]);
Salvar1.Visible := true;
TDFInversa(FRuiPe);
end;
procedure TFFourier.Patrones1Click(Sender: TObject);
begin
end;
// Define propiedades del patrón
procedure TFFourier.Propiedades1Click(Sender: TObject);
begin
FFPatron.ShowModal;
if FFPatron.ModalResult=mrOK then begin
BM.Assign(FFPatron.Image2.Picture.Bitmap);
Image1.Picture.Assign(BM);
Conv(BM,Mat0,Mx,My);
RuidoPeriodico1.Visible := true;
end;
end;
procedure TFFourier.RuidoPeriodico1Click(Sender: TObject);
begin
FFCapZonas.Show;
end;
// Filtro Pasa Baja de Butterworth
procedure TFFourier.ToolButton6Click(Sender: TObject);
begin
Panel3.Show;
Label8.Caption := 'Butterworth LP';
with ComboBox1 do begin
Items.Clear;
Style := csOwnerDrawFixed;
Items.Add('n = 1');
Items.Add('n = 2');
Items.Add('n = 3');
Items.Add('n = 4');
ItemIndex := 1;
end;
end;
procedure TFFourier.SpeedButton1Click(Sender: TObject);
var
n : byte;
begin
n := ComboBox1.ItemIndex;
FButterworth(sender, n);
end;
// Filtro de Butterworth
procedure TFFourier.FButterworth(Sender : TObject; k : byte);
var
i,j,cx,cy,
R0,p : integer;
x2,y2,z,t : real;
H : RMatrix2D;
begin
SetLength(H,Mx,My);
R0 := TrackBar1.Position;
cx := Mx shr 1;
cy := My shr 1;
p := 2*k;
for j := 0 to pred(My) do begin
y2 := sqr(j - cy + 0.5);
for i := 0 to pred(Mx) do begin
x2 := sqr(i - cx + 0.5);
z := sqrt(x2+y2)/R0;
t := power(z,p);
H[i][j] := 1.0/(1+t);
end;
end;
for j := 0 to pred(My) do
for i := 0 to pred(Mx) do
Matci[i][j] := ComplexProd(Matcd[i][j],H[i][j]);
TDFInversa(FButter);
Salvar1.Visible := true;
end;
{ ------------------------------------------------------------------------- }
{ ------------------------------ FIN -------------------------------------- }
{ ------------------------------------------------------------------------- }
end.
|
{===================================================================
NPC Schematics 2016
Warming Up: Wembo dan Hobi Berdendang
by Baharuddin Aziz
September 25, 2016
===================================================================}
program wembo_dan_hobi_berdendang;
var
// input
n : integer; // jumlah lagu yg dimiliki
q : integer; // jumlah pencarian lagu pd daftar putar
i : integer; // variabel utk loop
j : integer; // variabel utk loop
S : string; // string sebelum dimasukkan ke tabel
// process
lagu_dicari : string; // nama lagu yg dicari
tabel_lagu : array[1..1000] of string; // lagu-lagu yg dimiliki
tabel_pencarian : array[1..1000] of string; // lagu-lagu yg dicari
pencarian_ketemu : array[1..1000] of boolean; // utk proses pencarian lagu
hasil_pencarian : integer; // utk proses pencarian lagu
// output
tabel_hasil_pencarian : array[1..1000] of string; // hasil pencarian lagu-lagu
begin
{ INISIALISASI VARIABEL }
// inisialisasi tabel
for i := 1 to 1000 do tabel_lagu[i] := 'xx';
for i := 1 to 1000 do tabel_pencarian[i] := 'xx';
for i := 1 to 1000 do tabel_hasil_pencarian[i] := 'xx';
for i := 1 to 1000 do pencarian_ketemu[i] := false;
// membaca masukan user, value n dan q
readln(n,q); // HARUS readln(), cek KETERANGAN
// membaca masukan user, lagu-lagu yg dimiliki
for i := 1 to n do
begin
readln(S);
tabel_lagu[i] := S;
end;
// membaca masukan user, lagu-lagu yg dicari
for i := 1 to q do
begin
readln(S);
tabel_pencarian[i] := S;
end;
{ ALGORITMA }
// pencarian lagu
for i := 1 to q do
begin
// memeriksa satu-persatu lagu terhadap daftar putar
for j := 1 to n do
begin
if tabel_pencarian[i] = tabel_lagu[j] then
begin
pencarian_ketemu[i] := true;
hasil_pencarian := i;
end;
end;
// menuliskan hasil pencarian setiap lagu yg dicari
if pencarian_ketemu[i] then
tabel_hasil_pencarian[hasil_pencarian] := 'duk tek duk duk tek'
else if not pencarian_ketemu [i] then
tabel_hasil_pencarian[i] := 'tek tek duk tek dus';
end;
// menuliskan seluruh hasil pencarian
for i := 1 to q do
begin
writeln(tabel_hasil_pencarian[i]);
end;
end.
{===================================================================
KETERANGAN:
- readln(n,q);
HARUS readln() krn read() akan mengganggu proses pembacaan pada
readln(S). Setelah read() selesai membaca masukan user, ia akan
membuat BARIS BARU (NEW LINE) yg kemudian MENJADI INPUT pada
readln(S).
===================================================================
KODE DI BAWAH UNTUK DEBUGGING:
// DEBUGGING: mengecek masukan user
writeln('---');
writeln('daftar lagu:');
for i := 1 to n do
writeln(tabel_lagu[i]);
writeln('---');
writeln('daftar pencarian:');
for i := 1 to q do
writeln(tabel_pencarian[i]);
writeln('---');
===================================================================}
|
unit CardPiles;
{ Author: Kees Hemerik
Version history:
0.4 d.d. 20080318
- Added: invariant for TDeckPile, TDeckPile.Acceptable
0.3 d.d. 20080314
- Added: function IntToSuit
0.2 d.d. 20080310
- Corrected: TTableauPile.Acceptable; old version did not accept facedown
cards.
- Added: type TPileKind, class function PileKind, to be able to distinguish
between different kinds of piles.
0.1 d.d. 20080301
}
interface
type
// card characteristics
TSuit = (suHeart, suClub, suDiamond, suSpade);
TValue = 1..13;
TCardColor = (ccRed, ccBlack);
//----------------------------------------------------------------------------
// TPileKind is used to distinguish between different kinds of card piles.
// Each pile class has a class function PileKind: TPileKind, which returns
// a value which is unique for that class. E.g.
// TDeckPile.PileKind returns pkDeck
//----------------------------------------------------------------------------
TPileKind = (pkBase, pkDeck, pkDiscard, pkSuit, pkTableau);
//----------------------------------------------------------------------------
// TCard is the class for cards in the solitaire game
//----------------------------------------------------------------------------
TCard =
class(TObject)
private
FSuit: TSuit;
FValue: TValue;
FFaceUp: Boolean;
public
// construction/destruction
constructor Create(AValue: TValue; ASuit: TSuit);
// pre: true
// post: Value = AValue, Suit = ASuit, FaceUp = false
// primitive queries
function Suit: TSuit;
function Value: TValue;
function FaceUp: Boolean;
// derived queries
function Color: TCardColor;
// pre: true
// ret: ccRed if Suit in [suHeart, suDiamond],
// ccBlack if Suit in [suClub, suSpade]
//commands
procedure Flip;
// pre: true
// post: FaceUp' = not 'FaceUp
procedure SetFaceUp(AFaceUp: Boolean);
// pre: true
// post: FaceUp' = AFaceUp
end;
//----------------------------------------------------------------------------
// TPile is base class for all card piles in the solitaire game
//----------------------------------------------------------------------------
TPile =
class(TObject)
protected
FList: array of TCard;
FCapacity: Integer;
FCount: Integer;
// private invariants
// Pri0: FCapacity = Length(FList)
// Pri1: 0 <= FCount <= Length(FList)
// abstraction relation
// M = FList[0..FCount-1]
public
// construction/destruction
constructor Create(ACapacity: Integer);
// pre: 0 <= ACapacity
// post: M = [], Cap = ACapacity
destructor Destroy; override;
// queries
function Capacity: Integer;
// pre: true
// ret: Cap
function Count: Integer;
// pre: true
// ret: |M|
function Card(I: Integer): TCard;
// pre: 0 <= I < Count
// ret: M(I)
function IsEmpty: Boolean;
// pre: true
// ret: Count = 0
function Top: TCard;
// pre: Count > 0
// ret: Card(Count - 1)
function Acceptable(ACard: TCard): Boolean; virtual;
// pre: true
// ret: true
// N.B.: will be overridden in descendants
class function PileKind: TPileKind; virtual;
// commands
procedure Put(ACard: TCard); virtual;
// pre: (Count < Capacity) and Acceptable(ACard)
// post: M' = 'M ++ [ACard]
procedure Remove(var ACard: TCard); virtual;
// pre: M = S ++ [C]
// post: (M = S) and (ACard = C)
// model variables
// M: sequence of TCard
// Cap: integer (capacity)
// invariants
// SmallEnough: 0 <= Count <= Capacity
end;
//----------------------------------------------------------------------------
// TSuitPile is a class for a suit pile in the solitaire game.
// it has the following properties:
// - all cards in the pile are of the same suit, which is the suit of the pile
// - all cards in the pile are face-up
// - the cards in the pile have subsequent increasing values, starting with 1
// - the pile is complete when it contains all cards of the suit, i.e. it
// - contains the whole range 1..13 of values
//----------------------------------------------------------------------------
TSuitPile =
class(TPile)
private
FSuit: TSuit;
public
// construction/destruction
constructor Create(ACapacity: Integer; ASuit: TSuit);
// pre: 13 <= ACapacity
// post: (inherited Create).post and (Suit = ASuit)
// queries
function Suit: TSuit;
function Acceptable(ACard: TCard): Boolean; override;
// pre: true
// ret: (ACard.Suit = Suit) and (ACard.FaceUp) and
// ( ( (Count = 0) and ACard.Value = 1))
// or ( (Count > 0)
// and ACard.Value = Top.Value + 1 ) )
class function PileKind: TPileKind; override;
// pre: true
// ret: pkSuitPile
function IsComplete: Boolean;
// pre: true
// ret: Count = 13
// invariants
// AllSuit: (forall I: 0<=I<Count: Card(I).Suit = Suit)
// AllFaceUp: (forall I: 0 <=I<Count: Card(I).FaceUp)
// AllInPlace: (forall I: 0<=I<Count: Card(I).Value = I+1)
end;
TDeckPile =
class(TPile)
public
// construction/destruction
constructor Create;
// pre: true
// post: M contains all 52 cards of a deck of cards in some order
// queries
function Acceptable(ACard: TCard): Boolean; override;
// pre: true
// ret: not ACard.FaceUp
class function PileKind: TPileKind; override;
// pre: true
// ret: pkDeck
// commands
procedure Shuffle;
// pre: true
// post: M' is a (well-shuffled) permutation of 'M
// invariants:
// AllFaceDown: (forall I: 0 <=I<Count: not Card(I).FaceUp)
end;
//----------------------------------------------------------------------------
// TDiscardPile is the class for the discard pile in the solitaire game.
// It has the following properties:
// - all cards in the pile are face-up
//----------------------------------------------------------------------------
TDiscardPile =
class(TPile)
public
// queries
function Acceptable(ACard: TCard): Boolean; override;
// pre: true
// ret: ACard.FaceUp
class function PileKind: TPileKind; override;
// pre: true
// ret: pkDiscard
// invariants
// AllFaceUp: (forall I: 0 <=I<Count: Card(I).FaceUp)
end;
//----------------------------------------------------------------------------
// TTableauPile is the class for the tableau piles in the solitaire game.
// It has the following properties:
// - it has a bottom part (possibly empty) of cards which are all face-down
// - it has a top part (possibly empty) of cards which are all face-up
// - the cards in the top part have subsequent decreasing values
// - the cards in the top part have alternating red and black colors
//----------------------------------------------------------------------------
TTableauPile =
class(TPile)
private
FDownCount: Integer;
public
// queries
function DownCount: Integer; // number of face-down cards in the pile
// pre: true
// ret: (N i: 0 <= i < |M|: not M[i].FaceUp)
function Acceptable(ACard: TCard): Boolean; override;
// pre: true
// ret: ( (DownCount = Count) and ( ACard.FaceUp implies (ACard.Value = 13))
// or
// ( (DownCount < Count)
// and (Top.Value = ACard.Value + 1)
// and (Top.Color <> ACard.Color)
// and ACard.FaceUp
// )
class function PileKind: TPileKind; override;
// pre: true
// ret: pkTableau
function CanFlipTop: Boolean;
// pre: true
// ret: (0 < Count) and not Top.FaceUp
// commands
procedure Put(ACard: TCard); override;
procedure Remove(var ACard: TCard); override;
procedure FlipTop;
// pre: (1 <= DownCount) and (DownCount = Count) {or: not Top.FaceUp}
// effect: Top.Flip
// post: 0 <= DownCount = Count - 1
// invariants
// DownRange: 0 <= DownCount <= Count
// LowFaceDown: (forall I: 0 <= I < DownCount: not Card(I).FaceUp)
// HighFaceUp: (forall I: DownCount <= I < Count: Card(I).FaceUp)
// HighDecreasing:
// (forall I: DownCount <=I< Count-1: Card(I).Value = 1 + Card(I+1).Value)
// HighAlternating:
// (forall I: DownCount <= I < Count-1: Card(I).Color <> Card(I+1).Color)
end;
function IntToSuit(AValue: Integer): TSuit;
// pre: 1 <= AValue <= 4
// ret: S s.t. Ord(S) = AValue
implementation //===============================================================
uses
Math, SysUtils;
function IntToSuit(AValue: Integer): TSuit;
const
SuitValues: array[1..4] of TSuit = (suHeart, suClub, suDiamond, suSpade);
begin
// check precondition
Assert(AValue in [1..4],
Format('IntToSuit.pre failed; AValue = %d', [AValue]) );
Result := SuitValues[AValue];
end;
{ TCard }
function TCard.Color: TCardColor;
begin
case FSuit of
suHeart, suDiamond:
begin
Result := ccRed;
end;
suClub, suSpade:
begin
Result := ccBlack
end
end
end;
constructor TCard.Create(AValue: TValue; ASuit: TSuit);
begin
inherited Create;
FValue := AValue;
FSuit := ASuit;
FFaceUp := false;
end;
function TCard.FaceUp: Boolean;
begin
Result := FFaceUp;
end;
procedure TCard.Flip;
begin
FFaceUp := not FFaceUp;
end;
procedure TCard.SetFaceUp(AFaceUp: Boolean);
begin
FFaceUp := AFaceUp;
end;
function TCard.Suit: TSuit;
begin
Result := FSuit;
end;
function TCard.Value: TValue;
begin
Result := FValue;
end;
{ TPile }
function TPile.Acceptable(ACard: TCard): Boolean;
begin
Result := true;
end;
function TPile.Capacity: Integer;
begin
Result := FCapacity;
end;
function TPile.Card(I: Integer): TCard;
begin
// check pre-condition
Assert( (0 <= I) and (I < Count),
Format('TPile.Card.Pre failed; I = %d, Count = %d', [I, Count] ) );
Result := FList[I];
end;
function TPile.Count: Integer;
begin
Result := FCount;
end;
constructor TPile.Create(ACapacity: Integer);
begin
inherited Create;
FCapacity := ACapacity;
FCount := 0;
SetLength(FList, FCapacity);
end;
destructor TPile.Destroy;
begin
Finalize(FList);
inherited;
end;
function TPile.IsEmpty: Boolean;
begin
Result := Count = 0;
end;
class function TPile.PileKind: TPileKind;
begin
Result := pkBase;
end;
procedure TPile.Put(ACard: TCard);
begin
// check pre-condition
Assert( (Count <= Capacity) and Acceptable(ACard), 'TPile.Put.pre failed: %i');
Flist[FCount] := ACard;
FCount := FCount + 1;
end;
procedure TPile.Remove(var ACard: TCard);
begin
// check pre-condition
Assert(Count > 0, 'TPile.Remove.pre failed');
ACard := FList[FCount - 1];
FCount := FCount - 1;
end;
function TPile.Top: TCard;
begin
// check pre-condition
Assert(not IsEmpty, 'TPile.Top.pre failed');
Result := Card(Count - 1);
end;
{ TSuitPile }
function TSuitPile.Acceptable(ACard: TCard): Boolean;
begin
Result :=
(ACard.Suit = Suit)
and (ACard.FaceUp)
and ( ( (Count = 0) and (ACard.Value = 1))
or ( (Count > 0)
and (Card(Count-1).Value + 1 = ACard.Value) ) )
end;
constructor TSuitPile.Create(ACapacity: Integer; ASuit: TSuit);
begin
// check pre-condition
Assert( 13 <= Acapacity,
Format('TSuitPile.Create.pre failed; ACapacity = %d', [ACapacity]) );
inherited Create(ACapacity);
FSuit := ASuit;
end;
function TSuitPile.IsComplete: Boolean;
begin
Result := Count = 13;
end;
class function TSuitPile.PileKind: TPileKind;
begin
Result := pkSuit;
end;
function TSuitPile.Suit: TSuit;
begin
Result := FSuit;
end;
{ TDeckPile }
function TDeckPile.Acceptable(ACard: TCard): Boolean;
begin
Result := not ACard.FaceUp;
end;
constructor TDeckPile.Create;
var
VSuit: TSuit;
VValue: TValue;
VCard: TCard;
begin
inherited Create(52);
for VSuit := suHeart to suSpade do
for VValue := 1 to 13 do
begin
VCard := TCard.Create(VValue, VSuit);
Put(VCard);
end;
end;
class function TDeckPile.PileKind: TPileKind;
begin
Result := pkDeck;
end;
procedure TDeckPile.Shuffle;
var
I, J: Integer;
VCard: TCard;
begin
// initialize random generator
Randomize;
for I := 0 to FCount - 1 do
begin
// get a random index
J := RandomRange(0, FCount - 1);
// swap card at position I with card at random index J
VCard := FList[I];
FList[I] := FList[J];
FList[J] := VCard;
end;
end;
{ TDiscardPile }
function TDiscardPile.Acceptable(ACard: TCard): Boolean;
begin
Result := ACard.FaceUp;
end;
class function TDiscardPile.PileKind: TPileKind;
begin
Result := pkDiscard;
end;
{ TTableauPile }
function TTableauPile.Acceptable(ACard: TCard): Boolean;
begin
Result :=
( (DownCount = Count) and
( not ACard.FaceUp or (ACard.Value = 13) )
)
or
( (DownCount < Count) and
(Top.Value = ACard.Value + 1) and
(Top.Color <> ACard.Color) and
ACard.FaceUp
)
end;
function TTableauPile.CanFlipTop: Boolean;
begin
Result := (0 < Count) and not Top.FaceUp;
end;
function TTableauPile.DownCount: Integer;
begin
Result := FDownCount;
end;
procedure TTableauPile.FlipTop;
begin
// check precondition
Assert(CanFlipTop, 'TTableauPile.FlipTop.pre failed');
{not Top.FaceUp}
Top.Flip;
{Top.FaceUp}
FDownCount := FDownCount - 1;
end;
class function TTableauPile.PileKind: TPileKind;
begin
Result := pkTableau;
end;
procedure TTableauPile.Put(ACard: TCard);
begin
inherited;
if not ACard.FaceUp
then FDownCount := FDownCount + 1;
end;
procedure TTableauPile.Remove(var ACard: TCard);
begin
inherited;
if not ACard.FaceUp
then FDownCount := FDownCount - 1;
end;
end.
|
unit Security.Permission;
interface
uses
System.SysUtils, System.Classes, Vcl.ExtCtrls, System.UITypes, Vcl.StdCtrls, Vcl.Forms,
Security.Permission.Interfaces,
Security.Permission.View
;
type
TPermissionNotifyEvent = Security.Permission.Interfaces.TPermissionNotifyEvent;
TResultNotifyEvent = Security.Permission.Interfaces.TResultNotifyEvent;
TSecurityPermissionView = Security.Permission.View.TSecurityPermissionView;
TSecurityPermission = class(TComponent)
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
strict private
FView: TSecurityPermissionView;
FOnPermission: TPermissionNotifyEvent;
FOnResult : TResultNotifyEvent;
strict private
{ Strict private declarations }
function getID: Int64;
procedure setID(const Value: Int64);
function getUpdatedAt: TDateTime;
procedure setUpdatedAt(const Value: TDateTime);
function getCan: string;
procedure setCan(const Value: string);
function getNamePermission: string;
procedure setNamePermission(const Value: string);
private
procedure SetComputerIP(const Value: string);
procedure SetServerIP(const Value: string);
procedure SetSigla(const Value: string);
procedure setUpdatedIn(const Value: string);
procedure SetVersion(const Value: string);
function getComputerIP: string;
function getLogo: TImage;
function getServerIP: string;
function getSigla: string;
function getUpdatedIn: string;
function getVersion: string;
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
function View: iPermissionView;
property Logo: TImage read getLogo;
procedure Execute;
public
{ Published hide declarations }
property ServerIP : string read getServerIP write SetServerIP;
property ComputerIP: string read getComputerIP write SetComputerIP;
property Sigla : string read getSigla write SetSigla;
property Version : string read getVersion write SetVersion;
property UpdatedIn : string read getUpdatedIn write setUpdatedIn;
published
{ Published declarations }
property ID : Int64 read getID write setID;
property UpdatedAt : TDateTime read getUpdatedAt write setUpdatedAt;
property Can : string read getCan write setCan;
property NamePermission: string read getNamePermission write setNamePermission;
property OnPermission: TPermissionNotifyEvent read FOnPermission write FOnPermission;
property OnResult : TResultNotifyEvent read FOnResult write FOnResult;
end;
implementation
{ -$R Security.Permission.rc Security.Permission.dcr }
uses
Security.Internal;
{ TSecurityPermission }
constructor TSecurityPermission.Create(AOwner: TComponent);
begin
FView := TSecurityPermissionView.Create(Screen.FocusedForm);
inherited;
end;
destructor TSecurityPermission.Destroy;
begin
FreeAndNil(FView);
inherited;
end;
function TSecurityPermission.getCan: string;
begin
Result := FView.EditCan.Text;
end;
function TSecurityPermission.getComputerIP: string;
begin
Result := FView.LabelIPComputerValue.Caption;
end;
function TSecurityPermission.getLogo: TImage;
begin
Result := FView.ImageLogo;
end;
function TSecurityPermission.getNamePermission: string;
begin
Result := FView.EditName.Text;
end;
function TSecurityPermission.getServerIP: string;
begin
Result := FView.LabelIPServerValue.Caption;
end;
function TSecurityPermission.getSigla: string;
begin
Result := FView.PanelTitleLabelSigla.Caption;
end;
function TSecurityPermission.getUpdatedAt: TDateTime;
begin
Result := FView.UpdatedAt;
end;
function TSecurityPermission.getUpdatedIn: string;
begin
Result := FView.PanelTitleAppInfoUpdatedValue.Caption;
end;
function TSecurityPermission.getVersion: string;
begin
Result := FView.PanelTitleAppInfoVersionValue.Caption;
end;
procedure TSecurityPermission.setCan(const Value: string);
begin
FView.Can := Value;
end;
procedure TSecurityPermission.SetComputerIP(const Value: string);
begin
FView.LabelIPComputerValue.Caption := Value;
end;
procedure TSecurityPermission.setID(const Value: Int64);
begin
FView.ID := Value;
end;
procedure TSecurityPermission.setNamePermission(const Value: string);
begin
FView.NamePermission := Value;
end;
function TSecurityPermission.getID: Int64;
begin
Result := FView.ID;
end;
procedure TSecurityPermission.SetServerIP(const Value: string);
begin
FView.LabelIPServerValue.Caption := Value;
end;
procedure TSecurityPermission.SetSigla(const Value: string);
begin
FView.PanelTitleLabelSigla.Caption := Value;
end;
procedure TSecurityPermission.setUpdatedAt(const Value: TDateTime);
begin
FView.UpdatedAt := Value;
end;
procedure TSecurityPermission.setUpdatedIn(const Value: string);
begin
FView.PanelTitleAppInfoUpdatedValue.Caption := Value;
end;
procedure TSecurityPermission.SetVersion(const Value: string);
begin
FView.PanelTitleAppInfoVersionValue.Caption := Value;
end;
function TSecurityPermission.View: iPermissionView;
begin
Result := FView;
end;
procedure TSecurityPermission.Execute;
begin
Internal.Required(Self.FOnPermission);
FView.OnPermission := Self.FOnPermission;
FView.OnResult := Self.FOnResult;
FView.Show;
end;
end.
|
unit srvrdm;
interface
{ This DataModule is the COM object that the TRemoteServer component will
connect to. Each remote connection gets a new DataModule that is used
during that clients session. When using a TDatabase on a Remote Data
Module, be sure to set it's HandleShared property to True. If you use
a TSession then set it's AutoSessionName property to True.
}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComServ, ComObj, VCLCom, StdVcl, DataBkr, Serv_TLB,
DBTables, Provider, Db, DBClient, BDE;
type
TProjectData = class(TRemoteDataModule, IProjectData)
Project: TTable;
Employee: TQuery;
EmpProj: TQuery;
ProjectProvider: TDataSetProvider;
UpdateQuery: TQuery;
Database: TDatabase;
ProjectSource: TDataSource;
EmployeeProvider: TDataSetProvider;
procedure ProjectProviderBeforeUpdateRecord(Sender: TObject;
SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind;
var Applied: Boolean);
protected
class procedure UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); override;
end;
var
ProjectData: TProjectData;
implementation
{$R *.dfm}
{ This function implements cascaded deletes. Normally, you would do this in a
trigger, but for the sake of this demo, it is done here. }
procedure TProjectData.ProjectProviderBeforeUpdateRecord(Sender: TObject;
SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind;
var Applied: Boolean);
const
DeleteQuery = 'delete from EMPLOYEE_PROJECT where PROJ_ID = :ProjID';
begin
if (UpdateKind = ukDelete) and (SourceDS = Project) then
begin
UpdateQuery.SQL.Text := DeleteQuery;
UpdateQuery.Params[0].AsString := DeltaDS.FieldByName('PROJ_ID').AsString;
UpdateQuery.ExecSQL;
end;
end;
class procedure TProjectData.UpdateRegistry(Register: Boolean; const ClassID, ProgID: string);
begin
if Register then
begin
inherited UpdateRegistry(Register, ClassID, ProgID);
EnableSocketTransport(ClassID);
EnableWebTransport(ClassID);
end else
begin
DisableSocketTransport(ClassID);
DisableWebTransport(ClassID);
inherited UpdateRegistry(Register, ClassID, ProgID);
end;
end;
initialization
TComponentFactory.Create(ComServer, TProjectData,
Class_ProjectData, ciMultiInstance);
end.
|
unit CSettlementSheetPrintUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, StdCtrls, Grids, DBGrids, DBTables, Wwdbigrd, Wwdbgrid, Buttons,
RPCanvas, RPrinter, RPDefine, RPBase, RPFiler, Mask;
type
TCertiorariSettlementForm = class(TForm)
SortSettlementSheetTable: TTable;
Label1: TLabel;
SortSettlementSheetDataSource: TDataSource;
SettlementGrid: TwwDBGrid;
TotalRefundLabel: TLabel;
Label2: TLabel;
EditPetitioner: TEdit;
EditLawyers: TEdit;
Label3: TLabel;
Label4: TLabel;
EditPropertyType: TEdit;
Label5: TLabel;
PrintButton: TBitBtn;
CancelButton: TBitBtn;
CertiorariTable: TTable;
LawyerTable: TTable;
PropertyClassTable: TTable;
Label6: TLabel;
EditSpecialTerms: TEdit;
TaxRateTable: TTable;
ReportFiler: TReportFiler;
ReportPrinter: TReportPrinter;
PrintDialog: TPrintDialog;
Label7: TLabel;
EditDate: TMaskEdit;
SwisCodeTable: TTable;
AssessorsOfficeTable: TTable;
SchoolCodeTable: TTable;
Label8: TLabel;
EditOwner: TEdit;
procedure PrintButtonClick(Sender: TObject);
procedure ReportPrint(Sender: TObject);
procedure SettlementGridColExit(Sender: TObject);
procedure SortSettlementSheetTableAfterEdit(DataSet: TDataSet);
procedure SortSettlementSheetTableAfterPost(DataSet: TDataSet);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure SortSettlementSheetTableBeforePost(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
SwisSBLKey, UnitName : String;
OrigCorrectedAssessment : LongInt;
FillingGrid, CorrectedAssessmentChanged : Boolean;
Procedure FillInCertiorariSettlementGrid;
Function ComputeCertiorariRefund_OneLine(TaxYear : String;
SwisCode : String;
TaxableValue : LongInt;
GeneralTaxType : String) : Double;
Procedure ComputeCertiorariRefund_WholeGrid;
Procedure InitializeForm;
end;
Procedure ExecuteSettlementSheetPrint(_SwisSBLKey : String);
var
CertiorariSettlementForm: TCertiorariSettlementForm;
implementation
{$R *.DFM}
uses Utilitys, WinUtils, PASUtils, GlblVars, GlblCnst, Preview, PASTypes;
{===============================================================}
Procedure TCertiorariSettlementForm.FormKeyPress( Sender: TObject;
var Key: Char);
begin
If (Key = #13)
then
If not (ActiveControl is TwwDBGrid)
then
begin
{not a grid so go to next control on form}
Perform(WM_NEXTDLGCTL, 0, 0);
Key := #0;
end;
end; {FormKeyPress}
{===============================================================}
Procedure TCertiorariSettlementForm.FillInCertiorariSettlementGrid;
var
Done, FirstTimeThrough : Boolean;
begin
FillingGrid := True;
Done := False;
FirstTimeThrough := True;
CertiorariTable.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else CertiorariTable.Next;
If CertiorariTable.EOF
then Done := True;
{Make sure to not pick up closed years.}
If ((not Done) and
(Deblank(CertiorariTable.FieldByName('Disposition').Text) = ''))
then
begin
with SortSettlementSheetTable do
try
Insert;
FieldByName('TaxRollYr').Text := CertiorariTable.FieldByName('TaxRollYr').Text;
FieldByName('CertiorariNumber').AsInteger := CertiorariTable.FieldByName('CertiorariNumber').AsInteger;
try
FieldByName('OriginalAssessment').AsInteger := CertiorariTable.FieldByName('CurrentTotalValue').AsInteger;
except
FieldByName('OriginalAssessment').AsInteger := 0;
end;
try
FieldByName('CorrectedAssessment').AsInteger := CertiorariTable.FieldByName('GrantedTotalValue').AsInteger;
except
FieldByName('CorrectedAssessment').AsInteger := 0;
end;
try
FieldByName('AssessmentReduction').AsInteger := FieldByName('OriginalAssessment').AsInteger -
FieldByName('CorrectedAssessment').AsInteger;
except
FieldByName('AssessmentReduction').AsInteger := 0;
end;
{CHG01152003-1: Let them include or exclude lines. Default it so that settled ones
are not marked include.}
If (FieldByName('AssessmentReduction').AsInteger = 0)
then FieldByName('Include').AsBoolean := False
else FieldByName('Include').AsBoolean := True;
Post;
except
SystemSupport(001, SortSettlementSheetTable, 'Error posting to sort settlement table.',
UnitName, GlblErrorDlgBox);
end;
end; {If ((not Done) and ...}
until Done;
FillingGrid := False;
end; {FillInCertiorariSettlementGrid}
{===============================================================}
Function TCertiorariSettlementForm.ComputeCertiorariRefund_OneLine(TaxYear : String;
SwisCode : String;
TaxableValue : LongInt;
GeneralTaxType : String) : Double;
var
Done, FirstTimeThrough, UseThisRate : Boolean;
begin
Result := 0;
Done := False;
FirstTimeThrough := True;
SetRangeOld(TaxRateTable,
['TaxRollYr', 'CollectionType', 'CollectionNo', 'PrintOrder'],
[TaxYear, 'MU', '1', '1'],
[TaxYear, 'MU', '1', '99']);
TaxRateTable.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else TaxRateTable.Next;
If TaxRateTable.EOF
then Done := True;
If ((not Done) and
(TaxRateTable.FieldByName('GeneralTaxType').Text = GeneralTaxType) and
(Pos('POLICE', TaxRateTable.FieldByName('Description').Text) = 0))
then
begin
{Make sure this swis is good.}
UseThisRate := False;
If (Length(TaxRateTable.FieldByName('SwisCode').Text) <= 4)
then UseThisRate := True;
If ((Length(TaxRateTable.FieldByName('SwisCode').Text) = 6) and
(TaxRateTable.FieldByName('SwisCode').Text = SwisCode))
then UseThisRate := True;
If UseThisRate
then
try
Result := (TaxableValue / 1000) * TaxRateTable.FieldByName('HomesteadRate').AsFloat;
Result := Roundoff(Result, 2);
except
Result := 0;
end;
end; {If not Done}
until Done;
end; {ComputeCertiorariRefund_OneLine}
{===============================================================}
Procedure TCertiorariSettlementForm.ComputeCertiorariRefund_WholeGrid;
var
Done, FirstTimeThrough : Boolean;
TotalRefund, TotalThisLine : Double;
Bookmark : TBookmark;
begin
FillingGrid := True;
TotalRefund := 0;
SortSettlementSheetTable.DisableControls;
Done := False;
FirstTimeThrough := True;
Bookmark := SortSettlementSheetTable.GetBookmark;
SortSettlementSheetTable.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else SortSettlementSheetTable.Next;
If SortSettlementSheetTable.EOF
then Done := True;
{Compute the refund for this line.}
{CHG01152003-1: Let them include or exclude lines.}
{FXX01152003-2: If the assessment reduction is 0, then do not recompute - this was a taxable
value change and they enter the amounts manually.}
If ((not Done) and
SortSettlementSheetTable.FieldByName('Include').AsBoolean and
(SortSettlementSheetTable.FieldByName('AssessmentReduction').AsInteger > 0))
then
begin
with SortSettlementSheetTable do
try
TotalThisLine := ComputeCertiorariRefund_OneLine(FieldByName('TaxRollYr').Text,
Copy(SwisSBLKey, 1, 6),
FieldByName('AssessmentReduction').AsInteger,
'TO');
Edit;
FieldByName('TaxRefund').AsFloat := TotalThisLine;
Post;
except
TotalThisLine := 0;
SystemSupport(002, SortSettlementSheetTable, 'Error editing sort settlement line.',
UnitName, GlblErrorDlgBox);
end;
TotalRefund := TotalRefund + TotalThisLine;
end; {If not Done}
until Done;
SortSettlementSheetTable.EnableControls;
SortSettlementSheetTable.GotoBookmark(Bookmark);
TotalRefundLabel.Caption := FormatFloat(CurrencyDecimalDisplay, TotalRefund);
FillingGrid := False;
end; {ComputeCertiorariRefund_WholeGrid}
{===============================================================}
Procedure TCertiorariSettlementForm.SortSettlementSheetTableAfterEdit(DataSet: TDataSet);
begin
OrigCorrectedAssessment := SortSettlementSheetTable.FieldByName('CorrectedAssessment').AsInteger;
end;
{===============================================================}
Procedure TCertiorariSettlementForm.SortSettlementSheetTableBeforePost(DataSet: TDataSet);
begin
If not FillingGrid
then
begin
CorrectedAssessmentChanged := True;
with SortSettlementSheetTable do
try
FieldByName('AssessmentReduction').AsInteger := FieldByName('OriginalAssessment').AsInteger -
FieldByName('CorrectedAssessment').AsInteger;
except
FieldByName('AssessmentReduction').AsInteger := 0;
end;
end; {If not FillingGrid}
end; {SortSettlementSheetTableBeforePost}
{===============================================================}
Procedure TCertiorariSettlementForm.SortSettlementSheetTableAfterPost(DataSet: TDataSet);
begin
If not FillingGrid
then ComputeCertiorariRefund_WholeGrid;
end; {SortSettlementSheetTableAfterPost}
{===============================================================}
Procedure TCertiorariSettlementForm.SettlementGridColExit(Sender: TObject);
{If they change the corrected assessment, then change the reduction
amount and recalculate.}
begin
If ((SortSettlementSheetTable.State = dsEdit) and
(SettlementGrid.GetActiveField.FieldName = 'CorrectedAssessment') and
(OrigCorrectedAssessment <> SortSettlementSheetTable.FieldByName('CorrectedAssessment').AsInteger))
then
begin
with SortSettlementSheetTable do
try
{CHG02122004-1(2.07l): If the corrected and original assessments are now the same, then
set the refund amount to 0.}
If (FieldByName('OriginalAssessment').AsInteger =
FieldByName('CorrectedAssessment').AsInteger)
then
begin
FieldByName('TaxRefund').AsFloat := 0;
MessageDlg('The tax refund for this certiorari item has been set to $0.' + #13 +
'If this settlement offer involves granting a new exemption,' + #13 +
'please manually calculate the amount and enter it in the tax refund column.',
mtInformation, [mbOK], 0);
end; {If (FieldByName('AssessmentReduction').AsInteger = 0)}
Post;
except
SystemSupport(003, SortSettlementSheetTable, 'Error posting corrected assessment change.',
UnitName, GlblErrorDlgBox);
end;
end; {If ((SortSettlementSheetTable.State = dsEdit) and ...}
end; {SettlementGridColExit}
{===============================================================}
Procedure TCertiorariSettlementForm.InitializeForm;
var
_Found : Boolean;
begin
FillingGrid := False;
CorrectedAssessmentChanged := False;
SortSettlementSheetTable.EmptyTable;
UnitName := 'CSettlementSheetPrintUnit';
OpenTablesForForm(Self, NextYear);
with SortSettlementSheetTable do
begin
TFloatField(FieldByName('OriginalAssessment')).DisplayFormat := CurrencyDisplayNoDollarSign;
TFloatField(FieldByName('CorrectedAssessment')).DisplayFormat := CurrencyDisplayNoDollarSign;
TFloatField(FieldByName('AssessmentReduction')).DisplayFormat := CurrencyDisplayNoDollarSign;
TFloatField(FieldByName('TaxRefund')).DisplayFormat := DecimalEditDisplay;
end; {with SortSettlementSheetTable do}
Caption := 'Settlement Sheet Print for ' + ConvertSwisSBLToDashDot(SwisSBLKey);
{We will assume that the most recent cert year is open for now.}
SetRangeOld(CertiorariTable, ['SwisSBLKey', 'TaxRollYr'],
[SwisSBLKey, '1950'], [SwisSBLKey, '3999']);
CertiorariTable.Last;
{FXX01152003-1: The petitioner name shold come from PetitName1 instead.}
EditPetitioner.Text := CertiorariTable.FieldByName('PetitName1').Text;
{CHG01152003-2: Allow them to see and change the owner name.}
EditOwner.Text := CertiorariTable.FieldByName('CurrentName1').Text;
_Found := FindKeyOld(LawyerTable, ['Code'], [CertiorariTable.FieldByName('LawyerCode').Text]);
If _Found
then EditLawyers.Text := LawyerTable.FieldByName('Name1').Text
else EditLawyers.Text := CertiorariTable.FieldByName('LawyerCode').Text;
_Found := FindKeyOld(PropertyClassTable, ['MainCode'], [CertiorariTable.FieldByName('PropertyClassCode').Text]);
If _Found
then EditPropertyType.Text := PropertyClassTable.FieldByName('Description').Text
else EditPropertyType.Text := CertiorariTable.FieldByName('PropertyClassCode').Text;
EditSpecialTerms.Text := 'None';
EditDate.Text := DateToStr(Date);
FillInCertiorariSettlementGrid;
ComputeCertiorariRefund_WholeGrid;
end; {InitializeForm}
{===============================================================}
Procedure PrintLabel(Sender : TObject;
TempStr : String);
begin
with Sender as TBaseReport do
begin
Bold := True;
Print(#9 + TempStr);
Bold := False;
end; {with Sender as TBaseReport do}
end; {PrintLabel}
{===============================================================}
Procedure TCertiorariSettlementForm.ReportPrint(Sender: TObject);
var
TaxYear, SwisCode,
SchoolName, AssessorsName, AttorneyName : String;
_Found, Done, FirstTimeThrough : Boolean;
Bookmark : TBookmark;
TotalTaxRefund : Double;
I : Integer;
AssessmentYearControlTable : TTable;
begin
AssessmentYearControlTable := FindTableInDataModuleForProcessingType(DataModuleAssessmentYearControlTableName,
ThisYear);
AssessorsName := AssessorsOfficeTable.FieldByName('AssessorName').Text;
AttorneyName := AssessorsOfficeTable.FieldByName('AttorneyName').Text;
CertiorariTable.Last;
with Sender as TBaseReport do
begin
SetFont('Times New Roman', 12);
ClearTabs;
SetTab(0.3, pjLeft, 0.6, 0, BoxLineNone, 0);
SetTab(1.0, pjLeft, 5.0, 0, BoxLineNone, 0);
For I := 1 to 6 do
Println('');
PrintLabel(Sender, 'To:');
Println(#9 + 'Supervisor and Town Board');
PrintLabel(Sender, 'From:');
Println(#9 + AttorneyName + ' and ' + AssessorsName);
PrintLabel(Sender, 'Date:');
Println(#9 + EditDate.Text);
PrintLabel(Sender, 'Re:');
Println(#9 + 'Certiorari');
Println('');
ClearTabs;
SetTab(0.3, pjCenter, 8.1, 0, BoxLineNone, 0);
Println('');
Println(#9 + EditPetitioner.Text);
Println(#9 + 'vs.');
Println(#9 + 'TOWN OF RAMAPO');
Println('');
ClearTabs;
SetTab(0.3, pjLeft, 8.1, 0, BoxLineNone, 0);
Println(#9 + 'We propose that the following certiorari matter be settled with the condition that no refunds will be made');
Println(#9 + 'unless and until any and all tax delinquencies are satisfied.');
Println('');
ClearTabs;
SetTab(0.3, pjLeft, 1.2, 0, BoxLineNone, 0);
SetTab(1.6, pjLeft, 5.0, 0, BoxLineNone, 0);
PrintLabel(Sender, 'Tax Parcel:');
Println(#9 + ConvertSBLOnlyToDashDot(Copy(SwisSBLKey, 7, 20)));
PrintLabel(Sender, 'Old ID:');
Println(#9 + ConvertSBLOnlyToOldDashDot(Copy(SwisSBLKey, 7, 20),
AssessmentYearControlTable));
{CHG01152003-2: Allow them to see and change the owner name.}
PrintLabel(Sender, 'Owner:');
Println(#9 + EditOwner.Text);
PrintLabel(Sender, 'Prop Address:');
Println(#9 + GetLegalAddressFromTable(CertiorariTable));
SwisCode := Copy(SwisSBLKey, 1, 6);
_Found := FindKeyOld(SwisCodeTable, ['SwisCode'], [SwisCode]);
If _Found
then
begin
PrintLabel(Sender, 'Village:');
Println(#9 + SwisCodeTable.FieldByName('MunicipalityName').Text);
end;
PrintLabel(Sender, 'Prop Type:');
Println(#9 + EditPropertyType.Text);
Println('');
Println('');
{The refund grid.}
Bold := True;
ClearTabs;
SetTab(1.0, pjCenter, 0.5, 0, BoxLineNone, 0); {Cert Index}
SetTab(1.6, pjCenter, 0.9, 0, BoxLineNone, 0); {Tax Year}
SetTab(2.6, pjCenter, 1.1, 0, BoxLineNone, 0); {Original AV}
SetTab(3.8, pjCenter, 1.1, 0, BoxLineNone, 0); {Corrected AV}
SetTab(5.0, pjCenter, 1.1, 0, BoxLineNone, 0); {AV Reduction}
SetTab(6.2, pjCenter, 1.3, 0, BoxLineNone, 0); {Tax Refund}
Println(#9 + 'Cert' +
#9 + 'Tax' +
#9 + 'Original' +
#9 + 'Corrected' +
#9 + 'Assessment' +
#9 + 'Town Tax');
ClearTabs;
SetTab(1.0, pjCenter, 0.5, 0, BoxLineBottom, 0); {Cert Index}
SetTab(1.6, pjCenter, 0.9, 0, BoxLineBottom, 0); {Tax Year}
SetTab(2.6, pjCenter, 1.1, 0, BoxLineBottom, 0); {Original AV}
SetTab(3.8, pjCenter, 1.1, 0, BoxLineBottom, 0); {Corrected AV}
SetTab(5.0, pjCenter, 1.1, 0, BoxLineBottom, 0); {AV Reduction}
SetTab(6.2, pjCenter, 1.3, 0, BoxLineBottom, 0); {Tax Refund}
Println(#9 + 'Index' +
#9 + 'Year' +
#9 + 'Assessment' +
#9 + 'Assessment' +
#9 + 'Reduction' +
#9 + 'Refund');
Bold := False;
ClearTabs;
SetTab(1.0, pjLeft, 0.5, 0, BoxLineNone, 0); {Cert Index}
SetTab(1.6, pjLeft, 0.9, 0, BoxLineNone, 0); {Tax Year}
SetTab(2.6, pjRight, 1.1, 0, BoxLineNone, 0); {Original AV}
SetTab(3.8, pjRight, 1.1, 0, BoxLineNone, 0); {Corrected AV}
SetTab(5.0, pjRight, 1.1, 0, BoxLineNone, 0); {AV Reduction}
SetTab(6.2, pjRight, 1.3, 0, BoxLineNone, 0); {Tax Refund}
SortSettlementSheetTable.DisableControls;
Done := False;
FirstTimeThrough := True;
TotalTaxRefund := 0;
Bookmark := SortSettlementSheetTable.GetBookmark;
SortSettlementSheetTable.First;
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else SortSettlementSheetTable.Next;
If SortSettlementSheetTable.EOF
then Done := True;
{Compute the refund for this line.}
with SortSettlementSheetTable do
If ((not Done) and
FieldByName('Include').AsBoolean)
then
begin
TotalTaxRefund := TotalTaxRefund +
FieldByName('TaxRefund').AsFloat;
TaxYear := FieldByName('TaxRollYr').Text + '/' +
IntToStr(FieldByName('TaxRollYr').AsInteger + 1);
Println(#9 + FieldByName('CertiorariNumber').Text +
#9 + TaxYear +
#9 + FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('OriginalAssessment').AsFloat) +
#9 + FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('CorrectedAssessment').AsFloat) +
#9 + FormatFloat(CurrencyDisplayNoDollarSign,
FieldByName('AssessmentReduction').AsFloat) +
#9 + FormatFloat(CurrencyDecimalDisplay,
FieldByName('TaxRefund').AsFloat));
end; {If ((not Done) and ...}
until Done;
SortSettlementSheetTable.EnableControls;
SortSettlementSheetTable.GotoBookmark(Bookmark);
ClearTabs;
SetTab(4.1, pjLeft, 2.0, 0, BoxLineNone, 0); {Corrected AV}
SetTab(6.2, pjRight, 1.3, 0, BoxLineNone, 0); {Tax Refund}
Println(#9 + #9 + '--------------');
Bold := True;
Println(#9 + 'Total Refund of Town Taxes:' +
#9 + FormatFloat(CurrencyDecimalDisplay,
TotalTaxRefund));
Bold := False;
ClearTabs;
SetTab(0.3, pjLeft, 1.2, 0, BoxLineNone, 0);
SetTab(1.6, pjLeft, 5.0, 0, BoxLineNone, 0);
Println('');
PrintLabel(Sender, 'Special Terms:');
If (Deblank(EditSpecialTerms.Text) = '')
then Println(#9 + 'None.')
else Println(#9 + EditSpecialTerms.Text);
Println('');
Println('');
ClearTabs;
SchoolName := '';
If (CertiorariTable.FieldByName('SchoolCode').Text = '392601')
then SchoolName := 'Ramapo Central';
If (CertiorariTable.FieldByName('SchoolCode').Text = '392602')
then SchoolName := 'East Ramapo';
SetTab(1.0, pjLeft, 8.0, 0, BoxLineNone, 0);
Println(#9 + Trim(EditLawyers.Text) + ' know(s) of the above settlement and will present it to the');
Println(#9 + SchoolName + ' School District for approval.');
Println('');
Println('');
Println('');
Println('');
ClearTabs;
SetTab(1.0, pjLeft, 2.0, 0, BoxLineTop, 0);
SetTab(4.3, pjLeft, 2.0, 0, BoxLineTop, 0);
Println(#9 + AssessorsName +
#9 + AttorneyName);
ClearTabs;
SetTab(1.0, pjLeft, 2.0, 0, BoxLineNone, 0);
SetTab(4.3, pjLeft, 2.0, 0, BoxLineNone, 0);
Println(#9 + 'Assessor' +
#9 + 'Town Attorney');
Println('');
Println('');
ClearTabs;
SetTab(0.5, pjLeft, 8.0, 0, BoxLineNone, 0);
Println(#9 + 'NOTE: THIS RECOMMENDATION FOR SETTLEMENT INCLUDES ONLY REFUND DUE FROM');
Println(#9 + ' THE TOWN OF RAMAPO. ANY REFUNDS DUE FROM OTHER TAXING JURISDICTIONS');
Println(#9 + ' ARE NOT REFLECTED IN THE ABOVE CALCULATIONS.');
end; {with Sender as TBaseReport do}
end; {ReportPrint}
{===============================================================}
Procedure TCertiorariSettlementForm.PrintButtonClick(Sender: TObject);
var
NewFileName: String;
Quit : Boolean;
begin
{CHG10121998-1: Add user options for default destination and show vet max msg.}
If (SortSettlementSheetTable.State = dsEdit)
then SortSettlementSheetTable.Post;
SetPrintToScreenDefault(PrintDialog);
If PrintDialog.Execute
then
begin
AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptLaser],
False, Quit);
If not Quit
then
begin
GlblPreviewPrint := False;
{If they want to preview the print (i.e. have it
go to the screen), then we need to come up with
a unique file name to tell the ReportFiler
component where to put the output.
Once we have done that, we will execute the
report filer which will print the report to
that file. Then we will create and show the
preview print form and give it the name of the
file. When we are done, we will delete the file
and make sure that we go back to the original
directory.}
{FXX07221998-1: So that more than one person can run the report
at once, use a time based name first and then
rename.}
{If they want to see it on the screen, start the preview.}
If PrintDialog.PrintToFile
then
begin
GlblPreviewPrint := True;
NewFileName := GetPrintFileName(Self.Caption, True);
ReportFiler.FileName := NewFileName;
try
PreviewForm := TPreviewForm.Create(self);
PreviewForm.FilePrinter.FileName := NewFileName;
PreviewForm.FilePreview.FileName := NewFileName;
PreviewForm.FilePreview.ZoomFactor := 130;
ReportFiler.Execute;
{FXX09071999-6: Tell people that printing is starting and
done.}
PreviewForm.ShowModal;
finally
PreviewForm.Free;
end;
end
else ReportPrinter.Execute;
end; {If not Quit}
ResetPrinter(ReportPrinter);
end; {If PrintDialog.Execute}
end; {PrintButtonClick}
{===============================================================}
Procedure ExecuteSettlementSheetPrint(_SwisSBLKey : String);
begin
try
CertiorariSettlementForm := TCertiorariSettlementForm.Create(nil);
with CertiorariSettlementForm do
begin
SwisSBLKey := _SwisSBLKey;
InitializeForm;
ShowModal;
end;
finally
CertiorariSettlementForm.Free;
end;
end; {ExecuteSettlementSheetPrint}
end. |
unit DMHelper.MainScreen.View;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.Layouts,
FMX.Objects,
FMX.Controls.Presentation,
FMX.StdCtrls;
type
TfrmMain = class(TForm)
layoutMain: TLayout;
layoutFull: TLayout;
layoutMenu: TLayout;
recMenu: TRectangle;
btnPrincipal: TSpeedButton;
btnUsuario: TSpeedButton;
layoutTop: TLayout;
recTop: TRectangle;
recMain: TRectangle;
procedure FormCreate(Sender: TObject);
private
procedure ApplyStyle;
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
uses
DMHelper.View.Styles.Colors,
DMHelper.View.Pages.Main,
Router4D;
{$R *.fmx}
procedure TfrmMain.FormCreate(Sender: TObject);
begin
TRouter4D.Render<TfrmMainPage>.SetElement(layoutMain);
ApplyStyle;
end;
procedure TfrmMain.ApplyStyle;
var
Settings: ITextSettings;
Instance: TComponent;
I: Integer;
begin
recMain.Fill.Color := COLOR_BACKGROUND;
recMenu.Fill.Color := COLOR_BACKGROUND_MENU;
recTop.Fill.Color := COLOR_BACKGROUND_TOP;
//recLogo.Fill.Color := COLOR_BACKGROUND_DESTAK;
for I := 0 to ComponentCount - 1 do
begin
Instance := Components[i];
if IInterface(Instance).QueryInterface(ITextSettings, Settings) = S_OK then
begin
Settings.TextSettings.BeginUpdate;
try
Settings.DefaultTextSettings.Font.Size := FONT_H6;
Settings.DefaultTextSettings.Font.Family := FONT;
Settings.DefaultTextSettings.FontColor := FONT_COLOR;
finally
Settings.TextSettings.EndUpdate;
end;
end;
end;
end;
end.
|
{ -----------------------------------------------------------------------------
Unit Name: ufraQuickViewer
Author: 黄伟
Date: 07-六月-2018
Purpose: 观测数据速览显示单元
本单元通过检查每只仪器最近两次观测数据变化、月变化,将超过限值的仪器及其
数据显示出来,同时统计数据增大和减小的数量,了解当前趋势。
History:
2018-06-14 增加了显示数据增量的功能,目前尚不能指定日期,但可以过滤掉微小
变化。
----------------------------------------------------------------------------- }
unit ufraQuickViewer;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, System.Types,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, HTMLUn2, HtmlView, Vcl.ExtCtrls,
Vcl.StdCtrls, Vcl.ComCtrls, Vcl.WinXCtrls, Vcl.Menus, Vcl.OleCtrls, SHDocVw;
type
TfraQuickViewer = class(TFrame)
Panel1: TPanel;
HtmlViewer: THtmlViewer;
btnCreateQuickView: TButton;
pnlProgress: TPanel;
ProgressBar: TProgressBar;
Label1: TLabel;
lblDesignName: TLabel;
lblProgress: TLabel;
btnShowIncrement: TButton;
chkUseFilter: TCheckBox;
PopupMenu1: TPopupMenu;
miCopy: TMenuItem;
dlgPrint: TPrintDialog;
miPrint: TMenuItem;
dlgSave: TSaveDialog;
miSave: TMenuItem;
N1: TMenuItem;
GroupBox1: TGroupBox;
chkTableByType: TCheckBox;
chkUseIE: TCheckBox;
chkAllMeters: TCheckBox;
wbViewer: TWebBrowser;
btnSpecificDates: TButton;
pnlDateSelector: TPanel;
GroupBox2: TGroupBox;
GroupBox3: TGroupBox;
dtp1: TDateTimePicker;
dtp2: TDateTimePicker;
cmbDate1Opt: TComboBox;
cmbDate2Opt: TComboBox;
btnDateSelected: TButton;
DateTimePicker1: TDateTimePicker;
DateTimePicker2: TDateTimePicker;
chkSimpleSDGrid: TCheckBox;
procedure btnCreateQuickViewClick(Sender: TObject);
procedure btnShowIncrementClick(Sender: TObject);
procedure HtmlViewerHotSpotClick(Sender: TObject; const SRC: string; var Handled: Boolean);
procedure miCopyClick(Sender: TObject);
procedure miPrintClick(Sender: TObject);
procedure miSaveClick(Sender: TObject);
procedure wbViewerBeforeNavigate2(ASender: TObject; const pDisp: IDispatch; const URL, Flags,
TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool);
procedure btnSpecificDatesClick(Sender: TObject);
procedure btnDateSelectedClick(Sender: TObject);
private
{ Private declarations }
FMeterList: TStrings;
{ 显示两个指定日期的数据,及其增量 }
procedure ShowSpecificDatesData;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{ 显示观测情况速览 }
procedure ShowQuickView;
{ 显示观测数据增量,若UseFilter = False则显示全部仪器的数据增量,否则只显示超限的 }
procedure ShowDataIncrement(UseFilter: Boolean = False);
end;
implementation
uses
uHJX.Data.Types, uHJX.Intf.AppServices, uHJX.Intf.FunctionDispatcher, uHJX.Intf.Datas,
uHJX.Classes.Meters,
uWebGridCross, uWBLoadHTML;
{$R *.dfm}
const
{ 注:这里的CSS设置使得表格呈现细线边框 }
{ 针对表格的表头、单元格使用了CSS定义 }
htmPageCode2 = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">'#13#10
+ '<html>'#13#10
+ '<head>'#13#10
+ '<meta http-equiv="Content-Type" content="text/html; charset=GB2312" />'#13#10
{ + '@PageTitle@'#13#10 }
+ '<style type="text/css">'#13#10
+ '.DataGrid {border:1px solid #000099;border-width:1px 1px 1px 1px;margin:1px 1px 1px 1px;border-collapse:collapse}'#13#10
+ '.thStyle {font-size: 8pt; font-family: Tahoma; color: #000000; padding:3px;border:1px solid #000099}'#13#10
+ '.tdStyle {font-size: 8pt; font-family: Tahoma; color: #000000; background-color:#FFFFFF;empty-cells:show;'
// #F7F7F7
+ ' border:1px solid #000099; padding:3px}'#13#10
+ '.CaptionStyle {font-family:黑体;font-size: 9pt;color: #000000; padding:3px;border:1px solid #000099; background-color:#FFFF99}'#13#10
+ '</style>'#13#10
+ '</head>'#13#10
+ '<body>'#13#10
+ '@PageContent@'#13#10
+ '</body>'#13#10
+ '</html>';
var
MaxDeltaDDWY: Double = 0.1;
MaxDeltaMS : Double = 5;
MaxDeltaMG : Double = 5;
MaxDeltaSY : Double = 1;
constructor TfraQuickViewer.Create(AOwner: TComponent);
begin
inherited;
dtp2.Date := Now;
dtp1.Date := Now - 1;
dtp1.Time := 0;
dtp2.Time := 0;
FMeterList := TStringList.Create;
end;
destructor TfraQuickViewer.Destroy;
begin
FMeterList.Free;
inherited;
end;
{ -----------------------------------------------------------------------------
Procedure : ShowQuickView
Description: 显示速览内容
----------------------------------------------------------------------------- }
procedure TfraQuickViewer.btnCreateQuickViewClick(Sender: TObject);
begin
ShowQuickView;
end;
procedure TfraQuickViewer.ShowQuickView;
var
MTList : TStrings;
Meter : TMeterDefine;
MeterType : string;
V1, V2 : TDoubleDynArray;
iMeter, i : Integer;
iMeterCount: Integer;
iInc, iDec : Integer;
iOverLine : Integer;
WCV : TWebCrossView;
Page : string;
Body : string;
// 判断是否值得显示出来,目前的判断比较僵化,还需要考虑到时间间隔问题,即变化速率
function _NeedShow: Boolean;
var
Delta: Double;
procedure CountDelta;
begin
if Delta > 0 then
Inc(iInc)
else
Inc(iDec);
end;
begin
Result := True;
if MeterType = '多点位移计' then
begin
Delta := V2[1] - V1[1];
// CountDelta;
if abs(Delta) < abs(V2[2] - V1[2]) then
Delta := V2[2] - V1[2];
// CountDelta;
if abs(Delta) < abs(V2[3] - V1[3]) then
Delta := V2[3] - V1[3];
// CountDelta;
if abs(Delta) < abs(V2[4] - V1[4]) then
Delta := V2[4] - V1[4];
CountDelta;
if abs(Delta) < MaxDeltaDDWY then
Result := False;
end
else if MeterType = '锚索测力计' then
begin
Delta := V2[1] - V1[1];
CountDelta;
if abs(Delta) < MaxDeltaMS then
Result := False;
end
else if MeterType = '锚杆应力计' then
begin
Delta := V2[1] - V1[1];
CountDelta;
if abs(Delta) < MaxDeltaMG then
Result := False;
end
else if MeterType = '渗压计' then
begin
Delta := V2[1] - V1[1];
CountDelta;
if abs(Delta) < MaxDeltaSY then
Result := False;
end
else if MeterType = '基岩变形计' then
begin
Delta := V2[1] - V1[1];
CountDelta;
if abs(Delta) < MaxDeltaDDWY then
Result := False;
end;
end;
// 只显示一次数据
procedure ShowOneData;
begin
end;
// 显示两次数据
procedure ShowTwoData;
var
DataRow: array of variant;
i : Integer;
begin
// 如果不值一提就继续下一个
if not _NeedShow then
Exit;
Inc(iOverLine); // 多个超限的
WCV.Reset;
WCV.ColCount := Length(V1); //
WCV.TitleRows := 1;
SetLength(DataRow, WCV.ColCount);
DataRow[0] := '观测日期';
for i := 0 to Meter.PDDefines.Count - 1 do
DataRow[i + 1] := Meter.PDName(i);
WCV.AddRow(DataRow);
DataRow[0] := FormatDateTime('yyyy-mm-dd', V1[0]);
for i := 1 to High(V1) do
DataRow[i] := V1[i];
WCV.AddRow(DataRow);
DataRow[0] := FormatDateTime('yyyy-mm-dd', V2[0]);
for i := 1 to High(V2) do
DataRow[i] := V2[i];
WCV.AddRow(DataRow);
DataRow[0] := '增量';
for i := 1 to High(V2) do
DataRow[i] := V2[i] - V1[i];
WCV.AddRow(DataRow);
Body := Body + '<h3>' + Meter.Params.MeterType + '<a href="PopGraph:' +
Meter.DesignName + '">' + Meter.DesignName + '</a>' + '</h3>' + WCV.CrossGrid;
end;
begin
if ExcelMeters.Count = 0 then
Exit;
// Body := '';
Body := '<h2>测值增量超过关注阈值的仪器:</h2>'
+ Format('<div>多点位移计限差:%fmm;锚索测力计限差:%fkN;锚杆应力计限差:%fkN</div>',
[MaxDeltaDDWY, MaxDeltaMS, MaxDeltaMG]);
iInc := 0;
iDec := 0;
iOverLine := 0;
MTList := TStringList.Create;
try
// 准备仪器列表
if chkAllMeters.Checked then
for i := 0 to ExcelMeters.Count - 1 do
MTList.Add(ExcelMeters.Items[i].DesignName)
else
begin
with IAppServices.FuncDispatcher as IFunctionDispatcher do
begin
// 如果能选择部分仪器则
if HasProc('PopupMeterSelector') then
CallFunction('PopupMeterSelector', MTList)
else // 否则选择全部仪器
begin
for i := 0 to ExcelMeters.Count - 1 do
MTList.Add(ExcelMeters.Items[i].DesignName)
end;
end;
end;
Screen.Cursor := crHourGlass;
ProgressBar.Max := { ExcelMeters.Count } MTList.Count;
ProgressBar.Min := 1;
ProgressBar.Position := 1;
lblDesignName.Caption := '';
lblProgress.Caption := '';
pnlProgress.Visible := True;
pnlProgress.Left := (Self.Width - pnlProgress.Width) div 2;
pnlProgress.Top := (Self.Height - pnlProgress.Height) div 2;
WCV := TWebCrossView.Create;
for iMeter := 0 to { ExcelMeters.Count } MTList.Count - 1 do
begin
// Meter := ExcelMeters.Items[iMeter];
Meter := ExcelMeters.Meter[MTList.Strings[iMeter]];
MeterType := Meter.Params.MeterType;
ProgressBar.Position := iMeter + 1;
lblDesignName.Caption := Meter.Params.MeterType + Meter.DesignName;
lblProgress.Caption := Format('正在处理第%d支仪器,共%d支', [iMeter + 1, { ExcelMeters } MTList.Count]);
IAppServices.ProcessMessages;
if IAppServices.ClientDatas.GetLastPDDatas(Meter.DesignName, V2) then
begin
if IAppServices.ClientDatas.GetLastPDDatasBeforeDate(Meter.DesignName, V2[0], V1)
then
begin
ShowTwoData;
end
else
ShowOneData; // 没有完成这个方法,没有考虑好如何显示单次数据
Inc(iMeterCount);
end;
end;
// 显示增减数量
Body := Body + Format('<hr>本次测值增量超过关注阈值的仪器有%d支,其余仪器观测数据变化较小。<br>', [iOverLine]);
Body := Body + Format('在最近两次观测中,有%d支仪器(传感器)数据增大,有%d支仪器数据减小。', [iInc, iDec]);
Page := StringReplace(htmPageCode2, '@PageContent@', Body, []);
if chkUseIE.Checked then
begin
wbViewer.Visible := True;
HtmlViewer.Visible := False;
WB_LoadHTML(wbViewer, Page);
end
else
begin
HtmlViewer.Visible := True;
wbViewer.Visible := False;
HtmlViewer.LoadFromString(Page);
end;
finally
MTList.Free;
WCV.Free;
pnlProgress.Visible := False;
Screen.Cursor := crDefault;
end;
end;
procedure TfraQuickViewer.wbViewerBeforeNavigate2(ASender: TObject; const pDisp: IDispatch;
const URL, Flags, TargetFrameName, PostData, Headers: OleVariant; var Cancel: WordBool);
var
s, cmd, sName: String;
i : Integer;
begin
s := VarToStr(URL);
if Pos('about', s) > 0 then // 加载空页面
Cancel := False
else if Pos('popgraph', s) > 0 then
begin
i := Pos(':', s);
cmd := Copy(s, 1, i - 1);
sName := Copy(s, i + 1, Length(s) - 1);
// ShowMessage('Hot link: ' + s);
if cmd = 'popgraph' then
(IAppServices.FuncDispatcher as IFunctionDispatcher).PopupDataGraph(sName);
Cancel := True;
end;
end;
{ -----------------------------------------------------------------------------
Procedure : ShowDataIncrement
Description: 本方法查询全部仪器在指定时间的观测数据增量及月增量,并在HTMLViewer
中显示出来。如果UseFilter=True,则过滤掉变化较小的数据,只保留变化大的。
----------------------------------------------------------------------------- }
procedure TfraQuickViewer.btnDateSelectedClick(Sender: TObject);
begin
pnlDateSelector.Visible := False;
ShowSpecificDatesData;
end;
procedure TfraQuickViewer.btnShowIncrementClick(Sender: TObject);
begin
ShowDataIncrement(chkUseFilter.Checked);
end;
{ -----------------------------------------------------------------------------
Procedure : btnSpecificDatesClick
Description: 显示指定日期的两次观测数据,及其增量
----------------------------------------------------------------------------- }
procedure TfraQuickViewer.btnSpecificDatesClick(Sender: TObject);
begin
pnlDateSelector.Visible := True;
pnlDateSelector.Left := (Self.Width - pnlDateSelector.Width) div 2;
pnlDateSelector.Top := (Self.Height - pnlDateSelector.Height) div 2;
end;
{ -----------------------------------------------------------------------------
Procedure : HtmlViewerHotSpotClick
Description: 点击仪器编号超链接,弹出该仪器的过程线或其他类型数据图
----------------------------------------------------------------------------- }
procedure TfraQuickViewer.HtmlViewerHotSpotClick(Sender: TObject; const SRC: string;
var Handled: Boolean);
var
cmd, s: string;
i : Integer;
begin
// ShowMessage(src);
i := Pos(':', SRC);
cmd := Copy(SRC, 1, i - 1);
s := Copy(SRC, i + 1, Length(SRC) - i);
// ShowMessage(s);
if cmd = 'PopGraph' then
(IAppServices.FuncDispatcher as IFunctionDispatcher).PopupDataGraph(s);;
end;
procedure TfraQuickViewer.miCopyClick(Sender: TObject);
begin
HtmlViewer.SelectAll;
HtmlViewer.CopyToClipboard;
HtmlViewer.SelLength := 0;
end;
procedure TfraQuickViewer.miPrintClick(Sender: TObject);
begin
with dlgPrint do
if Execute then
if PrintRange = prAllPages then
HtmlViewer.Print(1, 9999)
else
HtmlViewer.Print(FromPage, ToPage);
end;
procedure TfraQuickViewer.miSaveClick(Sender: TObject);
var
strs: TStrings;
begin
with dlgSave do
if Execute then
begin
strs := TStringList.Create;
try
strs.Text := HtmlViewer.DocumentSource;
strs.SaveToFile(dlgSave.FileName);
finally
strs.Free;
end;
end;
end;
procedure TfraQuickViewer.ShowDataIncrement(UseFilter: Boolean = False);
var
{ MTList: TStrings; }
Meter : TMeterDefine;
iMeter: Integer;
i : Integer;
iCount: Integer;
WCV : TWebCrossView;
V : TVariantDynArray;
vH : array of variant;
Body : String;
Page : String;
sType : string;
sPos : String;
k : Integer; // 特征值项的序号;
kIdx : set of Byte; // 特征值序号集合,假设特征值项不超过127个。
procedure ClearValues;
var
ii: Integer;
begin
SetLength(vH, 0);
if Length(V) > 0 then
for ii := 0 to High(V) do
VarClear(V[ii]);
SetLength(V, 0);
end;
procedure SetGrid;
var
ii: Integer;
begin
WCV.TitleRows := 1;
WCV.ColCount := 8;
WCV.ColHeader[0].AllowColSpan := True;
WCV.ColHeader[1].AllowColSpan := True;
WCV.ColHeader[0].AllowRowSpan := True;
WCV.ColHeader[3].Align := taCenter;
WCV.ColHeader[4].Align := taCenter;
for ii := 5 to 7 do
WCV.ColHeader[ii].Align := taRightJustify;
SetLength(vH, 8);
vH[0] := '仪器类型';
vH[1] := '设计编号';
vH[2] := '物理量';
vH[3] := '观测日期';
vH[4] := '间隔天数';
vH[5] := '当前测值';
vH[6] := '最新增量';
vH[7] := '最近30天增量';
WCV.AddRow(vH);
end;
function IgnoreData(AData: variant; ALimit: Double): Boolean;
begin
Result := True;
if VarIsEmpty(AData) or VarIsNull(AData) then
Exit;
if abs(AData) >= ALimit then
Result := False;
end;
begin
HtmlViewer.Clear;
if chkUseIE.Checked then
begin
HtmlViewer.Visible := False;
wbViewer.Visible := True;
wbViewer.Align := alClient;
end
else
begin
HtmlViewer.Visible := True;
wbViewer.Visible := False;
end;
{ MTList := TStringList.Create; }
if ExcelMeters.Count = 0 then
Exit;
Body := '<h2>观测数据变化情况表</h2>';
WCV := TWebCrossView.Create;
// 如果不是按仪器类型分表,则SetGrid。按类型分表是在遇到新仪器类型的时候才SetGrid,若在此处
// SetGrid将造成只有表头的空表。
if not chkTableByType.Checked then SetGrid;
sType := '';
sPos := '';
IHJXClientFuncs.SessionBegin;
// 准备仪器列表
if chkAllMeters.Checked then
begin
FMeterList.Clear;
for i := 0 to ExcelMeters.Count - 1 do
{ MTList } FMeterList.Add(ExcelMeters.Items[i].DesignName)
end
else
begin
with IAppServices.FuncDispatcher as IFunctionDispatcher do
begin
// 如果能选择部分仪器则
if HasProc('PopupMeterSelector') then
CallFunction('PopupMeterSelector', { MTList } FMeterList)
else // 否则选择全部仪器
begin
for i := 0 to ExcelMeters.Count - 1 do
{ MTList } FMeterList.Add(ExcelMeters.Items[i].DesignName)
end;
end;
end;
try
Screen.Cursor := crHourGlass;
ProgressBar.Position := 1;
ProgressBar.Max := { MTList } FMeterList.Count; // ExcelMeters.Count;
lblProgress.Caption := '';
lblDesignName.Caption := '';
iCount := { MTList } FMeterList.Count; // ExcelMeters.Count;
pnlProgress.Visible := True;
// sPos := ExcelMeters.Items[0].PrjParams.Position;
sPos := ExcelMeters.Meter[ { MTList } FMeterList.Strings[0]].PrjParams.Position;
Body := Body + '<h3>' + sPos + '</h3>';
for iMeter := 0 to { ExcelMeters.Count - 1 } { MTList } FMeterList.Count - 1 do
begin
// Meter := ExcelMeters.Items[iMeter];
Meter := ExcelMeters.Meter[ { MTList } FMeterList.Strings[iMeter]];
lblDesignName.Caption := Meter.DesignName;
lblProgress.Caption := Format('正在处理第%d支,共%d支', [iMeter, iCount]);
ProgressBar.Position := iMeter;
IAppServices.ProcessMessages;
if Meter.PrjParams.Position <> sPos then
begin
sPos := Meter.PrjParams.Position;
Body := Body + WCV.CrossGrid;
Body := Body + '<h3>' + sPos + '</h3>';
// 若不是按类型分表,则就是按部位分表
if not chkTableByType.Checked then
begin
WCV.Reset;
SetGrid;
end;
sType := '';
end;
if Meter.Params.MeterType = '测斜孔' then
Continue;
if Meter.Params.MeterType <> sType then
begin
if chkTableByType.Checked then
begin
// 当stype =''时,说明已经是另一个部位的仪器了,此时WCV内容已经在添加部位标题之前添加到
// Body了,再添加表格就会在部位标题下面显示一个重复的表格。
if sType <> '' then
Body := Body + WCV.CrossGrid;
Body := Body + '<h4>' + Meter.Params.MeterType + '</h4>';
WCV.Reset;
SetGrid;
end
else
WCV.AddCaptionRow([Meter.Params.MeterType]);
sType := Meter.Params.MeterType;
end;
{ 查询仪器数据增量 }
{ 2019-07-31 查询增量的方法已经改为查询仪器带有特征值标记的物理量项目 }
if IHJXClientFuncs.GetDataIncrement(Meter.DesignName, Now, V) then
begin
{ todo:改变这个愚蠢的方法,将定义写到配置文件中去 }
(*
if (sType = '锚索测力计') or (sType = '锚杆应力计') or (sType = '渗压计') or (sType = '基岩变形计')
or (sType = '测缝计') or (sType = '裂缝计') or (sType = '位错计') or (sType = '钢筋计')
or (sType = '钢板计') or (sType = '水位计') or (sType = '水位') or (sType = '量水堰')
or (sType = '应变计') or (sType = '无应力计') then
begin
if UseFilter then
if sType = '锚索测力计' then
begin
if IgnoreData(V[0][4], MaxDeltaMS) and IgnoreData(V[0][5], MaxDeltaMS)
then
Continue
end
else if sType = '锚杆应力计' then
begin
if IgnoreData(V[0][4], MaxDeltaMG) and IgnoreData(V[0][5], MaxDeltaMG)
then
Continue;
end
else if sType = '渗压计' then
begin
if IgnoreData(V[0][4], MaxDeltaSY) and IgnoreData(V[0][5], MaxDeltaSY) then
Continue;
end
else if sType = '基岩变形计' then
begin
if IgnoreData(V[0][4], MaxDeltaDDWY) and IgnoreData(V[0][5], MaxDeltaDDWY) then
Continue;
end;
vH[0] := sType;
vH[1] := '<a href="PopGraph:' + Meter.DesignName + '">' +
Meter.DesignName + '</a>';
vH[2] := Meter.PDName(0);
vH[3] := FormatDateTime('yyyy-mm-dd', V[0][1]);
vH[4] := V[0][2];
vH[5] := V[0][3];
vH[6] := V[0][4];
vH[7] := V[0][5];
WCV.AddRow(vH);
end
else if sType = '多点位移计' then
begin
for i := Low(V) to High(V) do
begin
if UseFilter then
if IgnoreData(V[i][4], MaxDeltaDDWY) and
IgnoreData(V[i][5], MaxDeltaDDWY)
then
Continue;
vH[0] := sType;
vH[1] := '<a href="PopGraph:' + Meter.DesignName + '">' +
Meter.DesignName + '</a>';
vH[2] := Meter.PDName(i);
vH[3] := FormatDateTime('yyyy-mm-dd', V[i][1]);
vH[4] := V[i][2];
vH[5] := V[i][3];
vH[6] := V[i][4];
vH[7] := V[i][5];
WCV.AddRow(vH);
end;
end
else if sType = '平面位移测点' then
begin
for i := Low(V) to High(V) do
begin
vH[0] := sType;
vH[1] := '<a href="PopGraph:' + Meter.DesignName + '">' +
Meter.DesignName + '</a>';
vH[2] := V[i][0]; // Meter.PDName(i);
vH[3] := FormatDateTime('yyyy-mm-dd', V[i][1]);
vH[4] := V[i][2];
vH[5] := V[i][3];
vH[6] := V[i][4];
vH[7] := V[i][5];
WCV.AddRow(vH);
end;
end;
*)
{ 2019-07-31 因增量查询方法已经改为查询具有特征值标记的物理量,因此这里也修改为列出具备特征值
标记的物理量,暂时不考虑过滤小变化量的情况。关于查询的结果V,参见uHJX.Excel.DataQuery单元中的
GetDataIncrement方法中的定义 }
k := 0;
kIdx := [];
for i := 0 to Meter.PDDefines.Count - 1 do
if Meter.PDDefine[i].HasEV then
begin
Inc(k);
include(kIdx, i);
end;
if k > 0 then
begin
i := 0;
for k in kIdx do
begin
vH[0] := sType;
vH[1] := '<a href="PopGraph:' + Meter.DesignName + '">' +
Meter.DesignName + '</a>';
vH[2] := V[i][0]; // 物理量名
vH[3] := FormatDateTime('yyyy-mm-dd', V[i][1]);
vH[4] := V[i][2]; // 间隔日期
vH[5] := V[i][3]; // 最后测值
vH[6] := V[i][4]; // 与上次测值的增量
vH[7] := V[i][5]; // 30日增量
WCV.AddRow(vH);
Inc(i);
end;
end;
end;
end;
Body := Body + WCV.CrossGrid;
Page := StringReplace(htmPageCode2, '@PageContent@', Body, []);
if chkUseIE.Checked then
WB_LoadHTML(wbViewer, Page)
else
HtmlViewer.LoadFromString(Page);
finally
{ MTList.Free; }
WCV.Free;
ClearValues;
IHJXClientFuncs.SessionEnd;
Screen.Cursor := crDefault;
pnlProgress.Visible := False;
end;
end;
{ -----------------------------------------------------------------------------
Procedure : ShowSpecificDatesData
Description: 显示两个指定日期的观测数据,及其增量
----------------------------------------------------------------------------- }
procedure TfraQuickViewer.ShowSpecificDatesData;
var
WCV : TWebCrossView;
Meter: TMeterDefine;
i, j : Integer;
k : Integer;
kIdx : Set of Byte;
V, V1: TDoubleDynArray;
vH : array of variant;
dt1, dt2, d1, d2 : Double;
sPage, sBody, sType, sPos: string;
procedure _ClearValues;
var
ii: Integer;
begin
for ii := Low(vH) to High(vH) do VarClear(vH[ii]);
end;
procedure _SetGrid;
var
ii: Integer;
begin
WCV.TitleRows := 2;
if chkSimpleSDGrid.Checked then
begin
WCV.ColCount := 5;
WCV.ColHeader[4].AllowRowSpan := True;
WCV.ColHeader[0].AllowColSpan := True;
for ii in [2, 3, 4] do WCV.ColHeader[ii].Align := taRightJustify;
SetLength(vH, 5);
vH[0] := '设计编号';
vH[1] := '物理量';
for ii := 2 to 3 do vH[ii] := '观测数据';
vH[4] := '增量';
WCV.AddRow(vH);
vH[2] := '%dt1%'; // 第一个日期
vH[3] := '%dt2%'; // 第二个日期
WCV.AddRow(vH);
end
else
begin
WCV.ColCount := 9;
WCV.ColHeader[6].AllowRowSpan := True;
WCV.ColHeader[0].AllowColSpan := True;
WCV.ColHeader[2].AllowColSpan := True;
WCV.ColHeader[4].AllowColSpan := True;
WCV.ColHeader[3].Align := taRightJustify;
for ii in [3, 5, 6, 7, 8] do WCV.ColHeader[ii].Align := taRightJustify;
SetLength(vH, 9);
vH[0] := '设计编号';
vH[1] := '物理量';
for ii := 2 to 5 do vH[ii] := '观测数据';
vH[6] := '增量';
vH[7] := '日期间隔';
vH[8] := '变化速率';
WCV.AddRow(vH);
vH[2] := '日期1';
vH[3] := '测值';
vH[4] := '日期2';
vH[5] := '测值';
WCV.AddRow(vH);
end;
end;
begin
if ExcelMeters.Count = 0 then Exit;
if chkUseIE.Checked then
begin
HtmlViewer.Visible := False;
wbViewer.Visible := True;
wbViewer.Align := alClient;
end
else
begin
HtmlViewer.Visible := True;
wbViewer.Visible := False;
end;
// 选择仪器
if chkAllMeters.Checked then
begin
FMeterList.Clear;
for i := 0 to ExcelMeters.Count - 1 do
FMeterList.Add(ExcelMeters.Items[i].DesignName);
end
else
with IAppServices.FuncDispatcher as IFunctionDispatcher do
if HasProc('PopupMeterSelector') then
CallFunction('PopupMeterSelector', FMeterList);
if FMeterList.Count = 0 then
begin
ShowMessage('没有选择监测仪器');
Exit;
end;
// 准备表格对象
IAppServices.ClientDatas.SessionBegin;
if chkSimpleSDGrid.Checked then SetLength(vH, 5)
else SetLength(vH, 9);
WCV := TWebCrossView.Create;
_SetGrid;
sType := '';
sPos := ExcelMeters.Meter[FMeterList[0]].PrjParams.Position;
sBody := '<h3>' + sPos + '</h3>';
try
// 准备仪器数据,及填写内容
for i := 0 to FMeterList.Count - 1 do
begin
Meter := ExcelMeters.Meter[FMeterList[i]];
if Meter.DataSheet = '' then Continue;
// 部位处理
if Meter.PrjParams.Position <> sPos then
begin
sPos := Meter.PrjParams.Position;
sBody := sBody + WCV.CrossGrid + #13#10'<h3>' + sPos + '</h3>'#13#10;
WCV.Reset;
_SetGrid;
end;
if Meter.Params.MeterType = '测斜孔' then Continue;
// 类型检查、处理
if Meter.Params.MeterType <> sType then
begin
sType := Meter.Params.MeterType;
WCV.AddCaptionRow([sType]);
end;
(*
// 准备数据
if Meter.Params.MeterType = '多点位移计' then
begin
_ClearValues;
vH[0] := '<a href="PopGraph:' + Meter.DesignName + '">' + Meter.DesignName + '</a>';
IAppServices.ClientDatas.GetNearestPDDatas(FMeterList[i], dtp1.Date, V);
IAppServices.ClientDatas.GetNearestPDDatas(FMeterList[i], dtp2.Date, V1);
if V[0] = 0 then Continue;
dt1 := V[0];
dt2 := V1[0];
vH[2] := FormatDateTime('yyyy-mm-dd', dt1);
vH[4] := FormatDateTime('yyyy-mm-dd', dt2);
vH[7] := dt2 - dt1;
// 第一点
// vH[1] := Meter.PDName(0);
// vH[3] := V[1];
// vH[5] := V1[1];
// vH[6] := V1[1] - V[1];
// if dt2 - dt1 <> 0 then vH[8] := (V1[1] - V[1]) / (dt2 - dt1);
// WCV.AddRow(vH);
for j := 0 to 3 do
begin
vH[1] := Meter.PDName(j);
vH[3] := V[j + 1];
vH[5] := V1[j + 1];
vH[6] := V1[j + 1] - V[j + 1];
if dt2 - dt1 <> 0 then vH[8] := (V1[j + 1] - V[j + 1]) / (dt2 - dt1);
WCV.AddRow(vH);
end;
end
else if Meter.Params.MeterType = '平面位移测点' then
begin
_ClearValues;
vH[0] := '<a href="PopGraph:' + Meter.DesignName + '">' + Meter.DesignName + '</a>';
IAppServices.ClientDatas.GetNearestPDDatas(FMeterList[i], dtp1.Date, V);
IAppServices.ClientDatas.GetNearestPDDatas(FMeterList[i], dtp2.Date, V1);
if V[0] = 0 then Continue;
dt1 := V[0];
dt2 := V1[0];
vH[2] := FormatDateTime('yyyy-mm-dd', dt1);
vH[4] := FormatDateTime('yyyy-mm-dd', dt2);
vH[7] := dt2 - dt1; // 日期间隔
{ 平面位移测点只比较本地坐标和高程的差值 }
for j in [11, 12, 8] do
begin
vH[1] := Meter.PDName(j);
vH[3] := V[j + 1];
vH[5] := V1[j + 1];
vH[6] := V1[j + 1] - V[j + 1];
if dt2 - dt1 <> 0 then vH[8] := (V1[j + 1] - V[j + 1]) / (dt2 - dt1);
WCV.AddRow(vH);
end;
end
else
begin
_ClearValues;
// 读第一次数据
IAppServices.ClientDatas.GetNearestPDDatas(FMeterList[i], dtp1.Date, V);
if V[0] = 0 then Continue;
vH[2] := FormatDateTime('yyyy-mm-dd', V[0]);
vH[3] := V[1];
dt1 := V[0];
d1 := V[1];
// 读第二次数据
IAppServices.ClientDatas.GetNearestPDDatas(FMeterList[i], dtp2.Date, V);
vH[4] := FormatDateTime('yyyy-mm-dd', V[0]);
vH[5] := V[1];
dt2 := V[0];
d2 := V[1];
// 填入
vH[0] := '<a href="PopGraph:' + Meter.DesignName + '">' + Meter.DesignName + '</a>';
// Meter.DesignName;
vH[1] := Meter.PDName(0);
// vH[2] := dtp1.DateTime;
// vH[4] := dtp2.DateTime;
vH[6] := d2 - d1;
vH[7] := dt2 - dt1;
if d2 - d1 <> 0 then
vH[8] := (d2 - d1) / (dt2 - dt1)
else
vH[8] := '';
WCV.AddRow(vH);
end;
*)
{ 2019-07-31采用列出特征值项的方式创建表格,即仪器的特征值量都列入数据查询之中 }
_ClearValues;
// 下面的代码查询和统计仪器的特征值项数量,并将PD序号填入kIdx集合
j := 0;
kIdx := [];
for k := 0 to Meter.PDDefines.Count - 1 do
if Meter.PDDefine[k].HasEV then
begin
Inc(j);
include(kIdx, k);
end;
{ 当仪器的特征值项不为零,则创建表格 }
if j > 0 then
begin
vH[0] := '<a href="PopGraph:' + Meter.DesignName + '">' + Meter.DesignName + '</a>';
// 查询数据
IAppServices.ClientDatas.GetNearestPDDatas(FMeterList[i], dtp1.Date, V);
IAppServices.ClientDatas.GetNearestPDDatas(FMeterList[i], dtp2.Date, V1);
if V[0] = 0 then Continue;
dt1 := V[0];
dt2 := V1[0];
if not chkSimpleSDGrid.Checked then
begin
vH[2] := FormatDateTime('yyyy-mm-dd', dt1);
vH[4] := FormatDateTime('yyyy-mm-dd', dt2);
vH[7] := dt2 - dt1; // 日期间隔
end;
for j in kIdx do // 逐个添加特征值数据行
begin
vH[1] := Meter.PDName(j);
if chkSimpleSDGrid.Checked then
begin
vH[2] := V[j + 1];
vH[3] := V1[j + 1];
vH[4] := V1[j + 1] - V[j + 1];
end
else
begin
vH[3] := V[j + 1];
vH[5] := V1[j + 1];
vH[6] := V1[j + 1] - V[j + 1];
if dt2 - dt1 <> 0 then vH[8] := (V1[j + 1] - V[j + 1]) / (dt2 - dt1);
end;
WCV.AddRow(vH);
end;
end;
end;
// 显示结果
sBody := sBody + WCV.CrossGrid;
if chkSimpleSDGrid.Checked then
begin
sBody := StringReplace(sBody, '%dt1%', FormatDateTime('yyyy-mm-dd', dt1), []);
sBody := StringReplace(sBody, '%dt2%', FormatDateTime('yyyy-mm-dd', dt2), []);
end;
sPage := StringReplace(htmPageCode2, '@PageContent@', sBody, []);
if chkUseIE.Checked then
WB_LoadHTML(wbViewer, sPage)
else
HtmlViewer.LoadFromString(sPage);
finally
SetLength(vH, 0);
WCV.Free;
Screen.Cursor := crDefault;
pnlProgress.Visible := False;
IAppServices.ClientDatas.SessionEnd;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ XML Document Support }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit XSLProd;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Web.HTTPApp, Web.HTTPProd, Xml.XMLDoc, Xml.xmldom, Xml.XMLIntf,
WebComp;
{$ENDIF}
{$IFDEF LINUX}
SysUtils, Classes, HTTPApp, HTTPProd, XMLDoc, xmldom, XMLIntf,
WebComp;
{$ENDIF}
type
TCustomXSLPageProducer = class(TXMLDocument, IProduceContent, IProduceContentFrom,
ISetAppDispatcher, IGetAppDispatcher, IProducerEditorViewSupport,
IGetProducerTemplate)
private
FXMLData: TComponent;
FDispatcher: TComponent;
procedure SetXMLData(const Value: TComponent);
function GetXSLStream(var AOwned: Boolean): TStream;
function GetDispatcher: IWebDispatcherAccess;
procedure SetDispatcher(Value: TComponent);
protected
function GetXMLDocument(out AXMLDocument: IXMLDocument): Boolean;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function GetTemplateStream(out AOwned: Boolean): TStream;
{ IGetProducerTemplate }
function GetProducerTemplateStream(out AOwned: Boolean): TStream;
function GetProducerTemplateFileName: string;
{ IProducerEditorViewSupport }
function HasScriptView: Boolean;
function HasXMLBrowserView: Boolean;
function HasXSLBrowserView: Boolean;
function HasHTMLBrowserView: Boolean;
function GetXMLData(var Owned: Boolean): TStream;
function GetXSLData(var Owned: Boolean): TStream;
function GetTemplateFileType: string;
{ ISetAppDispatcher }
procedure SetAppDispatcher(const ADispatcher: TComponent);
{ IGetAppDispatcher }
function GetAppDispatcher: TComponent;
{ IProduceContent }
function ProduceContent: string;
{ IProduceContentFrom }
function ProduceContentFromStream(Stream: TStream): string;
function ProduceContentFromString(const S: string): string;
public
function ContentFromString(const S: string): string;
function ContentFromStream(InStream: TStream): string; virtual;
function Content: string; virtual;
function ContentFromWideString(const S: WideString): string; virtual;
property Dispatcher: IWebDispatcherAccess read GetDispatcher;
property DispatcherComponent: TComponent read FDispatcher;
property XMLData: TComponent read FXMLData write SetXMLData;
end;
TXSLPageProducer = class(TCustomXSLPageProducer)
published
property XMLData;
end;
EXSLPageProducerError = class(EWebBrokerException)
end;
implementation
uses SiteConst;
function ExtractAttrValue(const AttrName, AttrLine: string;
const Default: DOMString = ''): DOMString;
var
P: PChar;
LineLen, ItemPos: Integer;
begin
ItemPos := Pos(AttrName, AttrLine);
LineLen := Length(AttrLine);
if ItemPos > 0 then
begin
Inc(ItemPos, Length(AttrName));
while (ItemPos < LineLen) and not (AnsiChar(AttrLine[ItemPos]) in ['''','"']) do
Inc(ItemPos);
if ItemPos < LineLen then
begin
P := PChar(AttrLine)+ItemPos-1;
Result := AnsiExtractQuotedStr(P, P^);
end;
end
else
Result := Default;
end;
procedure RaiseXSLPageProducerError(const Msg: string); overload;
begin
raise EXSLPageProducerError.Create(Msg);
end;
procedure RaiseNoXMLDocument;
begin
RaiseXSLPageProducerError(sNoXMLDocument);
end;
procedure RaiseNoXMLData;
begin
RaiseXSLPageProducerError(sNoXMLData);
end;
{ TCustomXSLPageProducer }
function TCustomXSLPageProducer.ContentFromStream(InStream: TStream): string;
var
XMLDocument: IXMLDocument;
W: WideString;
begin
if XMLData = nil then
RaiseNoXMLData;
if GetXMLDocument(XMLDocument) then
begin
Self.LoadFromStream(InStream);
XMLDocument.Active := True;
if Self.DocumentElement = nil then
RaiseNoXMLDocument
else if XMLDocument.Node = nil then
RaiseNoXMLData;
XMLDocument.Node.TransformNode(Self.DocumentElement, W);
Result := W;
end
else
RaiseNoXMLDocument;
end;
function TCustomXSLPageProducer.GetTemplateStream(out AOwned: Boolean): TStream;
begin
Result := GetXSLStream(AOwned);
end;
function TCustomXSLPageProducer.GetXSLStream(var AOwned: Boolean): TStream;
begin
if FileName <> '' then
begin
AOwned := True;
Result := nil;
if DesignerFileManager <> nil then
Result := DesignerFileManager.GetStream(FileName, AOwned);
if Result = nil then
Result := TFileStream.Create(QualifyFileName(FileName), fmOpenRead or fmShareDenyNone);
end
else
begin
Result := TMemoryStream.Create;
SaveToStream(Result);
end;
AOwned := True;
end;
procedure TCustomXSLPageProducer.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then
begin
if AComponent = FXMLData then
FXMLData := nil;
if AComponent = FDispatcher then
FDispatcher := nil;
end;
end;
procedure TCustomXSLPageProducer.SetXMLData(const Value: TComponent);
begin
if FXMLData <> Value then
begin
FXMLData := Value;
if Value <> nil then
Value.FreeNotification(Self);
end;
end;
procedure TCustomXSLPageProducer.SetDispatcher(Value: TComponent);
begin
if FDispatcher <> Value then
begin
if Value <> nil then Value.FreeNotification(Self);
FDispatcher := Value;
end;
end;
function TCustomXSLPageProducer.Content: string;
var
W: WideString;
XMLDocument: IXMLDocument;
begin
if XMLData = nil then
RaiseNoXMLData;
if GetXMLDocument(XMLDocument) then
begin
Self.Active := True;
if XMLDocument.Node = nil then
RaiseNoXMLData
else if XMLDocument.DocumentElement.ParentNode = nil then
RaiseNoXMLData
else if DocumentElement = nil then
RaiseNoXMLDocument;
XMLDocument.DocumentElement.ParentNode.TransformNode(Self.DocumentElement, W);
Result := W;
end
else
RaiseNoXMLDocument;
end;
procedure TCustomXSLPageProducer.SetAppDispatcher(
const ADispatcher: TComponent);
begin
SetDispatcher(ADispatcher);
end;
function TCustomXSLPageProducer.GetDispatcher: IWebDispatcherAccess;
begin
if Assigned(FDispatcher) then
Supports(IInterface(FDispatcher), IWebDispatcherAccess, Result)
else
Result := nil;
end;
function TCustomXSLPageProducer.ProduceContent: string;
begin
Result := Content;
end;
function TCustomXSLPageProducer.ProduceContentFromStream(
Stream: TStream): string;
begin
Result := ContentFromStream(Stream);
end;
function TCustomXSLPageProducer.ProduceContentFromString(
const S: string): string;
begin
Result := ContentFromString(S);
end;
function TCustomXSLPageProducer.GetAppDispatcher: TComponent;
begin
Result := FDispatcher;
end;
function TCustomXSLPageProducer.ContentFromString(const S: string): string;
var
Temp: TStream;
begin
Temp := TStringStream.Create(S);
try
Result := ContentFromStream(Temp)
finally
Temp.Free;
end;
end;
function TCustomXSLPageProducer.ContentFromWideString(const S: WideString): string;
var
XMLDocument: IXMLDocument;
W: WideString;
begin
if XMLData = nil then
RaiseNoXMLData;
if GetXMLDocument(XMLDocument) then
begin
Self.LoadFromXML(S);
Active := True;
XMLDocument.Active := True;
if Self.DocumentElement = nil then
RaiseNoXMLDocument;
XMLDocument.Node.TransformNode(Self.DocumentElement, W);
Result := W;
end
else
RaiseNoXMLDocument;
end;
function TCustomXSLPageProducer.GetXMLDocument(out AXMLDocument: IXMLDocument): Boolean;
var
Stream: TStream;
Owned: Boolean;
begin
Result := Supports(IUnknown(XMLData), IXMLDocument, AXMLDocument);
if Result then
if (csDesigning in ComponentState) and (AXMLDocument.FileName <> '') then
begin
// Load the file when designing
Result := False;
AXMLDocument := nil;
end;
if not Result then
begin
Owned := False;
Stream := GetXMLData(Owned);
if Stream <> nil then
try
AXMLDocument := TXMLDocument.Create('');
try
AXMLDocument.LoadFromStream(Stream);
except
FreeAndNil(AXMLDocument);
raise;
end;
Result := AXMLDocument <> nil;
finally
if Owned then
Stream.Free;
end;
end;
end;
function TCustomXSLPageProducer.HasScriptView: Boolean;
begin
Result := False;
end;
function TCustomXSLPageProducer.HasXMLBrowserView: Boolean;
begin
Result := True;
end;
function TCustomXSLPageProducer.GetXMLData(var Owned: Boolean): TStream;
var
XMLDocument: IXMLDocument;
GetXMLStream: IGetXMLStream;
begin
if Supports(IUnknown(XMLData), IGetXMLStream, GetXMLStream) then
Result := GetXMLStream.GetXMLStream(Owned)
else if Supports(IUnknown(XMLData), IXMLDocument, XMLDocument) then
begin
if (XMLDocument.FileName <> '') and (csDesigning in ComponentState) then
begin
// Load the file when designing
Owned := True;
Result := nil;
if DesignerFileManager <> nil then
Result := DesignerFileManager.GetStream(XMLDocument.FileName, Owned);
if Result = nil then
Result := TFileStream.Create(QualifyFileName(XMLDocument.FileName), fmOpenRead or fmShareDenyNone);
end
else
begin
Owned := True;
Result := TMemoryStream.Create;
try
SaveToStream(Result);
except
FreeAndNil(Result);
raise;
end;
end;
end
else
Result := nil;
end;
function TCustomXSLPageProducer.GetXSLData(var Owned: Boolean): TStream;
begin
Self.Active := True;
Owned := True;
Result := TMemoryStream.Create;
try
Self.SaveToStream(Result);
except
Result.Free;
raise;
end;
end;
function TCustomXSLPageProducer.HasHTMLBrowserView: Boolean;
begin
Result := True;
end;
function TCustomXSLPageProducer.HasXSLBrowserView: Boolean;
begin
Result := True;
end;
function TCustomXSLPageProducer.GetTemplateFileType: string;
begin
Result := 'XSL';
end;
function TCustomXSLPageProducer.GetProducerTemplateFileName: string;
begin
Result := FileName;
end;
function TCustomXSLPageProducer.GetProducerTemplateStream(
out AOwned: Boolean): TStream;
begin
Result := GetXSLStream(AOwned);
end;
end.
|
unit Devices.TR101;
interface
uses Windows, GMConst, Devices.Modbus.ReqCreatorBase, GMGlobals;
type
TTR101ReqCreator = class(TModbusRTUDevReqCreator)
protected
function PrepareCommand(var prmIds: TChannelIds; var Val: double): bool; override;
public
procedure AddRequests(); override;
end;
const
COUNT_TR101_STATE = 6;
COUNT_TR101_SP1 = 1;
COUNT_TR101_SP2 = 1;
COUNT_TR101_SP3 = 1;
COUNT_TR101_SP4 = 1;
ADDR_TR101_STATE = 2;
ADDR_TR101_SP1 = 32;
ADDR_TR101_SP2 = 46;
ADDR_TR101_SP3 = 60;
ADDR_TR101_SP4 = 74;
implementation
{ TTR101ReqCreator }
procedure TTR101ReqCreator.AddRequests;
begin
// состояние, аварии, температуры
AddModbusRequestToSendBuf(ADDR_TR101_STATE, COUNT_TR101_STATE, rqtTR101_STATE);
// уставка Т1
AddModbusRequestToSendBuf(ADDR_TR101_SP1, COUNT_TR101_SP1, rqtTR101_SP1);
// уставка Т2
AddModbusRequestToSendBuf(ADDR_TR101_SP2, COUNT_TR101_SP2, rqtTR101_SP2);
// уставка Т3
AddModbusRequestToSendBuf(ADDR_TR101_SP3, COUNT_TR101_SP3, rqtTR101_SP3);
// уставка Т4
AddModbusRequestToSendBuf(ADDR_TR101_SP4, COUNT_TR101_SP4, rqtTR101_SP4);
end;
function TTR101ReqCreator.PrepareCommand(var prmIds: TChannelIds; var Val: double): bool;
var
Cmd: int;
wCmd: WORD;
begin
Result := inherited;
if not Result then Exit;
if Abs(Val) > $7FFFF then
Exit(false);
Cmd := Round(Val);
if Cmd < 0 then
wCmd := $FFFF + Cmd + 1 // перевод в отрицательные величины, понятные ТР-101
else
wCmd := Cmd;
Val := wCmd;
if prmIds.ID_PT = ID_PT_PRESET then
case prmIds.N_Src of
1:
prmIds.N_Src := ADDR_TR101_SP1;
2:
prmIds.N_Src := ADDR_TR101_SP2;
3:
prmIds.N_Src := ADDR_TR101_SP3;
4:
prmIds.N_Src := ADDR_TR101_SP4;
else
Exit(false);
end;
prmIds.ID_Src := SRC_AO;
Result := true;
end;
end.
|
{
FastCopyFile
By SiZiOUS 2014, based on the work by Davy Landman
www.sizious.com - @sizious - fb.com/sizious - sizious (at) gmail (dot) com
This unit was designed to copy a file using the Windows API.
It's faster than using the (old) BlockRead/Write and TFileStream methods.
Every destination file will be overwritten (by choice), unless you specify
the fcfmAppend CopyMode flag. In that case, the source file will be appened to
the destination file (instead of overwriting it).
You have the choice to use a normal procedure callback, method object callback
or no callback at all. The callback is used to cancel the copy process and to
display the copy progress on-screen.
Developed and tested under Delphi 2007 (ANSI).
If you are using a Unicode version of Delphi (greater than Delphi 2007), may
be you need to do some adapations (beware of the WideString type).
All credits flying to Davy Landman.
http://stackoverflow.com/questions/438260/delphi-fast-file-copy
}
unit FastCopy;
interface
uses
Windows, SysUtils;
type
TFastCopyFileMode = (fcfmCreate, fcfmAppend);
TFastCopyFileNormalCallback = procedure(const FileName: TFileName;
const CurrentSize, TotalSize: LongWord; var CanContinue: Boolean);
TFastCopyFileMethodCallback = procedure(const FileName: TFileName;
const CurrentSize, TotalSize: LongWord; var CanContinue: Boolean) of object;
// Simplest definition
function FastCopyFile(
const ASourceFileName, ADestinationFileName: TFileName): Boolean; overload;
// Definition with CopyMode and without any callbacks
function FastCopyFile(
const ASourceFileName, ADestinationFileName: TFileName;
CopyMode: TFastCopyFileMode): Boolean; overload;
// Definition with normal procedure callback
function FastCopyFile(
const ASourceFileName, ADestinationFileName: TFileName;
CopyMode: TFastCopyFileMode;
Callback: TFastCopyFileNormalCallback): Boolean; overload;
// Definition with object method callback
function FastCopyFile(
const ASourceFileName, ADestinationFileName: TFileName;
CopyMode: TFastCopyFileMode;
Callback: TFastCopyFileMethodCallback): Boolean; overload;
implementation
{ Dummy Callback: Method Version }
type
TDummyCallBackClient = class(TObject)
private
procedure DummyCallback(const FileName: TFileName;
const CurrentSize, TotalSize: LongWord; var CanContinue: Boolean);
end;
procedure TDummyCallBackClient.DummyCallback(const FileName: TFileName;
const CurrentSize, TotalSize: LongWord; var CanContinue: Boolean);
begin
// Nothing
CanContinue := True;
end;
{ Dummy Callback: Classical Procedure Version }
procedure DummyCallback(const FileName: TFileName;
const CurrentSize, TotalSize: LongWord; var CanContinue: Boolean);
begin
// Nothing
CanContinue := True;
end;
{ CreateFileW API abstract layer }
function OpenLongFileName(ALongFileName: string; DesiredAccess, ShareMode,
CreationDisposition: LongWord): THandle;
var
IsUNC: Boolean;
FileName: PWideChar;
begin
// Translate relative paths to absolute ones
ALongFileName := ExpandFileName(ALongFileName);
// Check if already an UNC path
IsUNC := Copy(ALongFileName, 1, 2) = '\\';
if not IsUNC then
ALongFileName := '\\?\' + ALongFileName;
// Preparing the FileName for the CreateFileW API call
FileName := PWideChar(WideString(ALongFileName));
// Calling the API
Result := CreateFileW(FileName, DesiredAccess, ShareMode, nil,
CreationDisposition, FILE_ATTRIBUTE_NORMAL, 0);
end;
{ FastCopyFile implementation }
function FastCopyFile(const ASourceFileName, ADestinationFileName: TFileName;
CopyMode: TFastCopyFileMode;
Callback: TFastCopyFileNormalCallback;
Callback2: TFastCopyFileMethodCallback): Boolean; overload;
const
BUFFER_SIZE = 524288; // 512KB blocks, change this to tune your speed
var
Buffer: array of Byte;
ASourceFile, ADestinationFile: THandle;
FileSize, BytesRead, BytesWritten, BytesWritten2, TotalBytesWritten,
CreationDisposition: LongWord;
CanContinue, CanContinueFlag: Boolean;
begin
FileSize := 0;
TotalBytesWritten := 0;
CanContinue := True;
SetLength(Buffer, BUFFER_SIZE);
// Manage the Creation Disposition flag
CreationDisposition := CREATE_ALWAYS;
if CopyMode = fcfmAppend then
CreationDisposition := OPEN_ALWAYS;
// Opening the source file in read mode
ASourceFile := OpenLongFileName(ASourceFileName, GENERIC_READ, 0, OPEN_EXISTING);
if ASourceFile <> 0 then
try
FileSize := FileSeek(ASourceFile, 0, FILE_END);
FileSeek(ASourceFile, 0, FILE_BEGIN);
// Opening the destination file in write mode (in create/append state)
ADestinationFile := OpenLongFileName(ADestinationFileName, GENERIC_WRITE,
FILE_SHARE_READ, CreationDisposition);
if ADestinationFile <> 0 then
try
// If append mode, jump to the file end
if CopyMode = fcfmAppend then
FileSeek(ADestinationFile, 0, FILE_END);
// For each blocks in the source file
while CanContinue and (LongWord(FileSeek(ASourceFile, 0, FILE_CURRENT)) < FileSize) do
begin
// Reading from source
if (ReadFile(ASourceFile, Buffer[0], BUFFER_SIZE, BytesRead, nil)) and (BytesRead <> 0) then
begin
// Writing to destination
WriteFile(ADestinationFile, Buffer[0], BytesRead, BytesWritten, nil);
// Read/Write secure code block (e.g. for WiFi connections)
if BytesWritten < BytesRead then
begin
WriteFile(ADestinationFile, Buffer[BytesWritten], BytesRead - BytesWritten, BytesWritten2, nil);
Inc(BytesWritten, BytesWritten2);
if BytesWritten < BytesRead then
RaiseLastOSError;
end;
// Notifying the caller for the current state
Inc(TotalBytesWritten, BytesWritten);
CanContinueFlag := True;
if Assigned(Callback) then
Callback(ASourceFileName, TotalBytesWritten, FileSize, CanContinueFlag);
CanContinue := CanContinue and CanContinueFlag;
if Assigned(Callback2) then
Callback2(ASourceFileName, TotalBytesWritten, FileSize, CanContinueFlag);
CanContinue := CanContinue and CanContinueFlag;
end;
end;
finally
CloseHandle(ADestinationFile);
end;
finally
CloseHandle(ASourceFile);
end;
// Check if cancelled or not
if not CanContinue then
if FileExists(ADestinationFileName) then
DeleteFile(ADestinationFileName);
// Results (checking CanContinue flag isn't needed)
Result := (FileSize <> 0) and (FileSize = TotalBytesWritten);
end;
{ FastCopyFile simple definition }
function FastCopyFile(const ASourceFileName, ADestinationFileName: TFileName): Boolean; overload;
begin
Result := FastCopyFile(ASourceFileName, ADestinationFileName, fcfmCreate);
end;
{ FastCopyFile definition without any callbacks }
function FastCopyFile(const ASourceFileName, ADestinationFileName: TFileName;
CopyMode: TFastCopyFileMode): Boolean; overload;
begin
Result := FastCopyFile(ASourceFileName, ADestinationFileName, CopyMode,
DummyCallback);
end;
{ FastCopyFile definition with normal procedure callback }
function FastCopyFile(const ASourceFileName, ADestinationFileName: TFileName;
CopyMode: TFastCopyFileMode;
Callback: TFastCopyFileNormalCallback): Boolean; overload;
var
DummyObj: TDummyCallBackClient;
begin
DummyObj := TDummyCallBackClient.Create;
try
Result := FastCopyFile(ASourceFileName, ADestinationFileName, CopyMode,
Callback, DummyObj.DummyCallback);
finally
DummyObj.Free;
end;
end;
{ FastCopyFile definition with object method callback }
function FastCopyFile(const ASourceFileName, ADestinationFileName: TFileName;
CopyMode: TFastCopyFileMode;
Callback: TFastCopyFileMethodCallback): Boolean; overload;
begin
Result := FastCopyFile(ASourceFileName, ADestinationFileName, CopyMode,
DummyCallback, Callback);
end;
end.
|
unit record_constructor_6;
interface
implementation
type
TRec = record
FData: Int32;
constructor Init;
destructor Final;
end;
var G: Int32;
constructor TRec.Init;
begin
FData := 12;
end;
destructor TRec.Final;
begin
G := 13;
end;
function GetRec: TRec;
begin
Assert(Result.FData = 12);
end;
procedure Test;
var
R: TRec;
begin
R := GetRec();
end;
initialization
Test();
finalization
Assert(G = 13);
end. |
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLSDLContext<p>
SDL specific Context and Viewer.<p>
NOTA: SDL notifies use of context destruction *after* it happened, this prevents
clean release of allocated stuff and requires a temporary switch to
"ignore OpenGL errors" mode during destruction, thus potentially
leaking memory (depending on hardware drivers willingness to perform
automatic releases)<p>
<b>History : </b><font size=-1><ul>
<li>23/08/10 - Yar - Replaced OpenGL1x to OpenGLTokens
<li>06/06/10 - Yar - Make outputDevice HWND type
<li>15/02/07 - DaStr - Integer -> Cardinal because $R- was removed in GLScene.pas
<li>11/09/06 - NC - Changes for Multiple-Render-Target
<li>12/12/01 - EG - Creation
</ul></font>
}
unit GLSDLContext;
interface
uses
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
Classes,
SysUtils,
GLContext,
GLSDLWindow,
GLScene,
//SDL
SDL;
type
// TGLSDLViewer
//
{: A viewer using SDL.<p>
Beware: only one at a time, no other viewers allowed!<br>
Will also close the application when the window is closed! }
TGLSDLViewer = class(TGLNonVisualViewer)
private
{ Private Declarations }
FCaption: string;
FOnSDLEvent: TSDLEvent;
FOnEventPollDone: TNotifyEvent;
FOnResize: TNotifyEvent;
protected
{ Protected Declarations }
procedure SetCaption(const val: string);
procedure DoOnOpen(sender: TObject);
procedure DoOnClose(sender: TObject);
procedure DoOnResize(sender: TObject);
procedure DoOnSDLEvent(sender: TObject; const event: TSDL_Event);
procedure DoOnEventPollDone(sender: TObject);
procedure DoBufferStructuralChange(Sender: TObject); override;
procedure PrepareGLContext; override;
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Render(baseObject: TGLBaseSceneObject = nil); override;
function Active: Boolean;
published
{ Public Declarations }
property Caption: string read FCaption write SetCaption;
property OnResize: TNotifyEvent read FOnResize write FOnResize;
{: Fired whenever an SDL Event is polled.<p>
SDL_QUITEV and SDL_VIDEORESIZE are not passed to this event handler,
they are passed via OnClose and OnResize respectively. }
property OnSDLEvent: TSDLEvent read FOnSDLEvent write FOnSDLEvent;
{: Fired whenever an event polling completes with no events left to poll. }
property OnEventPollDone: TNotifyEvent read FOnEventPollDone write FOnEventPollDone;
end;
// TGLSDLContext
//
{: A context driver for OpenGL via SDL (libsdl.org).<p>
Due to limitations of SDL:<ul>
<li>you may have only one SDL window opened at any time (you cannot
have memory viewers)
<li>closing the SDL window will terminate the application
</ul> }
TGLSDLContext = class(TGLScreenControlingContext)
private
{ Private Declarations }
FSDLWin: TSDLWindow;
FSimulatedValidity: Boolean; // Hack around SDL's post-notified destruction of context
protected
{ Protected Declarations }
procedure DoCreateContext(outputDevice: HDC); override;
procedure DoCreateMemoryContext(outputDevice: HWND; width, height: Integer; BufferCount: integer); override;
function DoShareLists(aContext: TGLContext): Boolean; override;
procedure DoDestroyContext; override;
procedure DoActivate; override;
procedure DoDeactivate; override;
public
{ Public Declarations }
constructor Create; override;
destructor Destroy; override;
function IsValid: Boolean; override;
procedure SwapBuffers; override;
function RenderOutputDevice: Pointer; override;
property SDLWindow: TSDLWindow read FSDLWin;
end;
procedure Register;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses
OpenGLAdapter,
GLCrossPlatform,
XOpenGL;
procedure Register;
begin
RegisterComponents('GLScene', [TGLSDLViewer]);
end;
// ------------------
// ------------------ TGLSDLViewer ------------------
// ------------------
// Create
//
constructor TGLSDLViewer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Width := 640;
Height := 480;
end;
// Destroy
//
destructor TGLSDLViewer.Destroy;
begin
inherited Destroy;
end;
// DoBufferStructuralChange
//
procedure TGLSDLViewer.DoBufferStructuralChange(Sender: TObject);
begin
// ignore that, supporting it with SDL is not very praticable as of now...
end;
// PrepareGLContext
//
procedure TGLSDLViewer.PrepareGLContext;
begin
with Buffer.RenderingContext as TGLSDLContext do
begin
Width := Self.Width;
Height := Self.Height;
with FSDLWin do
begin
Caption := Self.Caption;
OnOpen := DoOnOpen;
OnClose := DoOnClose;
OnResize := DoOnResize;
OnSDLEvent := DoOnSDLEvent;
OnEventPollDone := DoOnEventPollDone;
end;
end;
end;
// Render
//
procedure TGLSDLViewer.Render(baseObject: TGLBaseSceneObject = nil);
begin
LoadOpenGL;
if Buffer.RenderingContext = nil then
begin
Buffer.CreateRC(0, False);
end;
Buffer.Render(baseObject);
end;
// Active
//
function TGLSDLViewer.Active: Boolean;
begin
Result := Assigned(Buffer.RenderingContext) and Buffer.RenderingContext.IsValid;
end;
// SetCaption
//
procedure TGLSDLViewer.SetCaption(const val: string);
begin
if val <> FCaption then
begin
FCaption := val;
if Buffer.RenderingContext <> nil then
with Buffer.RenderingContext as TGLSDLContext do
if Assigned(FSDLWin) then
FSDLWin.Caption := FCaption;
end;
end;
// DoOnOpen
//
procedure TGLSDLViewer.DoOnOpen(sender: TObject);
begin
// nothing yet
end;
// DoOnClose
//
procedure TGLSDLViewer.DoOnClose(sender: TObject);
begin
// nothing yet
end;
// DoOnResize
//
procedure TGLSDLViewer.DoOnResize(sender: TObject);
begin
with Buffer.RenderingContext as TGLSDLContext do
begin
Self.Width := FSDLWin.Width;
Self.Height := FSDLWin.Height;
Buffer.Resize(0, 0, FSDLWin.Width, FSDLWin.Height);
end;
if Assigned(FOnResize) then
FOnResize(Self);
end;
// DoOnSDLEvent
//
procedure TGLSDLViewer.DoOnSDLEvent(sender: TObject; const event: TSDL_Event);
begin
if Assigned(FOnSDLEvent) then
FOnSDLEvent(sender, event);
end;
// DoOnEventPollDone
//
procedure TGLSDLViewer.DoOnEventPollDone(sender: TObject);
begin
if Assigned(FOnEventPollDone) then
FOnEventPollDone(sender);
end;
// ------------------
// ------------------ TGLSDLContext ------------------
// ------------------
// Create
//
constructor TGLSDLContext.Create;
begin
inherited Create;
FSDLWin := TSDLWindow.Create(nil);
end;
// Destroy
//
destructor TGLSDLContext.Destroy;
var
oldIgnore: Boolean;
begin
oldIgnore := vIgnoreOpenGLErrors;
FSimulatedValidity := True;
vIgnoreOpenGLErrors := True;
try
inherited Destroy;
finally
vIgnoreOpenGLErrors := oldIgnore;
FSimulatedValidity := False;
end;
FreeAndNil(FSDLWin);
end;
// DoCreateContext
//
procedure TGLSDLContext.DoCreateContext(outputDevice: HDC);
var
sdlOpt: TSDLWindowOptions;
begin
// Just in case it didn't happen already.
if not InitOpenGL then
RaiseLastOSError;
FSDLWin.Width := Width;
FSDLWin.Height := Height;
if ColorBits > 16 then
FSDLWin.PixelDepth := vpd24bits
else
FSDLWin.PixelDepth := vpd16bits;
sdlOpt := [voOpenGL, voHardwareAccel];
if FullScreen then
sdlOpt := sdlOpt + [voFullScreen]
else
sdlOpt := sdlOpt + [voResizable];
if rcoDoubleBuffered in Options then
sdlOpt := sdlOpt + [voDoubleBuffer];
if StencilBits > 0 then
sdlOpt := sdlOpt + [voStencilBuffer];
FSDLWin.Open;
if not FSDLWin.Active then
raise Exception.Create('SDLWindow open failed.');
FGL.Initialize;
MakeGLCurrent;
end;
// DoCreateMemoryContext
//
procedure TGLSDLContext.DoCreateMemoryContext(outputDevice: HWND; width, height: Integer; BufferCount: integer);
begin
raise Exception.Create(ClassName + ': Memory contexts not supported');
end;
// DoShareLists
//
function TGLSDLContext.DoShareLists(aContext: TGLContext): Boolean;
begin
// nothing (only one context at all times... no need to share)
Result := False;
end;
// DoDestroyContext
//
procedure TGLSDLContext.DoDestroyContext;
begin
// Beware, SDL will also terminate the application
FGL.Close;
FSDLWin.Close;
end;
// DoActivate
//
procedure TGLSDLContext.DoActivate;
begin
if not FGL.IsInitialized then
FGL.Initialize;
end;
// Deactivate
//
procedure TGLSDLContext.DoDeactivate;
begin
// nothing particular (only one context, always active)
end;
// IsValid
//
function TGLSDLContext.IsValid: Boolean;
begin
Result := (Assigned(FSDLWin) and (FSDLWin.Active)) or FSimulatedValidity;
end;
// SwapBuffers
//
procedure TGLSDLContext.SwapBuffers;
begin
FSDLWin.SwapBuffers;
end;
// RenderOutputDevice
//
function TGLSDLContext.RenderOutputDevice: Pointer;
begin
// unsupported
Result := nil;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterClass(TGLSDLViewer);
RegisterGLContextClass(TGLSDLContext);
end.
|
{ intrinsics }
program Intrinsics;
begin
writeln('sqrt(9.0) = ', sqrt(9.0));
writeln('sqrt(9) = ', sqrt(9));
writeln('abs(-5.0) = ', abs(-5.0));
writeln('abs(-5) = ', abs(-5));
end.
|
unit BrickCamp.Resources.TUser;
interface
uses
System.JSON,
System.Classes,
System.SysUtils,
Spring.Container.Common,
Spring.Container,
MARS.Core.Registry,
MARS.Core.Attributes,
MARS.Core.MediaType,
MARS.Core.JSON,
MARS.Core.MessageBodyWriters,
MARS.Core.MessageBodyReaders,
BrickCamp.Repositories.IUser,
BrickCamp.Resources.IUser,
BrickCamp.Model.IUser,
BrickCamp.Model.TUser;
type
[Path('/user'), Produces(TMediaType.APPLICATION_JSON_UTF8)]
TUserResource = class(TInterfacedObject, IUserResurce)
protected
function GetUserFromJSON(const Value: TJSONValue): TUser;
public
[GET, Path('/getone/{Id}')]
function GetOne(const [PathParam] Id: Integer): TUser;
[GET, Path('/getonebyname/{Name}')]
function GetOneByName(const [PathParam] Name: string): TUser;
[GET, Path('/getlist/')]
function GetList: TJSONArray;
[POST]
procedure Insert(const [BodyParam] Value: TJSONValue {TUser});
[PUT]
procedure Update(const [BodyParam] Value: TJSONValue);
[DELETE, Path('/{Id}')]
procedure Delete(const [PathParam] Id: Integer);
end;
implementation
{ THelloWorldResource }
function TUserResource.GetOne(const Id: Integer): TUser;
begin
Result := GlobalContainer.Resolve<IUserRepository>.GetOne(Id);
end;
function TUserResource.GetOneByName(const Name: string): TUser;
begin
Result := GlobalContainer.Resolve<IUserRepository>.GetOneByName(Name);
end;
function TUserResource.GetUserFromJSON(const Value: TJSONValue): TUser;
var
JSONObject: TJSONObject;
begin
Result := GlobalContainer.Resolve<TUser>;
JSONObject := TJSONObject.ParseJSONValue(Value.ToJSON) as TJSONObject;
try
Result.Name := JSONObject.ReadStringValue('Name', '');
finally
JSONObject.Free;
end;
end;
procedure TUserResource.Delete(const Id: Integer);
begin
GlobalContainer.Resolve<IUserRepository>.Delete(Id);
end;
procedure TUserResource.Insert(const Value: TJSONValue);
var
User: TUser;
begin
User := GetUserFromJSON(Value);
try
if Assigned(User) then
GlobalContainer.Resolve<IUserRepository>.Insert(User);
finally
User.Free;
end;
end;
procedure TUserResource.Update(const Value: TJSONValue);
var
User: TUser;
begin
User := GetUserFromJSON(Value);
try
if Assigned(User) then
GlobalContainer.Resolve<IUserRepository>.Update(User);
finally
User.Free;
end;
end;
function TUserResource.GetList: TJSONArray;
begin
result := GlobalContainer.Resolve<IUserRepository>.GetList;
end;
initialization
TMARSResourceRegistry.Instance.RegisterResource<TUserResource>;
end.
|
{$mode objfpc}
unit Asm_Converter;
interface
function HexToWord(b : string; var c : integer) : word;
function StrToWord(s : string; var c : integer; hex : boolean = false) : Word;
function WordToHex(b : word) : string;
implementation
function HexCharToByte(c : char) : byte;
begin
HexCharToByte := 0;
case c of
'0'..'9' : HexCharToByte := Ord(c) - Ord('0');
'a'..'f' : HexCharToByte := Ord(c) - Ord('a') + 10;
'A'..'F' : HexCharToByte := Ord(c) - Ord('A') + 10;
end;
end;
function HexToWord(b : string; var c : integer) : word;
var
i, r : Word;
n : longint;
begin
n := 1; r := 0;
for i := Length(b) downto 1 do begin
if not ((b[i] in ['0'..'9']) or (b[i] in ['a'..'f']) or (b[i] in ['A'..'F'])) then begin
c := i;
HexToWord := 0;
exit;
end;
r := r + HexCharToByte(b[i]) * n;
n := n * 16;
end;
HexToWord := r;
end;
function StrToWord(s : string; var c : integer; hex : boolean = false) : Word;
begin
if (s[1] = '$') then
begin
delete(s, 1, 1);
StrToWord := HexToWord(s, c);
exit;
end;
if hex then StrToWord := HexToWord(s, c)
else val(s, StrToWord, c);
end;
function WordToHex(b : word) : string;
var
s : string;
begin
s := '';
while (b > 0) do begin
case (b mod 16) of
0..9 : s := Chr((b mod 16) + Ord('0')) + s;
10..15 : s := Chr((b mod 16) - 10 + Ord('A')) + s;
end;
b := b div 16;
end;
WordToHex := s;
end;
end. |
unit untCadastroUsuario;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Buttons,
Vcl.Mask, Vcl.DBCtrls, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TfrmCadastroUsuario = class(TForm)
pnlRodape: TPanel;
pnlCentro: TPanel;
btnNovo: TBitBtn;
btnGravar: TBitBtn;
btnCancelar: TBitBtn;
btnExcluir: TBitBtn;
btnFechar: TBitBtn;
lblUsuario: TLabel;
lblSenha: TLabel;
lblCodigo: TLabel;
btnPesquisar: TBitBtn;
edtUsuario: TDBEdit;
edtSenha: TDBEdit;
qryUsuario: TFDQuery;
dtsUsuario: TDataSource;
edtCodigo: TEdit;
procedure btnFecharClick(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure btnGravarClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure edtCodigoExit(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
private
{ Private declarations }
fNovo : Boolean;
public
{ Public declarations }
procedure CarregaCampos;
procedure PesquisaUsuario(vStatus : Boolean);
end;
var
frmCadastroUsuario: TfrmCadastroUsuario;
implementation
{$R *.dfm}
uses untFuncoes, untDM, untPesquisa, untPrincipal;
procedure TfrmCadastroUsuario.btnExcluirClick(Sender: TObject);
begin
if fNovo = False then
begin
if qryUsuario.RecordCount > 0 then
begin
frmFuncoes.Botoes('Excluir', qryUsuario);
end;
end;
end;
procedure TfrmCadastroUsuario.btnFecharClick(Sender: TObject);
begin
qryUsuario.Close;
qryUsuario.SQL.Clear;
Close;
end;
procedure TfrmCadastroUsuario.btnGravarClick(Sender: TObject);
begin
if fNovo = True then
begin
qryUsuario.FieldByName('id').AsString := edtCodigo.Text;
end;
qryUsuario.FieldByName('CODEMPRESA').AsInteger := frmPrincipal.vEmpresa; //Versao 1.4 - 14/10/2018
qryUsuario.ApplyUpdates(-1);
btnNovo.Enabled := True;
btnExcluir.Enabled := True;
edtUsuario.Enabled := True;
frmFuncoes.AutoIncre('USUARIO', 'Gravar');
ShowMessage('Cadastro realizado com sucesso.');
end;
procedure TfrmCadastroUsuario.btnNovoClick(Sender: TObject);
begin
fNovo := True;
qryUsuario.Insert;
btnNovo.Enabled := False;
btnGravar.Enabled := True;
btnExcluir.Enabled := False;
edtUsuario.SetFocus;
edtCodigo.Enabled := False;
edtCodigo.Text := IntToStr(frmFuncoes.AutoIncre('USUARIO', 'Novo'));
end;
procedure TfrmCadastroUsuario.btnPesquisarClick(Sender: TObject);
begin
PesquisaUsuario(False);
end;
procedure TfrmCadastroUsuario.CarregaCampos;
begin
edtUsuario.DataField := 'NOME';
edtSenha.DataField := 'SENHA';
end;
procedure TfrmCadastroUsuario.edtCodigoExit(Sender: TObject);
begin
if (Trim(edtCodigo.Text) <> '') and (fNovo = False) then
begin
PesquisaUsuario(True);
end;
end;
procedure TfrmCadastroUsuario.FormActivate(Sender: TObject);
begin
frmFuncoes.ExecutaSQL('Select * from USUARIO where ID is null', 'Abrir', qryUsuario);
CarregaCampos;
edtCodigo.SetFocus;
end;
procedure TfrmCadastroUsuario.FormKeyPress(Sender: TObject; var Key: Char);
begin
If key = #13 then
Begin
Key:= #0;
Perform(Wm_NextDlgCtl,0,0);
end;
end;
procedure TfrmCadastroUsuario.PesquisaUsuario(vStatus: Boolean);
begin
if vStatus = True then
begin
if Trim(edtCodigo.Text) <> '' then
begin
qryUsuario.Close;
qryUsuario.SQL.Clear;
qryUsuario.SQL.Add('Select * from USUARIO where ID = ' + QuotedStr(edtCodigo.Text));
qryUsuario.Open;
if qryUsuario.RecordCount > 0 then
begin
qryUsuario.Edit;
CarregaCampos;
end
else
begin
Application.MessageBox('Registro não encontrado.', 'Curral Novo', MB_OK);
end;
end;
end
else
begin
frmPesquisa := TfrmPesquisa.Create(Self);
try
frmPesquisa.vTabela := 'USUARIO';
frmPesquisa.vTela := 'CAD_USUARIO';
frmPesquisa.vComando := 'Select id, nome from USUARIO';
frmPesquisa.ShowModal;
finally
frmPesquisa.Release;
end;
end;
end;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000, 2001 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit QTypes;
{$R-,T-,H+,X+}
interface
uses
Qt, SysUtils, Types, Classes;
type
EHandleComponentException = class(Exception);
EInvalidParam = class(Exception);
TCaption = type WideString;
THandleComponent = class(TComponent)
private
FHooks: QObject_hookH;
FParentWidget: QWidgetH;
FHelpContext: THelpContext;
FHelpKeyword: string;
FHelpFile: string;
FHelpType: THelpType;
function GetHooks: QObject_hookH;
procedure DestroyedHook; cdecl;
function GetHandle: QObjectH;
function GetParentWidget: QWidgetH;
procedure SetParentWidget(const Value: QWidgetH);
function IsHelpContextStored: Boolean;
protected
FHandle: QObjectH;
procedure CreateHandle; virtual;
procedure CreateWidget; virtual; abstract;
procedure DestroyWidget; virtual;
function EventFilter(Sender: QObjectH; Event: QEventH): Boolean; virtual; cdecl;
procedure HookEvents; virtual;
procedure InitWidget; virtual;
procedure InvokeHelp; virtual;
procedure SetHelpContext(const Value: THelpContext);
procedure SetHelpKeyword(const Value: String);
procedure WidgetDestroyed; virtual;
property HelpFile: string read FHelpFile write FHelpFile;
property HelpType: THelpType read FHelpType write FHelpType default htKeyword;
property HelpKeyword: string read FHelpKeyword write SetHelpKeyword;
property HelpContext: THelpContext read FHelpContext write SetHelpContext stored IsHelpContextStored default 0;
public
destructor Destroy; override;
procedure HandleNeeded;
function HandleAllocated: Boolean;
property Handle: QObjectH read GetHandle;
property Hooks: QObject_hookH read GetHooks write FHooks;
property ParentWidget: QWidgetH read GetParentWidget write SetParentWidget;
end;
TMimeSource = class(TPersistent)
private
FOwnHandle: Boolean;
function GetHandle: QMimeSourceH;
procedure SetHandle(const Value: QMimeSourceH);
procedure HandleNeeded;
protected
FHandle: QMimeSourceH;
procedure CreateHandle; virtual;
function HandleAllocated: Boolean;
public
constructor Create(AHandle: QMimeSourceH = nil);
destructor Destroy; override;
function SaveToStream(const Format: string; Stream: TStream): Boolean;
procedure SupportedFormats(List: TStrings);
function Provides(const Format: string): Boolean;
procedure OwnHandle;
procedure ReleaseHandle;
property Handle: QMimeSourceH read GetHandle write SetHandle;
end;
TClxMimeSource = class(TMimeSource)
private
function GetHandle: QClxMimeSourceH;
procedure SetHandle(const Value: QClxMimeSourceH);
public
constructor Create(const Format: string; Data: TStream); overload;
constructor Create(MimeSourceH: QClxMimeSourceH); overload;
procedure LoadFromStream(Stream: TStream; const Format: string);
property Handle: QClxMimeSourceH read GetHandle write SetHandle;
end;
procedure CopyQStringListToTStrings(Handle: QStringListH; Strings: TStrings);
function QStringListToTStringList(Handle: QStringListH): TStringList;
function TStringsToQStringList(Strings: TStrings): QStringListH;
function IODeviceFromStream(Stream: TStream; Owned: Boolean = False): QIODeviceH;
implementation
uses QControls, QForms, QConsts;
procedure CopyQStringListToTStrings(Handle: QStringListH; Strings: TStrings);
var
I: Integer;
S: WideString;
begin
Strings.Clear;
for I := 0 to QOpenStringList_count(QOpenStringListH(Handle)) - 1 do
begin
QOpenStringList_value(QOpenStringListH(handle), PWideString(@S), I);
Strings.Add(S);
end;
end;
function QStringListToTStringList(Handle: QStringListH): TStringList;
begin
{ It is the user's responsibility to free the result. }
Result := TStringList.Create;
CopyQStringListToTStrings(Handle, Result);
end;
function TStringsToQStringList(Strings: TStrings): QStringListH;
var
I: Integer;
S: WideString;
begin
{ It is the user's responsibility to free the result. }
Result := QStringList_create;
for I := 0 to Strings.Count - 1 do
begin
S := Strings.Strings[I];
QOpenStringList_append(QOpenStringListH(Result), PWideString(@S));
end;
end;
type
PIODevice = ^TIODevice;
TStreamReadProc = function (Rec: PIODevice; var Buffer; Size: Integer): Integer cdecl;
TStreamWriteProc = function (Rec: PIODevice; var Buffer; Size: Integer): Integer cdecl;
TStreamSeekProc = function (Rec: PIODevice; Location: Integer; Offset: Integer): Integer cdecl;
TStreamFreeProc = procedure (Rec: PIODevice) cdecl;
TIODevice = packed record
Read: TStreamReadProc;
Write: TStreamWriteProc;
Seek: TStreamSeekProc;
Free: TStreamFreeProc;
Stream: TStream;
Owned: Boolean;
end;
function StreamRead(Rec: PIODevice; var Buffer; Size: Integer): Integer; cdecl;
begin
try
Result := Rec.Stream.Read(Buffer, Size);
except
Application.HandleException(Rec.Stream);
Result := -1;
end;
end;
function StreamWrite(Rec: PIODevice; var Buffer; Size: Integer): Integer; cdecl;
begin
try
Result := Rec.Stream.Write(Buffer,Size);
except
Application.HandleException(Rec.Stream);
Result := 1;
end;
end;
function StreamSeek(Rec: PIODevice; Location: Integer; Offset: Integer): Integer; cdecl;
begin
try
Result := Rec.Stream.Seek(Location, Offset);
except
Application.HandleException(Rec.Stream);
Result := -1;
end;
end;
procedure StreamFree(Rec: PIODevice); cdecl;
begin
try
if Rec.Owned then
Rec.Stream.Free;
Dispose(Rec);
except
Application.HandleException(nil);
end;
end;
const
InitDevice: TIODevice = (
Read: StreamRead;
Write: StreamWrite;
Seek: StreamSeek;
Free: StreamFree;
);
function IODeviceFromStream(Stream: TStream; Owned: Boolean): QIODeviceH;
var
Rec: PIODevice;
begin
New(Rec);
Rec^ := InitDevice;
Rec.Stream := Stream;
Rec.Owned := Owned;
Result := QClxIODevice_create(Rec);
end;
{ THandleComponent }
procedure THandleComponent.CreateHandle;
begin
if FHandle = nil then
begin
CreateWidget;
InitWidget;
HookEvents;
if (FHandle = nil) then
raise EHandleComponentException.CreateResFmt(@SInvalidCreateWidget, [ClassName]);
QClxObjectMap_add(FHandle, Integer(Self));
end;
end;
destructor THandleComponent.Destroy;
begin
if FHandle <> nil then
begin
DestroyWidget;
FHandle := nil;
end;
inherited Destroy;
end;
procedure THandleComponent.DestroyedHook;
begin
try
WidgetDestroyed;
except
Application.HandleException(Self);
end;
end;
procedure THandleComponent.DestroyWidget;
var
TmpHandle: QObjectH;
begin
if FHandle <> nil then
begin
TmpHandle := FHandle;
WidgetDestroyed;
QObject_destroy(TmpHandle);
end;
end;
function THandleComponent.EventFilter(Sender: QObjectH; Event: QEventH): Boolean;
begin
try
Result := False;
if (QEvent_type(Event) = QEventType_KeyPress) and
(QKeyEvent_key(QKeyEventH(Event)) = Application.HelpKey) and (Sender = FHandle) then
begin
Result := True;
InvokeHelp;
end;
except
Application.HandleException(Self);
Result := False;
end;
end;
function THandleComponent.GetHandle: QObjectH;
begin
HandleNeeded;
Result := FHandle;
end;
function THandleComponent.GetHooks: QObject_hookH;
begin
HandleNeeded;
Result := FHooks;
end;
type TOpenApplication = class(TApplication);
function THandleComponent.GetParentWidget: QWidgetH;
begin
if FParentWidget <> nil then
Result := FParentWidget
else if not assigned(Application.MainForm) then
Result := QApplication_desktop
else
Result := TOpenApplication(Application).AppWidget;
end;
function THandleComponent.HandleAllocated: Boolean;
begin
Result := FHandle <> nil;
end;
procedure THandleComponent.HandleNeeded;
begin
if FHandle = nil then CreateHandle;
end;
procedure THandleComponent.HookEvents;
var
Method: TMethod;
begin
if FHooks = nil then
begin
Assert(FHandle <> nil);
FHooks := QObject_hook_create(Handle);
end;
TEventFilterMethod(Method) := EventFilter;
Qt_hook_hook_events(FHooks, Method);
QObject_destroyed_event(Method) := Self.DestroyedHook;
QObject_hook_hook_destroyed(FHooks, Method);
end;
procedure THandleComponent.InitWidget;
begin
{ Notification }
end;
procedure THandleComponent.InvokeHelp;
begin
case HelpType of
htKeyword:
Application.KeywordHelp(HelpKeyword);
htContext:
Application.ContextHelp(HelpContext);
end;
end;
function THandleComponent.IsHelpContextStored: Boolean;
begin
Result := True;
end;
procedure THandleComponent.SetParentWidget(const Value: QWidgetH);
begin
FParentWidget := Value;
end;
procedure THandleComponent.SetHelpContext(const Value: THelpContext);
begin
if not (csLoading in ComponentState) then FHelpType := htContext;
FHelpContext := Value;
end;
procedure THandleComponent.SetHelpKeyword(const Value: String);
begin
if not (csLoading in ComponentState) then FHelpType := htKeyword;
FHelpKeyword := Value;
end;
procedure THandleComponent.WidgetDestroyed;
begin
QClxObjectMap_remove(FHandle);
FHandle := nil;
QObject_hook_destroy(FHooks);
FHooks := nil;
end;
{ TClxMimeSource }
constructor TClxMimeSource.Create(const Format: string; Data: TStream);
begin
inherited Create;
LoadFromStream(Data, Format);
end;
constructor TClxMimeSource.Create(MimeSourceH: QClxMimeSourceH);
begin
inherited Create;
FHandle := MimeSourceH;
end;
function TClxMimeSource.GetHandle: QClxMimeSourceH;
begin
HandleNeeded;
Result := QClxMimeSourceH(FHandle);
end;
procedure TClxMimeSource.LoadFromStream(Stream: TStream; const Format: string);
var
IO: QIODeviceH;
ByteArray: QByteArrayH;
begin
if not Assigned(Stream) then
raise EInvalidParam.CreateRes(@SInvalidMimeSourceStream);
IO := IODeviceFromStream(Stream);
ByteArray := nil;
try
ByteArray := QByteArray_create(0);
QIODevice_readAll(IO, ByteArray);
QClxMimeSource_addFormat(Handle, PChar(Format), ByteArray);
finally
QIODevice_destroy(IO);
if Assigned(ByteArray) then
QByteArray_destroy(ByteArray);
end;
end;
procedure TClxMimeSource.SetHandle(const Value: QClxMimeSourceH);
begin
if FHandle <> Value then
FHandle := Value;
end;
{ TMimeSource }
constructor TMimeSource.Create(AHandle: QMimeSourceH);
begin
inherited Create;
FHandle := AHandle;
end;
procedure TMimeSource.CreateHandle;
begin
FHandle := QClxMimeSource_create;
end;
destructor TMimeSource.Destroy;
begin
if HandleAllocated and FOwnHandle then
QMimeSource_destroy(FHandle);
inherited Destroy;
end;
function TMimeSource.GetHandle: QMimeSourceH;
begin
HandleNeeded;
Result := FHandle;
end;
function TMimeSource.HandleAllocated: Boolean;
begin
Result := FHandle <> nil;
end;
procedure TMimeSource.HandleNeeded;
begin
if not HandleAllocated then
CreateHandle;
end;
function TMimeSource.Provides(const Format: string): Boolean;
begin
Result := QMimeSource_provides(Handle, PChar(Format));
end;
function TMimeSource.SaveToStream(const Format: string;
Stream: TStream): Boolean;
var
IO: QIODeviceH;
ByteArray: QByteArrayH;
begin
Result := False;
if not Assigned(Stream) then
raise EInvalidParam.CreateRes(@SInvalidMimeSourceStream);
if Provides(Format) then
begin
IO := IODeviceFromStream(Stream);
try
ByteArray := QByteArray_create(0);
try
QMimeSource_encodedData(Handle, ByteArray, PChar(Format));
if not Boolean(QIODevice_writeBlock(IO, ByteArray)) then
Stream.Size := 0;
Result := True;
finally
QByteArray_destroy(ByteArray);
end;
finally
QIODevice_destroy(IO);
end;
end;
end;
procedure TMimeSource.SetHandle(const Value: QMimeSourceH);
begin
if FHandle <> Value then
begin
FHandle := Value;
OwnHandle;
end;
end;
procedure TMimeSource.SupportedFormats(List: TStrings);
var
I: Integer;
Str: PChar;
begin
if Assigned(List) then
begin
List.Clear;
I := 0;
while True do
begin
Str := QMimeSource_format(Handle, i);
if not Assigned(Str) then
Exit;
List.Add(Str);
Inc(I);
end;
end;
end;
procedure TMimeSource.ReleaseHandle;
begin
FHandle := nil;
FOwnHandle := False;
end;
procedure TMimeSource.OwnHandle;
begin
FOwnHandle := True;
end;
end.
|
unit FC.Trade.ChooseExpertsDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmDialogOKCancel_B, ActnList, StdCtrls, ExtendControls, ExtCtrls,
Buttons, ComCtrls,FC.Definitions, ImgList, ToolWin, VirtualTrees,
StockChart.Definitions;
type
TfmSelectExpertsDialog = class(TfmDialogOkCancel_B)
ToolBar1: TToolBar;
paWorkspace: TPanel;
tvProperties: TVirtualStringTree;
Label1: TLabel;
procedure tvPropertiesGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer);
procedure tvPropertiesBeforeItemErase(Sender: TBaseVirtualTree; TargetCanvas: TCanvas; Node: PVirtualNode;
ItemRect: TRect; var ItemColor: TColor; var EraseAction: TItemEraseAction);
procedure acOKUpdate(Sender: TObject);
procedure tvPropertiesGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: string);
private
procedure SetChecked(const aStockExpert: ISCExpert; aChecked: boolean);
function GetChecked(const aStockExpert: ISCExpert): boolean;
function NodeByExpert(const aStockExpert: ISCExpert): PVirtualNode;
public
procedure AddExpert(const aStockExpert: ISCExpert);
property Checked[const aStockExpert: ISCExpert]: boolean read GetChecked write SetChecked;
constructor Create(aOwner:TComponent); override;
end;
implementation
{$R *.dfm}
type
TItemKind = (ikChart,ikExp);
TItemData = record
ID : TGUID;
Kind : TItemKind;
Text : string;
end;
PItemData = ^TItemData;
{ TfmCreateTraderDialog }
constructor TfmSelectExpertsDialog.Create(aOwner: TComponent);
begin
inherited;
end;
procedure TfmSelectExpertsDialog.AddExpert(const aStockExpert: ISCExpert);
var
aNodeData : PItemData;
aNode,aTmp : PVirtualNode;
aChart: IStockChart;
begin
aNode:=nil;
aChart:=GetParentStockChart(aStockExpert);
aTmp:=tvProperties.GetFirst;
while aTmp<>nil do
begin
aNodeData:= tvProperties.GetNodeData(aTmp);
if (aNodeData.Kind=ikChart) and (IsEqualGUID(aNodeData.ID,aChart.GetID)) then
begin
aNode:=aTmp;
break;
end;
aTmp:=tvProperties.GetNext(aTmp);
end;
if aNode=nil then
begin
aNode:=tvProperties.AddChild(nil);
aNodeData:=tvProperties.GetNodeData(aNode);
aNodeData.ID:=aChart.GetID;
aNodeData.Kind:=ikChart;
aNodeData.Text:=aChart.StockSymbol.GetTimeIntervalName;
end;
//tvProperties.Expanded[aNode]:=true;
aNode:=tvProperties.AddChild(aNode);
aNodeData:=tvProperties.GetNodeData(aNode);
aNodeData.ID:=aStockExpert.GetID;
aNodeData.Kind:=ikExp;
aNodeData.Text:=aStockExpert.GetName;
aNode.CheckType := ctCheckBox;
tvProperties.CheckState[aNode]:=csCheckedNormal;
tvProperties.FullExpand();
end;
procedure TfmSelectExpertsDialog.acOKUpdate(Sender: TObject);
begin
TAction(Sender).Enabled:=true;
end;
procedure TfmSelectExpertsDialog.tvPropertiesBeforeItemErase(Sender: TBaseVirtualTree; TargetCanvas: TCanvas;
Node: PVirtualNode; ItemRect: TRect; var ItemColor: TColor; var EraseAction: TItemEraseAction);
var
Data: PItemData;
begin
Data := Sender.GetNodeData(Node);
if Data=nil then exit;
EraseAction:=eaColor;
if Data.Kind=ikChart then
ItemColor:=clSkyBlue
else
ItemColor:=clWindow;
end;
procedure TfmSelectExpertsDialog.tvPropertiesGetNodeDataSize(Sender: TBaseVirtualTree; var NodeDataSize: Integer);
begin
NodeDataSize := SizeOf(TItemData);
end;
procedure TfmSelectExpertsDialog.tvPropertiesGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: string);
var
aNodeData : PItemData;
begin
aNodeData:=Sender.GetNodeData(Node);
if aNodeData<>nil then
CellText:=aNodeData.Text;
end;
procedure TfmSelectExpertsDialog.SetChecked(const aStockExpert: ISCExpert; aChecked: boolean);
var
aNode: PVirtualNode;
begin
aNode:=NodeByExpert(aStockExpert);
if aChecked then
tvProperties.CheckState[aNode]:=csCheckedNormal
else
tvProperties.CheckState[aNode]:=csUncheckedNormal;
end;
function TfmSelectExpertsDialog.GetChecked(const aStockExpert: ISCExpert): boolean;
var
aNode: PVirtualNode;
begin
aNode:=NodeByExpert(aStockExpert);
result:=tvProperties.CheckState[aNode]=csCheckedNormal;
end;
function TfmSelectExpertsDialog.NodeByExpert(const aStockExpert: ISCExpert): PVirtualNode;
var
aTmp : PVirtualNode;
aNodeData : PItemData;
begin
result:=nil;
aTmp:=tvProperties.GetFirst;
while aTmp<>nil do
begin
aNodeData:= tvProperties.GetNodeData(aTmp);
if (aNodeData.Kind=ikExp) and (IsEqualGUID(aNodeData.ID,aStockExpert.GetID)) then
begin
result:=aTmp;
break;
end;
aTmp:=tvProperties.GetNext(aTmp);
end;
if result = nil then
EStockError.Create('There is no such expert');
end;
end.
|
unit Unit3_3;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Menus;
type
TForm1 = class(TForm)
GroupBox1: TGroupBox;
RadioGroup1: TRadioGroup;
ColorDialog1: TColorDialog;
FontDialog1: TFontDialog;
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
Button3: TButton;
MainMenu1: TMainMenu;
Option: TMenuItem;
OptionColor: TMenuItem;
OptionFont: TMenuItem;
OptionAlign: TMenuItem;
OptionAlignLeft: TMenuItem;
OptionAlignRight: TMenuItem;
OptionAlignCenter: TMenuItem;
OptionHide: TMenuItem;
Help: TMenuItem;
N3: TMenuItem;
N1: TMenuItem;
PopupMenu1: TPopupMenu;
popup_color: TMenuItem;
popup_font: TMenuItem;
popup_align: TMenuItem;
popup_hide: TMenuItem;
popup_align_left: TMenuItem;
popup_align_center: TMenuItem;
popup_align_right: TMenuItem;
N8: TMenuItem;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure RadioGroup1Click(Sender: TObject);
procedure OptionAlignLeftClick(Sender: TObject);
procedure OptionAlignCenterClick(Sender: TObject);
procedure OptionAlignRightClick(Sender: TObject);
procedure HelpClick(Sender: TObject);
procedure OptionHideClick(Sender: TObject);
procedure popup_align_leftClick(Sender: TObject);
procedure popup_align_centerClick(Sender: TObject);
procedure popup_align_rightClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject); //设置颜色
begin
with ColorDialog1 do // 为了减少输入的字符,不必每次重复名字,直接写变量
begin
color := Memo1.Color;
if Execute then
begin
Memo1.Color := Color;
end;
end;
end;
procedure TForm1.Button2Click(Sender: TObject); //设置字体
begin
with FontDialog1 do
begin
font := Memo1.Font;
if Execute then
begin
Memo1.Font := Font;
end;
end;
end;
procedure TForm1.Button3Click(Sender: TObject); //修正内容
begin
Memo1.Lines.text := ' 布娃娃要睡觉' + chr(13) + chr(13) + //chr(13 )为回车符
'布娃娃,' + chr(13) + ' 要睡觉。' + chr(13) +
'小棉被,' + chr(13) + ' 盖盖好,' + chr(13) +
'伸出脚丫' + chr(13) + ' 乘风凉,' + chr(13) +
'阿嚏一声,' + chr(13) + ' 吓走小花猫。';
end;
procedure TForm1.RadioGroup1Click(Sender: TObject); //对齐设置
begin
case RadioGroup1.ItemIndex of
0: Memo1.Alignment := taLeftJustify;
1: Memo1.Alignment := taCenter;
2: Memo1.Alignment := taRightJustify;
end;
end;
procedure TForm1.OptionAlignLeftClick(Sender: TObject);
begin
Memo1.Alignment := taLeftJustify;
OptionAlignLeft.Checked := True; // 被选中状态,会有一个勾
OptionAlignCenter.Checked := False;
OptionAlignRight.Checked := False;
RadioGroup1.ItemIndex := 0; // radiogroup 选中
end;
procedure TForm1.OptionAlignCenterClick(Sender: TObject);
begin
Memo1.Alignment := taCenter;
OptionAlignLeft.Checked := False; // 被选中状态,会有一个勾
OptionAlignCenter.Checked := True;
OptionAlignRight.Checked := False;
RadioGroup1.ItemIndex := 1; // radiogroup 选中
end;
procedure TForm1.OptionAlignRightClick(Sender: TObject);
begin
Memo1.Alignment := taRightJustify;
OptionAlignLeft.Checked := False; // 被选中状态,会有一个勾
OptionAlignCenter.Checked := False;
OptionAlignRight.Checked := True;
RadioGroup1.ItemIndex := 2; // radiogroup 选中
end;
procedure TForm1.HelpClick(Sender: TObject);
begin
// Help.Enabled := not Help.Enabled; // 失效
Help.Visible := not Help.Visible; // 隐藏
if Help.visible then
begin
optionHide.caption := '隐藏';
end
else
begin
optionHide.caption := '显示';
end;
end;
procedure TForm1.OptionHideClick(Sender: TObject);
begin
if Help.Visible then
begin
Help.visible := false;
optionHide.caption := '显示';
end
else
begin
Help.visible := true;
optionHide.caption := '隐藏';
end;
end;
procedure TForm1.popup_align_leftClick(Sender: TObject);
begin
Memo1.Alignment := taLeftJustify;
popup_align_left.checked := True; // 被选中状态,会有一个勾
popup_align_center.checked := False;
popup_align_right.checked := False;
RadioGroup1.ItemIndex := 0; // radiogroup 选中
end;
procedure TForm1.popup_align_centerClick(Sender: TObject);
begin
Memo1.Alignment := taCenter;
popup_align_left.checked := False; // 被选中状态,会有一个勾
popup_align_center.checked := True;
popup_align_right.checked := False;
RadioGroup1.ItemIndex := 1; // radiogroup 选中
end;
procedure TForm1.popup_align_rightClick(Sender: TObject);
begin
Memo1.Alignment := taRightJustify;
popup_align_left.checked := False; // 被选中状态,会有一个勾
popup_align_center.checked := False;
popup_align_right.checked := True;
RadioGroup1.ItemIndex := 2; // radiogroup 选中
end;
end.
|
unit xSortInfo;
interface
uses System.Classes, system.SysUtils, xQuestionInfo, xQuestionAction, xFunction;
type
TSortInfo = class
private
FSortid : Integer ;
FSortname : String ;
FSortremark : String ;
FQuestionList: TStringList;
FQuestionAction : TQuestionAction;
function GetQuestionInfo(nIndex: Integer): TQuestionInfo;
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 复制对象
/// </summary>
procedure Assign(Source : TSortInfo);
/// <summary>
/// 题库ID
/// </summary>
property SortID : Integer read FSortid write FSortid ;
/// <summary>
/// 题库名称
/// </summary>
property SortName : String read FSortname write FSortname ;
/// <summary>
/// 题库备注
/// </summary>
property SortRemark : String read FSortremark write FSortremark;
/// <summary>
/// 考题列表
/// </summary>
property QuestionList : TStringList read FQuestionList write FQuestionList;
property QuestionInfo[nIndex : Integer] : TQuestionInfo read GetQuestionInfo;
/// <summary>
/// 获取考题
/// </summary>
function GetQInfo(nQID : Integer) : TQuestionInfo;
/// <summary>
/// 添加考题
/// </summary>
procedure AddQuestion(AQuestion : TQuestionInfo);
/// <summary>
/// 编辑考题
/// </summary>
procedure EditQuestion(AQuestion : TQuestionInfo);
/// <summary>
/// 删除考题
/// </summary>
procedure DelQuestion(nQID : Integer); overload;
procedure DelQuestion(AQuestion : TQuestionInfo); overload;
/// <summary>
/// 清空考题
/// </summary>
procedure ClearQuestion;
/// <summary>
/// 加载考题
/// </summary>
procedure LoadQuestion;
end;
implementation
{ TSortInfo }
procedure TSortInfo.AddQuestion(AQuestion : TQuestionInfo);
begin
if Assigned(AQuestion) then
begin
AQuestion.SortID := FSortid;
AQuestion.QID := FQuestionAction.GetMaxSN + 1;
FQuestionList.AddObject('', AQuestion);
FQuestionAction.AddQuestion(AQuestion);
end;
end;
procedure TSortInfo.Assign(Source: TSortInfo);
begin
FSortid := Source.Sortid;
FSortname := Source.Sortname;
FSortremark := Source.Sortremark;
end;
procedure TSortInfo.ClearQuestion;
begin
ClearStringList(FQuestionList);
FQuestionAction.DelQuestion(FSortid);
end;
constructor TSortInfo.Create;
begin
FQuestionList:= TStringList.Create;
FQuestionAction := TQuestionAction.Create;
end;
procedure TSortInfo.DelQuestion(nQID: Integer);
var
i : Integer;
begin
for i := FQuestionList.Count - 1 downto 0 do
begin
if TQuestionInfo(FQuestionList.Objects[i]).QID = nQID then
begin
FQuestionAction.DelQuestion(FSortid, nQID);
TQuestionInfo(FQuestionList.Objects[i]).Free;
FQuestionList.Delete(i);
Break;
end;
end;
end;
procedure TSortInfo.DelQuestion(AQuestion: TQuestionInfo);
begin
if Assigned(AQuestion) then
begin
DelQuestion(AQuestion.QID);
end;
end;
destructor TSortInfo.Destroy;
begin
ClearStringList(FQuestionList);
FQuestionList.Free;
FQuestionAction.Free;
inherited;
end;
procedure TSortInfo.EditQuestion(AQuestion: TQuestionInfo);
begin
if Assigned(AQuestion) then
FQuestionAction.EditQuestion(AQuestion);
end;
function TSortInfo.GetQInfo(nQID: Integer): TQuestionInfo;
var
i : Integer;
begin
Result := nil;
for i := FQuestionList.Count - 1 downto 0 do
begin
if TQuestionInfo(FQuestionList.Objects[i]).QID = nQID then
begin
Result := TQuestionInfo(FQuestionList.Objects[i]);
Break;
end;
end;
end;
function TSortInfo.GetQuestionInfo(nIndex: Integer): TQuestionInfo;
begin
if (nIndex >= 0) and (nIndex < FQuestionList.Count) then
begin
Result := TQuestionInfo(FQuestionList.Objects[nIndex]);
end
else
begin
Result := nil;
end;
end;
procedure TSortInfo.LoadQuestion;
begin
FQuestionAction.LoadQuestion(FSortid, FQuestionList);
end;
end.
|
unit Unit2;
interface
type
PElem = ^TElem;
TElem = record
info: integer;
next: PElem;
end;
// создать список из одного элемента
procedure CreateList(var ListN, ListK: PElem; r: integer);
// добавить новый элемент перед первым
procedure AddFirst(var ListN: PElem; ListK: PElem; r: integer);
// добавить новый элемент в конец
procedure AddLast(ListN: PElem; var ListK: PElem; r: integer);
// добавить новый элемент в середину после ListC (не в конец)
procedure AddMedium(ListN,ListC,ListK: PElem; r: integer);
// очистить список
procedure FreeList(var ListN, ListK: PElem);
implementation
// создать список из одного элемента
procedure CreateList(var ListN, ListK: PElem; r: integer);
begin
New(ListN);
ListK:=ListN; // конец и начало совпадают
ListN^.info:=r;
ListN^.next:=nil;
end;
// добавить новый элемент перед первым
procedure AddFirst(var ListN: PElem; ListK: PElem; r: integer);
var Elem: PElem;
begin
new(Elem);
Elem^.info:=r;
Elem^.next:=ListN;
ListN:=Elem; // теперь он 1-ый
end;
// добавить новый элемент в конец
procedure AddLast(ListN: PElem; var ListK: PElem; r: integer);
begin
new(ListK^.next);
ListK^.next^.info:=r;
ListK^.next^.next:=nil;
ListK:= ListK^.next;
end;
// добавить новый элемент в середину после ListC (не в конец)
procedure AddMedium(ListN,ListC,ListK: PElem; r: integer);
var Elem: PElem;
begin
new(Elem);
Elem^.info:=r;
Elem^.next:=ListC^.next; // после него то, что было после ListC
ListC^.next:=Elem; // а он сам после ListC
end;
// очистить список
procedure FreeList(var ListN, ListK: PElem);
var Elem: PElem;
begin
Elem:=ListN;
while Elem<>nil do
begin
ListN:=ListN^.next;
Dispose(Elem);
Elem:=ListN;
end;
ListK:=nil;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ SOAP Support }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Soap.OPConvert;
{$INCLUDE 'CompVer.inc'}
interface
uses
System.Classes, System.SysUtils, Soap.IntfInfo, Soap.InvokeRegistry,
Soap.OpConvertOptions, Soap.SOAPAttachIntf, Xml.xmldom;
type
//Note: If you have to use one of the enumerated values in TSOAPConvertOption
// you must add OpConvertOptions to your uses clause.
TSOAPConvertOption = Soap.OpConvertOptions.TSOAPConvertOption;
TSOAPConvertOptions = Soap.OpConvertOptions.TSOAPConvertOptions;
IOPConvert = interface
['{1F955FE3-890B-474C-A3A4-5E072D30CC4F}']
{ Property Accessors }
function GetOptions: TSOAPConvertOptions;
procedure SetOptions(const Value: TSOAPConvertOptions);
function GetAttachments: TSoapDataList;
procedure SetAttachments(Value: TSoapDataList);
function GetTempDir: string;
procedure SetTempDir(const Value: string);
function GetEncoding: DOMString;
procedure SetEncoding(const Encoding: DOMString);
{ client methods }
function InvContextToMsg(const IntfMD: TIntfMetaData;
MethNum: Integer;
Con: TInvContext;
Headers: THeaderList): TStream;
procedure ProcessResponse(const Resp: TStream;
const IntfMD: TIntfMetaData;
const MD: TIntfMethEntry;
Context: TInvContext;
Headers: THeaderList); overload;
{ Obsolete - use version that takes a stream as first parameter }
procedure ProcessResponse(const Resp: InvString;
const IntfMD: TIntfMetaData;
const MD: TIntfMethEntry;
Context: TInvContext); overload; deprecated;
{ server methods }
procedure MsgToInvContext(const Request: InvString;
const IntfMD: TIntfMetaData;
var MethNum: Integer;
Context: TInvContext); overload;
procedure MsgToInvContext(const Request: TStream;
const IntfMD: TIntfMetaData;
var MethNum: Integer;
Context: TInvContext;
Headers: THeaderList); overload;
procedure MakeResponse(const IntfMD: TIntfMetaData;
const MethNum: Integer;
Context: TInvContext;
Response: TStream;
Headers: THeaderList);
procedure MakeFault(const Ex: Exception; EStream: TStream);
property Attachments: TSoapDataList read GetAttachments write SetAttachments;
property Options: TSOAPConvertOptions read GetOptions write SetOptions;
property TempDir: string read GetTempDir write SetTempDir;
property Encoding: DOMString read GetEncoding write SetEncoding;
end;
implementation
end.
|
unit MVCInterfaces;
interface
// Aqui declaramos a Interfaces que por definição são Classes Abstratas
// IModel faz sentido pois obriga a criar os metodos
// mas não entendi a necessidade de IView e IControle
type
TModeloMudou = procedure of object;
IModel = interface
['{9E0A6ECC-2A12-461F-AD82-0319DFBAB589}'] // Ctrl Shift G gera esta chave
procedure Initialize;
function GetOnModeloMudou: TModeloMudou;
// Utilizando o metodo get no Delphi7 a variável não recebia valor
procedure SetOnModeloMudou(value: TModeloMudou);
property OnModeloMudou : TModeloMudou read GetOnModeloMudou write SetOnModeloMudou;
end;
IView = interface
['{665DFC9C-5757-4B72-8923-E5B47B9DCDC1}']
procedure Initialize;
end;
IControle = interface
['{4844BF80-0094-494B-BC29-289C2904E275}']
procedure Initialize;
end;
implementation
end.
|
unit adot.Win.Log;
interface
uses
Winapi.Windows,
adot.Win.Tools,
adot.Tools,
adot.Log,
adot.Strings,
System.SysUtils,
System.SyncObjs,
System.Math,
System.Classes,
System.Generics.Collections,
System.Generics.Defaults;
type
// buffered + asynchronous, thread-safe.
// most general class for logging.
TWinFileLog = class(TFileLog)
protected
procedure LogSysInfo; override;
function LogLinesPrefix: String; override;
end;
// NOT buffered, NOT asynchronous, thread-safe
// Use it only if you need to see result immediately.
TWinSyncFileLog = class(TSyncFileLog)
protected
procedure LogSysInfo; override;
function LogLinesPrefix: String; override;
end;
// buffered, NOT asynchronous, thread-safe
// Use it only if multithreading is not allowed for some reason.
TWinSyncBufFileLog = class(TSyncBufFileLog)
protected
procedure LogSysInfo; override;
function LogLinesPrefix: String; override;
end;
TWinNullLog = TNullLog;
// Makes any logger to be GetLastError-transparent (for logging from injected
// DLLs etc). Usually it will be TSysErrorTransparentLog
TSysErrorTransparentLog = class(TCustomLog)
protected
type
TCustomLogH = class(TCustomLog);
var
FLog: TCustomLogH;
FOwns: Boolean;
procedure LogSysInfo; override;
function LogLinesPrefix: String; override;
procedure Send(AData: pointer; ASize: Integer); override;
procedure DoFlush; override;
public
constructor Create(ALog: TCustomLog; AOwns: Boolean);
destructor Destroy; override;
end;
// single server, multiple clients (same machine, any process).
TSharedMemoryLog = class
public
type
// Receives data from client and sends to the actual log.
TOnNewLog = reference to function(const ALogfileName: string): TCustomLog;
TCustomLogH = class(TCustomLog);
TCmd = (cmdSend, cmdFlush, cmdClose);
PSharedMemoryLogRec = ^TSharedMemoryLogRec;
TSharedMemoryLogRec = record
// Clients should not perform any operations with closed server,
// all wait operations will never signalated. Normally clients should
// be shut down before server is closed.
ServerClosed: Boolean; // w: server
// Every server object generated uniqueue session ID.
// Named synchronization objects are based on this value
// (check EventCanReadName/EventCanWriteName).
SessionId: TGUID; // w: server
// Information to be send from client to server.
MsgCmd: TCmd;
LogNameLen: integer; // length in chars (not bytes!)
LogName: array[0..255] of Char;
MsgSize: integer; // size in bytes
MsgData: array[0..2047] of Byte;
function BaseName: string;
function EventCanReadName: string;
function EventCanWriteName: string;
procedure SetLogName(const AName: string);
function GetLogName: string;
end;
// Instead of logging it sends data to server.
TClient = class(TCustomLog)
protected
const
WaitWriteBufMs: cardinal = infinite; //3000;
var
FSharedMem: PSharedMemoryLogRec;
FEvtMsgCanRead: THandle;
FEvtMsgCanWrite: THandle;
FLogFileName: String;
FCS: TCriticalSection;
procedure Send(AData: pointer; ASize: Integer); override;
procedure DoFlush; override;
procedure SendClose;
function AquireMsgQueue: Boolean;
procedure ReleaseMsgQueue;
procedure LogSysInfo; override;
function LogLinesPrefix: String; override;
public
constructor Create(ASharedMem: PSharedMemoryLogRec; const ALogFileName: string);
destructor Destroy; override;
end;
TServer = class
protected
type
TLogThread = class(TThread)
protected
FSharedMem: PSharedMemoryLogRec;
FEvtMsgCanRead: TEvent;
FEvtMsgCanWrite: TEvent;
FLogs: TObjectDictionary<String, TCustomLog>;
FSrvStarted: TEvent;
public
constructor Create(ASharedMem: PSharedMemoryLogRec);
destructor Destroy; override;
procedure Execute; override;
end;
var
SrvLog: TLogThread;
public
constructor Create(ASharedMem: PSharedMemoryLogRec; ANewLog: TOnNewLog);
destructor Destroy; override;
end;
end;
implementation
function PCharLen(S: PChar; AMaxLen: integer): integer;
var
i: Integer;
begin
for i := 0 to AMaxLen-1 do
if S[i]=#0 then
begin
Result := i;
Exit;
end;
Result := AMaxLen;
end;
function LogLineExtraPrefix: string;
begin
result := ' ' + TStr.IntToString(GetCurrentThreadId, 9);
end;
procedure LogExtraSysInfo(ADst: TCustomLog);
begin
ADst.Add('PID='+IntToStr(GetCurrentProcessId));
ADst.Add('Ingerity level: '+TProcess.GetIntegrityLevel);
end;
{ TWinFileLog }
function TWinFileLog.LogLinesPrefix: String;
begin
result := inherited LogLinesPrefix + LogLineExtraPrefix;
end;
procedure TWinFileLog.LogSysInfo;
begin
inherited;
LogExtraSysInfo(Self);
end;
{ TWinSyncFileLog }
function TWinSyncFileLog.LogLinesPrefix: String;
begin
result := inherited LogLinesPrefix + LogLineExtraPrefix;
end;
procedure TWinSyncFileLog.LogSysInfo;
begin
inherited;
LogExtraSysInfo(Self);
end;
{ TWinSyncBufFileLog }
function TWinSyncBufFileLog.LogLinesPrefix: String;
begin
result := inherited LogLinesPrefix + LogLineExtraPrefix;
end;
procedure TWinSyncBufFileLog.LogSysInfo;
begin
inherited;
LogExtraSysInfo(Self);
end;
{ TSysErrorTransparentLog }
constructor TSysErrorTransparentLog.Create(ALog: TCustomLog; AOwns: Boolean);
begin
FLog := TCustomLogH(ALog);
FOwns := AOwns;
inherited Create;
end;
destructor TSysErrorTransparentLog.Destroy;
begin
inherited;
if FOwns then
FreeAndNil(FLog)
else
FLog := nil;
end;
procedure TSysErrorTransparentLog.DoFlush;
var
LastError: Cardinal;
begin
LastError := GetLastError;
FLog.DoFlush;
if LastError<>GetLastError then
SetLastError(LastError);
end;
function TSysErrorTransparentLog.LogLinesPrefix: String;
var
LastError: Cardinal;
begin
LastError := GetLastError;
Result := FLog.LogLinesPrefix;
if LastError<>GetLastError then
SetLastError(LastError);
end;
procedure TSysErrorTransparentLog.LogSysInfo;
var
LastError: Cardinal;
begin
if FHeaderSent then
Exit;
FHeaderSent := True;
LastError := GetLastError;
FLog.LogSysInfo;
if LastError<>GetLastError then
SetLastError(LastError);
end;
procedure TSysErrorTransparentLog.Send(AData: pointer; ASize: Integer);
var
LastError: Cardinal;
begin
LastError := GetLastError;
FLog.Send(AData, ASize);
if LastError<>GetLastError then
SetLastError(LastError);
end;
{ TSharedMemoryLog.TSharedMemoryLogRec }
function TSharedMemoryLog.TSharedMemoryLogRec.BaseName: string;
begin
result := THex.Encode(SessionId, SizeOf(SessionId));
end;
function TSharedMemoryLog.TSharedMemoryLogRec.EventCanReadName: string;
begin
Result := 'EvtRd' + BaseName;
end;
function TSharedMemoryLog.TSharedMemoryLogRec.EventCanWriteName: string;
begin
Result := 'EvtWr' + BaseName;
end;
procedure TSharedMemoryLog.TSharedMemoryLogRec.SetLogName(const AName: string);
begin
LogNameLen := Min(Length(AName), Length(LogName));
Move(AName[Low(AName)], LogName, LogNameLen*SizeOf(Char));
end;
function TSharedMemoryLog.TSharedMemoryLogRec.GetLogName: string;
begin
SetLength(Result, LogNameLen);
Move(LogName, Result[Low(Result)], LogNameLen*SizeOf(Char));
end;
{ TSharedMemoryLog.TClient }
constructor TSharedMemoryLog.TClient.Create(ASharedMem: PSharedMemoryLogRec; const ALogFileName: string);
begin
FSharedMem := ASharedMem;
FLogFileName := ALogFileName;
FEvtMsgCanRead := OpenEvent(SYNCHRONIZE or EVENT_MODIFY_STATE, False, PChar(FSharedMem.EventCanReadName));
FEvtMsgCanWrite := OpenEvent(SYNCHRONIZE or EVENT_MODIFY_STATE, False, PChar(FSharedMem.EventCanWriteName));
FCS := TCriticalSection.Create;
inherited Create;
end;
destructor TSharedMemoryLog.TClient.Destroy;
begin
if (FSharedMem<>nil) and
(FEvtMsgCanRead<>0) and
(FEvtMsgCanWrite<>0) and
(FLogFileName<>'') and
(FCS<>nil)
then
SendClose;
CloseHandle(FEvtMsgCanWrite);
CloseHandle(FEvtMsgCanRead);
FSharedMem := nil;
FReeAndNil(FCS);
inherited;
end;
function TSharedMemoryLog.TClient.AquireMsgQueue: Boolean;
const
BreakIntervalMs = 50;
var
RemainDelayMs, IntervalDelayMs: Cardinal;
begin
// Server can became unavailable any time, so we have to break waiting
// operation time to time to make sure, that server is not closed yet.
Result := False;
RemainDelayMs := WaitWriteBufMs;
IntervalDelayMs := Min(BreakIntervalMs, WaitWriteBufMs);
repeat
if FSharedMem.ServerClosed then
Exit;
Result := WaitForSingleObject(FEvtMsgCanWrite,IntervalDelayMs)=WAIT_OBJECT_0;
if Result then
Exit;
if RemainDelayMs<>INFINITE then
if RemainDelayMs<=IntervalDelayMs then
Exit
else
Dec(RemainDelayMs, IntervalDelayMs);
until False;
end;
procedure TSharedMemoryLog.TClient.ReleaseMsgQueue;
begin
// enable server to process the message
SetEvent(FEvtMsgCanRead);
end;
procedure TSharedMemoryLog.TClient.DoFlush;
begin
FCS.Enter;
try
if AquireMsgQueue then
try
FSharedMem.MsgCmd := cmdFlush;
finally
ReleaseMsgQueue;
end;
finally
FCS.Leave;
end;
end;
function TSharedMemoryLog.TClient.LogLinesPrefix: String;
begin
// AH: DLL injected into chrome.exe may fail on GetLocalTime function,
// so we should not use any API call except something really important here,
// timestamp etc can be added on the server side.
result := format('%.9d', [GetCurrentProcessId]);
end;
procedure TSharedMemoryLog.TClient.LogSysInfo;
begin
// AH: we should log here only absolutely required information.
end;
procedure TSharedMemoryLog.TClient.SendClose;
begin
FCS.Enter;
try
if AquireMsgQueue then
try
FSharedMem.MsgCmd := cmdClose;
FSharedMem.SetLogName(FLogFileName);
finally
ReleaseMsgQueue;
end;
finally
FCS.Leave;
end;
end;
procedure TSharedMemoryLog.TClient.Send(AData: pointer; ASize: Integer);
var
n: Integer;
begin
FCS.Enter;
try
while ASize>0 do
begin
n := Min(ASize, SizeOf(FSharedMem.MsgData));
if AquireMsgQueue then
try
FSharedMem.MsgCmd := cmdSend;
FSharedMem.SetLogName(FLogfileName);
Move(AData^, FSharedMem.MsgData, n);
FSharedMem.MsgSize := n;
finally
ReleaseMsgQueue;
end
else
Break;
inc(PByte(AData), n);
dec(ASize, n);
end;
finally
FCS.Leave;
end;
end;
{ TSharedMemoryLog.TServer }
constructor TSharedMemoryLog.TServer.Create(ASharedMem: PSharedMemoryLogRec;
ANewLog: TOnNewLog);
begin
SrvLog := TLogThread.Create(ASharedMem);
SrvLog.FSrvStarted.WaitFor(INFINITE);
end;
destructor TSharedMemoryLog.TServer.Destroy;
begin
FreeAndNil(SrvLog);
inherited;
end;
{ TLogThread }
constructor TSharedMemoryLog.TServer.TLogThread.Create(ASharedMem: PSharedMemoryLogRec);
var
Sec: TSecurity.TDescrAttr;
begin
FSharedMem := ASharedMem;
FSharedMem.ServerClosed := False;
CreateGUID(FSharedMem.SessionId);
TSecurity.NullDACL(Sec);
FEvtMsgCanRead := TEvent.Create(@Sec.Attrs, False, False, FSharedMem.EventCanReadName);
FEvtMsgCanWrite := TEvent.Create(@Sec.Attrs, False, True, FSharedMem.EventCanWriteName);
FLogs := TObjectDictionary<String, TCustomLog>.Create;
FSrvStarted := TEvent.Create;
inherited Create(False);
end;
destructor TSharedMemoryLog.TServer.TLogThread.Destroy;
begin
if FSharedMem<>nil then
FSharedMem.ServerClosed := True;
Terminate;
if FEvtMsgCanRead<>nil then
FEvtMsgCanRead.SetEvent;
inherited;
FreeAndNil(FLogs);
FreeAndNil(FEvtMsgCanWrite);
FreeAndNil(FEvtMsgCanRead);
FSharedMem := nil;
FReeAndNil(FSrvStarted);
end;
procedure TSharedMemoryLog.TServer.TLogThread.Execute;
function GetLog(const AName: string): TCustomLog;
begin
if not FLogs.TryGetValue(AName, TCustomLog(Result)) then
begin
Result := TFileLog.Create(TCustomLog.GetLogFolder + ExtractFileName(AName));
FLogs.Add(AName, Result);
end;
end;
var
L: TCustomLogH;
N: String;
begin
try
FSrvStarted.SetEvent;
// allow to send next msg
// we create it with initial state = true (already signalated)
//FEvtMsgCanWrite.SetEvent;
repeat
// wait for message in the buf
FEvtMsgCanRead.WaitFor(INFINITE);
if Terminated then
Break;
{$IF [Low(FSharedMem.MsgCmd)..High(FSharedMem.MsgCmd)]<>[cmdSend, cmdFlush, cmdClose]} Fix it here! {$ENDIF}
// read & execute log command
N := Trim(FSharedMem.GetLogName);
if N<>'' then
begin
L := TCustomLogH(GetLog(N));
case FSharedMem.MsgCmd of
cmdSend:
L.Send(@FSharedMem.MsgData, FSharedMem.MsgSize);
cmdFlush:
L.Flush;
cmdClose:
FLogs.Remove(N);
end;
end;
// allow to send next msg
FEvtMsgCanWrite.SetEvent;
until False;
except
on e: exception do
raise;
end;
end;
end.
|
unit ADAPT.UnitTests.Generics.Collections;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, fpcunit, testutils, testregistry;
type
TAdaptUnitTestGenericsArray = class(TTestCase)
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestHookUp;
end;
implementation
uses
ADAPT,
ADAPT.Collections;
procedure TAdaptUnitTestGenericsArray.TestHookUp;
begin
Fail('Write your own test');
end;
procedure TAdaptUnitTestGenericsArray.SetUp;
begin
end;
procedure TAdaptUnitTestGenericsArray.TearDown;
begin
end;
initialization
RegisterTest(TAdaptUnitTestGenericsArray);
end.
|
unit MOSQUITTO;
interface
uses Windows;
const LIBMOSQUITTO_MAJOR = 1;
const LIBMOSQUITTO_MINOR = 4;
const LIBMOSQUITTO_REVISION = 5;
const LIBMOSQUITTO_VERSION_NUMBER = (LIBMOSQUITTO_MAJOR*1000000+LIBMOSQUITTO_MINOR*1000+LIBMOSQUITTO_REVISION);
const MOSQ_LOG_NONE = $00;
const MOSQ_LOG_INFO = $01;
const MOSQ_LOG_NOTICE = $02;
const MOSQ_LOG_WARNING = $04;
const MOSQ_LOG_ERR = $08;
const MOSQ_LOG_DEBUG = $10;
const MOSQ_LOG_SUBSCRIBE = $20;
const MOSQ_LOG_UNSUBSCRIBE = $40;
const MOSQ_LOG_WEBSOCKETS = $80;
const MOSQ_LOG_ALL = $FFF;
const MOSQ_ERR_CONN_PENDING = -1;
const MOSQ_ERR_SUCCESS = 0;
const MOSQ_ERR_NOMEM = 1;
const MOSQ_ERR_PROTOCOL = 2;
const MOSQ_ERR_INVAL = 3;
const MOSQ_ERR_NO_CONN = 4;
const MOSQ_ERR_CONN_REFUSED = 5;
const MOSQ_ERR_NOT_FOUND = 6;
const MOSQ_ERR_CONN_LOST = 7;
const MOSQ_ERR_TLS = 8;
const MOSQ_ERR_PAYLOAD_SIZE = 9;
const MOSQ_ERR_NOT_SUPPORTED = 10;
const MOSQ_ERR_AUTH = 11;
const MOSQ_ERR_ACL_DENIED = 12;
const MOSQ_ERR_UNKNOWN = 13;
const MOSQ_ERR_ERRNO = 14;
const MOSQ_ERR_EAI = 15;
const MOSQ_ERR_PROXY = 16;
type mosq_err_t = Longint;
const MOSQ_OPT_PROTOCOL_VERSION = 1;
type T_mosq_opt = Longint;
const MOSQ_MQTT_ID_MAX_LENGTH = 23;
const MQTT_PROTOCOL_V31 = 3;
const MQTT_PROTOCOL_V311 = 4;
type T_mosquitto_message = record
mid: Integer;
topic: PAnsiChar;
payload: Pointer;
payloadlen: Integer;
qos: Integer;
retain: Char;
end;
type P_mosquitto_message = ^T_mosquitto_message;
type PP_mosquitto_message = ^P_mosquitto_message;
type Tmosquitto = record end;
type Pmosquitto = ^Tmosquitto;
type PPAnsiChar = ^PAnsiChar;
type PPPAnsiChar = ^PPAnsiChar;
type T_pw_callback = function(buf: PAnsiChar; size: Integer; rwflag: Integer; userdata: Pointer): Integer; cdecl;
type T_on_connect = procedure(mosq: Pmosquitto; obj: Pointer; rc: Integer); cdecl;
type T_on_disconnect = procedure(mosq: Pmosquitto; obj: Pointer; rc: Integer); cdecl;
type T_on_publish = procedure(mosq: Pmosquitto; obj: Pointer; mid: Integer); cdecl;
type T_on_message = procedure(mosq: Pmosquitto; obj: Pointer; mosquitto_message: P_mosquitto_message); cdecl;
type T_on_subscribe = procedure(mosq: Pmosquitto; obj: Pointer; mid: Integer; qos_count : Integer; granted_qos: PInteger); cdecl;
type T_on_unsubscribe = procedure(mosq: Pmosquitto; obj: Pointer; mid: Integer); cdecl;
type T_on_log = procedure(mosq: Pmosquitto; obj: Pointer; level: Integer; str : PAnsiChar); cdecl;
function mosquitto_lib_version(major: PInteger; minor: PInteger; revision: PInteger):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_lib_init:Integer; cdecl; external 'mosquitto.dll';
function mosquitto_lib_cleanup:Integer; cdecl; external 'mosquitto.dll';
function mosquitto_new(id: PAnsiChar; clean_session: Byte; obj: Pointer): Pmosquitto; cdecl; external 'mosquitto.dll';
procedure mosquitto_destroy(mosq: Pmosquitto); cdecl; external 'mosquitto.dll';
function mosquitto_reinitialise(mosq: Pmosquitto; id: PAnsiChar; clean_session: Char; obj: Pointer):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_will_set(mosq: Pmosquitto; topic: PAnsiChar; payloadlen: Integer; payload: Pointer; qos: Integer; retain: Byte):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_will_clear(mosq: Pmosquitto):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_username_pw_set(mosq: Pmosquitto; username: PAnsiChar; password: PAnsiChar):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_connect(mosq: Pmosquitto; host: PAnsiChar; port: Integer; keepalive: Integer):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_connect_bind(mosq: Pmosquitto; host: PAnsiChar; port: Integer; keepalive: Integer; bind_address: PAnsiChar):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_connect_async(mosq: Pmosquitto; host: PAnsiChar; port: Integer; keepalive: Integer):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_connect_bind_async(mosq: Pmosquitto; host: PAnsiChar; port: Integer; keepalive: Integer; bind_address: PAnsiChar):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_connect_srv(mosq: Pmosquitto; host: PAnsiChar; keepalive: Integer; bind_address: PAnsiChar):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_reconnect(mosq: Pmosquitto):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_reconnect_async(mosq: Pmosquitto):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_disconnect(mosq: Pmosquitto):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_publish(mosq: Pmosquitto; mid: PInteger; topic: PAnsiChar; payloadlen: Integer; payload: Pointer; qos: Integer; retain: Byte):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_subscribe(mosq: Pmosquitto; mid: PInteger; sub: PAnsiChar; qos: Integer):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_unsubscribe(mosq: Pmosquitto; mid: PInteger; sub: PAnsiChar):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_message_copy(dst: P_mosquitto_message; src : P_mosquitto_message):Integer; cdecl; external 'mosquitto.dll';
procedure mosquitto_message_free(msg : PP_mosquitto_message); cdecl; external 'mosquitto.dll';
procedure mosquitto_message_clear(msg: P_mosquitto_message ); cdecl; external 'mosquitto.dll';
function mosquitto_loop(mosq: Pmosquitto; timeout:Integer; max_packets: Integer):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_loop_forever(mosq: Pmosquitto; timeout:Integer; max_packets: Integer):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_loop_start(mosq: Pmosquitto):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_loop_stop(mosq: Pmosquitto; force: Byte):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_socket(mosq: Pmosquitto):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_loop_read(mosq: Pmosquitto; max_packets: Integer):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_loop_write(mosq: Pmosquitto; max_packets: Integer):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_loop_misc(mosq: Pmosquitto):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_want_write(mosq: Pmosquitto):Char; cdecl; external 'mosquitto.dll';
function mosquitto_threaded_set(mosq: Pmosquitto; threaded: Char):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_opts_set(mosq: Pmosquitto; option: T_mosq_opt; value: Pointer):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_tls_set(mosq: Pmosquitto; cafile: PAnsiChar; capath: PAnsiChar; certfile: PAnsiChar; keyfile : PAnsiChar; pw_callback: T_pw_callback):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_tls_insecure_set(mosq: Pmosquitto; value: Char):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_tls_opts_set(mosq: Pmosquitto; cert_reqs: Integer; tls_version: PAnsiChar; ciphers: PAnsiChar):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_tls_psk_set(mosq: Pmosquitto; psk: PAnsiChar; identity: PAnsiChar; ciphers: PAnsiChar):Integer; cdecl; external 'mosquitto.dll';
procedure mosquitto_connect_callback_set(mosq: Pmosquitto; on_connect: T_on_connect); cdecl; external 'mosquitto.dll';
procedure mosquitto_disconnect_callback_set(mosq: Pmosquitto; on_disconnect:T_on_disconnect); cdecl; external 'mosquitto.dll';
procedure mosquitto_publish_callback_set(mosq: Pmosquitto; on_publish:T_on_publish); cdecl; external 'mosquitto.dll';
procedure mosquitto_message_callback_set(mosq: Pmosquitto; on_message: T_on_message); cdecl; external 'mosquitto.dll';
procedure mosquitto_subscribe_callback_set(mosq: Pmosquitto; on_subscribe: T_on_subscribe); cdecl; external 'mosquitto.dll';
procedure mosquitto_unsubscribe_callback_set(mosq: Pmosquitto; on_unsubscribe: T_on_unsubscribe); cdecl; external 'mosquitto.dll';
procedure mosquitto_log_callback_set(mosq: Pmosquitto; on_log: T_on_log); cdecl; external 'mosquitto.dll';
function mosquitto_reconnect_delay_set(mosq: Pmosquitto; reconnect_delay: Longword; reconnect_delay_max: Longword; reconnect_exponential_backoff: Char):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_max_inflight_messages_set(mosq: Pmosquitto; max_inflight_messages: Longword):Integer; cdecl; external 'mosquitto.dll';
procedure mosquitto_message_retry_set(mosq: Pmosquitto; message_retry: Longword); cdecl; external 'mosquitto.dll';
procedure mosquitto_user_data_set(mosq: Pmosquitto; obj: Pointer); cdecl; external 'mosquitto.dll';
function mosquitto_socks5_set(mosq: Pmosquitto; host: PAnsiChar; port: Integer; username: PAnsiChar; password: PAnsiChar):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_strerror(mosq_errno: Integer):PAnsiChar; cdecl; external 'mosquitto.dll';
function mosquitto_connack_string(connack_code: Integer):PAnsiChar; cdecl; external 'mosquitto.dll';
function mosquitto_sub_topic_tokenise(subtopic: PAnsiChar; topics: PPPAnsiChar; count: PInteger):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_sub_topic_tokens_free(topics: PPPAnsiChar; count: Integer):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_topic_matches_sub(sub: PAnsiChar; topic: PAnsiChar; result: PAnsiChar):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_pub_topic_check(topic: PAnsiChar):Integer; cdecl; external 'mosquitto.dll';
function mosquitto_sub_topic_check(topic: PAnsiChar):Integer; cdecl; external 'mosquitto.dll';
implementation
end.
|
{===============================================================================
Copyright(c) 2014, 北京北研兴电力仪表有限责任公司
All rights reserved.
学员信息单元
+ TStudentInfo 学员信息类
===============================================================================}
unit xStudentInfo;
interface
uses
System.Classes, System.SysUtils;
type
/// <summary>
/// 学员信息类
/// </summary>
TStudentInfo = class(TPersistent)
private
FstuTel: string;
FstuNumber: LongInt;
FstuSex: string;
FstuArea: string;
FstuLogin: string;
FstuName: string;
FstuPwd: string;
FstuIdCard: string;
FstuNote2: string;
FstuNote1: string;
public
/// <summary>
/// 学员编号
/// </summary>
property stuNumber : LongInt read FstuNumber write FstuNumber;
/// <summary>
/// 学员姓名
/// </summary>
property stuName : string read FstuName write FstuName;
/// <summary>
/// 性别
/// </summary>
property stuSex : string read FstuSex write FstuSex;
/// <summary>
/// 身份证号
/// </summary>
property stuIdCard : string read FstuIdCard write FstuIdcard;
/// <summary>
/// 登录名
/// </summary>
property stuLogin : string read FstuLogin write FstuLogin;
/// <summary>
/// 登录密码
/// </summary>
property stuPwd : string read FstuPwd write FstuPwd;
/// <summary>
/// 所在区域
/// </summary>
property stuArea : string read FstuArea write FstuArea;
/// <summary>
/// 联系电话
/// </summary>
property stuTel : string read FstuTel write FstuTel;
/// <summary>
/// 备注1
/// </summary>
property stuNote1 : string read FstuNote1 write FstuNote1;
/// <summary>
/// 备注2
/// </summary>
property stuNote2 : string read FstuNote2 write FstuNote2;
constructor Create;
/// <summary>
/// 清空信息
/// </summary>
procedure Clear;
/// <summary>
/// 复制对象
/// </summary>
procedure Assign(Source : TPersistent); override;
end;
implementation
{ TStuDentInfo }
procedure TStuDentInfo.Assign(Source: TPersistent);
begin
Assert(Source is TStuDentInfo);
FstuTel := TStuDentInfo(Source).stuTel;
FstuNumber := TStuDentInfo(Source).stuNumber;
FstuSex := TStuDentInfo(Source).stuSex;
FstuArea := TStuDentInfo(Source).stuArea;
FstuLogin := TStuDentInfo(Source).stuLogin;
FstuName := TStuDentInfo(Source).stuName;
FstuPwd := TStuDentInfo(Source).stuPwd;
FstuIdCard := TStuDentInfo(Source).stuIdCard;
FstuNote2 := TStuDentInfo(Source).stuNote2;
FstuNote1 := TStuDentInfo(Source).stuNote1;
end;
procedure TStudentInfo.Clear;
begin
FstuTel := '';
FstuNumber := 0;
FstuSex := '';
FstuArea := '';
FstuLogin := '';
FstuName := '';
FstuPwd := '';
FstuIdCard := '';
FstuNote2 := '';
FstuNote1 := '';
end;
constructor TStuDentInfo.Create;
begin
Clear;
end;
end.
|
{
"Window Handle Pool" - Copyright (c) Danijel Tkalcec
@html(<br>)
This unit implements a pool of Window Handles, associated with their threads.
Sicne creating Windows Handles takes a considerable ammount of processing time,
using a Window handle pool will speed things up.
@exclude
}
unit rtcHWndPool;
{$INCLUDE rtcDefs.inc}
interface
uses
rtcTrashcan,
Windows,
Messages,
SysUtils,
Classes,
rtcSyncObjs;
const
RTC_HWND_MSG_CODES=100000; // Number of message codes needed to separate messages from old and new handles
var
RTC_HWND_CLASS_NAME:PAnsiChar=''; // Class Name to be used when creating windows
RTC_WND_THREAD_PRIORITY:TThreadPriority=tpNormal;
procedure rtcInitMainHWND;
procedure rtcReleaseMainHWND;
function rtcGetHWND(Multi_Threaded:boolean):HWND;
procedure rtcReturnHWND(W:HWND);
function rtcGetNextMsgCode(W:HWND):longword;
implementation
type
tHWndThread=class(TThread)
public
constructor Create(CreateSuspended:boolean);
destructor Destroy; override;
procedure Execute; override;
end;
var
MyHdl,MyHdl_MT:HWND;
MyHdl_cnt, MyHdl_MT_cnt:integer;
MyMsgCode:cardinal=0;
CSHWND:TRtcCritSec;
thr:THwndThread;
Inside:TRtcEvent;
function RtcAllocateHWnd:HWND;
begin
Result := CreateWindowEx(WS_EX_TOOLWINDOW,
RTC_HWND_CLASS_NAME,
'', { Window name }
WS_POPUP, { Window Style }
0, 0, { X, Y }
0, 0, { Width, Height }
0, { hWndParent }
0, { hMenu }
HInstance, { hInstance }
nil); { CreateParam }
SetWindowLong(Result,GWL_USERDATA, 0);
end;
function RtcDeallocateHWnd(Wnd: HWND): boolean;
begin
Result := DestroyWindow(Wnd);
end;
{ tWSocketThread -> will be catching all multithreaded socket messages }
constructor tHWndThread.Create(CreateSuspended: boolean);
begin
inherited Create(True);
FreeOnTerminate:=True;
Priority:=RTC_WND_THREAD_PRIORITY;
if not CreateSuspended then Resume;
end;
destructor tHWndThread.Destroy;
begin
Inside.SetEvent;
inherited;
end;
procedure tHWndThread.Execute;
var
MsgRec:TMsg;
begin
MyHdl_MT:=RtcAllocateHWnd;
Inc(MyHdl_MT_cnt);
try
Inside.SetEvent;
while GetMessage(MsgRec,0,0,0) do
begin
TranslateMessage(MsgRec);
DispatchMessage(MsgRec);
end;
finally
rtcReturnHWND(MyHdl_MT);
end;
end;
function rtcGetHWND(Multi_Threaded:boolean):HWND;
begin
CSHWND.Enter;
try
if Multi_Threaded then
begin
if myHdl_MT=0 then
begin
Inside:=TRtcEvent.Create(True,False);
thr:=THWndThread.Create(False);
Inside.WaitFor(INFINITE); // wait for the thread to start and create a thread window handle.
end;
Inc(MyHdl_MT_cnt);
Result:=MyHdl_MT;
end
else
begin
if MyHdl=0 then
MyHdl:=RtcAllocateHWnd;
Inc(MyHdl_cnt);
Result:=MyHdl;
end;
finally
CSHWND.Leave;
end;
end;
procedure rtcInitMainHWND;
begin
CSHWND.Enter;
try
if MyHdl<>0 then
RtcDeallocateHWnd(myHdl);
MyHdl:=RtcAllocateHWnd;
Inc(MyHdl_cnt);
finally
CSHWND.Leave;
end;
end;
procedure rtcReleaseMainHWND;
begin
CSHWND.Enter;
try
Dec(MyHdl_cnt);
if (MyHdl_cnt=0) and (MyHdl<>0) then
begin
RtcDeallocateHWnd(myHdl);
MyHdl:=0;
end;
finally
CSHWND.Leave;
end;
end;
procedure rtcReturnHWND(W:HWND);
begin
CSHWND.Enter;
try
if W=myHdl_MT then
begin
Dec(MyHdl_MT_cnt);
if myHdl_MT_cnt=0 then
begin
RtcDeallocateHWnd(myHdl_MT);
myHdl_MT:=0;
end;
end
else if W=myHdl then
begin
Dec(MyHdl_cnt);
if myHdl_cnt=0 then
begin
RtcDeallocateHWnd(myHdl);
myHdl:=0;
end;
end;
finally
CSHWND.Leave;
end;
end;
function rtcGetNextMsgCode(W:HWND):longword;
begin
CSHWND.Enter;
try
MyMsgCode:=MyMsgCode+1;
if MyMsgCode>RTC_HWND_MSG_CODES then
MyMsgCode:=1;
Result:=MyMsgCode;
finally
CSHWND.Leave;
end;
end;
initialization
MyHdl:=0; MyHdl_cnt:=0;
MyHdl_MT:=0; MyHdl_MT_cnt:=0;
MyMsgCode:=0;
thr:=nil;
CSHWND:=TRtcCritSec.Create;
finalization
if assigned(thr) then
begin
try
// Stop background thread ...
Inside.ResetEvent;
PostThreadMessage(thr.ThreadID, WM_QUIT,0,0);
Inside.WaitFor(10000); // wait up to 10 seconds for thread to close
Sleep(10); // Allow the thread to terminate.
Inside.Free;
except
end;
end;
Garbage(CSHWND);
end.
|
unit form_AdvancedCopy;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Spin64, frame_Location, ComCtrls, zlibex;
type
Tfrm_AdvancedCopy = class(TForm)
pcMain: TPageControl;
tsSource: TTabSheet;
Label2: TLabel;
tsDestination: TTabSheet;
Label6: TLabel;
tsOptions: TTabSheet;
Label1: TLabel;
Label7: TLabel;
lblLimitBytes: TLabel;
Label3: TLabel;
Label5: TLabel;
se64StartOffset: TSpinEdit64;
ckLimitCopy: TCheckBox;
se64MaxBytesToCopy: TSpinEdit64;
seBlockSize: TSpinEdit64;
lblProgress: TLabel;
Label4: TLabel;
pbCopy: TButton;
pbCancel: TButton;
fmeLocationSrc: Tfme_Location;
fmeLocationDest: Tfme_Location;
pbClose: TButton;
tsCompression: TTabSheet;
rbNoCompression: TRadioButton;
rbDecompress: TRadioButton;
rbCompress: TRadioButton;
cbCompressionLevel: TComboBox;
lblCompression: TLabel;
procedure pbCloseClick(Sender: TObject);
procedure pbAboutClick(Sender: TObject);
procedure pbCancelClick(Sender: TObject);
procedure ckLimitCopyClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure pbCopyClick(Sender: TObject);
procedure rbSelectCompression(Sender: TObject);
private
Processing: boolean;
CancelFlag: boolean;
procedure EnableDisableControls();
procedure PopulateCompressionLevel();
procedure SetCompressionLevel(Value: TZCompressionLevel);
function GetCompressionLevel(): TZCompressionLevel;
procedure ProgressCallback(progress: int64; var cancel: boolean);
public
{ Public declarations }
end;
implementation
{$R *.dfm}
uses
SDUGeneral,
SDUDialogs,
SDUFilenameEdit_U,
gzipWrap,
AppGlobals,
About_U;
const
SECTOR_SIZE = 512;
procedure Tfrm_AdvancedCopy.ckLimitCopyClick(Sender: TObject);
begin
EnableDisableControls();
end;
procedure Tfrm_AdvancedCopy.FormShow(Sender: TObject);
begin
lblProgress.Caption := 'n/a';
pcMain.activepage := tsSource;
pbCancel.Enabled := FALSE;
fmeLocationSrc.SaveLocation := fetOpen;
fmeLocationDest.SaveLocation := fetSave;
fmeLocationSrc.Initialize();
fmeLocationDest.Initialize();
PopulateCompressionLevel();
rbNoCompression.checked := TRUE;
SetCompressionLevel(zcDefault);
EnableDisableControls();
end;
procedure Tfrm_AdvancedCopy.pbAboutClick(Sender: TObject);
begin
ShowAboutDialog();
end;
procedure Tfrm_AdvancedCopy.pbCancelClick(Sender: TObject);
begin
CancelFlag := TRUE;
end;
procedure Tfrm_AdvancedCopy.pbCloseClick(Sender: TObject);
begin
ModalResult := mrOK;
end;
procedure Tfrm_AdvancedCopy.pbCopyClick(Sender: TObject);
var
allOK: boolean;
length: int64;
prevCursor: TCursor;
locationSrc, locationDest: string;
gzFilename: string;
begin
allOK := TRUE;
CancelFlag := FALSE;
locationSrc:= fmeLocationSrc.GetLocation();
locationDest:= fmeLocationDest.GetLocation();
if allOK then
begin
if (locationSrc = '') then
begin
SDUMessageDlg(
'Please specify where you wish to copy data from',
mtError,
[mbOK],
0
);
allOK := FALSE;
end;
end;
if allOK then
begin
if (locationDest = '') then
begin
SDUMessageDlg(
'Please specify where you wish to copy data to',
mtError,
[mbOK],
0
);
allOK := FALSE;
end;
end;
if allOK then
begin
if (locationSrc = locationDest) then
begin
SDUMessageDlg(
'Source location cannot be the same as the destination',
mtError,
[mbOK],
0
);
allOK := FALSE;
end;
end;
if allOK then
begin
allOK := (SDUMessageDlg(
'About to copy FROM:'+SDUCRLF+
SDUCRLF+
locationSrc+SDUCRLF+
SDUCRLF+
'TO:'+SDUCRLF+
SDUCRLF+
locationDest+SDUCRLF+
SDUCRLF+
'Do you wish to proceed?',
mtConfirmation, [mbYes, mbNo], 0) = mrYes);
end;
if allOK then
begin
allOK := (SDUMessageDlg(
'WARNING:'+SDUCRLF+
SDUCRLF+
'THIS WILL OVERWRITE:'+SDUCRLF+
SDUCRLF+
locationDest+SDUCRLF+
SDUCRLF+
'Are you sure you wish to proceed?',
mtWarning, [mbYes, mbNo], 0) = mrYes);
end;
if allOK then
begin
length := -1;
if (ckLimitCopy.checked) then
begin
length := se64MaxBytesToCopy.Value;
end;
prevCursor := Screen.Cursor;
Screen.Cursor := crAppStart;
try
Processing := TRUE;
EnableDisableControls();
if rbNoCompression.checked then
begin
SDUCopyFile(
locationSrc,
locationDest,
se64StartOffset.value,
length,
seBlockSize.value,
ProgressCallback
);
end
else
begin
gzFilename := ExtractFilename(locationDest);
if (gzFilename = '') then
begin
gzFilename := COMPRESSED_FILE;
end;
gzip_Compression(
locationSrc,
locationDest,
rbCompress.checked,
GetCompressionLevel(),
se64StartOffset.value,
gzFilename,
length,
seBlockSize.value,
ProgressCallback
);
end;
finally
Processing := FALSE;
EnableDisableControls();
Screen.Cursor := prevCursor;
end;
end;
end;
procedure Tfrm_AdvancedCopy.EnableDisableControls();
begin
SDUEnableControl(pcMain, not(Processing));
SDUEnableControl(pbCopy, not(Processing));
SDUEnableControl(pbCancel, Processing);
SDUEnableControl(pbClose, not(Processing));
if not(Processing) then
begin
SDUEnableControl(se64MaxBytesToCopy, ckLimitCopy.checked);
SDUEnableControl(lblLimitBytes, ckLimitCopy.checked);
end;
SDUEnableControl(cbCompressionLevel, rbCompress.checked);
end;
procedure Tfrm_AdvancedCopy.ProgressCallback(progress: int64; var cancel: boolean);
begin
lblProgress.caption := inttostr(progress);
Application.ProcessMessages();
cancel := CancelFlag;
end;
procedure Tfrm_AdvancedCopy.PopulateCompressionLevel();
var
i: TZCompressionLevel;
begin
cbCompressionLevel.Items.Clear();
for i:=low(i) to high(i) do
begin
// Skip - indicate no compression via radiobutton
if (i = zcNone) then
begin
continue;
end;
cbCompressionLevel.Items.Add(GZLibCompressionLevelTitle(i));
end;
end;
procedure Tfrm_AdvancedCopy.SetCompressionLevel(Value: TZCompressionLevel);
begin
cbCompressionLevel.ItemIndex := cbCompressionLevel.Items.IndexOf(GZLibCompressionLevelTitle(Value));
end;
function Tfrm_AdvancedCopy.GetCompressionLevel(): TZCompressionLevel;
var
i: TZCompressionLevel;
retval: TZCompressionLevel;
begin
// Default...
retval := zcNone;
for i:=low(i) to high(i) do
begin
if (cbCompressionLevel.Items[cbCompressionLevel.ItemIndex] = GZLibCompressionLevelTitle(i)) then
begin
retval := i;
break;
end;
end;
Result := retval;
end;
procedure Tfrm_AdvancedCopy.rbSelectCompression(Sender: TObject);
begin
EnableDisableControls();
end;
END.
|
unit SLP.App;
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
Windows, SysUtils,
//JPL.Strings,
//JPL.Conversion,
{$IFDEF DEBUG}JPL.TimeLogger,{$ENDIF}
JPL.Console, JPL.ConsoleApp, JPL.CmdLineParser, JPL.Strings, JPL.TStr, JPL.Conversion, JPL.Win.SimpleTimer, JPL.DateTime,
//JPL.Win.SimpleTimer,
SLP.Types;
type
TApp = class(TJPConsoleApp)
private
AppParams: TAppParams;
public
procedure Init;
procedure Run;
procedure RegisterOptions;
procedure ProcessOptions;
procedure PerformMainAction;
procedure DisplayHelpAndExit(const ExCode: integer);
procedure DisplayShortUsageAndExit(const Msg: string; const ExCode: integer);
procedure DisplayBannerAndExit(const ExCode: integer);
procedure DisplayMessageAndExit(const Msg: string; const ExCode: integer);
end;
implementation
function NtQueryTimerResolution(var MinResolution: ULONG; var MaxResolution: ULONG; var ActualResolution: ULONG): ULONG; stdcall; external 'ntdll.dll';
{$region ' Init '}
procedure TApp.Init;
const
SEP_LINE = '-------------------------------------------------';
var
xmin, xmax, xcurrent: ULONG;
sTimerResMin, sTimerResMax: string;
begin
//----------------------------------------------------------------------------
AppName := 'Sleep';
MajorVersion := 1;
MinorVersion := 0;
Self.Date := EncodeDate(2020, 8, 25);
FullNameFormat := '%AppName% %MajorVersion%.%MinorVersion% [%OSShort% %Bits%-bit] (%AppDate%)';
Description := 'Pauses for a specified <color=white,black>NUMBER</color> of time <color=yellow>unit</color> (seconds by default).';
LicenseName := 'Freeware, Open Source';
License := 'This program is completely free. You can use it without any restrictions, also for commercial purposes.' + ENDL +
'The program''s source files are available at https://github.com/jackdp/sleep';
Author := 'Jacek Pazera';
HomePage := 'https://www.pazera-software.com/products/sleep/';
HelpPage := HomePage;
TrimExtFromExeShortName := True;
AppParams.ShowTime := False;
AppParams.TimeToWait := 0;
xmin := 0;
sTimerResMin := '';
sTimerResMax := '';
if NtQueryTimerResolution(xmin, xmax{%H-}, xcurrent{%H-}) = 0 then
begin
sTimerResMin := FormatFloat('0.000 ms', xmin / 1000 / 10);
sTimerResMax := FormatFloat('0.000 ms', xmax / 1000 / 10);
end;
HintBackgroundColor := TConsole.clLightGrayBg;
HintTextColor := TConsole.clBlackText;
//-----------------------------------------------------------------------------
TryHelpStr := ENDL + 'Try <color=white,black>' + ExeShortName + ' --help</color> for more information.';
ShortUsageStr :=
ENDL +
'Usage: ' + ExeShortName +
' <color=white,black>NUMBER</color>[<color=yellow>UNIT</color>] [-st] [-h] [-V] [--license] [--home]' + ENDL +
ENDL +
//'Mandatory arguments to long options are mandatory for short options too.' + ENDL +
'Options are case-sensitive. Options and values in square brackets are optional.';
ExtraInfoStr :=
ENDL +
'<color=white,black>NUMBER</color>' + ENDL +
'Any combination of real, integer, hexadecimal, or binary numbers. Each number may be followed by a time <color=yellow>unit</color> suffix. ' +
'The total waiting time will be the sum of all the numbers provided. ' + ENDL +
'The decimal separator in real numbers can be <color=white,darkcyan> . </color> (period) or <color=white,darkcyan> , </color> (comma).' + ENDL +
'Hexadecimal numbers must be prefixed with <color=white,darkcyan> 0x </color> or <color=white,darkcyan> $ </color> (dollar), '+
'eg. <color=white,black>0x0A</color>, <color=white,black>$0A</color>.' + ENDL +
'The letter <color=black,lightgray> D </color> at the end of the number is treated as a unit of time (days), ' +
'so if you want to set the wait time to $0D seconds, you must use <color=white,black>$ODs</color> and not <color=red>$OD</color>.' + ENDL +
'Binary numbers must be prefixed with <color=white,darkcyan> % </color> (percent), ' +
'eg. <color=white,black>%1010</color>.' + ENDL +
ENDL +
'Maximum waiting time: 2^32 ms = <color=white>' + MsToTimeStrEx(TIME_MAX) + '</color>';
if (sTimerResMin <> '') and (sTimerResMax <> '') then ExtraInfoStr := ExtraInfoStr +
ENDL + 'Timer resolution: min = ' + sTimerResMin + ', max = ' + sTimerResMax;
ExtraInfoStr := ExtraInfoStr +
ENDL + SEP_LINE + ENDL +
'Available time units:' + ENDL +
' <color=yellow,black>ms</color> for milliseconds' + ENDL +
' <color=yellow,black>s</color> for seconds (default)' + ENDL +
' <color=yellow,black>m</color> for minutes' + ENDL +
' <color=yellow,black>h</color> for hours' + ENDL +
' <color=yellow,black>d</color> for days' +
ENDL + SEP_LINE + ENDL +
'Exit codes:' + ENDL +
' ' + CON_EXIT_CODE_OK.ToString + ' - OK - no errors.' + ENDL +
' ' + CON_EXIT_CODE_SYNTAX_ERROR.ToString + ' - Syntax error.' + ENDL +
' ' + CON_EXIT_CODE_ERROR.ToString + ' - Other error.';
ExamplesStr :=
SEP_LINE + ENDL +
'Examples:' + ENDL +
' Pause for 1 second:' + ENDL + ' ' + ExeShortName + ' 1' + ENDL +
ENDL +
' Pause for 3.5 minutes: ' + ENDL +
' ' + ExeShortName + ' 3.5m' + ENDL +
' ' + ExeShortName + ' "3.5 m"' + ENDL +
' ' + ExeShortName + ' 3m 30s' + ENDL +
' ' + ExeShortName + ' 3500ms' + ENDL +
ENDL +
' Pause for 12h 12m 42s:' + ENDL +
' ' + ExeShortName + ' $ABBA' + ENDL +
' ' + ExeShortName + ' %1010101110111010' + ENDL +
' ' + ExeShortName + ' 12h 12m 42s' + ENDL +
ENDL +
' Pause for 2 minutes and 50 seconds:' + ENDL +
' ' + ExeShortName + ' 2m 50s' + ENDL +
' ' + ExeShortName + ' 3m "-10s"' + ENDL +
' ' + ExeShortName + ' 1.7e+2';
//------------------------------------------------------------------------------
end;
{$endregion Init}
{$region ' Run '}
procedure TApp.Run;
begin
inherited;
RegisterOptions;
Cmd.Parse;
ProcessOptions;
if Terminated then Exit;
PerformMainAction; // <----- the main procedure
end;
{$endregion Run}
{$region ' RegisterOptions '}
procedure TApp.RegisterOptions;
const
MAX_LINE_LEN = 120;
var
Category: string;
begin
Cmd.CommandLineParsingMode := cpmCustom;
Cmd.UsageFormat := cufWget;
Cmd.AcceptAllNonOptions := True;
// ------------ Registering command-line options -----------------
Category := 'info';
Cmd.RegisterOption('st', 'show-time', cvtNone, False, False, 'Show the calculated waiting time.', '', Category);
Cmd.RegisterOption('h', 'help', cvtNone, False, False, 'Show this help.', '', Category);
Cmd.RegisterShortOption('?', cvtNone, False, True, '', '', '');
Cmd.RegisterOption('V', 'version', cvtNone, False, False, 'Show application version.', '', Category);
Cmd.RegisterLongOption('license', cvtNone, False, False, 'Display program license.', '', Category);
Cmd.RegisterLongOption('home', cvtNone, False, False, 'Opens program home page in the default browser.', '', Category);
UsageStr :=
ENDL +
'Options:' + ENDL + Cmd.OptionsUsageStr(' ', 'info', MAX_LINE_LEN, ' ', 30);
end;
{$endregion RegisterOptions}
{$region ' ProcessOptions '}
procedure TApp.ProcessOptions;
var
i: integer;
sNum: string;
ms: Int64;
begin
// ---------------------------- Invalid options -----------------------------------
if Cmd.ErrorCount > 0 then
begin
DisplayShortUsageAndExit(Cmd.ErrorsStr, TConsole.ExitCodeSyntaxError);
Exit;
end;
//------------------------------------ Help ---------------------------------------
if (ParamCount = 0) or (Cmd.IsLongOptionExists('help')) or (Cmd.IsOptionExists('?')) then
begin
DisplayHelpAndExit(TConsole.ExitCodeOK);
Exit;
end;
//---------------------------------- Home -----------------------------------------
{$IFDEF MSWINDOWS}
if Cmd.IsLongOptionExists('home') then
begin
GoToHomePage;
Terminate;
Exit;
end;
{$ENDIF}
//------------------------------- Version ------------------------------------------
if Cmd.IsOptionExists('version') then
begin
DisplayBannerAndExit(TConsole.ExitCodeOK);
Exit;
end;
//------------------------------- Version ------------------------------------------
if Cmd.IsLongOptionExists('license') then
begin
TConsole.WriteTaggedTextLine('<color=white,black>' + LicenseName + '</color>');
DisplayLicense;
Terminate;
Exit;
end;
// --------------------------- Option: -st, --show-time -------------------------
AppParams.ShowTime := Cmd.IsOptionExists('st');
//---------------------------- NUMBERS --------------------------
if Cmd.UnknownParamCount = 0 then
begin
DisplayError('No time interval was specified!');
ExitCode := TConsole.ExitCodeError;
Terminate;
Exit;
end;
for i := 0 to Cmd.UnknownParamCount - 1 do
begin
sNum := Cmd.UnknownParams[i].ParamStr;
if not TryGetMilliseconds(sNum, ms) then
begin
DisplayError('Invalid time interval value: ' + sNum);
ExitCode := TConsole.ExitCodeError;
Terminate;
Exit;
end;
AppParams.TimeToWait += ms;
end;
if AppParams.TimeToWait > TIME_MAX then
begin
DisplayError('Time interval too large: ' + MsToTimeStrEx(AppParams.TimeToWait) + ' (max = ' + MsToTimeStrEx(TIME_MAX) + ')');
ExitCode := TConsole.ExitCodeError;
Terminate;
end;
end;
{$endregion ProcessOptions}
{$region ' PerformMainAction '}
procedure TApp.PerformMainAction;
var
st: TJPSimpleTimer;
dtNow, dtEnd: TDateTime;
msNow, msEnd: Comp;
s, sFormat: string;
function InsertColors(const sTime: string): string;
var
i, x: integer;
begin
Result := sTime;
for i := 1 to Length(Result) do
if (Result[i] <> '.') and (Result[i] <> '0') and (Result[i] <> ':') and (Result[i] <> ' ') then
begin
x := i;
if (x > 1) and (Result[i - 1] = '0') then Dec(x);
Result :=
'<color=darkgray>' + Copy(Result, 1, x - 1) + '</color>' +
'<color=yellow>' + Copy(Result, x, Length(Result)) + '</color>';
Break;
end;
end;
begin
if Terminated then Exit;
if AppParams.TimeToWait < 0 then
begin
DisplayError('The time interval can not be a negative number.');
ExitCode := TConsole.ExitCodeError;
DisplayTryHelp;
Exit;
end;
if AppParams.TimeToWait = 0 then Exit;
if AppParams.ShowTime then
begin
dtNow := Now;
msNow := TimeStampToMSecs(DateTimeToTimeStamp(dtNow));
msEnd := msNow + AppParams.TimeToWait;
dtEnd := TimeStampToDateTime(MSecsToTimeStamp(msEnd));
sFormat := 'yyyy-mm-dd hh:nn:ss.zzz';
s := MsToTimeStrEx(AppParams.TimeToWait, False, 'd ');
//s := '<color=darkgray>' + s + '</color>';
s := InsertColors(s);
TConsole.WriteTaggedTextLine('Time to wait: ' + s + ' / ' + TStr.InsertNumSep(AppParams.TimeToWait) + ' ms');
TConsole.WriteTaggedTextLine('From: ' + FormatDateTime(sFormat, dtNow) + ' To: <color=cyan,black>' + FormatDateTime(sFormat, dtEnd) + '</color>');
end;
st := TJPSimpleTimer.Create(nil, UINT(AppParams.TimeToWait), 1);
try
{$IFDEF DEBUG}TTimeLogger.StartLog;{$ENDIF}
st.Start;
finally
st.Free;
{$IFDEF DEBUG}
TTimeLogger.EndLog;
Writeln('The real elapsed time: ', TTimeLogger.ElapsedTimeStr);
Writeln('Difference: ', TTimeLogger.ElapsedTime - AppParams.TimeToWait, ' ms');
{$ENDIF}
end;
end;
{$endregion PerformMainAction}
{$region ' Display... procs '}
procedure TApp.DisplayHelpAndExit(const ExCode: integer);
begin
DisplayBanner;
DisplayShortUsage;
DisplayUsage;
DisplayExtraInfo;
DisplayExamples;
ExitCode := ExCode;
Terminate;
end;
procedure TApp.DisplayShortUsageAndExit(const Msg: string; const ExCode: integer);
begin
if Msg <> '' then Writeln(Msg);
DisplayShortUsage;
DisplayTryHelp;
ExitCode := ExCode;
Terminate;
end;
procedure TApp.DisplayBannerAndExit(const ExCode: integer);
begin
DisplayBanner;
ExitCode := ExCode;
Terminate;
end;
procedure TApp.DisplayMessageAndExit(const Msg: string; const ExCode: integer);
begin
Writeln(Msg);
ExitCode := ExCode;
Terminate;
end;
{$endregion Display... procs}
end.
|
// *******************************************************
//
// playIoT DataSnap Common
//
// Copyright(c) 2016 playIoT.
//
// jsf3rd@playiot.biz
//
// Update 2016. 04. 22
//
// *******************************************************
unit JdcGlobal.DSCommon;
interface
uses
Classes, SysUtils, FireDAC.Comp.Client, FireDAC.Stan.Intf, Data.DBXPlatform,
FireDAC.Comp.DataSet, FireDAC.Stan.Param, REST.JSON, XSuperObject,
System.Generics.Collections, System.DateUtils, Data.DB, Data.SqlTimSt,
JdcGlobal
{$IF CompilerVersion > 26} // upper XE5
, System.JSON
{$ELSE}
, Data.DBXJSON
{$ENDIF}
;
type
TDSOpenProc = function(const ARequestFilter: string = ''): TStream of object;
TDSOpenParamProc = function(AParams: TJSONObject; const ARequestFilter: string = '')
: TStream of object;
TDSCommon = class
private
public
// Clear JSONObject Members
class procedure ClearJSONObject(AValue: TJSONObject); overload;
class procedure ClearJSONObject(AValue: TJSONArray); overload;
// TDBXStream to TBytesStream
class function DSStreamToBytesStream(AStream: TStream): TBytesStream;
deprecated 'DBXStreamToMemoryStream';
// TDBXStream to TMemoryStream
class function DBXStreamToMemoryStream(AStream: TStream): TMemoryStream;
// FDQuery to TSream
class function DataSetToStream(AQuery: TFDQuery): TStream; overload;
deprecated 'TFDQueryHelper.ToStream';
// FDMemTable to TStream
class function DataSetToStream(AMemTab: TFDMemTable): TStream; overload;
deprecated 'TFDMemTableHelper.ToStream';
// DataSnap TStream to TFDDataSet
class procedure DSStreamToFDDataSet(AStream: TStream; ADataSet: TFDDataSet); static;
deprecated 'TFDDataSetHelper.LoadFromDSStream';
class procedure AddJSONValue<T: record >(var AObject: TJSONObject; ARecord: T;
APreFix: string = '');
class procedure AddJSONArray<T: record >(var AObject: TJSONObject; ARecord: T);
class function DSProcToRecord<T: record >(AProc: TDSOpenProc): T; overload;
class function DSProcToRecord<T: record >(AProc: TDSOpenParamProc; AParam: TJSONObject)
: T; overload;
class function DSProcToRecordArray<T: record >(AProc: TDSOpenProc): TArray<T>; overload;
class function DSProcToRecordArray<T: record >(AProc: TDSOpenParamProc;
AParam: TJSONObject): TArray<T>; overload;
end;
TFDDataSetHelper = class helper for TFDDataSet
private
function FieldToJSONVlaue(AField: TField): TJSONValue;
function GetNameValue(AValue: TJSONValue; AName: String): TJSONValue;
function GetJSONObject(AValue: TJSONObject; AName: String): TJSONObject;
function GetJSONArray(AValue: TJSONArray; AName: String): TJSONArray;
procedure FieldByJsonValue(AField: TField; AValue: TJSONValue;
AProc: TLogProc = nil); overload;
procedure FieldByJsonValue(AValue: TJSONValue; AName: String;
AProc: TLogProc = nil); overload;
procedure FieldByJSONArray(AValue: TJSONArray; AName: String; AProc: TLogProc = nil);
public
procedure LoadFromDSStream(AStream: TStream);
function ToJSON: TJSONObject;
function ToRecord<T: Record >(AName: String = ''): T;
function ToRecordArray<T: Record >(AName: String = ''): TArray<T>;
procedure FieldByJSONObject(AObject: TJSONObject; AProc: TLogProc = nil); overload;
procedure FieldByJSONObject(AJSON: String; AProc: TLogProc = nil); overload;
end;
TFDQueryHelper = class helper for TFDQuery
private
procedure ParamByJsonValue(AParam: TFDParam; AValue: TJSONValue;
AProc: TLogProc = nil); overload;
procedure ParamByJsonValue(AValue: TJSONValue; AName: String;
AProc: TLogProc = nil); overload;
procedure ParamByJSONArray(AValue: TJSONArray; AName: String; AProc: TLogProc = nil);
public
function Clone: TFDQuery;
function ToStream: TStream;
procedure LoadFromDSStream(AStream: TStream);
function ToJSON: TJSONObject;
function ToRecord<T: Record >(AName: String = ''): T;
function ToRecordArray<T: Record >(AName: String = ''): TArray<T>;
procedure ParamByJSONObject(AObject: TJSONObject; AProc: TLogProc = nil);
procedure FieldByJSONObject(AObject: TJSONObject; AProc: TLogProc = nil); overload;
procedure FieldByJSONObject(AJSON: String; AProc: TLogProc = nil); overload;
end;
TFDMemTableHelper = class helper for TFDMemTable
public
function Clone: TFDMemTable;
function ToStream: TStream;
procedure LoadFromDSStream(AStream: TStream);
function ToJSON: TJSONObject;
function ToRecord<T: Record >(AName: String = ''): T;
function ToRecordArray<T: Record >(AName: String = ''): TArray<T>;
procedure FieldByJSONObject(AObject: TJSONObject; AProc: TLogProc = nil); overload;
procedure FieldByJSONObject(AJSON: String; AProc: TLogProc = nil); overload;
end;
function GetFieldTypeName(AType: TFieldType): string;
const
FieldTypeName: array [0 .. 51] of string = //
('Unknown', 'String', 'Smallint', 'Integer', 'Word', // 0..4
'Boolean', 'Float', 'Currency', 'BCD', 'Date', 'Time', 'DateTime', // 5..11
'Bytes', 'VarBytes', 'AutoInc', 'Blob', 'Memo', 'Graphic', 'FmtMemo', // 12..18
'ParadoxOle', 'DBaseOle', 'TypedBinary', 'Cursor', 'FixedChar', 'WideString', // 19..24
'Largeint', 'ADT', 'Array', 'Reference', 'DataSet', 'OraBlob', 'OraClob', // 25..31
'Variant', 'Interface', 'IDispatch', 'Guid', 'TimeStamp', 'FMTBcd', // 32..37
'FixedWideChar', 'WideMemo', 'OraTimeStamp', 'OraInterval', // 38..41
'LongWord', 'Shortint', 'Byte', 'Extended', 'Connection', 'Params', 'Stream', // 42..48
'TimeStampOffset', 'Object', 'Single'); // 49..51
implementation
uses JdcGlobal.ClassHelper;
function GetFieldTypeName(AType: TFieldType): string;
begin
if Integer(AType) > Length(FieldTypeName) - 1 then
result := Integer(AType).ToString
else
result := FieldTypeName[Integer(AType)];
end;
{ TDSCommon }
class procedure TDSCommon.AddJSONArray<T>(var AObject: TJSONObject; ARecord: T);
var
tmp: TJSONObject;
MyPair: TJSONPair;
ArrayTemp: TStringList;
MyElem: TJSONValue;
begin
tmp := REST.JSON.TJson.RecordToJsonObject<T>(ARecord);
for MyPair in tmp do
begin
if MyPair.JsonValue is TJSONObject then
Continue;
if MyPair.JsonValue is TJSONArray then
begin
ArrayTemp := TStringList.Create;
for MyElem in TJSONArray(MyPair.JsonValue) do
begin
if MyElem is TJSONObject then
Continue;
ArrayTemp.Add(MyElem.Value);
end;
AObject.AddPair(MyPair.JsonString.Value, ArrayTemp.CommaText);
ArrayTemp.Free;
end
else if MyPair.JsonValue is TJSONString then
AObject.AddPair(MyPair.Clone as TJSONPair);
end;
tmp.Free;
end;
class procedure TDSCommon.AddJSONValue<T>(var AObject: TJSONObject; ARecord: T;
APreFix: string);
var
tmp: TJSONObject;
MyPair: TJSONPair;
NewKey: string;
begin
tmp := REST.JSON.TJson.RecordToJsonObject<T>(ARecord);
if not APreFix.IsEmpty then
begin
for MyPair in tmp do
begin
NewKey := APreFix + MyPair.JsonString.Value;
MyPair.JsonString.Free;
MyPair.JsonString := TJSONString.Create(NewKey);
end;
end;
try
for MyPair in tmp do
begin
AObject.AddPair(MyPair.Clone as TJSONPair);
end;
finally
tmp.Free;
end;
end;
class procedure TDSCommon.ClearJSONObject(AValue: TJSONArray);
begin
{$IF CompilerVersion > 26} // upper XE5
while AValue.Count > 0 do
{$ELSE}
while AValue.Size > 0 do
{$ENDIF}
begin
AValue.Remove(0).Free;
end;
end;
class function TDSCommon.DataSetToStream(AQuery: TFDQuery): TStream;
begin
result := AQuery.ToStream;
end;
class function TDSCommon.DataSetToStream(AMemTab: TFDMemTable): TStream;
begin
result := AMemTab.ToStream;
end;
class procedure TDSCommon.ClearJSONObject(AValue: TJSONObject);
var
Name: String;
begin
if not Assigned(AValue) then
Exit;
{$IF CompilerVersion > 26} // upper XE5
while AValue.Count > 0 do
begin
Name := AValue.Pairs[0].JsonString.Value;
{$ELSE}
while AValue.Size > 0 do
begin
Name := AValue.Get(0).JsonString.Value;
{$ENDIF}
AValue.RemovePair(Name).Free;
end;
end;
class function TDSCommon.DSProcToRecord<T>(AProc: TDSOpenParamProc; AParam: TJSONObject): T;
var
MemTab: TFDMemTable;
begin
MemTab := TFDMemTable.Create(nil);
try
MemTab.LoadFromDSStream(AProc(AParam));
result := MemTab.ToRecord<T>;
finally
MemTab.Free;
end;
end;
class function TDSCommon.DSProcToRecord<T>(AProc: TDSOpenProc): T;
var
MemTab: TFDMemTable;
begin
MemTab := TFDMemTable.Create(nil);
try
MemTab.LoadFromDSStream(AProc);
result := MemTab.ToRecord<T>;
finally
MemTab.Free;
end;
end;
class function TDSCommon.DSProcToRecordArray<T>(AProc: TDSOpenParamProc; AParam: TJSONObject)
: TArray<T>;
var
MemTab: TFDMemTable;
begin
MemTab := TFDMemTable.Create(nil);
try
MemTab.LoadFromDSStream(AProc(AParam));
result := MemTab.ToRecordArray<T>;
finally
MemTab.Free;
end;
end;
class function TDSCommon.DSProcToRecordArray<T>(AProc: TDSOpenProc): TArray<T>;
var
MemTab: TFDMemTable;
begin
MemTab := TFDMemTable.Create(nil);
try
MemTab.LoadFromDSStream(AProc);
result := MemTab.ToRecordArray<T>;
finally
MemTab.Free;
end;
end;
class function TDSCommon.DSStreamToBytesStream(AStream: TStream): TBytesStream;
const
BufferSize = 1024 * 32;
var
Buffer: TBytes;
BytesReadCount: Integer;
begin
result := TBytesStream.Create;
SetLength(Buffer, BufferSize);
repeat
BytesReadCount := AStream.Read(Buffer[0], BufferSize);
result.Write(Buffer[0], BytesReadCount);
until BytesReadCount < BufferSize;
result.Position := 0;
end;
class function TDSCommon.DBXStreamToMemoryStream(AStream: TStream): TMemoryStream;
const
BufferSize = 1024 * 32;
var
Buffer: TBytes;
ReadCount: Integer;
begin
result := TMemoryStream.Create;
try
SetLength(Buffer, BufferSize);
repeat
ReadCount := AStream.Read(Buffer[0], BufferSize);
result.Write(Buffer[0], ReadCount);
until ReadCount < BufferSize;
result.Position := 0;
except
result.Free;
raise;
end;
end;
class procedure TDSCommon.DSStreamToFDDataSet(AStream: TStream; ADataSet: TFDDataSet);
begin
ADataSet.LoadFromDSStream(AStream);
end;
{ TFDQueryHelper }
function TFDQueryHelper.Clone: TFDQuery;
var
I: Integer;
begin
result := TFDQuery.Create(nil);
result.Connection := Self.Connection;
result.OnExecuteError := Self.OnExecuteError;
result.OnReconcileError := Self.OnReconcileError;
result.CachedUpdates := Self.CachedUpdates;
result.UpdateOptions.KeyFields := Self.UpdateOptions.KeyFields;
result.UpdateOptions.UpdateTableName := Self.UpdateOptions.UpdateTableName;
result.SQL.Text := Self.SQL.Text;
result.Name := Self.Name + '_' + Format('%0.5d', [Random(100000)]);
for I := 0 to Self.ParamCount - 1 do
result.Params.Items[I].DataType := Self.Params.Items[I].DataType;
end;
procedure TFDQueryHelper.FieldByJSONObject(AObject: TJSONObject; AProc: TLogProc);
begin
TFDDataSet(Self).FieldByJSONObject(AObject, AProc);
end;
procedure TFDQueryHelper.FieldByJSONObject(AJSON: String; AProc: TLogProc);
begin
TFDDataSet(Self).FieldByJSONObject(AJSON, AProc);
end;
procedure TFDQueryHelper.LoadFromDSStream(AStream: TStream);
begin
TFDDataSet(Self).LoadFromDSStream(AStream);
end;
procedure TFDQueryHelper.ParamByJsonValue(AParam: TFDParam; AValue: TJSONValue;
AProc: TLogProc);
var
Msg: String;
begin
if not Assigned(AParam) then
Exit;
Msg := Format('DataSet=%s,ParamName=%s,DataType=%s,Value=%s',
[Self.Name, AParam.Name, GetFieldTypeName(AParam.DataType), AValue.Value]);
if Assigned(AProc) then
AProc(msDebug, 'SQLParameter', Msg);
PrintDebug(Msg);
case AParam.DataType of
ftUnknown:
raise Exception.Create(Format('DataSet=%s,ParamName=%s,Unknown DataType',
[Self.Name, AParam.Name]));
ftString, ftWideString:
if Self.Params.ArraySize = 1 then
AParam.AsString := (AValue as TJSONString).Value
else
AParam.AsStrings[Self.Tag] := (AValue as TJSONString).Value;
ftSmallint, ftInteger, ftWord, ftShortint:
if Self.Params.ArraySize = 1 then
AParam.AsInteger := (AValue as TJSONNumber).AsInt
else
AParam.AsIntegers[Self.Tag] := (AValue as TJSONNumber).AsInt;
{$IF CompilerVersion > 26} // upper XE5
ftBoolean:
if Self.Params.ArraySize = 1 then
AParam.AsBoolean := (AValue as TJSONBool).AsBoolean
else
AParam.AsBooleans[Self.Tag] := (AValue as TJSONBool).AsBoolean;
ftDate:
if Self.Params.ArraySize = 1 then
AParam.AsDate := StrToDate((AValue as TJSONString).Value, DefaultFormatSettings)
else
AParam.AsDates[Self.Tag] := StrToDate((AValue as TJSONString).Value,
DefaultFormatSettings);
ftTime:
if Self.Params.ArraySize = 1 then
AParam.AsTime := StrToTime((AValue as TJSONString).Value, DefaultFormatSettings)
else
AParam.AsTimes[Self.Tag] := StrToTime((AValue as TJSONString).Value,
DefaultFormatSettings);
ftDateTime:
if Self.Params.ArraySize = 1 then
AParam.AsDateTime := ISO8601ToDate((AValue as TJSONString).Value)
else
AParam.AsDateTimes[Self.Tag] := ISO8601ToDate((AValue as TJSONString).Value);
ftTimeStamp:
if Self.Params.ArraySize = 1 then
AParam.AsSQLTimeStamp := DateTimeToSQLTimeStamp
(ISO8601ToDate((AValue as TJSONString).Value))
else
AParam.AsSQLTimeStamps[Self.Tag] :=
DateTimeToSQLTimeStamp(ISO8601ToDate((AValue as TJSONString).Value));
{$ELSE}
ftBoolean:
if Self.Params.ArraySize = 1 then
AParam.AsBoolean := AValue is TJSONTrue
else
AParam.AsBooleans[Self.Tag] := AValue is TJSONTrue;
ftDate, ftTime, ftDateTime, ftTimeStamp:
if Self.Params.ArraySize = 1 then
AParam.Value := AValue.Value
else
AParam.Values[Self.Tag] := AValue.Value;
{$ENDIF}
ftFloat:
if Self.Params.ArraySize = 1 then
AParam.AsFloat := (AValue as TJSONNumber).AsDouble
else
AParam.AsFloats[Self.Tag] := (AValue as TJSONNumber).AsDouble;
ftCurrency:
if Self.Params.ArraySize = 1 then
AParam.AsCurrency := (AValue as TJSONNumber).AsDouble
else
AParam.AsCurrencys[Self.Tag] := (AValue as TJSONNumber).AsDouble;
ftGuid:
if Self.Params.ArraySize = 1 then
AParam.AsGUID := TGUID.Create((AValue as TJSONString).Value)
else
AParam.AsGUIDs[Self.Tag] := TGUID.Create((AValue as TJSONString).Value);
ftLargeint:
if Self.Params.ArraySize = 1 then
AParam.AsLargeInt := (AValue as TJSONNumber).AsInt64
else
AParam.AsLargeInts[Self.Tag] := (AValue as TJSONNumber).AsInt64;
ftExtended:
if Self.Params.ArraySize = 1 then
AParam.AsExtended := (AValue as TJSONNumber).AsDouble
else
AParam.AsExtendeds[Self.Tag] := (AValue as TJSONNumber).AsDouble;
ftLongWord:
if Self.Params.ArraySize = 1 then
AParam.AsLongword := (AValue as TJSONNumber).AsInt
else
AParam.AsLongwords[Self.Tag] := (AValue as TJSONNumber).AsInt;
ftSingle:
if Self.Params.ArraySize = 1 then
AParam.AsSingle := (AValue as TJSONNumber).AsDouble
else
AParam.AsSingles[Self.Tag] := (AValue as TJSONNumber).AsDouble;
ftWideMemo:
if Self.Params.ArraySize = 1 then
AParam.AsWideMemo := (AValue as TJSONString).Value
else
AParam.AsWideMemos[Self.Tag] := (AValue as TJSONString).Value;
else
raise Exception.Create(Format('DataSet=%s,ParamName=%s,UnsurportDataType=%s',
[Self.Name, AParam.Name, GetFieldTypeName(AParam.DataType)]));
end;
end;
procedure TFDQueryHelper.ParamByJSONArray(AValue: TJSONArray; AName: String; AProc: TLogProc);
var
MyElem: TJSONValue;
Index: Integer;
begin
Index := 1;
for MyElem in AValue do
begin
ParamByJsonValue(MyElem, AName + '_' + Index.ToString, AProc);
Inc(Index);
end;
end;
procedure TFDQueryHelper.ParamByJSONObject(AObject: TJSONObject; AProc: TLogProc);
var
MyElem: TJSONPair;
begin
for MyElem in AObject do
ParamByJsonValue(MyElem.JsonValue, MyElem.JsonString.Value, AProc);
end;
procedure TFDQueryHelper.ParamByJsonValue(AValue: TJSONValue; AName: String; AProc: TLogProc);
begin
if AValue is TJSONObject then
ParamByJSONObject(AValue as TJSONObject, AProc)
else if AValue is TJSONArray then
begin
ParamByJSONArray(AValue as TJSONArray, AName, AProc)
end
else
ParamByJsonValue(Self.FindParam(AName), AValue, AProc);
end;
function TFDQueryHelper.ToStream: TStream;
begin
result := TMemoryStream.Create;
Self.Close;
Self.Open;
Self.Refresh;
Self.SaveToStream(result, sfBinary);
result.Position := 0;
end;
function TFDQueryHelper.ToRecordArray<T>(AName: String): TArray<T>;
begin
result := TFDDataSet(Self).ToRecordArray<T>(AName);
end;
function TFDQueryHelper.ToJSON: TJSONObject;
begin
result := TFDDataSet(Self).ToJSON;
end;
function TFDQueryHelper.ToRecord<T>(AName: String): T;
begin
result := TFDDataSet(Self).ToRecord<T>(AName);
end;
{ TFDMemTableHelper }
function TFDMemTableHelper.Clone: TFDMemTable;
var
Stream: TStream;
StoreItems: TFDStoreItems;
begin
result := TFDMemTable.Create(Self.Owner);
StoreItems := Self.ResourceOptions.StoreItems;
Self.ResourceOptions.StoreItems := [siData, siDelta, siMeta];
Stream := TMemoryStream.Create;
try
Self.SaveToStream(Stream);
Stream.Position := 0;
result.LoadFromStream(Stream);
finally
Self.ResourceOptions.StoreItems := StoreItems;
FreeAndNil(Stream);
end;
end;
procedure TFDMemTableHelper.FieldByJSONObject(AObject: TJSONObject; AProc: TLogProc);
begin
TFDDataSet(Self).FieldByJSONObject(AObject, AProc);
end;
procedure TFDMemTableHelper.FieldByJSONObject(AJSON: String; AProc: TLogProc);
begin
TFDDataSet(Self).FieldByJSONObject(AJSON, AProc);
end;
procedure TFDMemTableHelper.LoadFromDSStream(AStream: TStream);
begin
TFDDataSet(Self).LoadFromDSStream(AStream);
end;
function TFDMemTableHelper.ToRecordArray<T>(AName: String): TArray<T>;
begin
result := TFDDataSet(Self).ToRecordArray<T>(AName);
end;
function TFDMemTableHelper.ToJSON: TJSONObject;
begin
result := TFDDataSet(Self).ToJSON;
end;
function TFDMemTableHelper.ToRecord<T>(AName: String): T;
begin
result := TFDDataSet(Self).ToRecord<T>(AName);
end;
function TFDMemTableHelper.ToStream: TStream;
begin
result := TMemoryStream.Create;
Self.SaveToStream(result, sfBinary);
result.Position := 0;
end;
{ TFDDataSetHelper }
procedure TFDDataSetHelper.FieldByJsonValue(AField: TField; AValue: TJSONValue;
AProc: TLogProc);
var
Msg: String;
begin
if not Assigned(AField) then
Exit;
Msg := Format('DataSet=%s,FieldName=%s,DataType=%s,Value=%s',
[Self.Name, AField.Name, GetFieldTypeName(AField.DataType), AValue.Value]);
if Assigned(AProc) then
AProc(msDebug, 'SQLParameter', Msg);
PrintDebug(Msg);
case AField.DataType of
ftUnknown:
raise Exception.Create(Format('DataSet=%s,ParamName=%s,Unknown DataType',
[Self.Name, AField.Name]));
ftString, ftWideString:
AField.AsString := (AValue as TJSONString).Value;
ftSmallint, ftInteger, ftWord, ftShortint:
AField.AsInteger := (AValue as TJSONNumber).AsInt;
{$IF CompilerVersion > 26} // upper XE5
ftBoolean:
AField.AsBoolean := (AValue as TJSONBool).AsBoolean;
ftDate, ftTime, ftDateTime:
AField.AsDateTime := ISO8601ToDate((AValue as TJSONString).Value);
ftTimeStamp:
AField.AsSQLTimeStamp := DateTimeToSQLTimeStamp
(ISO8601ToDate((AValue as TJSONString).Value));
{$ELSE}
ftBoolean:
AField.AsBoolean := AValue is TJSONTrue;
ftDate, ftTime, ftDateTime, ftTimeStamp:
AField.Value := AValue.Value;
{$ENDIF}
ftGuid:
TGuidField(AField).AsGUID := TGUID.Create((AValue as TJSONString).Value);
ftFloat:
AField.AsFloat := (AValue as TJSONNumber).AsDouble;
ftCurrency:
AField.AsCurrency := (AValue as TJSONNumber).AsDouble;
ftLargeint:
AField.AsLargeInt := (AValue as TJSONNumber).AsInt64;
ftExtended:
AField.AsExtended := (AValue as TJSONNumber).AsDouble;
ftLongWord:
AField.AsLongword := (AValue as TJSONNumber).AsInt;
ftSingle:
AField.AsSingle := (AValue as TJSONNumber).AsDouble;
else
raise Exception.Create(Format('DataSet=%s,ParamName=%s,UnsurportDataType=%s',
[Self.Name, AField.Name, GetFieldTypeName(AField.DataType)]));
end;
end;
procedure TFDDataSetHelper.FieldByJsonValue(AValue: TJSONValue; AName: String;
AProc: TLogProc);
begin
if AValue is TJSONObject then
FieldByJSONObject(AValue as TJSONObject, AProc)
else if AValue is TJSONArray then
begin
FieldByJSONArray(AValue as TJSONArray, AName, AProc)
end
else
FieldByJsonValue(Self.FindField(AName), AValue, AProc);
end;
function TFDDataSetHelper.FieldToJSONVlaue(AField: TField): TJSONValue;
begin
if not Assigned(AField) then
Exit(TJSONString.Create);
case AField.DataType of
ftUnknown:
raise Exception.Create(Format('DataSet=%s,FieldName=%s,Unknown DataType',
[Self.Name, AField.FieldName]));
ftString, ftWideString:
result := TJSONString.Create(AField.AsString);
ftSmallint, ftInteger, ftWord, ftShortint, ftAutoInc:
result := TJSONNumber.Create(AField.AsInteger);
{$IF CompilerVersion > 26} // upper XE5
ftBoolean:
result := TJSONBool.Create(AField.AsBoolean);
ftDate, ftTime, ftDateTime:
result := TJSONString.Create(AField.AsDateTime.ToISO8601);
ftTimeStamp:
result := TJSONString.Create(SQLTimeStampToDateTime(AField.AsSQLTimeStamp).ToISO8601);
{$ELSE}
ftBoolean:
begin
if AField.AsBoolean then
result := TJSONTrue.Create
else
result := TJSONFalse.Create;
end;
ftDate, ftTime, ftDateTime:
result := TJSONString.Create(AField.AsDateTime.ToString);
ftTimeStamp:
result := TJSONString.Create(SQLTimeStampToDateTime(AField.AsSQLTimeStamp).ToString);
{$ENDIF}
ftFloat:
result := TJSONNumber.Create(AField.AsFloat);
ftCurrency:
result := TJSONNumber.Create(AField.AsCurrency);
ftLargeint:
result := TJSONNumber.Create(AField.AsLargeInt);
ftGuid:
result := TJSONString.Create(TGuidField(AField).AsGUID.ToString);
ftExtended:
result := TJSONNumber.Create(AField.AsExtended);
ftLongWord:
result := TJSONNumber.Create(AField.AsLongword);
ftSingle:
result := TJSONNumber.Create(AField.AsSingle);
else
raise Exception.Create(Format('DataSet=%s,FieldName=%s,UnsurportDataType=%s',
[Self.Name, AField.FieldName, GetFieldTypeName(AField.DataType)]));
end;
PrintDebug('DataSet=%s,FieldName=%s,DataType=%s,Value=%s',
[Self.Name, AField.FieldName, GetFieldTypeName(AField.DataType), result.Value]);
end;
procedure TFDDataSetHelper.FieldByJSONArray(AValue: TJSONArray; AName: String;
AProc: TLogProc);
var
MyElem: TJSONValue;
Index: Integer;
begin
Index := 1;
for MyElem in AValue do
begin
FieldByJsonValue(MyElem, AName + '_' + Index.ToString, AProc);
Inc(Index);
end;
end;
procedure TFDDataSetHelper.FieldByJSONObject(AObject: TJSONObject; AProc: TLogProc = nil);
var
MyElem: TJSONPair;
begin
for MyElem in AObject do
FieldByJsonValue(MyElem.JsonValue, MyElem.JsonString.Value);
end;
procedure TFDDataSetHelper.FieldByJSONObject(AJSON: String; AProc: TLogProc);
var
JSONObject: TJSONObject;
begin
JSONObject := TJSONObject.ParseJSONValue(AJSON) as TJSONObject;
try
FieldByJSONObject(JSONObject, AProc);
finally
JSONObject.Free;
end;
end;
function TFDDataSetHelper.GetJSONArray(AValue: TJSONArray; AName: String): TJSONArray;
var
I: Integer;
Key: string;
begin
result := TJSONArray.Create;
{$IF CompilerVersion > 26} // upper XE5
for I := 0 to AValue.Count - 1 do
begin
Key := AName + '_' + (I + 1).ToString;
result.AddElement(GetNameValue(AValue.Items[I], Key));
end;
{$ELSE}
for I := 0 to AValue.Size - 1 do
begin
Key := AName + '_' + (I + 1).ToString;
result.AddElement(GetNameValue(AValue.Get(I), Key));
end;
{$ENDIF}
end;
function TFDDataSetHelper.GetJSONObject(AValue: TJSONObject; AName: String): TJSONObject;
var
MyElem: TJSONPair;
Key: string;
begin
result := TJSONObject.Create;
for MyElem in AValue do
begin
Key := AName + '_';
if AName.IsEmpty then
Key := '';
Key := Key + MyElem.JsonString.Value;
result.AddPair(MyElem.JsonString.Value, GetNameValue(MyElem.JsonValue, Key));
end;
end;
function TFDDataSetHelper.GetNameValue(AValue: TJSONValue; AName: String): TJSONValue;
begin
if AValue is TJSONObject then
result := GetJSONObject(AValue as TJSONObject, AName)
else if AValue is TJSONArray then
result := GetJSONArray(AValue as TJSONArray, AName)
else
result := FieldToJSONVlaue(Self.Fields.FindField(AName));
end;
procedure TFDDataSetHelper.LoadFromDSStream(AStream: TStream);
var
LStream: TMemoryStream;
begin
LStream := TDSCommon.DBXStreamToMemoryStream(AStream);
try
if LStream.Size = 0 then
raise Exception.Create('Reveiced Null Stream, ' + Self.Name);
Self.LoadFromStream(LStream, sfBinary);
finally
FreeAndNil(LStream);
end;
end;
function TFDDataSetHelper.ToRecordArray<T>(AName: String): TArray<T>;
var
_record: T;
begin
SetLength(result, 0);
Self.First;
while not Self.Eof do
begin
_record := Self.ToRecord<T>(AName);
result := result + [_record];
Self.Next;
end;
end;
function TFDDataSetHelper.ToJSON: TJSONObject;
var
MyField: TField;
JsonValue: TJSONValue;
begin
result := TJSONObject.Create;
for MyField in Self.Fields do
begin
JsonValue := FieldToJSONVlaue(MyField);
result.AddPair(MyField.FieldName, JsonValue);
end;
end;
function TFDDataSetHelper.ToRecord<T>(AName: String): T;
var
MyRecord: T;
TempContainer, ResultValue: TJSONObject;
begin
FillChar(MyRecord, SizeOf(T), 0);
TempContainer := REST.JSON.TJson.RecordToJsonObject<T>(MyRecord);
try
ResultValue := GetJSONObject(TempContainer, AName);
try
result := REST.JSON.TJson.JsonToRecord<T>(ResultValue);
finally
ResultValue.Free;
end;
finally
TempContainer.Free;
end;
end;
end.
|
unit fGMV_NewTemplate;
{
================================================================================
*
* Application: Vitals
* Revision: $Revision: 1 $ $Modtime: 12/20/07 12:43p $
* Developer: doma.user@domain.ext
* Site: Hines OIFO
*
* Description: Create form for a new vitals input template.
*
* Notes:
*
================================================================================
* $Archive: /Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/APP-VITALSMANAGER/fGMV_NewTemplate.pas $
*
* $History: fGMV_NewTemplate.pas $
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 8/12/09 Time: 8:29a
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_8/Source/APP-VITALSMANAGER
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 3/09/09 Time: 3:38p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_6/Source/APP-VITALSMANAGER
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/13/09 Time: 1:26p
* Created in $/Vitals/5.0 (Version 5.0)/5.0.23 (Patch 23)/VITALS_5_0_23_4/Source/APP-VITALSMANAGER
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/11/07 Time: 3:13p
* Created in $/Vitals GUI 2007/Vitals-5-0-18/APP-VITALSMANAGER
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:40p
* Created in $/Vitals/VITALS-5-0-18/APP-VitalsManager
* GUI v. 5.0.18 updates the default vital type IENs with the local
* values.
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/16/06 Time: 5:30p
* Created in $/Vitals/Vitals-5-0-18/VITALS-5-0-18/APP-VitalsManager
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 5/24/05 Time: 4:56p
* Created in $/Vitals/Vitals GUI v 5.0.2.1 -5.0.3.1 - Patch GMVR-5-7 (CASMed, CCOW) - Delphi 6/VitalsManager-503
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 4/16/04 Time: 4:21p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, CPRS, Delphi 7)/VITALSMANAGER-503
*
* ***************** Version 1 *****************
* User: Zzzzzzandria Date: 1/26/04 Time: 1:09p
* Created in $/Vitals/Vitals GUI Version 5.0.3 (CCOW, Delphi7)/V5031-D7/VitalsManager
*
* ***************** Version 3 *****************
* User: Zzzzzzandria Date: 8/02/02 Time: 4:14p
* Updated in $/Vitals GUI Version 5.0/Vitals Manager
* Weekly backup
*
* ***************** Version 2 *****************
* User: Zzzzzzpetitd Date: 6/06/02 Time: 11:11a
* Updated in $/Vitals GUI Version 5.0/Vitals Manager
* Roll-up to 5.0.0.27
*
* ***************** Version 1 *****************
* User: Zzzzzzpetitd Date: 4/04/02 Time: 3:42p
* Created in $/Vitals GUI Version 5.0/Vitals Manager
*
*
*
================================================================================
}
interface
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
ExtCtrls,
// TRPCB,
uGMV_Common,
mGMV_Lookup,
uGMV_Template
;
type
TfrmGMV_NewTemplate = class(TForm)
rgTemplateType: TRadioGroup;
edtTemplateName: TEdit;
lblType: TLabel;
lblName: TLabel;
btnCancel: TButton;
btnOK: TButton;
edtTemplateDescription: TEdit;
Label1: TLabel;
fraEntityLookup: TfraGMV_Lookup;
procedure rgTemplateTypeClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
// FBroker: TRPCBroker;
{ Private declarations }
public
{ Public declarations }
end;
var
frmGMV_NewTemplate: TfrmGMV_NewTemplate;
//function CreateNewTemplate(Broker: TRPCBroker): TGMV_Template;
function CreateNewTemplate: TGMV_Template;
implementation
uses uGMV_Const
//, fROR_PCall
, uGMV_Engine, system.UITypes;
{$R *.DFM}
//function CreateNewTemplate(Broker: TRPCBroker): TGMV_Template;
function CreateNewTemplate: TGMV_Template;
var
s,ss:String;
Entity: string;
begin
with TfrmGMV_NewTemplate.Create(application) do
try
ShowModal;
// FBroker := Broker;
if ModalResult <> mrOK then
Result := nil
else
begin
case rgTemplateType.ItemIndex of
0: Entity := 'SYS';
1: Entity := fraEntityLookup.IEN + ';DIC(4,';
2: Entity := fraEntityLookup.IEN + ';SC(';
3: Entity := fraEntityLookup.IEN + ';VA(200,';
end;
s := edtTemplateDescription.Text;
ss := edtTemplateName.Text;
// CallREMOTEProc(Broker, RPC_MANAGER,['NEWTEMP', Entity + '^' + edtTemplateName.Text + '^' + edtTemplateDescription.Text], nil);
// if piece(Broker.Results[0], '^') = '-1' then
s := NewTemplate(Entity,edtTemplateName.Text,edtTemplateDescription.Text);
if piece(s, '^') = '-1' then
begin
MessageDlg('Unable to Create New Template'
// + #13 +'Reason:'+#13+'<'+ piece(s, '^',2)+'>'
,
mtError, [mbOK], 0);
Result := nil;
end
else
// Result := TGMV_Template.CreateFromXPAR(Broker.Results[0]);
Result := TGMV_Template.CreateFromXPAR(s);
end;
finally
free;
end;
end;
procedure TfrmGMV_NewTemplate.rgTemplateTypeClick(Sender: TObject);
begin
fraEntityLookup.Enabled := (rgTemplateType.ItemIndex > 0);
lblType.Caption := rgTemplateType.Items[rgTemplateType.ItemIndex] + ' Name:';
if rgTemplateType.ItemIndex > 0 then
begin
// fraEntityLookup.InitFrame(RPCBroker, piece('4^44^200', '^', rgTemplateType.ItemIndex));
fraEntityLookup.InitFrame(piece('4^44^200', '^', rgTemplateType.ItemIndex));
fraEntityLookup.Enabled := True;
end
else
begin
fraEntityLookup.edtValue.Text := 'SYSTEM';
fraEntityLookup.Enabled := False;
end;
end;
procedure TfrmGMV_NewTemplate.btnOKClick(Sender: TObject);
begin
if rgTemplateType.ItemIndex < 0 then
MessageDlg('Please select a Template Type', mtInformation, [mbok], 0)
else if (fraEntityLookup.IEN = '') and (rgTemplateType.ItemIndex > 0) then
MessageDlg('Please select a ' + rgTemplateType.Items[rgTemplateType.ItemIndex], mtInformation, [mbok], 0)
else if edtTemplateName.Text = '' then
MessageDlg('Please enter a name for this template.', mtInformation, [mbok], 0)
else
ModalResult := mrOK;
end;
procedure TfrmGMV_NewTemplate.FormCreate(Sender: TObject);
begin
rgTemplateType.ItemIndex := 0;
edtTemplateName.Text := '';
edtTemplateDescription.Text := '';
end;
end.
|
unit iaDemo.chakracore.SimpleExec.MainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Vcl.Themes,
ChakraCoreClasses; //replace project search path for your location of source files from: https://github.com/tondrej/chakracore-delphi
type
TForm1 = class(TForm)
memJS: TMemo;
Button1: TButton;
edtResult: TEdit;
Label1: TLabel;
labMS: TLabel;
Label2: TLabel;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FRuntime: TChakraCoreRuntime;
FContext: TChakraCoreContext;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
System.Diagnostics, System.Math, System.TimeSpan,
ChakraCommon, ChakraCoreUtils;
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
FRuntime := TChakraCoreRuntime.Create();
FContext := TChakraCoreContext.Create(FRuntime);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FContext.Free();
FRuntime.Free();
end;
procedure TForm1.Button1Click(Sender: TObject);
var
vResult:JsValueRef;
vStopWatch:TStopWatch;
begin
vStopWatch := TStopwatch.StartNew;
vResult := FContext.RunScript(memJS.Text, 'MyScriptName');
vStopWatch.Stop;
if vStopWatch.ElapsedMilliseconds = 0 then
begin
labMS.Caption := FormatFloat('0.00', RoundTo(vStopWatch.ElapsedTicks / TTimeSpan.TicksPerMillisecond, -2)) + 'ms';
end
else
begin
labMS.Caption := IntToStr(vStopWatch.ElapsedMilliseconds) + 'ms';
end;
edtResult.Text := JsStringToUnicodeString(vResult);
end;
end.
|
unit ncBaseWebApi;
{
ResourceString: Dario 12/03/13
}
interface
uses Dialogs, SysUtils, Winsock, Windows, ExtActns, ActiveX, UrlMon, Automation, EmbeddedWB, SHFolder, Classes, Forms, idHttp;
type
TncDownloadUrl = class ( TThread )
protected
FRes: Integer;
FWB: TEmbeddedWB;
FURL,
FFileName,
FJS,
FJSFrame: String;
FOpen: Boolean;
FOpenParams: String;
FDownAction : TDownLoadUrl;
procedure Progress(Sender: TDownLoadURL; Progress,
ProgressMax: Cardinal; StatusCode: TURLDownloadStatus; StatusText: String;
var Cancel: Boolean);
procedure AfterDownload;
protected
procedure Execute; override;
public
constructor Create(aWB: TEmbeddedWB;
aURL, aFileName, aJS, aJSFrame: String;
aOpen: Boolean; aOpenParams: String);
end;
TDownFileStream = class ( TFileStream )
public
function Write(const Buffer; Count: Longint): Longint; override;
end;
TncBaseWebApi = class ( TObjectWrapper )
protected
WB: TEmbeddedWB;
Form: TForm;
public
constructor Create(aForm: TForm; aWB: TEmbeddedWB);
published
function Win32Platform: OleVariant;
function Win32MajorVersion: OleVariant;
function Win32MinorVersion: OleVariant;
function Win32BuildNumber: OleVariant;
function DotNetInstalled(const aVer: OleVariant): OleVariant;
function ScreenWidth: OleVariant;
function ScreenHeight: OleVariant;
function ExeName: OleVariant;
function FileVersion(const aFileName: OleVariant): OleVariant;
function GetParamStr(const aIndex: OleVariant): OleVariant;
function AppPath: OleVariant;
function CopyFile(const aFrom, aTo, aFailIfExists: OleVariant): OleVariant;
function FileExists(const aFileName: OleVariant): OleVariant;
function TextFromFile(const aFileName: OleVariant): OleVariant;
function ForceDirectories(const aFileName: OleVariant): OleVariant;
function LogInfo(const aString: OleVariant): OleVariant;
function DeleteFile(const aFileName: OleVariant): OleVariant;
function Conta: OleVariant;
function ContaFree: OleVariant;
function ContaPremium: OleVariant;
function AppVer: OleVariant;
function FullAppVer: OleVariant;
function DownloadURL(const aURL, aFName, aOpen, aParams, afterDownJS, afterDownJSIFrame: OleVariant): OleVariant;
{ function MonitorURLChange(aJSIFrame: OleVariant): OleVariant;
function MonitorEXEChange(aJSIFrame: OleVariant): OleVariant;}
function ShellStart(const aCmd, aParams, aDir: OleVariant): OleVariant;
function ServerIP: OleVariant; virtual;
function UsernameFunc: OleVariant; virtual;
function UserAdmin: OleVariant; virtual;
function CloseApp: OleVariant; virtual;
function CloseWindow: OleVariant; virtual;
function PopupUrl(const aURL: OleVariant): OleVariant; virtual;
end;
implementation
uses
ncShellStart, ncClassesBase, ncBrowserUtils, uVersionInfo, ncDebug,
ncWBFrameExecScript, ncFrmWebPopup;
{ TncBaseWebApi }
type
ThreadRenameExec = class ( TThread )
protected
OldName, NewName, Params: String;
Open: Boolean;
procedure Execute; override;
public
constructor Create(aOldName, aNewName: String; aOpen: Boolean; aParams: String);
end;
function TncBaseWebApi.UserAdmin: OleVariant;
begin
Result := 0;
end;
function TncBaseWebApi.AppPath: OleVariant;
begin
Result := ExtractFilePath(ParamStr(0));
end;
function TncBaseWebApi.AppVer: OleVariant;
begin
Result := Trim(Copy(SelfVersion, 7, 20));
end;
function TncBaseWebApi.CloseApp: OleVariant;
begin
Result := 0;
end;
function TncBaseWebApi.CloseWindow: OleVariant;
begin
Result := 0;
end;
function TncBaseWebApi.Conta: OleVariant;
begin
Result := gConfig.Conta;
end;
function TncBaseWebApi.ContaFree: OleVariant;
begin
Result := gConfig.FreePremium and (gConfig.AssinaturaVenceEm<Date);
end;
function TncBaseWebApi.ContaPremium: OleVariant;
begin
Result := gConfig.FreePremium and (gConfig.AssinaturaVenceEm>=Date);
end;
function TncBaseWebApi.CopyFile(const aFrom, aTo, aFailIfExists: OleVariant): OleVariant;
var
sFrom, sTo : String;
bFail : Boolean;
begin
sFrom := aFrom;
sTo := aTo;
bFail := (aFailIfExists=1);
DebugMsg('TncBaseWebApi.CopyFile - From: '+sFrom+' - To: '+sTo+' - FailIfExists: ' + BoolStr[bFail]); // do not localize
Result := Windows.CopyFile(pChar(sFrom), pChar(sTo), bFail);
end;
constructor TncBaseWebApi.Create(aForm: TForm; aWB: TEmbeddedWB);
begin
inherited Connect(aForm);
Form := aForm;
WB := aWB;
end;
function TncBaseWebApi.DeleteFile(const aFileName: OleVariant): OleVariant;
var s: String;
begin
s := aFileName;
Result := Windows.DeleteFile(PChar(s));
end;
function TncBaseWebApi.DotNetInstalled(const aVer: OleVariant): OleVariant;
var
s: String;
sr : TSearchRec;
begin
Result := 0;
s := GetSysFolder(CSIDL_WINDOWS) + '\Microsoft.NET\Framework'; // do not localize
if not DirectoryExists(s) then Exit;
if FindFirst(s+'\*.*', faDirectory, sr)=0 then
try
repeat
s := aVer;
if Pos(s, sr.Name)=1 then begin
Result := 1;
Exit;
end;
until (FindNext(sr)<>0);
finally
SysUtils.FindClose(sr);
end;
end;
function TncBaseWebApi.DownloadURL(const aURL, aFName, aOpen, aParams, afterDownJS,
afterDownJSIFrame: OleVariant): OleVariant;
var s1, s2: String;
begin
Result := 1;
s1 := aURL;
s2 := aFName;
CoInitialize(nil);
TncDownloadUrl.Create(WB, aUrl, aFName, afterDownJS, afterDownJSIFrame, (aOpen=1), aParams);
end;
function TncBaseWebApi.ExeName: OleVariant;
begin
Result := ExtractFileName(ParamStr(0));
end;
function TncBaseWebApi.FileExists(const aFileName: OleVariant): OleVariant;
begin
Result := SysUtils.FileExists(aFileName);
end;
function TncBaseWebApi.FileVersion(const aFileName: OleVariant): OleVariant;
begin
uVersionInfo.GetVersionInfo(aFileName);
end;
function TncBaseWebApi.ForceDirectories(const aFileName: OleVariant): OleVariant;
begin
SysUtils.ForceDirectories(aFileName);
end;
function TncBaseWebApi.FullAppVer: OleVariant;
begin
Result := SelfVersion;
end;
function TncBaseWebApi.GetParamStr(const aIndex: OleVariant): OleVariant;
begin
Result := ParamStr(aIndex);
end;
function TncBaseWebApi.LogInfo(const aString: OleVariant): OleVariant;
begin
DebugMsg('TncBaseWebApi.LogInfo: ' + aString); // do not localize
end;
function TncBaseWebApi.PopupUrl(const aURL: OleVariant): OleVariant;
var F: TFrmWebPopup;
begin
if FrmWebPopupClass<>nil then begin
F := FrmWebPopupClass.Create(nil);
F.URL := aURL;
F.Show;
Result := 1;
end else
Result := 0;
end;
function TncBaseWebApi.ScreenHeight: OleVariant;
begin
Result := Screen.Height;
end;
function TncBaseWebApi.ScreenWidth: OleVariant;
begin
Result := Screen.Width;
end;
function TncBaseWebApi.ServerIP: OleVariant;
begin
Result := '127.0.0.1'; // do not localize
end;
function TncBaseWebApi.ShellStart(const aCmd, aParams,
aDir: OleVariant): OleVariant;
var
sCmd, sParams, sDir: String;
begin
sCmd := aCmd;
sParams := aParams;
sDir := aDir;
DebugMsg('TncBaseWebApi.ShellStart - aCmd: ' + aCmd + ' - aParams: ' + aParams + ' - aDir: ' + aDir); // do not localize
ncShellStart.ShellStart(sCmd, sParams, sDir);
Result := 1;
end;
function TncBaseWebApi.TextFromFile(const aFileName: OleVariant): OleVariant;
var
sl : TStrings;
s : String;
begin
s := aFileName;
if SysUtils.FileExists(s) then begin
sl := TStringList.Create;
try
sl.LoadFromFile(s);
Result := sl.Text;
finally
sl.Free;
end;
end else
Result := '';
end;
function TncBaseWebApi.UsernameFunc: OleVariant;
begin
Result := ncClassesBase.UsernameAtual;
end;
function TncBaseWebApi.Win32BuildNumber: OleVariant;
begin
Result := SysUtils.Win32BuildNumber;
end;
function TncBaseWebApi.Win32MajorVersion: OleVariant;
begin
Result := SysUtils.Win32MajorVersion;
end;
function TncBaseWebApi.Win32MinorVersion: OleVariant;
begin
Result := SysUtils.Win32MinorVersion;
end;
function TncBaseWebApi.Win32Platform: OleVariant;
begin
Result := SysUtils.Win32Platform;
end;
{ ThreadRenameExec }
constructor ThreadRenameExec.Create(aOldName, aNewName: String; aOpen: Boolean;
aParams: String);
begin
inherited Create(True);
FreeOnTerminate := True;
OldName := aOldName;
NewName := aNewName;
Open := aOpen;
Params := aParams;
Resume;
end;
procedure ThreadRenameExec.Execute;
var C: Integer;
begin
inherited;
try
C := GetTickCount;
while ((GetTickCount-C)<20000) and (not Application.Terminated) do
if RenameFile(OldName, NewName) then begin
if Open then ShellStart(NewName, Params);
Break;
end;
except
on E: Exception do
DebugMsg('ncBaseWebApi.ThreadRenameExec.Execute - Exception: ' + E.Message); // do not localize
end;
end;
{ TDownFileStream }
function TDownFileStream.Write(const Buffer; Count: Integer): Longint;
begin
if Application.Terminated then
raise Exception.Create('application.terminated'); // do not localize
inherited Write(Buffer, Count);
end;
{ TncDownloadUrl }
procedure TncDownloadUrl.AfterDownload;
begin
try
if FJS>'' then
if FJSFrame='' then
FWB.ExecScript(FJS, 'JavaScript') else // do not localize
FrameExecScript(FWB, FJS, FJSFrame);
except
on E: Exception do
DebugMsg('TncDownloadUrl.AfterDownload - Exception: ' + E.Message); // do not localize
end;
ThreadRenameExec.Create(FDownAction.Filename, FFileName, FOpen, FOpenParams);
end;
constructor TncDownloadUrl.Create(aWB: TEmbeddedWB; aURL, aFileName, aJS,
aJSFrame: String; aOpen: Boolean; aOpenParams: String);
begin
inherited Create(True);
FreeOnTerminate := True;
FWB := aWB;
FURL := aURL;
FJS := aJS;
FJSFrame := aJSFrame;
FOpen := aOpen;
FOpenParams := aOpenParams;
FRes := 0;
FFilename := aFileName;
Resume;
end;
procedure TncDownloadUrl.Execute;
var D: TDownLoadURL;
s: String;
w: wsadata;
begin
CoInitialize(nil);
try
WSAStartup(MakeWord(1, 1), w);
try
FDownAction := TDownLoadUrl.Create(nil);
try
FDownAction.URL := FURL;
FDownAction.FileName := ExtractFilePath(FFileName)+IntToStr(GetTickCount)+'_'+ExtractFileName(FFileName);
FDownAction.OnDownloadProgress := progress;
FDownAction.ExecuteTarget(nil);
finally
FDownAction.Free;
end;
finally
WSACleanup;
end;
except
end;
end;
procedure ProcessMessages;
var Msg : TMsg;
begin
while PeekMessage(Msg, 0, 0, 0, PM_REMOVE) do begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
procedure TncDownloadUrl.Progress(Sender: TDownLoadURL; Progress,
ProgressMax: Cardinal; StatusCode: TURLDownloadStatus; StatusText: String;
var Cancel: Boolean);
begin
if ProgressMax > 0 then
if Progress >= ProgressMax then
AfterDownload;
ProcessMessages;
end;
end.
|
{
Лабораторная работа № 1 Множества и операции над ними
Написать программу, в которой для конечных упорядоченных множеств реализовать все основные операции (, , , \) с помощью алгоритма типа слияния (по материалам лекции 1). Допустима организация множеств в виде списка или в виде массива.
Работа программы должна происходить следующим образом:
1. На вход подаются два упорядоченных множества A и B (вводятся с клавиатуры, элементы множеств – буквы латинского алфавита).
2. После ввода множеств выбирается требуемая операция (посредством текстового меню, вводом определенного символа в ответ на запрос – выбор по желанию автора). Операции: вхождение AB, AB, AB (дополнительно: A\B, B\A, AB).
3. Программа посредством алгоритма типа слияния определяет результат выбранной операции и выдает его на экран с необходимыми пояснениями.
4. Возврат на п.2 (выбор операции).
5. Завершение работы программы – из п.2 (например, по ESC).
Дополнительно: возможность возврата (по выбору пользователя) на п.2 или п.1. Выход в таком случае должен быть предусмотрен из любого пункта (1 или 2).
}
program lab1;
uses
Crt;
const
Nmax = 50; { Макс. кол-во элементов множества }
type
T = Char; { Тип элементов множества }
TSet = Array[1..Nmax] of T; { Само множество }
{ Сортировка выбором по неубыванию }
procedure Sort(var A: TSet; const N: Integer);
var
i, j, k: Integer;
tmp: T;
begin
for i := 1 to N - 1 do begin
k := i;
for j := i + 1 to N do
if A[j] < A[k] then k := j;
tmp := A[i];
A[i] := A[k];
A[k] := tmp;
end;
end;
{ Ввод множества }
procedure Set_Input(var A: TSet; var N: Integer);
var
i, j: Integer;
tmp: T;
F: Boolean;
begin
Reset(Input);
N := 0;
while not SeekEoLn do begin
Inc(N);
Read(A[N]);
end;
Sort(A, N);
F := False;
i := 1;
while i < N do begin
if A[i] = A[i + 1] then begin
F := True;
Dec(N);
for j := i + 1 to N do
A[j] := A[j + 1];
end
else
Inc(i);
end;
if F then WriteLn('Повторяющиеся элементы удалены.');
end;
{ Печать множества }
procedure Print(const A: TSet; const N: Integer);
var
i: Integer;
begin
for i := 1 to N do
Write(A[i], ' ');
if N = 0 then Write('Пустое множество.');
WriteLn;
end;
{ Печать множеств A, B }
procedure Print_Sets(const A, B: TSet; const N, M: Integer);
var
i: Integer;
begin
WriteLn;
Write('Множество A: ');
for i := 1 to N do
Write(A[i], ' ');
WriteLn;
Write('Множество B: ');
for i := 1 to M do
Write(B[i], ' ');
WriteLn;
end;
{ Объединение множеств A и B методом слияния }
procedure Union(var U: TSet; var k: Integer; const A, B: TSet; const N, M: Integer);
var
i, j: Integer;
begin
i := 1;
j := 1;
k := 0;
while (i <= N) or (j <= M) do
if (j <= M) and (i <= N) and (A[i] = B[j]) then begin
Inc(k);
U[k] := A[i];
Inc(i);
Inc(j);
end
else if (j > M) or (i <= N) and (A[i] < B[j]) then begin
Inc(k);
U[k] := A[i];
Inc(i);
end
else begin
Inc(k);
U[k] := B[j];
Inc(j);
end;
end;
{ Пересечение множеств A, B методом слияния }
procedure Product(var P: TSet; var k: Integer; const A, B: TSet; const N, M: Integer);
var
i, j, W: Integer;
begin
i := 1;
j := 1;
k := 0;
while (i <= N) and (j <= M) do
if (A[i] = B[j]) then begin
Inc(k);
P[k] := A[i];
Inc(i);
Inc(j);
end
else if A[i] < B[j] then
Inc(i)
else
Inc(j);
end;
{ Разность множеств A, B методом слияния }
procedure Diff(var D: TSet; var k: Integer; const A, B: TSet; const N, M: Integer);
var
i, j: Integer;
begin
i := 1;
j := 1;
k := 0;
while (i <= N) and (j <= M) do
if A[i] = B[j] then begin
Inc(i);
Inc(j);
end
else if A[i] < B[j] then begin
Inc(k);
D[k] := A[i];
Inc(i);
end
else if A[i] > B[j] then
Inc(j);
while (i <= N) and (j > M) do begin
Inc(k);
D[k] := A[i];
Inc(i);
end;
end;
{ Проверка на вхождение A в B }
function Incl(const A, B: TSet; const N, M: Integer): Boolean;
var
i, j: Integer;
begin
Incl := False;
if N > M then Exit;
i := 1;
j := 1;
while (i <= N) and (j <= M) and (A[i] >= B[j]) do
if A[i] > B[j] then
Inc(j)
else if A[i] = B[j] then begin
Inc(i);
Inc(j);
end;
Incl := i - 1 = N;
end;
{ Вывод на экран клавиш управления }
procedure Keys;
begin
ClrScr;
WriteLn('Выберите действие:');
WriteLn;
WriteLn('1 - ввод множества A');
WriteLn('2 - ввод множества B');
WriteLn('3 - проверка вхождения A в B');
WriteLn('4 - вывести объеденение множеств A и B');
WriteLn('5 - вывести пересечение множеств A и B');
WriteLn('6 - вывести разность A \ B');
WriteLn('0 - очистка экрана');
WriteLn('Esc - выход');
WriteLn;
end;
var
N, M, K: Integer;
A, B, C: TSet;
v: Char;
begin
Keys;
N := 0;
M := 0;
repeat
v := ReadKey; { Получаем номер действия }
if v in ['3'..'6'] then Print_Sets(A, B, N, M);
case v of
'1':
begin
WriteLn('Введите множество A:');
Set_Input(A, N);
WriteLn('Готово.');
WriteLn;
end;
'2':
begin
WriteLn('Введите множество B:');
Set_Input(B, M);
WriteLn('Готово.');
WriteLn;
end;
'3': if Incl(A, B, N, M) then WriteLn('A входит в B') else WriteLn('A не входит в B');
'4':
begin
WriteLn('Объединение A и B:');
Union(C, K, A, B, N, M);
Print(C, K);
end;
'5':
begin
WriteLn('Пересечение A и B:');
Product(C, K, A, B, N, M);
Print(C, K);
end;
'6':
begin
WriteLn('Разность A \ B:');
Diff(C, K, A, B, N, M);
Print(C, K);
end;
'0': Keys;
end;
until v = #27;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC GUIx Forms memo }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.VCLUI.Memo;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Windows, Winapi.Messages, System.Win.Registry,
{$ENDIF}
System.Classes, Vcl.Controls, Vcl.Graphics, Vcl.StdCtrls
{$IFDEF FireDAC_SynEdit}
, synedit, synmemo, synhighlightersql, synedithighlighter
{$ENDIF}
, FireDAC.Stan.Intf;
type
{----------------------------------------------------------------------------}
{ TFDGUIxFormsMemo }
{----------------------------------------------------------------------------}
{$IFDEF FireDAC_SynEdit}
TFDGUIxFormsMemo = class(TSynMemo)
private
function GetCaretPos: TPoint;
procedure SetCaretPos(const AValue: TPoint);
function GetRDBMSKind: TFDRDBMSKind;
procedure SetRDBMSKind(const AValue: TFDRDBMSKind);
public
constructor Create(AOwner: TComponent); override;
property CaretPos: TPoint read GetCaretPos write SetCaretPos;
property RDBMSKind: TFDRDBMSKind read GetRDBMSKind write SetRDBMSKind;
end;
{$ELSE}
TFDGUIxFormsMemo = class(TMemo)
private
FRDBMSKind: TFDRDBMSKind;
public
constructor Create(AOwner: TComponent); override;
property RDBMSKind: TFDRDBMSKind read FRDBMSKind write FRDBMSKind;
end;
{$ENDIF}
implementation
uses
System.SysUtils, System.TypInfo,
FireDAC.Stan.Util;
{$IFDEF FireDAC_SynEdit}
{------------------------------------------------------------------------------}
{ TFDGUIxFormsHilighter }
{------------------------------------------------------------------------------}
type
TFDGUIxFormsHilighter = class(TSynSQLSyn)
private
{$IFDEF MSWINDOWS}
FReg: TRegistry;
{$ENDIF}
FFontName: String;
FFontSize: Integer;
{$IFDEF MSWINDOWS}
function GetEditorKey: String;
procedure LoadAttr(AAttrs: TSynHighlighterAttributes; const AKind: String);
procedure LoadSettings;
function ReadBool(const AIdent: string): Boolean;
{$ENDIF}
function GetRDBMSKind: TFDRDBMSKind;
procedure SetRDBMSKind(const AValue: TFDRDBMSKind);
public
constructor Create(AOwner: TComponent); override;
property RDBMSKind: TFDRDBMSKind read GetRDBMSKind write SetRDBMSKind;
end;
{------------------------------------------------------------------------------}
constructor TFDGUIxFormsHilighter.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
{$IFDEF MSWINDOWS}
FReg := TRegistry.Create;
try
FReg.RootKey := HKEY_CURRENT_USER;
LoadSettings;
finally
FDFree(FReg);
end;
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
{------------------------------------------------------------------------------}
function TFDGUIxFormsHilighter.GetEditorKey: String;
begin
Result := '\SOFTWARE\Embarcadero\BDS\12.0\Editor';
end;
{-------------------------------------------------------------------------------}
function TFDGUIxFormsHilighter.ReadBool(const AIdent: string): Boolean;
const
C_BoolArr: array [Boolean] of String = ('False', 'True');
begin
Result := FReg.ReadString(AIdent) = C_BoolArr[True];
end;
{------------------------------------------------------------------------------}
procedure TFDGUIxFormsHilighter.LoadAttr(AAttrs: TSynHighlighterAttributes;
const AKind: String);
var
eStyles: TFontStyles;
s: String;
begin
if not FReg.OpenKeyReadOnly(GetEditorKey + '\Highlight\' + AKind) then
Exit;
if not ReadBool('Default Foreground') then begin
s := FReg.ReadString('Foreground Color New');
if s <> '' then
AAttrs.Foreground := StringToColor(s);
end;
if not ReadBool('Default Background') then begin
s := FReg.ReadString('Background Color New');
if s <> '' then
AAttrs.Background := StringToColor(s);
end;
eStyles := [];
if ReadBool('Bold') then
Include(eStyles, fsBold)
else
Exclude(eStyles, fsBold);
if ReadBool('Italic') then
Include(eStyles, fsItalic)
else
Exclude(eStyles, fsItalic);
if ReadBool('Underline') then
Include(eStyles, fsUnderline)
else
Exclude(eStyles, fsUnderline);
AAttrs.Style := eStyles;
end;
{------------------------------------------------------------------------------}
procedure TFDGUIxFormsHilighter.LoadSettings;
begin
if not FReg.OpenKeyReadOnly(GetEditorKey + '\Options') then
Exit;
if FReg.ValueExists('Editor Font') then
FFontName := FReg.ReadString('Editor Font')
else
FFontName := 'Courier New';
if FReg.ValueExists('Font Size') then
FFontSize := FReg.ReadInteger('Font Size')
else
FFontSize := 10;
LoadAttr(SpaceAttri, 'Whitespace');
LoadAttr(CommentAttribute, 'Comment');
LoadAttr(CommentAttri, 'Comment');
LoadAttr(ConditionalCommentAttri, 'Preprocessor');
LoadAttr(KeywordAttribute, 'Reserved word');
LoadAttr(KeyAttri, 'Reserved word');
LoadAttr(PLSQLAttri, 'Reserved word');
LoadAttr(SQLPlusAttri, 'Reserved word');
LoadAttr(FunctionAttri, 'Reserved word');
LoadAttr(DataTypeAttri, 'Reserved word');
LoadAttr(NumberAttri, 'Number');
LoadAttr(StringAttribute, 'String');
LoadAttr(StringAttri, 'String');
LoadAttr(SymbolAttribute, 'Symbol');
LoadAttr(SymbolAttri, 'Symbol');
LoadAttr(IdentifierAttribute, 'Identifier');
LoadAttr(IdentifierAttri, 'Identifier');
LoadAttr(DelimitedIdentifierAttri, 'Identifier');
LoadAttr(VariableAttri, 'Identifier');
end;
{$ENDIF}
{------------------------------------------------------------------------------}
function TFDGUIxFormsHilighter.GetRDBMSKind: TFDRDBMSKind;
var
sSQLDialect: string;
begin
sSQLDialect := GetEnumName(TypeInfo(TSQLDialect), Ord(SQLDialect));
if SameText(sSQLDialect, 'sqlInterbase6') then Result := TFDRDBMSKinds.Interbase
else if SameText(sSQLDialect, 'sqlInterbase6') then Result := TFDRDBMSKinds.Interbase
else if SameText(sSQLDialect, 'sqlMSSQL7') then Result := TFDRDBMSKinds.MSSQL
else if SameText(sSQLDialect, 'sqlMySQL') then Result := TFDRDBMSKinds.MySQL
else if SameText(sSQLDialect, 'sqlOracle') then Result := TFDRDBMSKinds.Oracle
else if SameText(sSQLDialect, 'sqlSybase') then Result := TFDRDBMSKinds.MSSQL
else if SameText(sSQLDialect, 'sqlMSSQL2K') then Result := TFDRDBMSKinds.MSSQL
else if SameText(sSQLDialect, 'sqlPostgres') then Result := TFDRDBMSKinds.PostgreSQL
else Result := TFDRDBMSKinds.Other;
end;
{------------------------------------------------------------------------------}
procedure TFDGUIxFormsHilighter.SetRDBMSKind(const AValue: TFDRDBMSKind);
begin
case AValue of
TFDRDBMSKinds.Oracle: SQLDialect := sqlOracle;
TFDRDBMSKinds.MSSQL: SQLDialect := sqlMSSQL2K;
TFDRDBMSKinds.MySQL: SQLDialect := sqlMySQL;
TFDRDBMSKinds.SQLAnywhere: SQLDialect := sqlSybase;
TFDRDBMSKinds.Interbase: SQLDialect := sqlInterbase6;
TFDRDBMSKinds.Firebird: SQLDialect := sqlInterbase6;
TFDRDBMSKinds.PostgreSQL: SQLDialect := sqlPostgres;
TFDRDBMSKinds.SybaseASE: SQLDialect := sqlSybase;
else SQLDialect := sqlStandard;
end;
end;
{------------------------------------------------------------------------------}
{ TFDGUIxFormsMemo }
{------------------------------------------------------------------------------}
constructor TFDGUIxFormsMemo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Highlighter := TFDGUIxFormsHilighter.Create(Self);
if TFDGUIxFormsHilighter(Highlighter).FFontName <> '' then
Font.Name := TFDGUIxFormsHilighter(Highlighter).FFontName;
if TFDGUIxFormsHilighter(Highlighter).FFontSize <> 0 then
Font.Size := TFDGUIxFormsHilighter(Highlighter).FFontSize;
WordWrap := False;
end;
{------------------------------------------------------------------------------}
function TFDGUIxFormsMemo.GetCaretPos: TPoint;
begin
Result := Point(CaretX - 1, CaretY - 1);
end;
{------------------------------------------------------------------------------}
procedure TFDGUIxFormsMemo.SetCaretPos(const AValue: TPoint);
begin
CaretX := AValue.X + 1;
CaretY := AValue.Y + 1;
end;
{------------------------------------------------------------------------------}
function TFDGUIxFormsMemo.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDGUIxFormsHilighter(Highlighter).RDBMSKind;
end;
{------------------------------------------------------------------------------}
procedure TFDGUIxFormsMemo.SetRDBMSKind(const AValue: TFDRDBMSKind);
begin
TFDGUIxFormsHilighter(Highlighter).RDBMSKind := AValue;
end;
{$ELSE}
{------------------------------------------------------------------------------}
constructor TFDGUIxFormsMemo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Font.Name := 'Courier New';
WordWrap := False;
ScrollBars := ssBoth;
end;
{$ENDIF}
end.
|
(**
This module contains a class / interface for creating and managing a version RC file for the project.
@Author David Hoyle
@Version 1.0
@Date 07 Jan 2018
**)
Unit ITHelper.VersionManager;
Interface
Uses
ToolsAPI,
ITHelper.Interfaces;
Type
(** A class / interface to manage the create a version RC file for the project. **)
TITHVersionManager = Class(TInterfacedObject, IITHVersionManager)
Strict Private
FGlobalOps : IITHGlobalOptions;
FProjectOps : IITHProjectOptions;
FProject : IOTAProject;
FMsgMgr : IITHMessageManager;
Strict Protected
// IITHVersionManager
Procedure BuildProjectVersionResource();
// General Methods
Function ExpandMacro(Const strText, strMacroName, strValue: String): String;
Function CreateVersionRC : String;
Procedure IncrementBuildNumber(Const strFileName : String);
Procedure CompileVersionRC(Const strFileName : String);
Procedure ProcessMsgHandler(Const strMsg: String; Var boolAbort: Boolean);
Procedure IdleHandler;
Public
Constructor Create(Const GloablOps: IITHGlobalOptions; Const ProjectOps: IITHProjectOptions;
Const Project: IOTAProject; Const MsgMgr : IITHMessageManager);
End;
Implementation
Uses
SysUtils,
Classes,
Forms,
ITHelper.ExternalProcessInfo,
ITHelper.Types,
ITHelper.ProcessingForm,
ITHelper.CommonFunctions,
ITHelper.TestingHelperUtils;
(**
This method builds the ITHelper version resource for inclusion in the project.
@precon None.
@postcon Builds the ITHelper version resource for inclusion in the project.
**)
Procedure TITHVersionManager.BuildProjectVersionResource();
Var
strFileName : String;
Begin
strFileName := CreateVersionRC;
IncrementBuildNumber(strFileName);
CompileVersionRC(strFileName);
End;
(**
This method compiles the created RC file if the projects options require it.
@precon None.
@postcon The RC file is compiled and the output messages sent to the message view.
@param strFileName as a String as a constant
**)
Procedure TITHVersionManager.CompileVersionRC(Const strFileName : String);
ResourceString
strCompilingWithBRCC = 'Compiling %s with BRCC32';
strRunning = 'Running: %s (%s)';
strProcessing = 'Processing %s...';
strResourceRCCompiledForProject = 'Resource %s.RC compiled for project %s.';
Const
strBRCCExe = 'BRCC32.exe';
Var
Process : TITHProcessInfo;
iResult: Integer;
j: Integer;
Begin
If FProjectOps.CompileRes Then
Begin
Process.FEnabled := True;
Process.FTitle := Format(strCompilingWithBRCC, [FProjectOps.ResourceName]);
Process.FEXE := strBRCCExe;
Process.FParams := Format('-v "%s"', [strFileName]);
Process.FDir := GetCurrentDir;
FMsgMgr.ParentMsg :=
FMsgMgr.AddMsg(Format(strRunning,
[ExtractFileName(Process.FTitle), GetProjectName(FProject)]), fnHeader, ithfHeader);
TfrmITHProcessing.ShowProcessing(Format(strProcessing,
[ExtractFileName(Process.FTitle)]));
FMsgMgr.Clear;
iResult := DGHCreateProcess(Process, ProcessMsgHandler, IdleHandler);
For j := 0 To FMsgMgr.Count - 1 Do
Case iResult Of
0: FMsgMgr[j].ForeColour := FGlobalOps.FontColour[ithfSuccess];
Else
FMsgMgr[j].ForeColour := FGlobalOps.FontColour[ithfFailure];
End;
If iResult <> 0 Then
FMsgMgr.ParentMsg.ForeColour := FGlobalOps.FontColour[ithfFailure];
ShowHelperMessages(FGlobalOps.GroupMessages);
If iResult > 0 Then
Abort; //: @bug Change this!
FMsgMgr.AddMsg(Format(strResourceRCCompiledForProject, [
FProjectOps.ResourceName, GetProjectName(FProject)]), fnHeader, ithfDefault);
End;
End;
(**
A constructor for the TITHVersionManager class.
@precon None.
@postcon Stores references to the various interfaces for later use.
@param GloablOps as an IITHGlobalOptions as a constant
@param ProjectOps as an IITHProjectOptions as a constant
@param Project as an IOTAProject as a constant
@param MsgMgr as an IITHMessageManager as a constant
**)
Constructor TITHVersionManager.Create(Const GloablOps: IITHGlobalOptions; Const ProjectOps: IITHProjectOptions;
Const Project: IOTAProject; Const MsgMgr : IITHMessageManager);
Begin
FGlobalOps := GloablOps;
FProjectOps := ProjectOps;
FProject := Project;
FMsgMgr := MsgMgr;
End;
(**
This method creates a version RC file for compiling into the application.
@precon None.
@postcon The RC file is created with the projects version information.
@return a String
**)
Function TITHVersionManager.CreateVersionRC: String;
Const
strVersionTemplate =
'LANGUAGE LANG_ENGLISH,SUBLANG_ENGLISH_US'#13#10 +
''#13#10 +
'1 VERSIONINFO LOADONCALL MOVEABLE DISCARDABLE IMPURE'#13#10 +
'FILEVERSION $(Major), $(Minor), $(Release), $(Build)'#13#10 +
'PRODUCTVERSION $(Major), $(Minor), $(Release), $(Build)'#13#10 +
'FILEFLAGSMASK VS_FFI_FILEFLAGSMASK'#13#10 +
'FILEOS VOS__WINDOWS32'#13#10 +
'FILETYPE VFT_APP'#13#10 +
'{'#13#10 +
' BLOCK "StringFileInfo"'#13#10 +
' {'#13#10 +
' BLOCK "040904E4"'#13#10 +
' {'#13#10 +
'$(Details) }'#13#10 +
' }'#13#10 +
' BLOCK "VarFileInfo"'#13#10 +
' {'#13#10 +
' VALUE "Translation", 1033, 1252'#13#10 +
' }'#13#10 +
'}';
strMajor = '$(Major)';
strMinor = '$(Minor)';
strRelease = '$(Release)';
strBuild = '$(Build)';
strVALUE = ' VALUE "%s", "%s\000"'#13#10;
strRCDetails = '$(Details)';
strRCExt = '.RC';
Var
sl, slDetails : TStringList;
strDetails : String;
i : Integer;
Begin
sl := TStringList.Create;
Try
sl.Text := strVersionTemplate;
sl.Text := ExpandMacro(sl.Text, strMajor, FProjectOps.Major.ToString);
sl.Text := ExpandMacro(sl.Text, strMinor, FProjectOps.Minor.ToString);
sl.Text := ExpandMacro(sl.Text, strRelease, FProjectOps.Release.ToString);
sl.Text := ExpandMacro(sl.Text, strBuild, FProjectOps.Build.ToString);
slDetails := FProjectOps.VerInfo;
For i := 0 To slDetails.Count - 1 Do
strDetails := strDetails + Format(strVALUE, [slDetails.Names[i],
slDetails.ValueFromIndex[i]]);
sl.Text := ExpandMacro(sl.Text, strRCDetails, strDetails);
Result := ExtractFilePath(FProject.FileName) + FProjectOps.ResourceName + strRCExt;
sl.SaveToFile(Result);
Finally
sl.Free;
End;
End;
(**
This method replaces all instances of the given macro within the given text with the given string
value and returns the updates string.
@precon None.
@postcon If the macro is found in the text it is replaced with the value.
@param strText as a String as a constant
@param strMacroName as a String as a constant
@param strValue as a String as a constant
@return a String
**)
Function TITHVersionManager.ExpandMacro(Const strText, strMacroName, strValue: String): String;
Begin
Result := StringReplace(strText, strMacroName, strValue, [rfReplaceAll, rfIgnoreCase]);
End;
(**
This is an idle handler for them DGHCreateProcess fucntion to ensure that the IDE does not freeze.
@precon None.
@postcon Processes the message query.
**)
Procedure TITHVersionManager.IdleHandler;
Begin
Application.ProcessMessages;
End;
(**
This method increments the build number if that project option is enabled.
@precon None.
@postcon The project build number is incremented if required and the RC file added to the project.
@param strFileName as a String as a constant
**)
Procedure TITHVersionManager.IncrementBuildNumber(Const strFileName : String);
ResourceString
strVerInfoRRCCreated = 'Version information resource %s.RC created for project %s.';
Const
strResourceRCAdded = 'Resource %s.RC added to project %s.';
Var
boolFound: Boolean;
iModule: Integer;
Begin
FMsgMgr.AddMsg(Format(strVerInfoRRCCreated, [
FProjectOps.ResourceName, GetProjectName(FProject)]), fnHeader, ithfDefault);
If FProjectOps.IncResInProj Then
Begin
boolFound := False;
For iModule := 0 To FProject.GetModuleCount - 1 Do
If CompareText(FProject.GetModule(iModule).FileName, strFileName) = 0 Then
Begin
boolFound := True;
Break;
End;
If Not boolFound Then
Begin
FProject.AddFile(strFileName, True);
FMsgMgr.AddMsg(Format(strResourceRCAdded, [
FProjectOps.ResourceName, GetProjectName(FProject)]), fnHeader, ithfDefault);
End;
End;
End;
(**
This method processses the messages from DGHCreateProcess and outputs them to the messages window.
@precon None.
@postcon External process messages are output to the message window.
@nohint boolAbort
@param strMsg as a String as a constant
@param boolAbort as a Boolean as a reference
**)
Procedure TITHVersionManager.ProcessMsgHandler(Const strMsg: String; Var boolAbort: Boolean);
Begin
If strMsg <> '' Then
FMsgMgr.AddMsg(strMsg, fnTools, ithfDefault, FMsgMgr.ParentMsg.MessagePntr);
End;
End.
|
unit U_TContact;
interface
uses System.Classes;
type
TMobileOperator = Class
Name:string[30];
End;
TMobile = Class
AreaCode:string[10];
Number:string[11];
mOperator:TMobileOperator;
End;
TTelephoneOperator = Class
Name:string[30];
End;
TTelephone = class
AreaCode:string[10];
Number:string[11];
mOperator:TTelephoneOperator;
end;
TEmail = class
end;
TContact = class
MobileList:TList;
Telephone:TList;
end;
implementation
end.
|
unit u_xpl_processor;
{$ifdef fpc}
{$mode objfpc}{$H+}
{$endif}
interface
uses Classes
, SysUtils
, u_xpl_address
, u_xpl_custom_message
;
type // TxPLProcessor =========================================================
TxPLProcessor = class(TObject)
private
public
function Transform(const aAddress : TxPLAddress; const aString : string) : string;
end;
const K_PROCESSOR_KEYWORDS : Array[0..14] of String = ( 'TIMESTAMP','DATE_YMD','DATE_UK',
'DATE_US','DATE','DAY', 'MONTH',
'YEAR','TIME','HOUR','MINUTE','SECOND',
'DAWN','DUSK','NOON');
implementation // =============================================================
uses StrUtils
, DateUtils
;
const K_FORMATS : Array[0..14] of String = ( 'yyyymmddhhnnss','yyyy/mm/dd', 'dd/mm/yyyy',
'mm/dd/yyyy','dd/mm/yyyy','dd', 'm',
'yyyy', 'hh:nn:ss','hh','nn','ss','yyyymmddhhnnss',
'yyyymmddhhnnss','yyyymmddhhnnss');
// TxPLProcessor ==============================================================
function TxPLProcessor.Transform(const aAddress : TxPLAddress; const aString: string): string;
var b,e : integer;
constant, rep : string;
begin
result := aString;
if AnsiPos('{',result) = 0 then exit; // Nothing to search replace;
result := StringReplace(result, '{VDI}' , aAddress.RawxPL,[rfReplaceAll,rfIgnoreCase]);
result := StringReplace(result, '{INSTANCE}', aAddress.Instance,[rfReplaceAll,rfIgnoreCase]);
result := StringReplace(result, '{DEVICE}' , aAddress.Device,[rfReplaceAll,rfIgnoreCase]);
result := StringReplace(result, '{SCHEMA}' , aAddress.RawxPL,[rfReplaceAll,rfIgnoreCase]);
b := AnsiPos('{SYS::',Uppercase(result));
while b<>0 do begin
inc(b,6);
e := PosEx('}',result, b);
constant := Copy(result,b, e-b);
rep := K_FORMATS[AnsiIndexStr(AnsiUpperCase(constant),K_PROCESSOR_KEYWORDS)];
result := StringReplace( result, '{SYS::' + constant+'}', FormatDateTime(rep,now),[rfReplaceAll,rfIgnoreCase]);
b := PosEx('{SYS::',Uppercase(result),b);
end;
end;
end.
|
unit IETFLanguageCodeServices;
interface
uses
SysUtils, Classes,
StringSupport,
AdvObjects, AdvObjectLists, AdvFiles, AdvTextExtractors, AdvStringIntegerMatches,
FHIRTypes, FHIRResources, TerminologyServices, DateAndTime;
type
TIETFLanguageCodeConcept = class (TCodeSystemProviderContext)
private
code : string;
public
constructor create(code : String);
end;
TIETFLanguageCodeFilter = class (TCodeSystemProviderFilterContext)
end;
TIETFLanguageCodePrep = class (TCodeSystemProviderFilterPreparationContext)
end;
TIETFLanguageCodeServices = class (TCodeSystemProvider)
private
function describeLanguage(code : string) : String;
function describeCountry(code : string) : String;
public
Constructor Create; override;
Destructor Destroy; Override;
Function Link : TIETFLanguageCodeServices; overload;
function TotalCount : integer; override;
function ChildCount(context : TCodeSystemProviderContext) : integer; override;
function getcontext(context : TCodeSystemProviderContext; ndx : integer) : TCodeSystemProviderContext; override;
function system(context : TCodeSystemProviderContext) : String; override;
function version(context : TCodeSystemProviderContext) : String; override;
function name(context : TCodeSystemProviderContext) : String; override;
function getDisplay(code : String; lang : String):String; override;
function getDefinition(code : String):String; override;
function locate(code : String) : TCodeSystemProviderContext; override;
function locateIsA(code, parent : String) : TCodeSystemProviderContext; override;
function IsAbstract(context : TCodeSystemProviderContext) : boolean; override;
function Code(context : TCodeSystemProviderContext) : string; override;
function Display(context : TCodeSystemProviderContext; lang : String) : string; override;
procedure Displays(code : String; list : TStringList; lang : String); override;
procedure Displays(context : TCodeSystemProviderContext; list : TStringList; lang : String); override;
function Definition(context : TCodeSystemProviderContext) : string; override;
function getPrepContext : TCodeSystemProviderFilterPreparationContext; override;
function prepare(prep : TCodeSystemProviderFilterPreparationContext) : boolean; override;
function searchFilter(filter : TSearchFilterText; prep : TCodeSystemProviderFilterPreparationContext; sort : boolean) : TCodeSystemProviderFilterContext; override;
function filter(prop : String; op : TFhirFilterOperatorEnum; value : String; prep : TCodeSystemProviderFilterPreparationContext) : TCodeSystemProviderFilterContext; override;
function filterLocate(ctxt : TCodeSystemProviderFilterContext; code : String) : TCodeSystemProviderContext; override;
function FilterMore(ctxt : TCodeSystemProviderFilterContext) : boolean; override;
function FilterConcept(ctxt : TCodeSystemProviderFilterContext): TCodeSystemProviderContext; override;
function InFilter(ctxt : TCodeSystemProviderFilterContext; concept : TCodeSystemProviderContext) : Boolean; override;
function isNotClosed(textFilter : TSearchFilterText; propFilter : TCodeSystemProviderFilterContext = nil) : boolean; override;
procedure Close(ctxt : TCodeSystemProviderFilterPreparationContext); override;
procedure Close(ctxt : TCodeSystemProviderContext); override;
procedure Close(ctxt : TCodeSystemProviderFilterContext); override;
end;
implementation
{
a single primary language subtag based on a two-letter language code from ISO 639-1 (2002) or a three-letter code from ISO 639-2 (1998), ISO 639-3 (2007) or ISO 639-5 (2008), or registered through the BCP 47 process and composed of five to eight letters;
up to three optional extended language subtags composed of three letters each, separated by hyphens; (There is currently no extended language subtag registered in the Language Subtag Registry without an equivalent and preferred primary language subtag. This component of language tags is preserved for backwards compatibility and to allow for future parts of ISO 639.)
an optional script subtag, based on a four-letter script code from ISO 15924 (usually written in title case);
an optional region subtag based on a two-letter country code from ISO 3166-1 alpha-2 (usually written in upper case), or a three-digit code from UN M.49 for geographical regions;
optional variant subtags, separated by hyphens, each composed of five to eight letters, or of four characters starting with a digit; (Variant subtags are registered with IANA and not associated with any external standard.)
optional extension subtags, separated by hyphens, each composed of a single character, with the exception of the letter x, and a hyphen followed by one or more subtags of two to eight characters each, separated by hyphens;
an optional private-use subtag, composed of the letter x and a hyphen followed by subtags of one to eight characters each, separated by hyphens.
}
{ TIETFLanguageCodeServices }
Constructor TIETFLanguageCodeServices.create;
begin
inherited Create;
end;
function TIETFLanguageCodeServices.TotalCount : integer;
begin
result := -1; // not bounded
end;
function TIETFLanguageCodeServices.version(context: TCodeSystemProviderContext): String;
begin
result := '';
end;
function TIETFLanguageCodeServices.system(context : TCodeSystemProviderContext) : String;
begin
result := 'urn:ietf:bcp:47';
end;
function TIETFLanguageCodeServices.getDefinition(code: String): String;
begin
result := '';
end;
function TIETFLanguageCodeServices.getDisplay(code : String; lang : String):String;
var
parts : TArray<String>;
begin
if (code = '') then
result := '??'
else
begin
parts := code.Split(['-']);
result := describeLanguage(parts[0]);
if length(parts) > 1 then
result := result + '('+describeCountry(parts[1])+')';
end;
end;
function TIETFLanguageCodeServices.getPrepContext: TCodeSystemProviderFilterPreparationContext;
begin
raise Exception.Create('not done yet');
end;
procedure TIETFLanguageCodeServices.Displays(code : String; list : TStringList; lang : String);
begin
list.Add(getDisplay(code, lang));
end;
function TIETFLanguageCodeServices.locate(code : String) : TCodeSystemProviderContext;
begin
result := TIETFLanguageCodeConcept.Create(code);
end;
function TIETFLanguageCodeServices.Code(context : TCodeSystemProviderContext) : string;
begin
result := TIETFLanguageCodeConcept(context).code;
end;
function TIETFLanguageCodeServices.Definition(context: TCodeSystemProviderContext): string;
begin
result := '';
end;
function TIETFLanguageCodeServices.describeCountry(code: string): String;
begin
if (code = 'US') then
result := 'US'
else if (code = 'PT') then
result := 'Portugal'
else if (code = 'ES') then
result := 'Spain'
else if (code = 'CN') then
result := 'China'
else if (code = 'AD') then result := 'Andorra'
else if (code = 'AE') then result := 'United Arab Emirates'
else if (code = 'AF') then result := 'Afghanistan'
else if (code = 'AG') then result := 'Antigua and Barbuda'
else if (code = 'AI') then result := 'Anguilla'
else if (code = 'AL') then result := 'Albania'
else if (code = 'AM') then result := 'Armenia'
else if (code = 'AO') then result := 'Angola'
else if (code = 'AQ') then result := 'Antarctica'
else if (code = 'AR') then result := 'Argentina'
else if (code = 'AS') then result := 'American Samoa'
else if (code = 'AT') then result := 'Austria'
else if (code = 'AU') then result := 'Australia'
else if (code = 'AW') then result := 'Aruba'
else if (code = 'AX') then result := 'Åland Islands'
else if (code = 'AZ') then result := 'Azerbaijan'
else if (code = 'BA') then result := 'Bosnia and Herzegovina'
else if (code = 'BB') then result := 'Barbados'
else if (code = 'BD') then result := 'Bangladesh'
else if (code = 'BE') then result := 'Belgium'
else if (code = 'BF') then result := 'Burkina Faso'
else if (code = 'BG') then result := 'Bulgaria'
else if (code = 'BH') then result := 'Bahrain'
else if (code = 'BI') then result := 'Burundi'
else if (code = 'BJ') then result := 'Benin'
else if (code = 'BL') then result := 'Saint Barthélemy'
else if (code = 'BM') then result := 'Bermuda'
else if (code = 'BN') then result := 'Brunei Darussalam'
else if (code = 'BO') then result := 'Bolivia, Plurinational State of'
else if (code = 'BQ') then result := 'Bonaire, Sint Eustatius and Saba'
else if (code = 'BR') then result := 'Brazil'
else if (code = 'BS') then result := 'Bahamas'
else if (code = 'BT') then result := 'Bhutan'
else if (code = 'BV') then result := 'Bouvet Island'
else if (code = 'BW') then result := 'Botswana'
else if (code = 'BY') then result := 'Belarus'
else if (code = 'BZ') then result := 'Belize'
else if (code = 'CA') then result := 'Canada'
else if (code = 'CC') then result := 'Cocos (Keeling) Islands'
else if (code = 'CD') then result := 'Congo, the Democratic Republic of the'
else if (code = 'CF') then result := 'Central African Republic'
else if (code = 'CG') then result := 'Congo'
else if (code = 'CH') then result := 'Switzerland'
else if (code = 'CI') then result := 'Côte d''Ivoire'
else if (code = 'CK') then result := 'Cook Islands'
else if (code = 'CL') then result := 'Chile'
else if (code = 'CM') then result := 'Cameroon'
else if (code = 'CN') then result := 'China'
else if (code = 'CO') then result := 'Colombia'
else if (code = 'CR') then result := 'Costa Rica'
else if (code = 'CU') then result := 'Cuba'
else if (code = 'CV') then result := 'Cabo Verde'
else if (code = 'CW') then result := 'Curaçao'
else if (code = 'CX') then result := 'Christmas Island'
else if (code = 'CY') then result := 'Cyprus'
else if (code = 'CZ') then result := 'Czech Republic'
else if (code = 'DE') then result := 'Germany'
else if (code = 'DJ') then result := 'Djibouti'
else if (code = 'DK') then result := 'Denmark'
else if (code = 'DM') then result := 'Dominica'
else if (code = 'DO') then result := 'Dominican Republic'
else if (code = 'DZ') then result := 'Algeria'
else if (code = 'EC') then result := 'Ecuador'
else if (code = 'EE') then result := 'Estonia'
else if (code = 'EG') then result := 'Egypt'
else if (code = 'EH') then result := 'Western Sahara'
else if (code = 'ER') then result := 'Eritrea'
else if (code = 'ES') then result := 'Spain'
else if (code = 'ET') then result := 'Ethiopia'
else if (code = 'FI') then result := 'Finland'
else if (code = 'FJ') then result := 'Fiji'
else if (code = 'FK') then result := 'Falkland Islands (Malvinas)'
else if (code = 'FM') then result := 'Micronesia, Federated States of'
else if (code = 'FO') then result := 'Faroe Islands'
else if (code = 'FR') then result := 'France'
else if (code = 'GA') then result := 'Gabon'
else if (code = 'GB') then result := 'United Kingdom'
else if (code = 'GD') then result := 'Grenada'
else if (code = 'GE') then result := 'Georgia'
else if (code = 'GF') then result := 'French Guiana'
else if (code = 'GG') then result := 'Guernsey'
else if (code = 'GH') then result := 'Ghana'
else if (code = 'GI') then result := 'Gibraltar'
else if (code = 'GL') then result := 'Greenland'
else if (code = 'GM') then result := 'Gambia'
else if (code = 'GN') then result := 'Guinea'
else if (code = 'GP') then result := 'Guadeloupe'
else if (code = 'GQ') then result := 'Equatorial Guinea'
else if (code = 'GR') then result := 'Greece'
else if (code = 'GS') then result := 'South Georgia and the South Sandwich Islands'
else if (code = 'GT') then result := 'Guatemala'
else if (code = 'GU') then result := 'Guam'
else if (code = 'GW') then result := 'Guinea-Bissau'
else if (code = 'GY') then result := 'Guyana'
else if (code = 'HK') then result := 'Hong Kong'
else if (code = 'HM') then result := 'Heard Island and McDonald Islands'
else if (code = 'HN') then result := 'Honduras'
else if (code = 'HR') then result := 'Croatia'
else if (code = 'HT') then result := 'Haiti'
else if (code = 'HU') then result := 'Hungary'
else if (code = 'ID') then result := 'Indonesia'
else if (code = 'IE') then result := 'Ireland'
else if (code = 'IL') then result := 'Israel'
else if (code = 'IM') then result := 'Isle of Man'
else if (code = 'IN') then result := 'India'
else if (code = 'IO') then result := 'British Indian Ocean Territory'
else if (code = 'IQ') then result := 'Iraq'
else if (code = 'IR') then result := 'Iran, Islamic Republic of'
else if (code = 'IS') then result := 'Iceland'
else if (code = 'IT') then result := 'Italy'
else if (code = 'JE') then result := 'Jersey'
else if (code = 'JM') then result := 'Jamaica'
else if (code = 'JO') then result := 'Jordan'
else if (code = 'JP') then result := 'Japan'
else if (code = 'KE') then result := 'Kenya'
else if (code = 'KG') then result := 'Kyrgyzstan'
else if (code = 'KH') then result := 'Cambodia'
else if (code = 'KI') then result := 'Kiribati'
else if (code = 'KM') then result := 'Comoros'
else if (code = 'KN') then result := 'Saint Kitts and Nevis'
else if (code = 'KP') then result := 'Korea, Democratic People''s Republic of'
else if (code = 'KR') then result := 'Korea, Republic of'
else if (code = 'KW') then result := 'Kuwait'
else if (code = 'KY') then result := 'Cayman Islands'
else if (code = 'KZ') then result := 'Kazakhstan'
else if (code = 'LA') then result := 'Lao People''s Democratic Republic'
else if (code = 'LB') then result := 'Lebanon'
else if (code = 'LC') then result := 'Saint Lucia'
else if (code = 'LI') then result := 'Liechtenstein'
else if (code = 'LK') then result := 'Sri Lanka'
else if (code = 'LR') then result := 'Liberia'
else if (code = 'LS') then result := 'Lesotho'
else if (code = 'LT') then result := 'Lithuania'
else if (code = 'LU') then result := 'Luxembourg'
else if (code = 'LV') then result := 'Latvia'
else if (code = 'LY') then result := 'Libya'
else if (code = 'MA') then result := 'Morocco'
else if (code = 'MC') then result := 'Monaco'
else if (code = 'MD') then result := 'Moldova, Republic of'
else if (code = 'ME') then result := 'Montenegro'
else if (code = 'MF') then result := 'Saint Martin (French part)'
else if (code = 'MG') then result := 'Madagascar'
else if (code = 'MH') then result := 'Marshall Islands'
else if (code = 'MK') then result := 'Macedonia, the former Yugoslav Republic of'
else if (code = 'ML') then result := 'Mali'
else if (code = 'MM') then result := 'Myanmar'
else if (code = 'MN') then result := 'Mongolia'
else if (code = 'MO') then result := 'Macao'
else if (code = 'MP') then result := 'Northern Mariana Islands'
else if (code = 'MQ') then result := 'Martinique'
else if (code = 'MR') then result := 'Mauritania'
else if (code = 'MS') then result := 'Montserrat'
else if (code = 'MT') then result := 'Malta'
else if (code = 'MU') then result := 'Mauritius'
else if (code = 'MV') then result := 'Maldives'
else if (code = 'MW') then result := 'Malawi'
else if (code = 'MX') then result := 'Mexico'
else if (code = 'MY') then result := 'Malaysia'
else if (code = 'MZ') then result := 'Mozambique'
else if (code = 'NA') then result := 'Namibia'
else if (code = 'NC') then result := 'New Caledonia'
else if (code = 'NE') then result := 'Niger'
else if (code = 'NF') then result := 'Norfolk Island'
else if (code = 'NG') then result := 'Nigeria'
else if (code = 'NI') then result := 'Nicaragua'
else if (code = 'NL') then result := 'Netherlands'
else if (code = 'NO') then result := 'Norway'
else if (code = 'NP') then result := 'Nepal'
else if (code = 'NR') then result := 'Nauru'
else if (code = 'NU') then result := 'Niue'
else if (code = 'NZ') then result := 'New Zealand'
else if (code = 'OM') then result := 'Oman'
else if (code = 'PA') then result := 'Panama'
else if (code = 'PE') then result := 'Peru'
else if (code = 'PF') then result := 'French Polynesia'
else if (code = 'PG') then result := 'Papua New Guinea'
else if (code = 'PH') then result := 'Philippines'
else if (code = 'PK') then result := 'Pakistan'
else if (code = 'PL') then result := 'Poland'
else if (code = 'PM') then result := 'Saint Pierre and Miquelon'
else if (code = 'PN') then result := 'Pitcairn'
else if (code = 'PR') then result := 'Puerto Rico'
else if (code = 'PS') then result := 'Palestine, State of'
else if (code = 'PT') then result := 'Portugal'
else if (code = 'PW') then result := 'Palau'
else if (code = 'PY') then result := 'Paraguay'
else if (code = 'QA') then result := 'Qatar'
else if (code = 'RE') then result := 'Réunion'
else if (code = 'RO') then result := 'Romania'
else if (code = 'RS') then result := 'Serbia'
else if (code = 'RU') then result := 'Russian Federation'
else if (code = 'RW') then result := 'Rwanda'
else if (code = 'SA') then result := 'Saudi Arabia'
else if (code = 'SB') then result := 'Solomon Islands'
else if (code = 'SC') then result := 'Seychelles'
else if (code = 'SD') then result := 'Sudan'
else if (code = 'SE') then result := 'Sweden'
else if (code = 'SG') then result := 'Singapore'
else if (code = 'SH') then result := 'Saint Helena, Ascension and Tristan da Cunha'
else if (code = 'SI') then result := 'Slovenia'
else if (code = 'SJ') then result := 'Svalbard and Jan Mayen'
else if (code = 'SK') then result := 'Slovakia'
else if (code = 'SL') then result := 'Sierra Leone'
else if (code = 'SM') then result := 'San Marino'
else if (code = 'SN') then result := 'Senegal'
else if (code = 'SO') then result := 'Somalia'
else if (code = 'SR') then result := 'Suriname'
else if (code = 'SS') then result := 'South Sudan'
else if (code = 'ST') then result := 'Sao Tome and Principe'
else if (code = 'SV') then result := 'El Salvador'
else if (code = 'SX') then result := 'Sint Maarten (Dutch part)'
else if (code = 'SY') then result := 'Syrian Arab Republic'
else if (code = 'SZ') then result := 'Swaziland'
else if (code = 'TC') then result := 'Turks and Caicos Islands'
else if (code = 'TD') then result := 'Chad'
else if (code = 'TF') then result := 'French Southern Territories'
else if (code = 'TG') then result := 'Togo'
else if (code = 'TH') then result := 'Thailand'
else if (code = 'TJ') then result := 'Tajikistan'
else if (code = 'TK') then result := 'Tokelau'
else if (code = 'TL') then result := 'Timor-Leste'
else if (code = 'TM') then result := 'Turkmenistan'
else if (code = 'TN') then result := 'Tunisia'
else if (code = 'TO') then result := 'Tonga'
else if (code = 'TR') then result := 'Turkey'
else if (code = 'TT') then result := 'Trinidad and Tobago'
else if (code = 'TV') then result := 'Tuvalu'
else if (code = 'TW') then result := 'Taiwan, Province of China'
else if (code = 'TZ') then result := 'Tanzania, United Republic of'
else if (code = 'UA') then result := 'Ukraine'
else if (code = 'UG') then result := 'Uganda'
else if (code = 'UM') then result := 'United States Minor Outlying Islands'
else if (code = 'US') then result := 'United States'
else if (code = 'UY') then result := 'Uruguay'
else if (code = 'UZ') then result := 'Uzbekistan'
else if (code = 'VA') then result := 'Holy See (Vatican City State)'
else if (code = 'VC') then result := 'Saint Vincent and the Grenadines'
else if (code = 'VE') then result := 'Venezuela, Bolivarian Republic of'
else if (code = 'VG') then result := 'Virgin Islands, British'
else if (code = 'VI') then result := 'Virgin Islands, U.S.'
else if (code = 'VN') then result := 'Viet Nam'
else if (code = 'VU') then result := 'Vanuatu'
else if (code = 'WF') then result := 'Wallis and Futuna'
else if (code = 'WS') then result := 'Samoa'
else if (code = 'YE') then result := 'Yemen'
else if (code = 'YT') then result := 'Mayotte'
else if (code = 'ZA') then result := 'South Africa'
else if (code = 'ZM') then result := 'Zambia'
else if (code = 'ZW') then result := 'Zimbabwe'
else
raise Exception.Create('Unknown Country "'+code+'"');
end;
function TIETFLanguageCodeServices.describeLanguage(code: string): String;
begin
if (code = 'en') then
result := 'English'
else if (code = 'es') then
result := 'Spanish'
else if (code = 'pt') then
result := 'Portuguese'
else if (code = 'zh') then
result := 'Chinese'
else if (code = 'ab') then result := 'Abkhazian'
else if (code = 'aa') then result := 'Afar'
else if (code = 'af') then result := 'Afrikaans'
else if (code = 'sq') then result := 'Albanian'
else if (code = 'am') then result := 'sqsqAmharic'
else if (code = 'ar') then result := 'amamamArabic'
else if (code = 'an') then result := 'Aragonese'
else if (code = 'hy') then result := 'Armenian'
else if (code = 'as') then result := 'Assamese'
else if (code = 'ay') then result := 'Aymara'
else if (code = 'az') then result := 'Azerbaijani'
else if (code = 'ba') then result := 'Bashkir'
else if (code = 'eu') then result := 'Basque'
else if (code = 'bn') then result := 'Bengali (Bangla)'
else if (code = 'dz') then result := 'Bhutani'
else if (code = 'bh') then result := 'dzdzBihari'
else if (code = 'bi') then result := 'bhbhBislama'
else if (code = 'br') then result := 'bibiBreton'
else if (code = 'bg') then result := 'Bulgarian'
else if (code = 'my') then result := 'bgbgBurmese'
else if (code = 'be') then result := 'mymyByelorussian (Belarusian)'
else if (code = 'km') then result := 'Cambodian'
else if (code = 'ca') then result := 'Catalan'
else if (code = 'zh') then result := 'Chinese'
else if (code = 'co') then result := 'Corsican'
else if (code = 'hr') then result := 'Croatian'
else if (code = 'cs') then result := 'Czech'
else if (code = 'da') then result := 'Danish'
else if (code = 'nl') then result := 'Dutch'
else if (code = 'en') then result := 'English'
else if (code = 'eo') then result := 'Esperanto'
else if (code = 'et') then result := 'Estonian'
else if (code = 'fo') then result := 'Faeroese'
else if (code = 'fa') then result := 'Farsi'
else if (code = 'fj') then result := 'Fiji'
else if (code = 'fi') then result := 'Finnish'
else if (code = 'fr') then result := 'French'
else if (code = 'fy') then result := 'Frisian'
else if (code = 'gl') then result := 'Galician'
else if (code = 'gd') then result := 'Gaelic (Scottish)'
else if (code = 'gv') then result := 'Gaelic (Manx)'
else if (code = 'ka') then result := 'Georgian'
else if (code = 'de') then result := 'German'
else if (code = 'el') then result := 'Greek'
else if (code = 'kl') then result := 'Greenlandic'
else if (code = 'gn') then result := 'Guarani'
else if (code = 'gu') then result := 'Gujarati'
else if (code = 'ht') then result := 'Haitian Creole'
else if (code = 'ha') then result := 'Hausa'
else if (code = 'he') then result := 'Hebrew'
else if (code = 'iw') then result := 'Hebrew'
else if (code = 'hi') then result := 'Hindi'
else if (code = 'hu') then result := 'Hungarian'
else if (code = 'is') then result := 'Icelandic'
else if (code = 'io') then result := 'Ido'
else if (code = 'id') then result := 'Indonesian'
else if (code = 'in') then result := 'Indonesian'
else if (code = 'ia') then result := 'Interlingua'
else if (code = 'ie') then result := 'Interlingue'
else if (code = 'iu') then result := 'Inuktitut'
else if (code = 'ik') then result := 'Inupiak'
else if (code = 'ga') then result := 'Irish'
else if (code = 'it') then result := 'Italian'
else if (code = 'ja') then result := 'Japanese'
else if (code = 'jv') then result := 'Javanese'
else if (code = 'kn') then result := 'Kannada'
else if (code = 'ks') then result := 'Kashmiri'
else if (code = 'kk') then result := 'Kazakh'
else if (code = 'rw') then result := 'Kinyarwanda (Ruanda)'
else if (code = 'ky') then result := 'Kirghiz'
else if (code = 'rn') then result := 'Kirundi (Rundi)'
else if (code = 'ko') then result := 'Korean'
else if (code = 'ku') then result := 'Kurdish'
else if (code = 'lo') then result := 'Laothian'
else if (code = 'la') then result := 'Latin'
else if (code = 'lv') then result := 'Latvian (Lettish)'
else if (code = 'li') then result := 'Limburgish ( Limburger)'
else if (code = 'ln') then result := 'liliLingala'
else if (code = 'lt') then result := 'lnlnlnLithuanian'
else if (code = 'mk') then result := 'ltltMacedonian'
else if (code = 'mg') then result := 'mkmkMalagasy'
else if (code = 'ms') then result := 'mgmgMalay'
else if (code = 'ml') then result := 'msmsMalayalam'
else if (code = 'mt') then result := 'mlmlMaltese'
else if (code = 'mi') then result := 'mtmtMaori'
else if (code = 'mr') then result := 'Marathi'
else if (code = 'mo') then result := 'Moldavian'
else if (code = 'mn') then result := 'momoMongolian'
else if (code = 'na') then result := 'mnmnNauru'
else if (code = 'ne') then result := 'Nepali'
else if (code = 'no') then result := 'Norwegian'
else if (code = 'oc') then result := 'Occitan'
else if (code = 'or') then result := 'Oriya'
else if (code = 'om') then result := 'Oromo (Afaan Oromo)'
else if (code = 'ps') then result := 'Pashto (Pushto)'
else if (code = 'pl') then result := 'Polish'
else if (code = 'pt') then result := 'Portuguese'
else if (code = 'pa') then result := 'Punjabi'
else if (code = 'qu') then result := 'Quechua'
else if (code = 'rm') then result := 'Rhaeto-Romance'
else if (code = 'ro') then result := 'Romanian'
else if (code = 'ru') then result := 'Russian'
else if (code = 'sm') then result := 'Samoan'
else if (code = 'sg') then result := 'Sangro'
else if (code = 'sa') then result := 'Sanskrit'
else if (code = 'sr') then result := 'Serbian'
else if (code = 'sh') then result := 'Serbo-Croatian'
else if (code = 'st') then result := 'Sesotho'
else if (code = 'tn') then result := 'Setswana'
else if (code = 'sn') then result := 'Shona'
else if (code = 'ii') then result := 'Sichuan Yi'
else if (code = 'sd') then result := 'Sindhi'
else if (code = 'si') then result := 'Sinhalese'
else if (code = 'ss') then result := 'Siswati'
else if (code = 'sk') then result := 'Slovak'
else if (code = 'sl') then result := 'Slovenian'
else if (code = 'so') then result := 'Somali'
else if (code = 'es') then result := 'Spanish'
else if (code = 'su') then result := 'Sundanese'
else if (code = 'sw') then result := 'Swahili (Kiswahili)'
else if (code = 'sv') then result := 'Swedish'
else if (code = 'tl') then result := 'Tagalog'
else if (code = 'tg') then result := 'Tajik'
else if (code = 'ta') then result := 'Tamil'
else if (code = 'tt') then result := 'Tatar'
else if (code = 'te') then result := 'Telugu'
else if (code = 'th') then result := 'Thai'
else if (code = 'bo') then result := 'Tibetan'
else if (code = 'ti') then result := 'Tigrinya'
else if (code = 'to') then result := 'Tonga'
else if (code = 'ts') then result := 'Tsonga'
else if (code = 'tr') then result := 'Turkish'
else if (code = 'tk') then result := 'Turkmen'
else if (code = 'tw') then result := 'Twi'
else if (code = 'ug') then result := 'Uighur'
else if (code = 'uk') then result := 'Ukrainian'
else if (code = 'ur') then result := 'Urdu'
else if (code = 'uz') then result := 'Uzbek'
else if (code = 'vi') then result := 'Vietnamese'
else if (code = 'vo') then result := 'Volapük'
else if (code = 'wa') then result := 'Wallon'
else if (code = 'cy') then result := 'Welsh'
else if (code = 'wo') then result := 'Wolof'
else if (code = 'xh') then result := 'Xhosa'
else if (code = 'yi') then result := 'Yiddish'
else if (code = 'yo') then result := 'Yoruba'
else if (code = 'zu') then result := 'Zulu'
else
raise Exception.Create('Unknown Language "'+code+'"');
end;
destructor TIETFLanguageCodeServices.Destroy;
begin
// this does not own it: db.Free;
inherited;
end;
function TIETFLanguageCodeServices.Display(context : TCodeSystemProviderContext; lang : String) : string;
begin
result := getDisplay(TIETFLanguageCodeConcept(context).code, lang);
end;
procedure TIETFLanguageCodeServices.Displays(context: TCodeSystemProviderContext; list: TStringList; lang : String);
begin
list.Add(Display(context, lang));
end;
function TIETFLanguageCodeServices.IsAbstract(context : TCodeSystemProviderContext) : boolean;
begin
result := false; // IETFLanguageCode doesn't do abstract
end;
function TIETFLanguageCodeServices.isNotClosed(textFilter: TSearchFilterText; propFilter: TCodeSystemProviderFilterContext): boolean;
begin
result := true;
end;
function TIETFLanguageCodeServices.Link: TIETFLanguageCodeServices;
begin
result := TIETFLanguageCodeServices(Inherited Link);
end;
function TIETFLanguageCodeServices.ChildCount(context : TCodeSystemProviderContext) : integer;
begin
result := -1;
end;
function TIETFLanguageCodeServices.getcontext(context : TCodeSystemProviderContext; ndx : integer) : TCodeSystemProviderContext;
begin
raise Exception.Create('not done yet');
end;
function TIETFLanguageCodeServices.locateIsA(code, parent : String) : TCodeSystemProviderContext;
begin
result := nil; // no subsumption
end;
function TIETFLanguageCodeServices.name(context: TCodeSystemProviderContext): String;
begin
result := 'IETF langauge';
end;
function TIETFLanguageCodeServices.prepare(prep : TCodeSystemProviderFilterPreparationContext) : boolean;
begin
raise Exception.Create('not done yet');
end;
function TIETFLanguageCodeServices.searchFilter(filter : TSearchFilterText; prep : TCodeSystemProviderFilterPreparationContext; sort : boolean) : TCodeSystemProviderFilterContext;
begin
raise Exception.Create('not done yet');
end;
function TIETFLanguageCodeServices.filter(prop : String; op : TFhirFilterOperatorEnum; value : String; prep : TCodeSystemProviderFilterPreparationContext) : TCodeSystemProviderFilterContext;
begin
raise Exception.Create('not done yet');
end;
function TIETFLanguageCodeServices.filterLocate(ctxt : TCodeSystemProviderFilterContext; code : String) : TCodeSystemProviderContext;
begin
raise Exception.Create('not done yet');
end;
function TIETFLanguageCodeServices.FilterMore(ctxt : TCodeSystemProviderFilterContext) : boolean;
begin
raise Exception.Create('not done yet');
end;
function TIETFLanguageCodeServices.FilterConcept(ctxt : TCodeSystemProviderFilterContext): TCodeSystemProviderContext;
begin
raise Exception.Create('not done yet');
end;
function TIETFLanguageCodeServices.InFilter(ctxt : TCodeSystemProviderFilterContext; concept : TCodeSystemProviderContext) : Boolean;
begin
raise Exception.Create('not done yet');
end;
procedure TIETFLanguageCodeServices.Close(ctxt: TCodeSystemProviderContext);
begin
ctxt.free;
end;
procedure TIETFLanguageCodeServices.Close(ctxt : TCodeSystemProviderFilterContext);
begin
ctxt.free;
end;
procedure TIETFLanguageCodeServices.Close(ctxt: TCodeSystemProviderFilterPreparationContext);
begin
raise Exception.Create('not done yet');
end;
{ TIETFLanguageCodeConcept }
constructor TIETFLanguageCodeConcept.create(code: String);
begin
inherited create;
self.code := code;
end;
end.
|
{ ****************************************************************************** }
{ * distortion/Undistortion Rasterization, create by.qq600585 * }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
unit DistortionRaster;
{$INCLUDE zDefine.inc}
interface
uses CoreClasses,
DoStatusIO, PascalStrings, UnicodeMixedLib, Geometry2DUnit, Geometry3DUnit,
DataFrameEngine, MemoryRaster, Learn, LearnTypes;
// build ones sample picture for Undistortion Calibrate
function BuildDistortionCalibratePiture(const width, height, metric: Integer): TMemoryRaster;
// Least squares fitting by polynomial: model training for undistortion
function BuildDistortionModel_Polynomial(DistortionCoord: TArrayVec2; degree: Integer; var model: TBarycentricInterpolant): Boolean; overload;
function BuildDistortionModel_Polynomial(DistortionCoord: TArrayVec2; degree: Integer): TLVec; overload;
// Least squares fitting by polynomial: process for undistortion
function ProcessDistortionRaster_Polynomial(model: TBarycentricInterpolant; axis: TVec2; raster: TMemoryRaster; fast: Boolean): TMemoryRaster; overload;
function ProcessDistortionRaster_Polynomial(model: TBarycentricInterpolant; axis: TVec2; raster: TMemoryRaster): TMemoryRaster; overload;
function ProcessDistortionRaster_Polynomial(model: TLVec; axis: TVec2; raster: TMemoryRaster; fast: Boolean): TMemoryRaster; overload;
function ProcessDistortionRaster_Polynomial(model: TLVec; axis: TVec2; raster: TMemoryRaster): TMemoryRaster; overload;
// Least squares fitting by polynomial: end-to-end process for undistortion
function ProcessDistortionRaster_Polynomial(DistortionCoord: TArrayVec2; degree: Integer; raster: TMemoryRaster; fast: Boolean): TMemoryRaster; overload;
function ProcessDistortionRaster_Polynomial(DistortionCoord: TArrayVec2; degree: Integer; raster: TMemoryRaster): TMemoryRaster; overload;
implementation
function BuildDistortionCalibratePiture(const width, height, metric: Integer): TMemoryRaster;
var
metric_, i: Integer;
f, minSiz: TGeoFloat;
PT: TVec2;
textsiz: TVec2;
begin
Result := NewRaster();
Result.SetSize(umlMax(1024, width), umlMax(1024, height));
metric_ := umlMax(40, metric);
FillBlackGrayBackgroundTexture(Result, metric_ shr 1, RColorF(1.0, 1.0, 1.0), RColorF(0.98, 0.98, 0.98), RColorF(0.95, 0.95, 0.95));
Result.OpenAgg;
PT := Vec2(10, 10);
textsiz := Result.TextSize(PFormat('Sample size(%d * %d) metric: %d', [Result.width, Result.height, metric_]), 20);
Result.DrawText(PFormat('Sample size(%d * %d) metric: %d', [Result.width, Result.height, metric_]), round(PT[0]), round(PT[1]), 20, RColorF(0.0, 0.0, 0.0, 0.9));
Result.Agg.LineWidth := 2.0;
PT := Vec2(10, PT[1] + textsiz[1]);
i := 1;
PT := Vec2(10, PT[1] + 10);
textsiz := Result.TextSize(PFormat('metric * %f', [TGeoFloat(i), metric_ * i]), 24);
Result.DrawText(PFormat('metric * %f', [TGeoFloat(i), metric_ * i]), round(PT[0]), round(PT[1]), 24, RColorF(0.0, 0.0, 0.0, 0.9));
PT := Vec2(10, PT[1] + textsiz[1]);
Result.LineF(PT, Vec2Add(PT, Vec2(metric_ * i, 0)), RColorF(0.1, 0.1, 0.1, 0.9), True, 10, True);
for i := 1 to 4 do
begin
PT := Vec2(10, PT[1] + 10);
textsiz := Result.TextSize(PFormat('metric * %f', [pow(2, i), metric_ * pow(2, i)]), 24);
Result.DrawText(PFormat('metric * %f', [pow(2, i), metric_ * pow(2, i)]), round(PT[0]), round(PT[1]), 24, RColorF(0.0, 0.0, 0.0, 0.9));
PT := Vec2(10, PT[1] + textsiz[1]);
Result.LineF(PT, Vec2Add(PT, Vec2(metric_ * pow(2, i), 0)), RColorF(0.1, 0.1, 0.1, 0.9), True, 10, True);
end;
minSiz := umlMin(Result.width, Result.height);
for i := 1 to Trunc(minSiz / metric_ * 0.5) do
begin
f := 1.0 - (i / (Trunc(minSiz / metric_)));
Result.Agg.LineWidth := 4.0 * f;
Result.DrawCircle(Result.Centroid, i * metric_, RColorF(1 - f, 1 - f, 1 - f, f));
Result.Agg.LineWidth := 2.0 * f;
PT := Vec2Add(Result.Centroid, Vec2(i * metric_, 0));
Result.DrawCrossF(PT, metric_ * 0.2, RColorF(1 - f, 1 - f, 1 - f, f));
Result.DrawText(PFormat('%d', [i]), round(PT[0]), round(PT[1]), Vec2(0.5, 0.5), -45, 1.0, 12, RColorF(0.5, 0.5, 0.5));
PT := Vec2Sub(Result.Centroid, Vec2(i * metric_, 0));
Result.DrawCrossF(PT, metric_ * 0.2, RColorF(1 - f, 1 - f, 1 - f, f));
Result.DrawText(PFormat('%d', [i]), round(PT[0]), round(PT[1]), Vec2(0.5, 0.5), -45, 1.0, 12, RColorF(0.5, 0.5, 0.5));
PT := Vec2Add(Result.Centroid, Vec2(0, i * metric_));
Result.DrawCrossF(PT, metric_ * 0.2, RColorF(1 - f, 1 - f, 1 - f, f));
Result.DrawText(PFormat('%d', [i]), round(PT[0]), round(PT[1]), Vec2(0.5, 0.5), -45, 1.0, 12, RColorF(0.5, 0.5, 0.5));
PT := Vec2Sub(Result.Centroid, Vec2(0, i * metric_));
Result.DrawCrossF(PT, metric_ * 0.2, RColorF(1 - f, 1 - f, 1 - f, f));
Result.DrawText(PFormat('%d', [i]), round(PT[0]), round(PT[1]), Vec2(0.5, 0.5), -45, 1.0, 12, RColorF(0.5, 0.5, 0.5));
Result.DrawCircle(Vec2LerpTo(Result.Centroid, Vec2(0, 0), i * metric_), metric_ * 0.1, RColorF(1 - f, 1 - f, 1 - f, f));
Result.DrawCircle(Vec2LerpTo(Result.Centroid, Vec2(Result.Width0, 0), i * metric_), metric_ * 0.1, RColorF(1 - f, 1 - f, 1 - f, f));
Result.DrawCircle(Vec2LerpTo(Result.Centroid, Vec2(0, Result.Height0), i * metric_), metric_ * 0.1, RColorF(1 - f, 1 - f, 1 - f, f));
Result.DrawCircle(Vec2LerpTo(Result.Centroid, Vec2(Result.Width0, Result.Height0), i * metric_), metric_ * 0.1, RColorF(1 - f, 1 - f, 1 - f, f));
end;
i := 0;
f := 1.0;
Result.Agg.LineWidth := 5.0;
PT := Result.Centroid;
Result.DrawCrossF(PT, metric_ * 0.2, RColorF(0, 0, 0, 1.0));
Result.DrawText(PFormat('%d', [i]), round(PT[0]), round(PT[1]), Vec2(0.5, 0.5), -45, 1.0, 12, RColorF(0.0, 0.0, 0.0));
Result.CloseAgg;
Result.CloseVertex;
Result.CloseFont;
end;
function BuildDistortionModel_Polynomial(DistortionCoord: TArrayVec2; degree: Integer; var model: TBarycentricInterpolant): Boolean;
var
L: TVec2List;
d: TGeoFloat;
i: Integer;
formulaVec: TLVec;
distortionVec: TLVec;
N, M: TLInt;
Info: TLInt;
Rep: TPolynomialFitReport;
begin
Result := False;
L := TVec2List.Create;
L.AssignFromArrayV2(DistortionCoord);
// formula distortion
d := Vec2Distance(L[0]^, L[1]^);
N := L.Count;
M := degree;
formulaVec := LVec(N, 0);
distortionVec := LVec(N, 0);
for i := 1 to L.Count - 1 do
begin
formulaVec[i] := i * d;
distortionVec[i] := Vec2Distance(L[i]^, L[0]^);
end;
// Least squares fitting by polynomial
PolynomialFit(formulaVec, distortionVec, N, M, Info, model, Rep);
if Info > 0 then
begin
Result := True;
DoStatus('polynomial fitting solved.');
end
else
begin
DoStatusNoLn;
DoStatusNoLn('polynomial an error occured: ');
case Info of
- 4: DoStatusNoLn('means inconvergence of internal SVD');
-3: DoStatusNoLn('means inconsistent constraints');
-1: DoStatusNoLn('means another errors in parameters passed (N<=0, for example)');
end;
DoStatusNoLn;
end;
disposeObject(L);
end;
function BuildDistortionModel_Polynomial(DistortionCoord: TArrayVec2; degree: Integer): TLVec;
var
model: TBarycentricInterpolant;
RL: TLInt;
begin
if BuildDistortionModel_Polynomial(DistortionCoord, degree, model) then
BarycentricSerialize(model, Result, RL)
else
Result := LVec(0);
end;
function ProcessDistortionRaster_Polynomial(model: TBarycentricInterpolant; axis: TVec2; raster: TMemoryRaster; fast: Boolean): TMemoryRaster;
var
nRaster: TMemoryRaster;
{$IFDEF Parallel}
{$IFDEF FPC}
procedure Nested_ParallelFor(pass: Integer);
var
i: Integer;
f: TLFloat;
d, dx, dy: TGeoFloat;
begin
for i := 0 to nRaster.width - 1 do
begin
d := Vec2Distance(Vec2(i, pass), axis);
dx := axis[0];
dy := axis[1];
if d <> 0 then
begin
f := BarycentricCalc(model, d) / d;
dx := dx + (i - axis[0]) * f;
dy := dy + (pass - axis[1]) * f;
end;
if fast then
nRaster.FastPixel[i, pass] := raster.Pixel[round(dx), round(dy)]
else
nRaster.FastPixel[i, pass] := raster.PixelLinear[round(dx), round(dy)];
end;
end;
{$ENDIF FPC}
{$ELSE Parallel}
procedure DoFor;
var
pass: Integer;
i: Integer;
f: TLFloat;
d, dx, dy: TGeoFloat;
begin
for pass := 0 to nRaster.height - 1 do
begin
for i := 0 to nRaster.width - 1 do
begin
d := Vec2Distance(Vec2(i, pass), axis);
dx := axis[0];
dy := axis[1];
if d > 0 then
begin
f := BarycentricCalc(model, d) / d;
dx := dx + (i - axis[0]) * f;
dy := dy + (pass - axis[1]) * f;
end;
if fast then
nRaster.FastPixel[i, pass] := raster.Pixel[round(dx), round(dy)]
else
nRaster.FastPixel[i, pass] := raster.PixelLinear[round(dx), round(dy)];
end;
end;
end;
{$ENDIF Parallel}
begin
nRaster := NewRaster();
nRaster.SetSize(raster.width, raster.height);
{$IFDEF Parallel}
{$IFDEF FPC}
FPCParallelFor(@Nested_ParallelFor, 0, nRaster.height - 1);
{$ELSE FPC}
DelphiParallelFor(0, nRaster.height - 1, procedure(pass: Integer)
var
i: Integer;
f: TLFloat;
d, dx, dy: TGeoFloat;
begin
for i := 0 to nRaster.width - 1 do
begin
d := Vec2Distance(Vec2(i, pass), axis);
dx := axis[0];
dy := axis[1];
if d <> 0 then
begin
f := BarycentricCalc(model, d) / d;
dx := dx + (i - axis[0]) * f;
dy := dy + (pass - axis[1]) * f;
end;
if fast then
nRaster.FastPixel[i, pass] := raster.Pixel[round(dx), round(dy)]
else
nRaster.FastPixel[i, pass] := raster.PixelLinear[round(dx), round(dy)];
end;
end);
{$ENDIF FPC}
{$ELSE Parallel}
DoFor;
{$ENDIF Parallel}
Result := nRaster;
end;
function ProcessDistortionRaster_Polynomial(model: TBarycentricInterpolant; axis: TVec2; raster: TMemoryRaster): TMemoryRaster;
begin
Result := ProcessDistortionRaster_Polynomial(model, axis, raster, False);
end;
function ProcessDistortionRaster_Polynomial(model: TLVec; axis: TVec2; raster: TMemoryRaster; fast: Boolean): TMemoryRaster;
var
p: TBarycentricInterpolant;
begin
Result := nil;
if length(model) = 0 then
exit;
BarycentricUnserialize(model, p);
Result := ProcessDistortionRaster_Polynomial(p, axis, raster, False);
end;
function ProcessDistortionRaster_Polynomial(model: TLVec; axis: TVec2; raster: TMemoryRaster): TMemoryRaster;
var
p: TBarycentricInterpolant;
begin
Result := nil;
if length(model) = 0 then
exit;
BarycentricUnserialize(model, p);
Result := ProcessDistortionRaster_Polynomial(p, axis, raster);
end;
function ProcessDistortionRaster_Polynomial(DistortionCoord: TArrayVec2; degree: Integer; raster: TMemoryRaster; fast: Boolean): TMemoryRaster;
var
model: TBarycentricInterpolant;
begin
Result := nil;
if BuildDistortionModel_Polynomial(DistortionCoord, degree, model) then
Result := ProcessDistortionRaster_Polynomial(model, DistortionCoord[0], raster, False);
end;
function ProcessDistortionRaster_Polynomial(DistortionCoord: TArrayVec2; degree: Integer; raster: TMemoryRaster): TMemoryRaster;
var
model: TBarycentricInterpolant;
begin
Result := nil;
if BuildDistortionModel_Polynomial(DistortionCoord, degree, model) then
Result := ProcessDistortionRaster_Polynomial(model, DistortionCoord[0], raster);
end;
end.
|
// This is a simple sample of using a iprovider interface. Since
// IPRovider manages his own resultset, don't forget to set
// unidirectional property of tquery to true. Otherwize you will
// have two full resultsets in memory!
// aducom software
// (c) 2007
unit Sample07Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ExtCtrls, DBCtrls, Grids, DBGrids, ASGSQLite3, StdCtrls,
DBClient, Provider;
type
TForm1 = class(TForm)
ASQLite3DB1: TASQLite3DB;
DBGrid1: TDBGrid;
DBNavigator1: TDBNavigator;
DataSource1: TDataSource;
ASQLite3Query1: TASQLite3Query;
Button1: TButton;
DataSetProvider: TDataSetProvider;
ClientDataSet: TClientDataSet;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure ClientDataSetAfterPost(DataSet: TDataSet);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
{ Private declarations }
bOk : boolean;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
ASQLite3Query1.Open;
ClientDataSet.Open;
bOk := true;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ClientDataSet.ApplyUpdates(0);
bOk := true;
end;
procedure TForm1.ClientDataSetAfterPost(DataSet: TDataSet);
begin
bOk := false;
end;
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := true;
if not bOK then
if MessageDlg('Updates are not saved into the databaase. Exit now?',
mtConfirmation, [mbYes, mbNo], 0) = mrNo then CanClose := false;
end;
end.
|
{-------------------------------------------------------------------------------
HtmlViewer12TestForm.pas, (C) 03/2011 by Bernd Gabriel, all rights reserved
mailto: info@fast-function-factory.de
-------------------------------------------------------------------------------}
unit HtmlViewer12TestForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Menus, ComCtrls, ExtCtrls,
// shared units
TntDialogs,
VirtualTrees,
// fast function factory units
BegaComboBox,
BegaSplitter,
BegaVirtualTrees,
// own units
HtmlBoxes,
HtmlBuffer,
HtmlDocument,
HtmlDraw,
HtmlElements,
HtmlGlobals,
HtmlImages,
HtmlParser,
HtmlSymbols,
HtmlUri,
HtmlViewer,
StyleTypes;
type
TFormHtmlViewer12Test = class(TForm)
cbFiles: TBegaCombobox;
dlgFileOpen: TTntOpenDialog;
menu: TMainMenu;
menuFile: TMenuItem;
menuFileOpen: TMenuItem;
HtmlViewer: THtmlViewer12;
PageControl: TPageControl;
HtmlTab: TTabSheet;
CssTab: TTabSheet;
vtDocument: TBegaVirtualStringTree;
CssMemo: TMemo;
BegaSplitter1: TSplitter;
menuFileReload: TMenuItem;
procedure cbFilesKeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure menuFileOpenClick(Sender: TObject);
procedure vtDocumentGetText(Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
procedure vtDocumentInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode; var ChildCount: Cardinal);
procedure vtDocumentInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
procedure menuFileReloadClick(Sender: TObject);
private
FName: ThtString;
FStream: TStream;
FBuffer: TBuffer;
FDocument: THtmlDocument;
FParser: THtmlParser;
FView: THtmlBox;
public
procedure Load(FileName: ThtString);
end;
var
FormHtmlViewer12Test: TFormHtmlViewer12Test;
implementation
{$R *.dfm}
{ TFormHtmlViewer12Test }
//-- BG ---------------------------------------------------------- 28.03.2011 --
procedure TFormHtmlViewer12Test.menuFileOpenClick(Sender: TObject);
begin
dlgFileOpen.FileName := cbFiles.Text;
if dlgFileOpen.Execute then
begin
Load(dlgFileOpen.FileName);
cbFiles.AddItem(FName, nil);
end;
end;
//-- BG ---------------------------------------------------------- 17.12.2011 --
procedure TFormHtmlViewer12Test.menuFileReloadClick(Sender: TObject);
begin
Load(FName);
end;
//-- BG ---------------------------------------------------------- 30.03.2011 --
procedure TFormHtmlViewer12Test.vtDocumentGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: WideString);
var
Elem: THtmlElement;
Ed: THtmlElementDescription;
begin
Elem := THtmlElement(vtDocument.Objects[Node]);
case Column of
1: CellText := Implode(Elem.Classes, ' ');
2: CellText := Implode(Elem.Ids, ' ');
3: CellText := IntToStr(Elem.DocPos);
4: CellText := Elem.StyleProperties.ToString;
5: CellText := Elem.AttributeProperties.ToString;
6: CellText := Elem.OtherAttributes.ToString;
else
Ed := ElementSymbolToElementDescription(Elem.Symbol);
CellText := Ed.Name;
end;
end;
//-- BG ---------------------------------------------------------- 30.03.2011 --
procedure TFormHtmlViewer12Test.vtDocumentInitChildren(Sender: TBaseVirtualTree; Node: PVirtualNode;
var ChildCount: Cardinal);
var
Child: THtmlElement;
begin
ChildCount := 0;
Child := THtmlElement(vtDocument.Objects[Node]).FirstChild;
while Child <> nil do
begin
Inc(ChildCount);
Child := Child.Next;
end;
end;
//-- BG ---------------------------------------------------------- 30.03.2011 --
procedure TFormHtmlViewer12Test.vtDocumentInitNode(Sender: TBaseVirtualTree; ParentNode, Node: PVirtualNode;
var InitialStates: TVirtualNodeInitStates);
function GetChild(Element: THtmlElement; Index: Integer): THtmlElement;
begin
Result := Element.FirstChild;
while (Index > 0) and (Result <> nil) do
begin
Dec(Index);
Result := Result.Next;
end;
end;
var
Element: THtmlElement;
begin
Include(InitialStates, ivsExpanded);
if ParentNode = nil then
begin
vtDocument.Objects[Node] := FDocument.Tree;
if FDocument.Tree.FirstChild <> nil then
Include(InitialStates, ivsHasChildren);
end
else
begin
Element := GetChild(THtmlElement(vtDocument.Objects[ParentNode]), Node.Index);
vtDocument.Objects[Node] := Element;
if Element.FirstChild <> nil then
Include(InitialStates, ivsHasChildren);
end;
end;
//-- BG ---------------------------------------------------------- 30.03.2011 --
procedure TFormHtmlViewer12Test.cbFilesKeyPress(Sender: TObject; var Key: Char);
begin
case Key of
#13:
begin
Load(cbFiles.Text);
Key := #0;
end;
end;
end;
//-- BG ---------------------------------------------------------- 05.04.2011 --
procedure TFormHtmlViewer12Test.FormCreate(Sender: TObject);
// simple test example with parsing a document:
procedure InitTest;
begin
if ParamCount > 0 then
Load(ParamStr(1))
else
Load('HtmlViewer12Test.html');
end;
begin
InitTest;
end;
//-- BG ---------------------------------------------------------- 05.04.2011 --
procedure TFormHtmlViewer12Test.FormDestroy(Sender: TObject);
begin
if FView <> nil then
begin
FView.Image := nil;
FView.Free;
end;
Load('');
end;
var
Uri: TUri;
Filename: ThtString;
Filenames: ThtStringList;
//-- BG ---------------------------------------------------------- 30.03.2011 --
procedure TFormHtmlViewer12Test.Load(FileName: ThtString);
begin
vtDocument.RootNodeCount := 0;
CssMemo.Clear;
HtmlViewer.HtmlDocument := nil;
FreeAndNil(FParser);
FreeAndNil(FDocument);
FreeAndNil(FBuffer);
FreeAndNil(FStream);
FName := FileName;
if Length(FName) > 0 then
begin
FStream := TFileStream.Create(FName, fmOpenRead + fmShareDenyNone);
FBuffer := TBuffer.Create(FStream, StrToUriStr(FName, 'file'));
FDocument := THtmlDocument.Create;
FParser := THtmlParser.Create(FBuffer);
FParser.ParseHtmlDocument(FDocument);
if FDocument.Tree <> nil then
vtDocument.RootNodeCount := 1;
CssMemo.Lines.Text := FDocument.RuleSets.ToString;
HtmlViewer.HtmlDocument := FDocument;
if cbFiles.Items.IndexOf(FileName) < 0 then
cbFiles.Items.Insert(0, FileName);
end;
end;
initialization
Filenames := ThtStringList.Create;
finalization
Filenames.Free;
end.
|
{********************************************}
{ TeeChart Pro Charting Library }
{ Copyright (c) 1995-2004 by David Berneda }
{ All Rights Reserved }
{********************************************}
unit TeeSourceEdit;
{$I TeeDefs.inc}
interface
uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
{$ENDIF}
TeEngine, TeeProcs, TeCanvas;
type
TBaseSourceEditor = class(TForm)
LLabel: TLabel;
CBSources: TComboFlat;
BApply: TButton;
Pan: TPanel;
procedure CBSourcesChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
protected
TheSeries : TChartSeries;
SkipValidation : Boolean;
Procedure AddComponentDataSource( Const AComponent:TComponent;
AItems:TStrings;
AddCurrent:Boolean);
procedure CheckReplaceSource(NewSource:TTeeSeriesSource);
Function IsValid(AComponent:TComponent):Boolean; virtual;
public
{ Public declarations }
end;
{ special case for TFormDesigner in TeeCharteg unit }
TAddComponentDataSource=Procedure( Const AComponent:TComponent;
AItems:TStrings;
AddCurrent:Boolean) of object;
TOnGetDesignerNamesEvent=Procedure( AProc:TAddComponentDataSource;
ASeries:TChartSeries;
AItems:TStrings;
AddCurrent:Boolean);
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses TeeConst;
Procedure TBaseSourceEditor.AddComponentDataSource( Const AComponent:TComponent;
AItems:TStrings;
AddCurrent:Boolean);
Var tmp : String;
tmpFormName : TComponentName;
begin
if AItems.IndexOfObject(AComponent)=-1 then { 5.01 }
if AddCurrent or (TheSeries.DataSources.IndexOf(AComponent)=-1) then
if IsValid(AComponent) then
if SkipValidation or
TheSeries.ParentChart.IsValidDataSource(TheSeries,AComponent) then
begin
if AComponent is TChartSeries then
tmp:=SeriesTitleOrName(TChartSeries(AComponent))
else
tmp:=AComponent.Name;
if (TheSeries.Owner<>AComponent.Owner) and
Assigned(AComponent.Owner) then
begin
tmpFormName:=AComponent.Owner.Name;
if tmpFormName<>'' then tmp:=tmpFormName+'.'+tmp;
end;
AItems.AddObject(tmp,AComponent);
end;
end;
procedure TBaseSourceEditor.CBSourcesChange(Sender: TObject);
begin
BApply.Enabled:=True;
end;
procedure TBaseSourceEditor.FormShow(Sender: TObject);
begin
TheSeries:=TChartSeries({$IFDEF CLR}TObject{$ENDIF}(Tag));
BApply.Enabled:=False;
end;
type TButtonAccess=class(TButton);
procedure TBaseSourceEditor.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
inherited;
if BApply.Enabled then
Case MessageDlg(TeeMsg_SureToApply,mtConfirmation,[mbYes,mbNo,mbCancel],0) of
mrYes: begin
TButtonAccess(BApply).Click;
CanClose:=not BApply.Enabled;
end;
mrNo: begin
BApply.Enabled:=False;
CanClose:=True;
end;
mrCancel: CanClose:=False;
end;
end;
function TBaseSourceEditor.IsValid(AComponent: TComponent): Boolean;
begin
result:=False;
end;
procedure TBaseSourceEditor.CheckReplaceSource(
NewSource: TTeeSeriesSource);
var tmpSource : TTeeSeriesSource;
begin
if TheSeries.DataSource<>NewSource then
begin
{ if the datasource is an internal "Series Source",
remove and free it ! }
if Assigned(TheSeries.DataSource) and
(TheSeries.DataSource is TTeeSeriesSource) and
(TheSeries.DataSource.Owner=TheSeries) then
begin
tmpSource:=TTeeSeriesSource(TheSeries.DataSource);
tmpSource.Series:=nil;
tmpSource.Free;
end;
TheSeries.DataSource:=nil;
if not Assigned(NewSource.Series) then
NewSource.Series:=TheSeries;
TheSeries.DataSource:=NewSource;
end;
end;
procedure TBaseSourceEditor.FormCreate(Sender: TObject);
begin
SkipValidation:=False;
Align:=alClient;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.