text stringlengths 14 6.51M |
|---|
{******************************************************************************
* *
* PROJECT : EOS Digital Software Development Kit EDSDK *
* NAME : appmaster.pas *
* *
* Description: This is the Sample code to show the usage of EDSDK. *
* *
* *
*******************************************************************************
* *
* Written and developed by Camera Design Dept.53 *
* Copyright Canon Inc. 2006 All Rights Reserved *
* *
*******************************************************************************
* File Update Information: *
* DATE Identify Comment *
* ----------------------------------------------------------------------- *
* 06-03-22 F-001 create first version. *
* *
******************************************************************************}
unit appmaster;
interface
uses
Dialogs, SysUtils, Windows, MESSAGES, EDSDKApi, EDSDKType, EDSDKError, camera;
type
TAppMaster = class(TObject)
private
FhWnd : HWND;
FIsSDKLoaded : Bool;
FCamera : TCamera;
FIsConnect : Bool;
FIsLegacy : Bool;
camera : EdsCameraRef;
FSavePath : string;
public
constructor Create( hwnd : HWND );
destructor Destroy ; override;
property filePath : string read FSavePath write FSavePath;
property fLegacy : Bool read FIsLegacy;
procedure getCameraName( var name : string );
function saveSetting : EdsError;
function getCameraObject : TCamera;
function enableConnection : EdsUInt32;
function setEventCallBack : EdsError;
function getProperty( id : EdsPropertyID ) : EdsError;
function getPropertyDesc( id : EdsPropertyID) : EdsError;
function setProperty( id : EdsPropertyID; var value : EdsUInt32 ) : EdsError;
function takePicture : EdsError;
function getImageData(itemRef : EdsDirectoryItemRef; targetPath : string ) : EdsError;
end;
implementation
{==============================================================================}
{ E V E N T H A N D L E R
{==============================================================================}
{ Propery event handler }
function handlePropertyEvent( inEvent : EdsUInt32;
inPropertyID : EdsUInt32;
inParam : EdsUInt32;
inContext : EdsUInt32 ) : EdsError; stdcall;
begin
case inEvent of
kEdsPropertyEvent_PropertyChanged :
begin
case inPropertyID of
kEdsPropID_AEMode,
kEdsPropID_ISOSpeed,
kEdsPropID_Av,
kEdsPropID_Tv:
PostMessage( HWND(inContext), WM_USER+1 , integer(inEvent) , integer(inPropertyID) );
end;
end;
kEdsPropertyEvent_PropertyDescChanged :
begin
case inPropertyID of
kEdsPropID_AEMode,
kEdsPropID_ISOSpeed,
kEdsPropID_Av,
kEdsPropID_Tv:
PostMessage( HWND(inContext) , WM_USER+1 , integer(inEvent) , integer(inPropertyID) );
end;
end;
end;
Result := EDS_ERR_OK;
end;
{ Object event handler }
function handleObjectEvent( inEvent : EdsUInt32;
inRef : EdsBaseRef;
inContext : EdsUInt32 ) : EdsError; stdcall;
begin
case inEvent of
kEdsObjectEvent_DirItemRequestTransfer :
PostMessage( HWND(inContext), WM_USER+2 , integer(inEvent) , integer(inRef) );
end;
Result := EDS_ERR_OK;
end;
{ Progress callback function }
function ProgressFunc( inPercent : EdsUInt32;
inContext : EdsUInt32;
var outCancel : EdsBool ) : EdsError; stdcall;
begin
PostMessage( HWND(inContext) , WM_USER+3 , integer(inPercent) , integer( outCancel ) );
Result := EDS_ERR_OK;
end;
{===============================================================================}
{ TAppMaster class }
constructor TAppMaster.Create( hwnd : HWND );
var err : EdsError;
cameraList : EdsCameraListRef;
count : EdsUInt32;
deviceInfo : EdsDeviceInfo;
begin
FhWnd := hwnd;
FIsConnect := false;
FIsSDKLoaded := false;
cameraList := nil;
count := 0;
camera := nil;
{ load EDSDk and initialize }
err := EdsInitializeSDK;
if err = EDS_ERR_OK then
FIsSDKLoaded := true;
{ get list of camera }
if err = EDS_ERR_OK then
err := EdsGetCameraList( cameraList );
{ get number of camera }
if err = EDS_ERR_OK then begin
err := EdsGetChildCount( cameraList , count );
if count = 0 then begin
ShowMessage( 'Camera is not connected!' );
Exit;
end;
end;
{ get first camera }
if err = EDS_ERR_OK then
EdsGetChildAtIndex( cameraList , 0 , camera );
if camera <> nil then begin
err := EdsGetDeviceInfo( camera , deviceInfo );
if err = EDS_ERR_OK then begin
if deviceInfo.deviceSubType = 0 then
FIsLegacy := true
else
FIsLegacy := false;{ new type camera! }
end;
{ create TCamera class }
FCamera := TCamera.Create( deviceInfo );
end;
{ release camera list object }
if cameraList <> nil then
EdsRelease( cameraList );
end;
destructor TAppMaster.Destroy;
begin
if FIsSDKLoaded = true then begin
{ disconnect camera }
if FIsConnect = true then
EdsCloseSession( camera );
FCamera.Free;
EdsTerminateSDK;
end;
end;
{-------------------------------------------}
{ process of logical connection with camera }
{-------------------------------------------}
function TAppMaster.enableConnection: EdsUInt32;
var err : EdsError;
saveTo : EdsUInt32;
fLock : Bool;
capacity : EdsCapacity;
begin
fLock := false;
FIsConnect := false;
{ Open session with the connected camera }
err := EdsOpenSession( camera );
if err = EDS_ERR_OK then
FIsConnect := true;
if FIsLegacy = true then begin
{Preservation ahead is set to PC}
if err = EDS_ERR_OK then begin
saveTo := EdsUInt32(kEdsSaveTo_Host); { save to Host drive ! }
err := EdsSetPropertyData( camera, kEdsPropID_SaveTo, 0, Sizeof(saveTo), @saveTo );
end;
end else begin
{Preservation ahead is set to PC}
if err = EDS_ERR_OK then begin
saveTo := EdsUInt32(kEdsSaveTo_Host); { save to Host drive ! }
err := EdsSetPropertyData( camera, kEdsPropID_SaveTo, 0, Sizeof(saveTo), @saveTo );
end;
{ UI lock }
if err = EDS_ERR_OK then
err := EdsSendStatusCommand(camera, kEdsCameraState_UILock, 0);
if err = EDS_ERR_OK then
fLock := true;
if err = EDS_ERR_OK then begin
capacity.numberOfFreeClusters := EdsInt32($7FFFFFFF);
capacity.bytesPerSector := EdsInt32($1000);
capacity.reset := EdsInt32(1);
err := EdsSetCapacity( camera, capacity);
end;
{ It releases it when locked }
if fLock = true then
EdsSendStatusCommand(camera, kEdsCameraState_UIUnLock, 0);
end;
Result := err;
end;
{-------------------------------------------}
{ register event callback function to EDSDK }
{-------------------------------------------}
function TAppMaster.SetEventCallBack : EdsError;
var err : EdsError;
begin
err := EDS_ERR_OK;
if camera = nil then begin
Result := err;
Exit;
end;
{ register property event handler & object event handler }
err := EdsSetPropertyEventHandler( camera, kEdsPropertyEvent_All, @handlePropertyEvent, FhWnd );
if err = EDS_ERR_OK then
err := EdsSetObjectEventHandler( camera, kEdsObjectEvent_All, @handleObjectEvent, FhWnd );
Result := err;
end;
{------------------------------------------}
{ get camera model name }
{------------------------------------------}
procedure TAppMaster.getCameraName( var name : string );
begin
if FCamera <> nil then
FCamera.getModelName( name )
else
name := 'Camera is not detected!';
end;
{------------------------------------------}
{ get TCamera object }
{------------------------------------------}
function TAppMaster.getCameraObject: TCamera;
begin
Result := FCamera;
end;
{-------------------------------------}
{ set file saving location at capture }
{-------------------------------------}
function TAppMaster.saveSetting: EdsError;
var err : EdsError;
fLock : Bool;
saveTo : EdsUInt32;
begin
err := EDS_ERR_OK;
fLock := false;
if camera = nil then begin
Result := err;
Exit;
end;
{ For cameras earlier than the 30D, the camera UI must be
locked before commands are issued. }
if fLegacy = true then begin
err := EdsSendStatusCommand( camera, kEdsCameraState_UILock, 0 );
if err = EDS_ERR_OK then
fLock := true;
end;
saveTo := EdsUInt32(kEdsSaveTo_Host); { save to Host drive ! }
if err = EDS_ERR_OK then
err := EdsSetPropertyData( camera, kEdsPropID_SaveTo, 0, Sizeof(saveTo), @saveTo );
if err = EDS_ERR_OK then begin
if fLock = true then
err := EdsSendStatusCommand( camera, kEdsCameraState_UIUnLock, 0 );
end;
Result := err;
end;
{----------------------------------------}
{ get data from camera hardware directly }
{----------------------------------------}
function TAppMaster.getProperty( id: EdsPropertyID ): EdsError;
var err : EdsError;
dataSize : EdsUInt32;
dataType : EdsUInt32;
data : EdsUInt32;
str : array [0..EDS_MAX_NAME-1] of EdsChar;
P : Pointer;
begin
{ if property id is invalid value (kEdsPropID_Unknown),
EDSDK cannot identify the changed property.
So, we must retrieve the required property again. }
if id = kEdsPropID_Unknown then begin
err := getProperty( kEdsPropID_AEMode );
if err = EDS_ERR_OK then err := getProperty(kEdsPropID_Tv);
if err = EDS_ERR_OK then err := getProperty(kEdsPropID_Av);
if err = EDS_ERR_OK then err := getProperty(kEdsPropID_ISOSpeed );
Result := err;
Exit;
end;
err := EdsGetPropertySize( camera, id, 0, dataType, dataSize );
if err <> EDS_ERR_OK then begin
Result := err;
Exit;
end;
if dataType = EdsUInt32(kEdsDataType_UInt32) then begin
P := @data;
err := EdsGetPropertyData( camera, id, 0, dataSize, Pointer(P^) );
{ set property data into TCamera }
if err = EDS_ERR_OK then
FCamera.setPropertyUInt32( id, data );
end;
if dataType = EdsUInt32(kEdsDataType_String) then begin
P := @str;
err := EdsGetPropertyData( camera, id, 0, dataSize, Pointer(P^) );
{ set property string into TCamera }
if err = EDS_ERR_OK then
FCamera.setPropertyString( id, str );
end;
Result := err;
end;
{----------------------------------------}
{ get desc from camera hardware directly }
{----------------------------------------}
function TAppMaster.getPropertyDesc(id: EdsPropertyID ): EdsError;
var err : EdsError;
desc : EdsPropertyDesc;
begin
{ if property id is invalid value (kEdsPropID_Unknown),
EDSDK cannot identify the changed property.
So, we must retrieve the required property again. }
if id = kEdsPropID_Unknown then begin
err := getPropertyDesc( kEdsPropID_AEMode );
if err = EDS_ERR_OK then err := getPropertyDesc(kEdsPropID_Tv);
if err = EDS_ERR_OK then err := getPropertyDesc(kEdsPropID_Av);
if err = EDS_ERR_OK then err := getPropertyDesc(kEdsPropID_ISOSpeed );
Result := err;
Exit;
end;
err := EdsGetPropertyDesc( camera, id, desc );
if err = EDS_ERR_OK then
{ set available list into TCamera object }
FCamera.setPropertyDesc( id, desc );
Result := err;
end;
{-------------------------------- ---------}
{ set property data into hardware directly }
{------------------------------------------}
function TAppMaster.setProperty(id: EdsPropertyID; var value: EdsUInt32): EdsError;
var err : EdsError;
begin
err := EdsSetPropertyData( camera, id, 0, sizeof( value ), @value );
Result := err;
end;
{------------------------------------}
{ Process of handling remote release }
{------------------------------------}
function TAppMaster.takePicture: EdsError;
var err : EdsError;
fLock : Bool;
begin
fLock := false;
err := EDS_ERR_OK;
if camera = nil then begin
Result := err;
Exit;
end;
{ For cameras earlier than the 30D, the camera UI must be
locked before commands are issued. }
if fLegacy = true then begin
err := EdsSendStatusCommand( camera, kEdsCameraState_UILock, 0 );
if err = EDS_ERR_OK then
fLock := true;
end;
if err = EDS_ERR_OK then
err := EdsSendCommand( camera, kEdsCameraCommand_TakePicture, 0 );
if fLock = true then
err := EdsSendStatusCommand( camera, kEdsCameraState_UIUnLock, 0 );
Result := err;
end;
{ ---------------------------------------- }
{ Process of getting captured image }
{ ---------------------------------------- }
function TAppMaster.getImageData( itemRef : EdsDirectoryItemRef; targetPath : string ) : EdsError;
var dirInfo : EdsDirectoryItemInfo;
err : EdsError;
stream : EdsStreamRef;
fileName : string;
begin
{ get information of captured image }
err := EdsGetDirectoryItemInfo( itemRef, dirInfo );
if err <> EDS_ERR_OK then begin
Result := err;
Exit;
end;
fileName := IncludeTrailingPathDelimiter(targetPath) + string(dirInfo.szFileName);
{ create file stream }
stream := nil;
if err = EDS_ERR_OK then
err := EdsCreateFileStream( PChar(fileName), kEdsFileCreateDisposition_CreateAlways,
kEdsAccess_ReadWrite, stream );
{ set progress call back }
if err = EDS_ERR_OK then
err := EdsSetProgressCallback( stream, @ProgressFunc, kEdsProgressOption_Periodically, FhWnd );
{ download image data }
if err = EDS_ERR_OK then
err := EdsDownload( itemRef, dirInfo.size, stream );
{ completed trasnfer }
if err = EDS_ERR_OK then
err := EdsDownloadComplete( itemRef );
{ free resource }
if stream <> nil then
EdsRelease( stream );
EdsRelease( itemRef );
Result := err;
end;
end.
|
// ===============================================================================
// | THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF |
// | ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO |
// | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A |
// | PARTICULAR PURPOSE. |
// | Copyright (c)2010 ADMINSYSTEM SOFTWARE LIMITED |
// |
// | Project: It demonstrates how to use EASendMailObj to send email with synchronous mode
// |
// | Author: Ivan Lui ( ivan@emailarchitect.net )
// ===============================================================================
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, EASendMailObjLib_TLB, StdCtrls, OleCtrls, SHDocVw_TLB, MSHTML_TLB,
SHDocVw;
type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
textFrom: TEdit;
textTo: TEdit;
textCc: TEdit;
textSubject: TEdit;
Label5: TLabel;
GroupBox1: TGroupBox;
Label6: TLabel;
textServer: TEdit;
chkAuth: TCheckBox;
Label7: TLabel;
Label8: TLabel;
textUser: TEdit;
textPassword: TEdit;
chkSSL: TCheckBox;
chkSign: TCheckBox;
chkEncrypt: TCheckBox;
Label9: TLabel;
lstCharset: TComboBox;
Label10: TLabel;
textAttachment: TEdit;
btnAdd: TButton;
btnClear: TButton;
btnSend: TButton;
htmlEditor: TWebBrowser;
lstFont: TComboBox;
lstSize: TComboBox;
btnB: TButton;
btnI: TButton;
btnU: TButton;
btnC: TButton;
btnInsert: TButton;
ColorDialog1: TColorDialog;
textStatus: TLabel;
btnCancel: TButton;
lstProtocol: TComboBox;
procedure FormCreate(Sender: TObject);
procedure InitCharset();
procedure btnSendClick(Sender: TObject);
procedure chkAuthClick(Sender: TObject);
function ChAnsiToWide(const StrA: AnsiString): WideString;
procedure btnAddClick(Sender: TObject);
procedure DirectSend(oSmtp: TMail);
procedure btnClearClick(Sender: TObject);
procedure htmlEditorNavigateComplete2(ASender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
procedure btnInsertClick(Sender: TObject);
procedure InitFonts();
procedure btnBClick(Sender: TObject);
procedure btnIClick(Sender: TObject);
procedure btnUClick(Sender: TObject);
procedure btnCClick(Sender: TObject);
procedure lstFontChange(Sender: TObject);
procedure lstSizeChange(Sender: TObject);
// EASendMail event handler
procedure OnAuthenticated(ASender: TObject);
procedure OnConnected(ASender: TObject);
procedure OnClosed(ASender: TObject);
procedure OnError(ASender: TObject;
lError: Integer; const ErrDescription: WideString );
procedure OnSending(ASender: TObject; lSent: Integer; lTotal: Integer );
procedure btnCancelClick(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
const
CRYPT_MACHINE_KEYSET = 32;
CRYPT_USER_KEYSET = 4096;
CERT_SYSTEM_STORE_CURRENT_USER = 65536;
CERT_SYSTEM_STORE_LOCAL_MACHINE = 131072;
var
Form1: TForm1;
oSmtp: TMail;
m_arAttachments : TStringList;
m_arCharset: array[0..27,0..1] of WideString;
m_bError: Boolean; //this variable indicates if error occurs when sending email
m_bCancel: Boolean;
m_bIdle: Boolean;
m_lastErrDescription: string;
implementation
{$R *.dfm}
procedure TForm1.OnAuthenticated(ASender: TObject);
begin
textStatus.Caption := 'Authenticated';
end;
procedure TForm1.OnConnected(ASender: TObject);
begin
textStatus.Caption := 'Connected';
end;
procedure TForm1.OnClosed(ASender: TObject);
begin
if not m_bError then
textStatus.Caption := 'email was sent successfully';
m_bIdle := true;
end;
procedure TForm1.OnError(ASender: TObject;
lError: Integer; const ErrDescription: WideString );
begin
textStatus.Caption := 'Failed to send email with error: ' + ErrDescription;
m_lastErrDescription := ErrDescription;
m_bError := true;
m_bIdle := true;
end;
procedure TForm1.OnSending(ASender: TObject; lSent: Integer; lTotal: Integer );
begin
textStatus.Caption := Format( 'Sending %d/%d ...', [lSent, lTotal] );
end;
procedure TForm1.InitCharset();
var
i, index: integer;
begin
index := 0;
m_arCharset[index, 0] := 'Arabic(Windows)';
m_arCharset[index, 1] := 'windows-1256';
index := index + 1;
m_arCharset[index, 0] := 'Baltic(ISO)';
m_arCharset[index, 1] := 'iso-8859-4';
index := index + 1;
m_arCharset[index, 0] := 'Baltic(Windows)';
m_arCharset[index, 1] := 'windows-1257';
index := index + 1;
m_arCharset[index, 0] := 'Central Euporean(ISO)';
m_arCharset[index, 1] := 'iso-8859-2';
index := index + 1;
m_arCharset[index, 0] := 'Central Euporean(Windows)';
m_arCharset[index, 1] := 'windows-1250';
index := index + 1;
m_arCharset[index, 0] := 'Chinese Simplified(GB18030)';
m_arCharset[index, 1] := 'GB18030';
index := index + 1;
m_arCharset[index, 0] := 'Chinese Simplified(GB2312)';
m_arCharset[index, 1] := 'gb2312';
index := index + 1;
m_arCharset[index, 0] := 'Chinese Simplified(HZ)';
m_arCharset[index, 1] := 'hz-gb-2312';
index := index + 1;
m_arCharset[index, 0] := 'Chinese Traditional(Big5)';
m_arCharset[index, 1] := 'big5';
index := index + 1;
m_arCharset[index, 0] := 'Cyrillic(ISO)';
m_arCharset[index, 1] := 'iso-8859-5';
index := index + 1;
m_arCharset[index, 0] := 'Cyrillic(KOI8-R)';
m_arCharset[index, 1] := 'koi8-r';
index := index + 1;
m_arCharset[index, 0] := 'Cyrillic(KOI8-U)';
m_arCharset[index, 1] := 'koi8-u';
index := index + 1;
m_arCharset[index, 0] := 'Cyrillic(Windows)';
m_arCharset[index, 1] := 'windows-1251';
index := index + 1;
m_arCharset[index, 0] := 'Greek(ISO)';
m_arCharset[index, 1] := 'iso-8859-7';
index := index + 1;
m_arCharset[index, 0] := 'Greek(Windows)';
m_arCharset[index, 1] := 'windows-1253';
index := index + 1;
m_arCharset[index, 0] := 'Hebrew(Windows)';
m_arCharset[index, 1] := 'windows-1255';
index := index + 1;
m_arCharset[index, 0] := 'Japanese(JIS)';
m_arCharset[index, 1] := 'iso-2022-jp';
index := index + 1;
m_arCharset[index, 0] := 'Korean';
m_arCharset[index, 1] := 'ks_c_5601-1987';
index := index + 1;
m_arCharset[index, 0] := 'Korean(EUC)';
m_arCharset[index, 1] := 'euc-kr';
index := index + 1;
m_arCharset[index, 0] := 'Latin 9(ISO)';
m_arCharset[index, 1] := 'iso-8859-15';
index := index + 1;
m_arCharset[index, 0] := 'Thai(Windows)';
m_arCharset[index, 1] := 'windows-874';
index := index + 1;
m_arCharset[index, 0] := 'Turkish(ISO)';
m_arCharset[index, 1] := 'iso-8859-9';
index := index + 1;
m_arCharset[index, 0] := 'Turkish(Windows)';
m_arCharset[index, 1] := 'windows-1254';
index := index + 1;
m_arCharset[index, 0] := 'Unicode(UTF-7)';
m_arCharset[index, 1] := 'utf-7';
index := index + 1;
m_arCharset[index, 0] := 'Unicode(UTF-8)';
m_arCharset[index, 1] := 'utf-8';
index := index + 1;
m_arCharset[index, 0] := 'Vietnames(Windows)';
m_arCharset[index, 1] := 'windows-1258';
index := index + 1;
m_arCharset[index, 0] := 'Western European(ISO)';
m_arCharset[index, 1] := 'iso-8859-1';
index := index + 1;
m_arCharset[index, 0] := 'Western European(Windows)';
m_arCharset[index, 1] := 'windows-1252';
for i:= 0 to 27 do
begin
lstCharset.AddItem(m_arCharset[i,0], nil);
end;
// Set default encoding to utf-8, it supports all languages.
lstCharset.ItemIndex := 24;
lstProtocol.AddItem('SMTP Protocol - Recommended', nil);
lstProtocol.AddItem('Exchange Web Service - 2007/2010', nil);
lstProtocol.AddItem('Exchange WebDav - 2000/2003', nil);
lstProtocol.ItemIndex := 0;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
htmlDoc: HTMLDocument;
begin
oSmtp := TMail.Create(Application);
oSmtp.LicenseCode := 'TryIt';
// Set Asynchronous mode
oSmtp.Asynchronous := 1;
// Add event handler
oSmtp.OnConnected := OnConnected;
oSmtp.OnClosed := OnClosed;
oSmtp.OnError := OnError;
oSmtp.OnSending := OnSending;
oSmtp.OnAuthenticated := OnAuthenticated;
textSubject.Text := 'delphi html email test';
htmlEditor.Navigate('about:blank');
htmlDoc := htmlEditor.Document as HTMLDocument;
htmlDoc.designMode := 'on';
m_arAttachments := TStringList.Create();
InitCharset();
InitFonts();
end;
procedure TForm1.btnSendClick(Sender: TObject);
var
i: integer;
Rcpts: OleVariant;
RcptBound: integer;
RcptAddr: WideString;
oEncryptCert: TCertificate;
htmlDoc: HTMLDocument;
body: HTMLHtmlElement;
html: WideString;
begin
if trim(textFrom.Text) = '' then
begin
ShowMessage( 'Plese input From email address!' );
textFrom.SetFocus();
exit;
end;
if(trim(textTo.Text) = '' ) and
(trim(textCc.Text) = '' ) then
begin
ShowMessage( 'Please input To or Cc email addresses, please use comma(,) to separate multiple addresses!');
textTo.SetFocus();
exit;
end;
if chkAuth.Checked and ((trim(textUser.Text)='') or
(trim(textPassword.Text)='')) then
begin
ShowMessage( 'Please input User, Password for SMTP authentication!' );
textUser.SetFocus();
exit;
end;
btnSend.Enabled := False;
btnCancel.Enabled := True;
// because m_oSmtp is a member variahle, so we need to clear the the property
oSmtp.Reset();
oSmtp.Asynchronous := 1;
oSmtp.ServerAddr := '';
oSmtp.ServerPort := 25;
oSmtp.SSL_uninit();
oSmtp.UserName := '';
oSmtp.Password := '';
oSmtp.Charset := m_arCharset[lstCharset.ItemIndex, 1];
oSmtp.FromAddr := ChAnsiToWide(trim(textFrom.Text));
// Add recipient's
oSmtp.ClearRecipient();
oSmtp.AddRecipientEx(ChAnsiToWide(trim(textTo.Text)), 0 );
oSmtp.AddRecipientEx(ChAnsiToWide(trim(textCc.Text)), 0 );
// Set subject
oSmtp.Subject := ChAnsiToWide(textSubject.Text);
// Using HTML FORMAT to send mail
oSmtp.BodyFormat := 1;
// import html body with embedded images
html := GetCurrentDir();
htmlDoc := htmlEditor.document as HTMLDocument;
body := htmlDoc.body as HTMLHtmlElement;
html := body.innerHTML;
oSmtp.ImportHtml( html, GetCurrentDir());
// Add attachments
for i:= 0 to m_arAttachments.Count - 1 do
begin
oSmtp.AddAttachment(ChAnsiToWide(m_arAttachments[i]));
end;
// Add digital signature
oSmtp.SignerCert.Unload();
if chkSign.Checked then
begin
if not oSmtp.SignerCert.FindSubject( oSmtp.FromAddr,
CERT_SYSTEM_STORE_CURRENT_USER, 'my' ) then
begin
ShowMessage( 'Not cert found for signing: ' + oSmtp.SignerCert.GetLastError());
btnSend.Enabled := true;
btnCancel.Enabled := false;
exit;
end;
if not oSmtp.SignerCert.HasCertificate Then
begin
ShowMessage( 'Signer certificate has no private key, ' +
'this certificate can not be used to sign email');
btnSend.Enabled := true;
btnCancel.Enabled := false;
exit;
end;
end;
// get all to, cc, bcc email address to an array
Rcpts := oSmtp.Recipients;
RcptBound := VarArrayHighBound( Rcpts, 1 );
// search encrypting cert for every recipient.
oSmtp.RecipientsCerts.Clear();
if chkEncrypt.Checked then
for i := 0 to RcptBound do
begin
RcptAddr := VarArrayGet( Rcpts, i );
oEncryptCert := TCertificate.Create(Application);
if not oEncryptCert.FindSubject(RcptAddr,
CERT_SYSTEM_STORE_CURRENT_USER, 'AddressBook' ) then
if not oEncryptCert.FindSubject(RcptAddr,
CERT_SYSTEM_STORE_CURRENT_USER, 'my' ) then
begin
ShowMessage( 'Failed to find cert for ' + RcptAddr + ': ' + oEncryptCert.GetLastError());
btnSend.Enabled := true;
btnCancel.Enabled := false;
exit;
end;
oSmtp.RecipientsCerts.Add(oEncryptCert.DefaultInterface);
end;
oSmtp.ServerAddr := trim(textServer.Text);
oSmtp.Protocol := lstProtocol.ItemIndex;
if oSmtp.ServerAddr <> '' then
begin
if chkAuth.Checked then
begin
oSmtp.UserName := trim(textUser.Text);
oSmtp.Password := trim(textPassword.Text);
end;
if chkSSL.Checked then
begin
oSmtp.SSL_init();
// If SSL port is 465, please add the following codes
// oSmtp.ServerPort := 465;
// oSmtp.SSL_starttls := 0;
end;
end;
if (RcptBound > 0) and (oSmtp.ServerAddr = '') then
begin
// To send email without specified smtp server, we have to send the emails one by one
// to multiple recipients. That is because every recipient has different smtp server.
DirectSend( oSmtp );
btnSend.Enabled := true;
btnCancel.Enabled := false;
textStatus.Caption := '';
htmlEditor.SetFocus();
exit;
end;
btnSend.Enabled := false;
textStatus.Caption := 'start to send email ...';
m_bIdle := False;
m_bCancel := False;
m_bError := False;
oSmtp.SendMail();
while not m_bIdle do
Application.ProcessMessages();
if m_bCancel then
textStatus.Caption := 'Operation is canceled by user.'
else if m_bError then
textStatus.Caption := m_lastErrDescription
else
textStatus.Caption := 'Message was delivered successfully';
ShowMessage( textStatus.Caption );
btnSend.Enabled := True;
btnCancel.Enabled := False;
htmlEditor.SetFocus();
end;
procedure TForm1.DirectSend(oSmtp: TMail);
var
Rcpts: OleVariant;
i, RcptBound: integer;
RcptAddr: WideString;
begin
Rcpts := oSmtp.Recipients;
RcptBound := VarArrayHighBound( Rcpts, 1 );
for i := 0 to RcptBound do
begin
RcptAddr := VarArrayGet( Rcpts, i );
oSmtp.ClearRecipient();
oSmtp.AddRecipientEx( RcptAddr, 0 );
textStatus.Caption := 'Connecting server for ' + RcptAddr + '...';
m_bIdle := False;
m_bCancel := False;
m_bError := False;
oSmtp.SendMail();
// wait the asynchronous call finish.
while not m_bIdle do
Application.ProcessMessages();
if m_bCancel then
textStatus.Caption := 'Operation is canceled by user.'
else if m_bError then
textStatus.Caption := 'Failed to delivery to ' + RcptAddr +':' + m_lastErrDescription
else
textStatus.Caption := 'Message was delivered to " + RcptAddr + " successfully';
ShowMessage( textStatus.Caption );
if m_bCancel then
break;
end;
end;
procedure TForm1.chkAuthClick(Sender: TObject);
begin
textUser.Enabled := chkAuth.Checked;
textPassword.Enabled := chkAuth.Checked;
if( chkAuth.Checked ) then
begin
textUser.Color := clWindow;
textPassword.Color := clWindow;
end
else
begin
textUser.Color := cl3DLight;
textPassword.Color := cl3DLight;
end;
end;
// before delphi doesn't support unicode very well in VCL, so
// we have to convert the ansistring to unicode by current default codepage.
function TForm1.ChAnsiToWide(const StrA: AnsiString): WideString;
var
nLen: integer;
begin
Result := StrA;
if Result <> '' then
begin
// convert ansi string to widestring (unicode) by current system codepage
nLen := MultiByteToWideChar(GetACP(), 1, PAnsiChar(@StrA[1]), -1, nil, 0);
SetLength(Result, nLen - 1);
if nLen > 1 then
MultiByteToWideChar(GetACP(), 1, PAnsiChar(@StrA[1]), -1, PWideChar(@Result[1]), nLen - 1);
end;
end;
procedure TForm1.btnAddClick(Sender: TObject);
var
pFileDlg : TOpenDialog;
fileName : string;
index: integer;
begin
pFileDlg := TOpenDialog.Create(Form1);
if pFileDlg.Execute() then
begin
fileName := pFileDlg.FileName;
m_arAttachments.Add( fileName );
while true do
begin
index := Pos( '\', fileName );
if index <= 0 then
break;
fileName := Copy( fileName, index+1, Length(fileName)- index );
end;
textAttachment.Text := textAttachment.Text + fileName + ';';
end;
pFileDlg.Destroy();
htmlEditor.SetFocus();
end;
procedure TForm1.btnClearClick(Sender: TObject);
begin
m_arAttachments.Clear();
textAttachment.Text := '';
htmlEditor.SetFocus();
end;
procedure TForm1.htmlEditorNavigateComplete2(ASender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
var
s: WideString;
htmlDoc: HTMLDocument;
body: HTMLHtmlElement;
begin
s := '<div>This sample demonstrates how to send html email.</div><div> </div>'
+ '<div>If no sever address was specified, the email will be delivered to the recipient''s server directly,'
+ 'However, if you don''t have a static IP address, '
+ 'many anti-spam filters will mark it as a junk-email.</div><div> </div>';
htmlDoc := htmlEditor.Document as HTMLDocument;
body := htmlDoc.body as HTMLHtmlElement;
body.innerHTML := s;
end;
procedure TForm1.btnInsertClick(Sender: TObject);
var
htmlDoc: HTMLDocument;
parameter: OleVariant;
begin
htmlEditor.SetFocus();
htmlDoc := htmlEditor.document as HTMLDocument;
htmlDoc.execCommand('InsertImage', true, parameter );
htmlEditor.SetFocus();
end;
procedure TForm1.InitFonts();
var
arFont: array[0..11] of string;
i: integer;
begin
i := 0;
arFont[i] := 'Choose Font Style ...';
i := i+1;
arFont[i] := 'Arial';
i := i+1;
arFont[i] := 'Arial Baltic';
i := i+1;
arFont[i] := 'Arial Black';
i := i+1;
arFont[i] := 'Basemic Symbol';
i := i+1;
arFont[i] := 'Bookman Old Style';
i := i+1;
arFont[i] := 'Comic Sans MS';
i := i+1;
arFont[i] := 'Courier';
i := i+1;
arFont[i] := 'Courier New';
i := i+1;
arFont[i] := 'Microsoft Sans Serif';
i := i+1;
arFont[i] := 'Times New Roman';
i := i+1;
arFont[i] := 'Verdana';
i := i+1;
for i:= 0 to 11 do
lstFont.AddItem(arFont[i], nil);
lstFont.ItemIndex := 0;
lstSize.AddItem('Font Size ...', nil );
for i:= 1 to 7 do
lstSize.AddItem(IntToStr(i), nil);
lstSize.ItemIndex := 0;
end;
procedure TForm1.btnBClick(Sender: TObject);
var
htmlDoc: HTMLDocument;
parameter: OleVariant;
begin
htmlEditor.SetFocus();
htmlDoc := htmlEditor.document as HTMLDocument;
htmlDoc.execCommand('Bold', false, parameter);
htmlEditor.SetFocus();
end;
procedure TForm1.btnIClick(Sender: TObject);
var
htmlDoc: HTMLDocument;
parameter: OleVariant;
begin
htmlEditor.SetFocus();
htmlDoc := htmlEditor.document as HTMLDocument;
htmlDoc.execCommand('Italic', false, parameter);
htmlEditor.SetFocus();
end;
procedure TForm1.btnUClick(Sender: TObject);
var
htmlDoc: HTMLDocument;
parameter: OleVariant;
begin
htmlEditor.SetFocus();
htmlDoc := htmlEditor.document as HTMLDocument;
htmlDoc.execCommand('underline', false, parameter);
htmlEditor.SetFocus();
end;
procedure TForm1.btnCClick(Sender: TObject);
var
htmlDoc: HTMLDocument;
parameter: OleVariant;
myColor: TColor;
hexColor: string;
begin
htmlEditor.SetFocus();
if not ColorDialog1.Execute() then
exit;
myColor := ColorDialog1.Color;
hexColor := '#'+ IntToHex(GetRValue(myColor), 2) +
IntToHex(GetGValue(myColor), 2) +
IntToHex(GetBValue(myColor), 2) ;
parameter := hexColor;
htmlDoc := htmlEditor.document as HTMLDocument;
htmlDoc.execCommand('ForeColor', true, parameter);
htmlEditor.SetFocus();
end;
procedure TForm1.lstFontChange(Sender: TObject);
var
htmlDoc: HTMLDocument;
parameter: OleVariant;
begin
htmlEditor.SetFocus();
if lstFont.ItemIndex = 0 then
exit;
parameter := lstFont.Text;
lstFont.ItemIndex := 0;
htmlDoc := htmlEditor.document as HTMLDocument;
htmlDoc.execCommand('fontname', false, parameter );
htmlEditor.SetFocus();
end;
procedure TForm1.lstSizeChange(Sender: TObject);
var
htmlDoc: HTMLDocument;
parameter: OleVariant;
begin
htmlEditor.SetFocus();
if lstSize.ItemIndex = 0 then
exit;
parameter := lstSize.Text;
lstSize.ItemIndex := 0;
htmlDoc := htmlEditor.document as HTMLDocument;
htmlDoc.execCommand('fontsize', false, parameter );
htmlEditor.SetFocus();
end;
procedure TForm1.btnCancelClick(Sender: TObject);
begin
oSmtp.Terminate();
m_bCancel := True;
m_bIdle := True;
btnCancel.Enabled := False;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
if Form1.Width < 670 then
Form1.Width := 670;
if Form1.Height < 452 then
Form1.Height := 452;
htmlEditor.Width := Form1.Width - 30;
htmlEditor.Height := Form1.Height - 330;
btnSend.Top := htmlEditor.Top + htmlEditor.Height + 5;
btnSend.Left := Form1.Width - 30 - btnSend.Width - btnCancel.Width;
btnCancel.Top := btnSend.Top;
btnCancel.Left := btnSend.Left + btnSend.Width + 10;
textStatus.Top := btnSend.Top;
GroupBox1.Left := Form1.Width - GroupBox1.Width - 20;
textFrom.Width := Form1.Width - GroupBox1.Width - 110;
textSubject.Width := textFrom.Width;
textTo.Width := textFrom.Width;
textCc.Width := textFrom.Width;
end;
end.
|
unit ncDMProdClient;
interface
uses
SysUtils, Classes, nxdb, nxsrSqlEngineBase, nxsqlEngine,
nxllComponent, nxsdServerEngine, nxsrServerEngine, ncChecarServidor,
ncProdD, ncProdU, ncClassesBase;
type
TdmProdClient = class(TDataModule)
nxServerEngineDnld: TnxServerEngine;
nxSqlEngineDnld: TnxSqlEngine;
nxSessionDnld: TnxSession;
nxDatabaseDnld: TnxDatabase;
nxSqlEngineUpld: TnxSqlEngine;
nxServerEngineUpld: TnxServerEngine;
nxSessionUpld: TnxSession;
nxDatabaseUpld: TnxDatabase;
procedure DataModuleCreate(Sender: TObject);
private
fProgPath : string;
fdbPath : string;
fdbDownloadPath : string;
fdbUploadPath : string;
fUpdateSrvThread : TChecarServidorThread;
fSenha: String;
fEmailConta: String;
fCodEquip: String;
procedure IniciaDB;
{ Private declarations }
public
nexDB : TnxDatabase;
nexSession : TnxSession;
property EmailConta : String write fEmailConta;
property CodEquip : String write fCodEquip;
property Senha : String write fSenha;
class procedure Iniciar(aCodEquip, aEmailConta, aSenha: String);
class procedure Finalizar;
function StartUpdateSrvThread:boolean;
procedure StopUpdateSrvThread;
destructor Destroy; override;
{ Public declarations }
end;
procedure PackTable(nxTable: TnxTable; const aProgressCallback:TnxcgProgressCallback=nil);
procedure ReindexTable(nxTable: TnxTable; const aProgressCallback:TnxcgProgressCallback=nil);
procedure PackAndReindexTable(nxTable: TnxTable; const aProgressCallback:TnxcgProgressCallback=nil);
var
dmProdClient: TdmProdClient;
implementation
{$R *.dfm}
uses
nxllException, nxsdTypes, nxsdDataDictionary, uVersionInfo,
uLogs, ncServBD, uUtils;
function RCharPos(aChar: char; S: string): Integer;
var
i : integer;
begin
result := 0;
for i:=length(S) downto 1 do
if upcase(aChar)=upcase(s[i]) then begin
result := i;
break;
end;
end;
procedure PackTable(nxTable: TnxTable; const aProgressCallback:TnxcgProgressCallback=nil);
var
Dict : TnxDataDictionary;
ai : TnxAbstractTaskInfo;
st : TnxTaskStatus;
comp : boolean;
cancelTask : Boolean;
begin
Dict := TnxDataDictionary.create;
try
nxCheck(nxTable.Database.GetDataDictionaryEx(nxTable.tablename, '', Dict));
GLog.Log(nil,[lcTrace],'packing tabela '+nxTable.tablename);
ai := nxTable.PackTable;
repeat
ai.GetStatus(comp, st);
if Assigned(aProgressCallback) then
aProgressCallback(nxTable.tablename, st, cancelTask);
if comp then
break;
if cancelTask then
nxCheck(ai.Cancel);
sleep(100);
until comp;
GLog.Log(nil,[lcTrace],'tabela '+nxTable.tablename+' packed');
finally
Dict.free;
end;
end;
procedure ReindexTable(nxTable: TnxTable; const aProgressCallback:TnxcgProgressCallback=nil);
var
Dict : TnxDataDictionary;
i : integer;
ai : TnxAbstractTaskInfo;
st : TnxTaskStatus;
comp : boolean;
cancelTask : Boolean;
begin
Dict := TnxDataDictionary.create;
try
nxCheck(nxTable.Database.GetDataDictionaryEx(nxTable.tablename, '', Dict));
GLog.Log(nil,[lcTrace],'reindexando tabela '+nxTable.tablename);
for i:=0 to Dict.IndicesDescriptor.IndexCount-1 do begin
ai := nxTable.ReIndexTable(i);
repeat
ai.GetStatus(comp, st);
if Assigned(aProgressCallback) then
aProgressCallback(nxTable.tablename, st, cancelTask);
if comp then
break;
if cancelTask then
nxCheck(ai.Cancel);
sleep(100);
until comp;
end;
GLog.Log(nil,[lcTrace],'tabela '+nxTable.tablename+' reindexada');
finally
Dict.free;
end;
end;
procedure PackAndReindexTable(nxTable: TnxTable;const aProgressCallback:TnxcgProgressCallback=nil);
begin
PackTable(nxTable, aProgressCallback);
ReindexTable(nxTable, aProgressCallback);
end;
// -----------------------------------------------------------------------------
procedure TdmProdClient.DataModuleCreate(Sender: TObject);
begin
fUpdateSrvThread := nil;
fProgPath := ExtractFilePath(ParamStr(0));
fdbPath := fProgPath+'dados\';
fdbDownloadPath := fProgPath+'dadosDownload\';
fdbUploadPath := fProgPath+'dadosUpload\';
CleanUpAndDeleteDirectory(fdbDownloadPath, nil, nil);
CleanUpAndDeleteDirectory(fdbUploadPath, nil, nil);
fdbDownloadPath := fdbPath+'temp1\';
fdbUploadPath := fdbPath+'temp2\';
forcedirectories(fdbDownloadPath);
forcedirectories(fdbUploadPath);
nxServerEngineDnld.Options := [seoForceFailSafe, seoCloseInactiveFolders, seoCloseInactiveTables];
end;
destructor TdmProdClient.Destroy;
begin
if fUpdateSrvThread<>nil then begin
StopUpdateSrvThread;
fUpdateSrvThread.Free;
end;
inherited;
end;
class procedure TdmProdClient.Finalizar;
begin
if dmProdClient<>nil then begin
dmProdClient.StopUpdateSrvThread;
FreeAndNil(dmProdClient);
end;
end;
procedure TdmProdClient.IniciaDB;
begin
nexSession := nil;
nexDB := CreateDB(nexSession, Self);
nxDatabaseDnld.AliasPath := fdbDownloadPath;
nxDatabaseDnld.open;
nxDatabaseUpld.AliasPath := fdbUploadPath;
nxDatabaseUpld.open;
ncProdD.BuildDatabase(nxDatabaseDnld);
//movido pra a thread de ncChecarServidor
//ncProdU.BuildAndEvolveProduComIndices(nxDatabaseUpld);
end;
class procedure TdmProdClient.Iniciar(aCodEquip, aEmailConta, aSenha: String);
begin
Finalizar;
dmProdClient := TdmProdClient.Create(nil);
dmProdClient.CodEquip := aCodEquip;
dmProdClient.EmailConta := aEmailConta;
dmProdClient.Senha := aSenha;
dmProdClient.StartUpdateSrvThread;
end;
function TdmProdClient.StartUpdateSrvThread:boolean;
begin
result := false;
if dmProdClient<>nil then
with dmProdClient do
try
IniciaDB;
if GConfig.AutoCad then begin
fUpdateSrvThread := TChecarServidorThread.create(fProgPath, fdbPath, fdbDownloadPath, fdbUploadPath,
nil, nxServerEngineDnld, nxServerEngineUpld, fCodEquip, fEmailConta, fSenha);
//fUpdateSrvThread.OnMsg := Log;
fUpdateSrvThread.Resume;
result := true;
end;
except
FreeAndNil(dmProdClient);
Raise;
end;
end;
procedure TdmProdClient.StopUpdateSrvThread;
begin
if (dmProdClient<>nil) and (fUpdateSrvThread<>nil) then begin
fUpdateSrvThread.Terminate;
fUpdateSrvThread.WaitFor;
end;
end;
initialization
dmProdClient := nil;
end.
|
unit DyImage;
{$R-}
interface
uses Windows, TypInfo, SysUtils, Messages, Classes, Controls, Forms, ExtDlgs,
Graphics, Menus, StdCtrls, ExtCtrls, Mask, Buttons, ComCtrls, Clipbrd,
DyUtils;
type
TDyPictureStyle = (psZoomed,psAutoSize,psAutoFit,psTile);
TDyWallpaper = class(TGraphicControl)
private
FLock,FDrawing:boolean;
FPicture:TPicture;
FPictureTransparent:boolean;
procedure SetPicture(Value:TPicture);
procedure PictureChanged(Sender:TObject);
procedure SetPictureTransparent(Value:boolean);
function DoPaletteChange: Boolean;
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Picture:TPicture read FPicture write SetPicture;
property PictureTransparent:boolean read FPictureTransparent write SetPictureTransparent default false;
end;
TDyImage = class(TScrollingWinControl)
private
FCanvas:TCanvas;
FPicture:TPicture;
FPictureStyle:TDyPictureStyle;
FPictureZoom:Double;
FPictureTransparent:boolean;
FIncrementalDisplay: Boolean;
FOnProgress: TProgressEvent;
FReadOnly:boolean;
FOnChange:TNotifyEvent;
FLock,FDrawing:boolean;
procedure SetPicture(Value:TPicture);
procedure SetPictureStyle(Value:TDyPictureStyle);
procedure SetPictureZoom(Value:Double);
procedure SetPictureTransparent(Value:boolean);
procedure PictureChanged(Sender:TObject);
procedure DoChange;
{function DoStoreImage:boolean;}
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
procedure WMEraseBkgnd(var Message:TWMEraseBkgnd); message WM_ERASEBKGND;
procedure WMNCHitTest(var Message: TMessage); message WM_NCHITTEST;
procedure WMSize(var Message: TMessage); message WM_SIZE;
procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMCut(var Message: TMessage); message WM_CUT;
procedure WMCopy(var Message: TMessage); message WM_COPY;
procedure WMPaste(var Message: TMessage); message WM_PASTE;
procedure PopupClick(Sender:TObject);
protected
procedure Notification(AComponent:TComponent; Operation:TOperation); override;
procedure PaintWindow(DC: HDC); override;
function DoPaletteChange: Boolean;
function GetPalette: HPALETTE; override;
procedure Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: string); dynamic;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
function GetPopupMenu: TPopupMenu; override;
public
constructor Create(AOwner: TComponent); override;
procedure CreateParams(var Params: TCreateParams); override;
destructor Destroy; override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure CopyToClipboard;
procedure CutToClipboard;
procedure PasteFromClipboard;
procedure LoadFromFile(FileName:string);
procedure SaveToFile(FileName:string);
procedure Clear;
function PictureIsEmpty:boolean;
property Canvas:TCanvas read FCanvas;
published
property ReadOnly:boolean read FReadOnly write FReadOnly;
property IncrementalDisplay: Boolean read FIncrementalDisplay write FIncrementalDisplay default false;
property Picture:TPicture read FPicture write SetPicture {stored DoStoreImage};
property PictureStyle:TDyPictureStyle read FPictureStyle write SetPictureStyle;
property PictureZoom:Double read FPictureZoom write SetPictureZoom;
property PictureTransparent:boolean read FPictureTransparent write SetPictureTransparent default false;
property OnChange:TNotifyEvent read FOnChange write FOnChange;
property AutoScroll;
property Align;
property DragCursor;
property DragMode;
property Enabled;
property Color;
property Ctl3D;
property Font;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
end;
implementation
var
ImagePopup:TPopupMenu;
type
TDrawGraphicOptions=set of (dgoAutoFit,dgoProportion,dgoTile,dgoTransparent,dgoFillBkgrnd,dgoGradientFill,dgoBufferedDisplay);
procedure DrawGraphic(Canvas:TCanvas; G:TGraphic; R:TRect; Ofs:TPoint; var Zoom:double; C1,C2:TColor; Options:TDrawGraphicOptions);
var
Rct:TRect;
P:TPoint;
X,Y,W,H,X0:integer;
DC:THandle;
begin
Rct:=R;
if (G<>nil) and not G.Empty then
if dgoTile in Options then
Zoom:=1
else if dgoAutoFit in Options then
Zoom:=AutoFitRect(Rct,Rect(0,0,G.Width,G.Height),R)
else begin
if Zoom=0 then begin
Zoom:=(Rct.Right-Rct.Left)/G.Width;
if dgoProportion in Options then
Rct.Bottom:=Rct.Top+G.Height*trunc(Zoom);
end else begin
Rct.Right:=Rct.Left+trunc(G.Width*Zoom);
Rct.Bottom:=Rct.Top+trunc(G.Height*Zoom);
end;
OffsetRect(Rct,Ofs.X,Ofs.Y);
end
else Zoom:=0;
if (dgoFillBkgrnd in Options) then begin
DC:=SaveDC(Canvas.Handle);
if not (dgoTransparent in Options) and (G<>nil) and not G.Empty then
ExcludeClipRect(Canvas.Handle,Rct.Left,Rct.Top,Rct.Right,Rct.Bottom);
with Canvas.Brush do begin
Color:=C1;
Style:=bsSolid;
end;
Canvas.FillRect(R);
RestoreDC(Canvas.Handle,DC);
end;
if (G=nil) or G.Empty then Exit;
if dgoTile in Options then begin
W:=G.Width;
H:=G.Height;
P.X:=(R.Left-Ofs.X) mod W;
P.Y:=(R.Top-Ofs.Y) mod H;
X0:=R.Left-P.X;
Y:=R.Top-P.Y;
while Y<R.Bottom do begin
X:=X0;
while X<R.Right do begin
Canvas.Draw(X,Y,G);
X:=X+W;
end;
Y:=Y+H;
end;
end else begin
Canvas.StretchDraw(Rct,G);
end;
end;
{==================TDyWallpaper===============}
constructor TDyWallpaper.Create(AOwner:TComponent);
begin
inherited;
FPicture:=TPicture.Create;
FPicture.OnChange:=PictureChanged;
end;
destructor TDyWallpaper.Destroy;
begin
FPicture.Free;
inherited;
end;
procedure TDyWallpaper.SetPicture(Value:TPicture);
begin
FPicture.Assign(Value);
end;
procedure TDyWallpaper.SetPictureTransparent(Value:boolean);
begin
if FPictureTransparent=Value then Exit;
FPictureTransparent:=Value;
PictureChanged(self);
end;
function TDyWallpaper.DoPaletteChange: Boolean;
var
ParentForm: TCustomForm;
Tmp: TGraphic;
begin
Result := False;
Tmp := Picture.Graphic;
if Visible and (not (csLoading in ComponentState)) and (Tmp <> nil) and
(Tmp.PaletteModified) then
begin
if (Tmp.Palette = 0) then
Tmp.PaletteModified := False
else
begin
ParentForm := GetParentForm(Self);
if Assigned(ParentForm) and ParentForm.Active and Parentform.HandleAllocated then
begin
if FDrawing then
ParentForm.Perform(wm_QueryNewPalette, 0, 0)
else
PostMessage(ParentForm.Handle, wm_QueryNewPalette, 0, 0);
Result := True;
Tmp.PaletteModified := False;
end;
end;
end;
end;
procedure TDyWallpaper.PictureChanged(Sender:TObject);
begin
if FLock then Exit;
try
FLock:=true;
with FPicture do if (Graphic<>nil) and not Graphic.Empty then begin;
if Sender=Picture
then FPictureTransparent:=Graphic.Transparent
else Graphic.Transparent:=FPictureTransparent;
if DoPaletteChange and FDrawing then Update;
end;
if not FDrawing then Invalidate;
finally
FLock:=false;
end;
end;
procedure TDyWallpaper.Paint;
var
Optn:TDrawGraphicOptions;
B:boolean;
Zoom:Double;
begin
Canvas.Lock;
B:=FDrawing;
FDrawing:=true;
try
Optn:=[dgoTile,dgoFillBkgrnd];
if FPictureTransparent then Include(Optn,dgoTransparent);
DrawGraphic(Canvas,Picture.Graphic,ClientRect,Point(0,0),Zoom,Color,Color,Optn);
finally
FDrawing:=B;
Canvas.Unlock;
end;
end;
{=================TDyImage===================}
constructor TDyImage.Create(AOwner: TComponent);
begin
FLock:=false;
FDrawing:=false;
FReadOnly:=true;
inherited Create(AOwner);
ControlStyle := ControlStyle + [csAcceptsControls,csReplicatable,csOpaque];
FCanvas:=TControlCanvas.Create;
TControlCanvas(FCanvas).Control:=Self;
FPicture:=TPicture.Create;
FPicture.OnChange:=PictureChanged;
FPicture.OnProgress:=Progress;
VertScrollBar.Tracking:=true;
HorzScrollBar.Tracking:=true;
end;
procedure TDyImage.CreateParams(var Params: TCreateParams);
begin
inherited;
{with Params.WindowClass do
Style:=Style and not (CS_HREDRAW or CS_VREDRAW);}
end;
destructor TDyImage.Destroy;
begin
FPicture.Free;
FCanvas.Free;
inherited;
end;
procedure TDyImage.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
end;
procedure TDyImage.DoChange;
begin
if Assigned(FOnChange) then FOnChange(self);
end;
procedure TDyImage.WMNCHitTest(var Message: TMessage);
begin
DefaultHandler(Message);
end;
procedure TDyImage.WMEraseBkgnd(var Message:TWMEraseBkgnd);
begin
Message.Result:=1;
end;
procedure TDyImage.WMPaint(var Message: TWMPaint);
begin
PaintHandler(Message);
end;
procedure TDyImage.PaintWindow(DC: HDC);
var
Optn:TDrawGraphicOptions;
B:boolean;
begin
Canvas.Lock;
B:=FDrawing;
FDrawing:=true;
try
FCanvas.Handle := DC;
case FPictureStyle of
psZoomed : Optn:=[dgoFillBkgrnd];
psAutoSize : Optn:=[dgoFillBkgrnd,dgoProportion];
psAutoFit : Optn:=[dgoAutoFit,dgoFillBkgrnd];
psTile : Optn:=[dgoTile,dgoFillBkgrnd];
end;
if FPictureTransparent then Include(Optn,dgoTransparent);
DrawGraphic(FCanvas,Picture.Graphic,ClientRect,Point(-HorzScrollBar.Position,-VertScrollBar.Position),FPictureZoom,Color,Color,Optn);
finally
FDrawing:=B;
FCanvas.Handle := 0;
Canvas.Unlock;
end;
end;
function TDyImage.GetPalette: HPALETTE;
begin
Result := 0;
if FPicture.Graphic <> nil then
Result:=FPicture.Graphic.Palette;
end;
function TDyImage.DoPaletteChange: Boolean;
var
ParentForm: TCustomForm;
Tmp: TGraphic;
begin
Result := False;
Tmp := Picture.Graphic;
if Visible and (not (csLoading in ComponentState)) and (Tmp <> nil) and
(Tmp.PaletteModified) then
begin
if (Tmp.Palette = 0) then
Tmp.PaletteModified := False
else
begin
ParentForm := GetParentForm(Self);
if Assigned(ParentForm) and ParentForm.Active and Parentform.HandleAllocated then
begin
if FDrawing then
ParentForm.Perform(wm_QueryNewPalette, 0, 0)
else
PostMessage(ParentForm.Handle, wm_QueryNewPalette, 0, 0);
Result := True;
Tmp.PaletteModified := False;
end;
end;
end;
end;
procedure TDyImage.Progress(Sender: TObject; Stage: TProgressStage;
PercentDone: Byte; RedrawNow: Boolean; const R: TRect; const Msg: string);
begin
if FIncrementalDisplay and RedrawNow then
begin
if DoPaletteChange then Update
else Invalidate;
end;
if Assigned(FOnProgress) then FOnProgress(Sender, Stage, PercentDone, RedrawNow, R, Msg);
end;
procedure TDyImage.SetPicture(Value:TPicture);
begin
FPicture.Assign(Value);
end;
procedure TDyImage.SetPictureStyle(Value:TDyPictureStyle);
begin
if FPictureStyle=Value then Exit;
FPictureStyle:=Value;
PictureChanged(self);
end;
procedure TDyImage.SetPictureZoom(Value:double);
begin
if FPictureStyle in [psAutoFit,psTile] then Exit;
FPictureZoom:=Value;
PictureChanged(nil);
end;
procedure TDyImage.SetPictureTransparent(Value:boolean);
begin
if FPictureTransparent=Value then Exit;
FPictureTransparent:=Value;
PictureChanged(self);
end;
procedure TDyImage.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
if (FPictureStyle=psAutoSize) and (Picture.Graphic<>nil) and (not Picture.Graphic.Empty) then begin
if Width<>AWidth
then FPictureZoom:=AWidth/Picture.Graphic.Width
else if Height<>AHeight then FPictureZoom:=AHeight/Picture.Graphic.Height;
AHeight:=trunc(Picture.Graphic.Height*FPictureZoom);
AWidth:=trunc(Picture.Graphic.Width*FPictureZoom);
end;
inherited;
end;
procedure TDyImage.PictureChanged(Sender:TObject);
var
VRange,HRange:integer;
SAuto:boolean;
begin
if FLock then Exit;
try
FLock:=true;
HRange:=0; VRange:=0; SAuto:=true;
with FPicture do if (Graphic<>nil) and not Graphic.Empty then begin;
case FPictureStyle of
psZoomed: begin
if Sender=FPicture then FPictureZoom:=1;
HRange:=Trunc(Graphic.Width*FPictureZoom);
VRange:=Trunc(Graphic.Height*FPictureZoom);
SAuto:=false;
end;
psAutoSize: begin
SetBounds(Left,Top,self.Width,self.Height);
SAuto:=false;
end;
psAutoFit:SAuto:=false;
psTile:;
end;
if Sender=Picture
then FPictureTransparent:=Graphic.Transparent
else Graphic.Transparent:=FPictureTransparent;
if DoPaletteChange and FDrawing then Update;
end;
HorzScrollBar.Range:=HRange;
VertScrollBar.Range:=VRange;
AutoScroll:=SAuto;
if not FDrawing then Invalidate;
finally
FLock:=false;
end;
if (Sender<>nil) and not FDrawing then DoChange;
end;
procedure TDyImage.Clear;
begin
FPicture.Graphic := nil;
end;
procedure TDyImage.CopyToClipboard;
begin
if FPicture.Graphic<>nil then Clipboard.Assign(FPicture);
end;
procedure TDyImage.CutToClipboard;
begin
if FPicture.Graphic<>nil then begin
CopyToClipboard;
Clear;
end;
end;
procedure TDyImage.PasteFromClipboard;
begin
if Clipboard.HasFormat(CF_PICTURE) then begin
FPicture.Assign(Clipboard);
end;
end;
procedure TDyImage.LoadFromFile(FileName:string);
begin
FPicture.LoadFromFile(FileName);
end;
procedure TDyImage.SaveToFile(FileName:string);
begin
if FPicture.Graphic<>nil then begin
FPicture.SaveToFile(FileName);
end;
end;
procedure TDyImage.WMLButtonDown(var Message: TWMLButtonDown);
begin
if TabStop and CanFocus then SetFocus;
inherited;
end;
procedure TDyImage.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key, Shift);
case Key of
VK_INSERT:
if (ssShift in Shift) and not FReadOnly then PasteFromClipBoard else
if ssCtrl in Shift then CopyToClipBoard;
VK_DELETE:
if (ssShift in Shift) and not FReadOnly then CutToClipBoard;
end;
end;
procedure TDyImage.KeyPress(var Key: Char);
begin
inherited KeyPress(Key);
case Key of
^X: if not FReadOnly then CutToClipBoard else CopyToClipBoard;
^C: CopyToClipBoard;
^V: if not FReadOnly then PasteFromClipBoard;
end;
end;
procedure TDyImage.WMCut(var Message: TMessage);
begin
if FReadOnly then CopyToClipboard else CutToClipboard;
end;
procedure TDyImage.WMCopy(var Message: TMessage);
begin
CopyToClipboard;
end;
procedure TDyImage.WMPaste(var Message: TMessage);
begin
if not FReadOnly then PasteFromClipboard;
end;
procedure TDyImage.WMSize(var Message: TMessage);
begin
inherited;
if FPictureStyle in [psAutoSize,psAutoFit] then PictureChanged(nil);
end;
function TDyImage.GetPopupMenu: TPopupMenu;
begin
Result:= inherited GetPopupMenu;
if Result=nil then begin
if ImagePopup<>nil then ImagePopup.Destroy;
ImagePopup:=TPopupMenu.create(Application);
if FPictureStyle in [psZoomed,psAutoSize] then begin
CreatePopupItem(ImagePopup.Items,'Увеличить',(Picture.Graphic<>nil) AND NOT Picture.Graphic.Empty,11,PopupClick);
CreatePopupItem(ImagePopup.Items,'Уменьшить',(Picture.Graphic<>nil) AND NOT Picture.Graphic.Empty,12,PopupClick);
CreatePopupItem(ImagePopup.Items,'100%',(Picture.Graphic<>nil) AND NOT Picture.Graphic.Empty,13,PopupClick);
CreatePopupItem(ImagePopup.Items,'Автоподбор',(Picture.Graphic<>nil) AND NOT Picture.Graphic.Empty,14,PopupClick);
if not ReadOnly then CreatePopupItem(ImagePopup.Items,'-',true,0,nil);
end;
if not ReadOnly then begin
CreatePopupItem(ImagePopup.Items,'Вставить',Clipboard.HasFormat(CF_PICTURE),21,PopupClick);
CreatePopupItem(ImagePopup.Items,'Копировать',(Picture.Graphic<>nil) AND NOT Picture.Graphic.Empty,22,PopupClick);
CreatePopupItem(ImagePopup.Items,'Вырезать',(Picture.Graphic<>nil) AND NOT Picture.Graphic.Empty,23,PopupClick);
CreatePopupItem(ImagePopup.Items,'Очистить',(Picture.Graphic<>nil) AND NOT Picture.Graphic.Empty,24,PopupClick);
CreatePopupItem(ImagePopup.Items,'-',true,0,nil);
CreatePopupItem(ImagePopup.Items,'Загрузить ...',true,31,PopupClick);
CreatePopupItem(ImagePopup.Items,'Сохранить ...',(Picture.Graphic<>nil) AND NOT Picture.Graphic.Empty,32,PopupClick);
end;
if ImagePopup.Items.Count=0 then begin
ImagePopup.Free;
ImagePopup:=nil;
end;
Result:=ImagePopup;
end;
end;
procedure TDyImage.PopupClick(Sender:TObject);
var R:TRect;
begin
case TMenuItem(Sender).Tag of
11: PictureZoom:=FPictureZoom*1.4;
12: PictureZoom:=FPictureZoom/1.4;
13: PictureZoom:=1;
14: PictureZoom:=AutoFitRect(R,Rect(0,0,Picture.Graphic.Width,Picture.Graphic.Height),ClientRect);
21: PasteFromClipboard;
22: CopyToClipboard;
23: CutToClipboard;
24: Clear;
31: with TOpenPictureDialog.create(application) do try
if Execute then Picture.LoadFromFile(FileName);
finally
Destroy;
end;
32: with TSavePictureDialog.create(application) do try
DefaultExt:=GraphicExtension(TGraphicClass(Picture.Graphic.ClassType));
Filter:=GraphicFilter(TGraphicClass(Picture.Graphic.ClassType));
if Execute then Picture.SaveToFile(FileName);
finally
Destroy;
end;
end;
ImagePopup.Destroy;
ImagePopup:=nil;
end;
function TDyImage.PictureIsEmpty:boolean;
begin
Result:=(Picture.Graphic=nil) or Picture.Graphic.Empty;
end;
{function TDyImage.DoStoreImage:boolean;
begin
Result:=FStreamer=nil;
end;}
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC pool standard implementation }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Stan.Pool;
interface
implementation
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
System.SysUtils, System.Classes, System.SyncObjs,
FireDAC.Stan.Intf, FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.Stan.Error, FireDAC.Stan.Factory;
type
TFDResourcePoolGC = class;
TFDResourcePool = class;
TFDResourcePoolItem = class(TObject)
private
FObj: IFDStanObject;
FInUse: Boolean;
FLastUsed: Cardinal;
public
property Obj: IFDStanObject read FObj;
property InUse: Boolean read FInUse;
property LastUsed: Cardinal read FLastUsed;
end;
TFDResourcePoolGC = class(TThread)
private
FPool: TFDResourcePool;
FEvent: TEvent;
protected
procedure Execute; override;
public
constructor Create(APool: TFDResourcePool);
destructor Destroy; override;
end;
TFDResourcePool = class(TFDObject, IFDStanObjectFactory)
private
FHost: IFDStanObjectHost;
FList: TFDObjList;
FLock: TCriticalSection;
FGC: TFDResourcePoolGC;
FCleanupTimeout: Cardinal;
FExpireTimeout: Cardinal;
FMaximumItems: Integer;
FBusyItems: Cardinal;
FCloseTimeout: Cardinal;
procedure DoCleanup;
procedure InternalRelease(const AObject: IFDStanObject);
protected
// IFDStanObjectFactory
procedure Open(const AHost: IFDStanObjectHost; const ADef: IFDStanDefinition);
procedure Close;
procedure Acquire(out AObject: IFDStanObject);
procedure Release(const AObject: IFDStanObject);
public
procedure Initialize; override;
destructor Destroy; override;
end;
{ ---------------------------------------------------------------------------- }
{ TFDResourcePoolGC }
{ ---------------------------------------------------------------------------- }
constructor TFDResourcePoolGC.Create(APool: TFDResourcePool);
begin
inherited Create;
FPool := APool;
FEvent := TEvent.Create(nil, False, False, '');
end;
{ ---------------------------------------------------------------------------- }
destructor TFDResourcePoolGC.Destroy;
begin
FEvent.SetEvent;
inherited Destroy;
FPool := nil;
FDFreeAndNil(FEvent);
end;
{ ---------------------------------------------------------------------------- }
procedure TFDResourcePoolGC.Execute;
begin
while not Terminated do
case FEvent.WaitFor(FPool.FCleanupTimeout) of
wrTimeout: FPool.DoCleanup;
else Break;
end;
end;
{ ---------------------------------------------------------------------------- }
{ TFDResourcePool }
{ ---------------------------------------------------------------------------- }
procedure TFDResourcePool.Initialize;
begin
inherited Initialize;
FCleanupTimeout := C_FD_PoolCleanupTimeout;
FExpireTimeout := C_FD_PoolExpireTimeout;
FCloseTimeout := C_FD_PoolCloseTimeout;
FMaximumItems := C_FD_PoolMaximumItems;
FList := TFDObjList.Create;
FLock := TCriticalSection.Create;
end;
{ ---------------------------------------------------------------------------- }
destructor TFDResourcePool.Destroy;
begin
Close;
FDFreeAndNil(FList);
FDFreeAndNil(FLock);
inherited Destroy;
end;
{ ---------------------------------------------------------------------------- }
procedure TFDResourcePool.DoCleanup;
var
i: integer;
oList: TFDObjList;
begin
if FLock.TryEnter then begin
oList := TFDObjList.Create;
try
try
for i := FList.Count - 1 downto 0 do
if not TFDResourcePoolItem(FList[i]).InUse and
FDTimeout(TFDResourcePoolItem(FList[i]).LastUsed, FExpireTimeout) then begin
oList.Add(FList[i]);
FList.Delete(i);
end;
finally
FLock.Leave;
end;
for i := 0 to oList.Count - 1 do
FDFree(TFDResourcePoolItem(oList[i]));
finally
FDFree(oList);
end;
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TFDResourcePool.Acquire(out AObject: IFDStanObject);
var
i, iCreate: integer;
oItem: TFDResourcePoolItem;
begin
AObject := nil;
FLock.Enter;
try
ASSERT(FHost <> nil);
for i := 0 to FList.Count - 1 do begin
oItem := TFDResourcePoolItem(FList[i]);
if not oItem.InUse then begin
AObject := oItem.Obj;
oItem.FInUse := True;
Inc(FBusyItems);
Break;
end;
end;
if AObject = nil then begin
if (FMaximumItems > 0) and (FMaximumItems <= FList.Count) then
FDException(Self, [S_FD_LStan], er_FD_StanPoolTooManyItems, [FMaximumItems]);
iCreate := 5;
oItem := nil;
if (FMaximumItems > 0) and (iCreate > FMaximumItems - FList.Count) then
iCreate := FMaximumItems - FList.Count;
while iCreate > 0 do begin
oItem := TFDResourcePoolItem.Create;
try
oItem.FLastUsed := TThread.GetTickCount;
FHost.CreateObject(oItem.FObj);
except
FDFree(oItem);
raise;
end;
FList.Add(oItem);
Dec(iCreate);
end;
ASSERT((oItem <> nil) and not oItem.FInUse and (oItem.FObj <> nil));
AObject := oItem.FObj;
oItem.FInUse := True;
Inc(FBusyItems);
end;
finally
FLock.Leave;
end;
try
AObject.BeforeReuse;
except
InternalRelease(AObject);
AObject := nil;
raise;
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TFDResourcePool.InternalRelease(const AObject: IFDStanObject);
var
i: integer;
oItem: TFDResourcePoolItem;
begin
FLock.Enter;
try
for i := 0 to FList.Count - 1 do begin
oItem := TFDResourcePoolItem(FList[i]);
if oItem.Obj = AObject then begin
oItem.FInUse := False;
oItem.FLastUsed := TThread.GetTickCount;
Dec(FBusyItems);
Exit;
end;
end;
finally
FLock.Leave;
end;
end;
{ ---------------------------------------------------------------------------- }
procedure TFDResourcePool.Release(const AObject: IFDStanObject);
begin
try
AObject.AfterReuse;
finally
InternalRelease(AObject);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDResourcePool.Open(const AHost: IFDStanObjectHost; const ADef: IFDStanDefinition);
function Def(AValue, ADef: Integer): Integer;
begin
if AValue = 0 then
Result := ADef
else
Result := AValue;
end;
begin
FLock.Enter;
try
ASSERT(FHost = nil);
if ADef <> nil then begin
FCleanupTimeout := Cardinal(Def(ADef.AsInteger[S_FD_ConnParam_Common_Pool_CleanupTimeout], C_FD_PoolCleanupTimeout));
FExpireTimeout := Cardinal(Def(ADef.AsInteger[S_FD_ConnParam_Common_Pool_ExpireTimeout], C_FD_PoolExpireTimeout));
FMaximumItems := Def(ADef.AsInteger[S_FD_ConnParam_Common_Pool_MaximumItems], C_FD_PoolMaximumItems);
end;
FHost := AHost;
FGC := TFDResourcePoolGC.Create(Self);
finally
FLock.Leave;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDResourcePool.Close;
var
i: Integer;
iStartTime: Cardinal;
begin
if FHost <> nil then begin
FHost := nil;
iStartTime := TThread.GetTickCount;
while (FBusyItems > 0) and not FDTimeout(iStartTime, FCloseTimeout) do
Sleep(1);
FLock.Enter;
try
FDFreeAndNil(FGC);
for i := 0 to FList.Count - 1 do
FDFree(TFDResourcePoolItem(FList[i]));
FList.Clear;
finally
FLock.Leave;
end;
end;
end;
{-------------------------------------------------------------------------------}
var
oFact: TFDFactory;
initialization
oFact := TFDMultyInstanceFactory.Create(TFDResourcePool, IFDStanObjectFactory);
finalization
FDReleaseFactory(oFact);
end.
|
{**********************************************************************}
{ File archived using GP-Version }
{ GP-Version is Copyright 1999 by Quality Software Components Ltd }
{ }
{ For further information / comments, visit our WEB site at }
{ http://www.qsc.co.uk }
{**********************************************************************}
{}
{ $Log: C:\PROGRAM FILES\GP-VERSION LITE\Archives\Reve64\Source\HashTable.paV
{
{ Rev 1.0 28/09/03 20:28:21 Dgrava
{ Initial Revision
}
{}
unit HashTable;
interface
uses
ReveTypes;
const
VERY_LARGE_INDEX = $AAAAAA;
type
TValueType = (vtExact, vtLowerBound, vtUpperBound);
THashEntry = packed record
Key : THashKey;
Depth : ShortInt;
ColorToMove : Byte;
ValueType : TValueType;
Value : SmallInt;
FromSquare : Byte;
ToSquare : Byte;
end;
PHashEntry = ^THashEntry;
THashEntries = array [0..VERY_LARGE_INDEX] of THashEntry;
PHashEntries = ^THashEntries;
THashTable = record
HashEntries : PHashEntries;
NumEntries : Cardinal;
end;
procedure hashTable_Create(var aHashTable : THashTable; aSize : Integer);
procedure hashTable_Free(var aHashTable : THashTable);
procedure hashTable_AddEntry(
var aHashTable : THashTable;
var aKey : THashKey;
aDepth : Integer;
aColorToMove : Integer;
aValueType : TValueType;
aValue : Integer;
aFromSquare : Integer;
aToSquare : Integer
);
function hashTable_GetEntry(
var aHashTable : THashTable;
var aHashKey : THashKey
) : PHashEntry;
function CalculateHashKey (var aBoard : TBoard): THashKey;
procedure AdjustHashKey (var aHashKey : THashKey; aPieceType : Integer; aSquare : Integer);
procedure hashTable_Initialize (var aHashTable: THashTable);
const
RANDOM_NUMBERS : array [1..32, 1..4] of THashKey = (
($4C74F7D53CC32F2E, $C59C00027EB2779C, $EAA14A119FE7BA5A, $46758FC7BCAEEEE8),
($A1E2C0E08D5F40C6, $5D7ADFE34DF7EF74, $80F80149BFD22E72, $2AA6343F2A300540),
($C7AD9E458E302F5E, $1255E8DBCE9EFC4C, $4D9AA1815B5C2F8A, $25A899B7394DE098),
($131C46FD1C185AF6, $AB1922D03412FE24, $F8920AB94E321DA2, $635AA02F2CDDE0F0),
($D7D9A8B567EE238E, $66746DCBD74354FC, $7C0B1CF19EB458BA, $B51E27A793496648),
($3374A36DB0FBE926, $DA5BA9C3F57360D4, $F7D6B8299F7740D2, $3959101F8C0DD0A0),
($68E0172581800BBE, $E386B6BB7DBA81AC, $14E9BC61E0C335EA, $12F539975D3C7FF8),
($CBF2E3DD482CEB56, $A4F174B3FE841784, $F8DD0999F2149802, $30E0840F58FAD450),
($3CE7E995C1A8E7EE, $975BC3ABC30F825C, $C96D7FD1F39BC71A, $258CCF8713022DA8),
($33DE084D320E6186, $A8C983A370F02234, $BFFBFF09F7BD2332, $E06FFBFFE61FEC00),
($5C5820056E6BB81E, $6C02949BF58D570C, $CD0D674134910C4A, $8B83E977C9B56F58),
($C0BD10BDB6434BB6, $5812D693C3A280E4, $CBCA9879563E2602, $C6C677EF773817B0),
($85D7BA755D0B7C4E, $17CA298B60BEFFBC, $458072B1BC36057A, $8BB98767DFB14508),
($3656FD2D43AEA9E6, $E93C6D8342C63394, $C51FD5E9433BD592, $6EE2F7DFF13E5760),
($9E4DB8E5220B347E, $D41827BF0D6F7C6C, $BABDA221DE5DB2AA, $540CA957AC90AEB8),
($36B2CD9DA0737C16, $46F54873BFC63A44, $EF12B759DDCB7FCC, $2C047BCF8A6DAB10),
($20E11B55412DE0AE, $6B379F6B21A9CD1C, $86FBF591CA1B13DA, $5F9C4F47312EAC68),
($B217820D19F4C246, $2C676341400D94F4, $96FA3CC9308B57F2, $23AA03BF7A4112C0),
($8EF8E1C55D7680DE, $ECBB805B30B8F1CC, $46B26D01D9C1290A, $7A477937C7A63E18),
($570C1A7DB4D57C76, $3810CA53B34743A4, $846D6639A8E70022, $6B928FAFA9738E70),
($E03C0C356928150E, $D91C254B4B27EA7C, $48980871A2E2F23A, $9D2D2727D35263C8),
($25796EDC00F8AAA6, $96117143E9DE4654, $694333A9A243AA52, $F9BD1F9F62001E20),
($F2919AA5D5C59D3E, $F3E88E3BFEC1B72C, $FDA3C7E1B6536F6A, $686C591770CE1D78),
($2F00F75D15814CD6, $35DD5C33B27D9D04, $5192A5192DCEA182, $9468B38FFF21C1D0),
($FA208D15C412196E, $6CEFBB2BF69157DC, $690CAB518025A09A, $C4640F0725F46B28),
($664F3BCD28D26306, $97638B23C1D047B4, $13B2BA89AEFCCCB2, $C2144B7F9D537980),
($F14FE3853410899E, $D040AC1BAAE1CC8C, $9049B2C177AC85CA, $D1B348F791E04CD8),
($AFC9643D588EED36, $8ED2FE1325C14664, $C03A73F954C12BE2, $B97EE76FCA504530),
($8C69DF535003EDCE, $F62A610B113E153C, $EB11DE314F7B1EFA, $D93906E71CECC288),
($13670ADD99E00B66, $349AB503947B9914, $1200D169A14EBF12, $51A7875F351324E0),
($176BBC65156F45FE, $F33BD9FB4C7131EC, $D35C2DA125646C2A, $3C1448D7A8B4CC38),
($AE9D611D88165D96, $D569AFF3C96A3FC4, $DE1CD2D99A188642, $F1CD2B4F5DD71890)
);
implementation
procedure AdjustHashKey (var aHashKey : THashKey; aPieceType : Integer; aSquare : Integer);
begin
case aPieceType of
RP_BLACKMAN : aHashKey := aHashKey xor RANDOM_NUMBERS[aSquare, 1];
RP_BLACKKING : aHashKey := aHashKey xor RANDOM_NUMBERS[aSquare, 2];
RP_WHITEMAN : aHashKey := aHashKey xor RANDOM_NUMBERS[aSquare, 3];
RP_WHITEKING : aHashKey := aHashKey xor RANDOM_NUMBERS[aSquare, 4];
else
Assert(False, 'Unsupported piecetype');
end;
end; // AdjustHashKey
function CalculateHashKey (var aBoard : TBoard): THashKey;
var
i : Integer;
begin
result := 0;
for i := Low(aBoard) to High(aBoard) do begin
if aBoard[i] <> RP_FREE then begin
AdjustHashKey (result, aBoard[i], i);
end;
end;
end; // CalculateHashKey
procedure hashTable_Create(var aHashTable : THashTable; aSize : Integer);
var
pTable : PHashEntries;
begin
{ TODO : Eoutofresources afvangnen }
GetMem(pTable, aSize);
aHashTable.HashEntries := pTable;
aHashTable.NumEntries := aSize div SizeOf(THashEntry);
end; // hashTable_Create
procedure hashTable_Free(var aHashTable : THashTable);
begin
FreeMem(aHashTable.HashEntries);
aHashTable.HashEntries := nil;
aHashTable.NumEntries := 0;
end; // hashTable_Free
procedure hashTable_AddEntry(
var aHashTable : THashTable;
var aKey : THashKey;
aDepth : Integer;
aColorToMove : Integer;
aValueType : TValueType;
aValue : Integer;
aFromSquare : Integer;
aToSquare : Integer
);
var
entryIndex : Cardinal;
begin
entryIndex := Cardinal(aKey) mod aHashTable.NumEntries;
with aHashTable.HashEntries^[entryIndex] do begin
if (aDepth >= Depth) then begin
Key := aKey;
Depth := aDepth;
ColorToMove := aColorToMove;
ValueType := aValueType;
Value := aValue;
FromSquare := aFromSquare;
ToSquare := aToSquare;
end;
end;
end; // hashTable_AddEntry
function hashTable_GetEntry(
var aHashTable : THashTable;
var aHashKey : THashKey
) : PHashEntry;
var
entryIndex : Cardinal;
begin
entryIndex := Cardinal(aHashKey) mod aHashTable.NumEntries;
with aHashTable.HashEntries^[entryIndex] do begin
if Key = aHashKey then begin
//aHashTable.HashEntries^[entryIndex].IsRecent := True;
result := @(aHashTable.HashEntries^[entryIndex]);
end
else begin
result := nil;
end;
end;
end; // hashTable_GetEntry
procedure hashTable_Initialize (var aHashTable: THashTable);
var
i : Integer;
begin
for i := 0 to aHashTable.NumEntries - 1 do begin
aHashTable.HashEntries^[i].Depth := 0;
//aHashTable.HashEntries^[i].IsRecent := False;
end;
end; // hashTable_Initialize
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSPortFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IPPeerAPI;
type
TDSPortFram = class(TFrame)
LabelPort: TLabel;
EditPort: TEdit;
ButtonTest: TButton;
ButtonNextAvailable: TButton;
procedure ButtonTestClick(Sender: TObject);
procedure ButtonNextAvailableClick(Sender: TObject);
private
function GetPort: Integer;
procedure SetPort(const Value: Integer);
procedure OnExecute(AContext: IIPContext);
{ Private declarations }
public
{ Public declarations }
property Port: Integer read GetPort write SetPort;
end;
implementation
{$R *.dfm}
uses DSServerDsnResStrs;
procedure TDSPortFram.ButtonNextAvailableClick(Sender: TObject);
var
LPort: Integer;
LTestServer: IIPTestServer;
begin
LTestServer := PeerFactory.CreatePeer('', IIPTestServer) as IIPTestServer;
LPort := LTestServer.GetOpenPort;
Port := LPort;
end;
procedure TDSPortFram.ButtonTestClick(Sender: TObject);
var
LTestServer: IIPTestServer;
begin
try
LTestServer := PeerFactory.CreatePeer('', IIPTestServer) as IIPTestServer;
LTestServer.TestOpenPort(Port, OnExecute);
MessageDlg(rsTestPortOK, mtInformation, [mbOK], 0);
except
on E: Exception do
MessageDlg(E.Message, mtError, [mbOK], 0);
end;
end;
procedure TDSPortFram.OnExecute(AContext: IIPContext);
begin
//
end;
function TDSPortFram.GetPort: Integer;
begin
Result := StrToInt(EditPort.Text);
end;
procedure TDSPortFram.SetPort(const Value: Integer);
begin
EditPort.Text := IntToStr(Value);
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,Forms, Dialogs,
StdCtrls, ExtCtrls, ComCtrls, Buttons, inifiles, PrnServ, Printers;
const
IniFileName='sigma32.ini';
type
TForm1 = class(TForm)
StatusBar1: TStatusBar;
Splitter1: TSplitter;
Memo1: TMemo;
Panel1: TPanel;
SpeedButton1: TSpeedButton;
SaveDlg: TSaveDialog;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
ListBox2: TListBox;
ListBox3: TListBox;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton3Click(Sender: TObject);
procedure ListBox2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure SaveForm(Name:string);
procedure LoadForm(Name:string);
end;
var
Form1: TForm1;
FileName:String;
LsB: string;
r : string;
SigmaIni : TIniFile;
SigmaLocation : String;
implementation
uses Registry;
const
Sigma32_exe='Sigma32.exe';
StringReg = '\Software\MAI.609\SIGMA32\3.0';
Plugin_Edit_Form=1;
Plugin_Edit_Fortran=2;
MsgCount=32;
CheckHints:array [1..MsgCount] of String=
('1. NRC, размеры, свободные параметры, свойства КЭ.(DATA)', '2. Исходные координаты опорных точек зон.(GRIDDM)', '3. Связи зон разбиения.(GRIDDM)',
'4. Номера узлов по зонам (GRIDDM)', '5. Элементы-узлы по зонам (GRIDDM)', '6. Координаты узлов по зонам (GRIDDM)', '7. Характеристики сетки и неупорядоченой матрицы (GRIDDM)',
'8. Печать матрицы А (MAIN)', '9. Печать матрицы в ленточном виде', '10. Начальная нумерация - КЭ и его узлы. (RENMDD)',
'11. Структура смежности XADJ, ADJNCY. (RENMDD)', '12. Таблица номеров узлов- старые/новые номера (RENMDD)', '13. Таблица номеров узлов - новые/старые номера (RENMDD)',
'14. Конечная нумерация - КЭ и его узлы. ( MAIN )', '15. Печать результатов оптимизации сетки (REGULARIZATION)', '16. Печать множителя L (RCMSLV)', '17. Контрольная печать параметров задачи перед FNENDD (MAIN)',
'18. Резерв', '19. Координаты узлов (MAIN)', '20. Массив NOP перед и в FORMDD (MAIN)', '21. Параметры закрепления (BOUND)', '22. Свободные параметры в FORCE (контроль)',
'23. Распределение нагрузки по узлам. (FORCE)', '24. Резерв', '25. Характеристики модфицированной профильной схемы хранения', '26. Сообщения о работе программ', '27. Распределение памяти для профильного метода XENV (MAIN)',
'28. Размер оболочки, ширина ленты матрицы (MAIN)', '29. Резерв', '30. Резерв','31. Перемещения узлов (MAIN)','32. Напряжения в КЭ (STRDD)');
//******ИЮНЬ 2012
ResultSets:array [1..2*MsgCount] of String=
('**********Start DATA','*****Finish DATA','*****Start GRIDDM','*****Finish GRIDDM','CONNECTIVITY DATA','*****Finish GRIDDM',
'REGION 1 ****', '*****Finish GRIDDM','NEL NODE NUMBERS','*****Finish GRIDDM','COORDINATES NOTES OF REGION','*****Finish GRIDDM',
'Характеристики сетки','*****Finish GRIDDM', '*****Start PRNTDD','*****Finish PRNTDD','*****Start PRNTDD','*****Finish PRNTDD','*****Start RENMDD','*****Start STSM in RENMDD',
'СТРУКТУРА СМЕЖНОСТИ', '*****Start GENRCM in RENMDD','+OLD+ +NEW+ +OLD+ +NEW+ +OLD+ +NEW+','*****Finish RENMDD','+NEW+ +OLD+ +NEW+ +OLD+ +NEW+ +OLD+','*****Finish RENMDD',
'НОВАЯ НУМЕРАЦИЯ УЗЛОВ (ЭЛЕМЕНТ И ЕГО УЗЛЫ) MACCИB <<NOP>>','*****Start BOUND','*****Start REGULARIZATION in GRIDDM','*****Finish REGULARIZATION in GRIDDM',
'*****Finish ESFCT in RCMSLV','*****Start ELSLV in RCMSLV','КОНТРОЛЬНАЯ ПЕЧАТЬ ПАРАМЕТРОВ ЗАДАЧИ','*****Start FNENDD','Hello!','****good luck****',
' KOOPДИHATЫ УЗЛOB','*****Start FNENDD',' NOP ПЕРЕД FORMDD','*****Finish FORMDD','*****Start BOUND','*****Finish BOUND','*****Start FORCE','PACПPEДEЛEHИE HAГPУЗOK',
'PACПPEДEЛEHИE HAГPУЗOK','*****Finish FORCE','Hello!','****good luck****','begin memory','end memory','Hello!','****good luck****',
'*****Finish FNENDD','begin memory','*****Finish FNENDD','begin memory','Hello!','****good luck****','Hello!','****good luck****','ПEPEMEЩEHИЯ УЗЛOB','*****Start STRSDD',
'*****Start STRSDD', '*****Finish STRSDD');
//******ИЮНЬ 2012
{$R *.DFM}
procedure TForm1.LoadForm(Name:string);
var
Registry:TRegistry;
begin
Registry :=TRegistry.Create;
Registry.RootKey:=HKEY_CURRENT_USER;
if Registry.OpenKeyReadOnly(StringReg+'\'+Name) then
begin
if Registry.ValueExists('Top') then
Top:=Registry.ReadInteger('Top');
if Registry.ValueExists('Left') then
Left:=Registry.ReadInteger('Left');
if Registry.ValueExists('Width') then
Width:=Registry.ReadInteger('Width');
if Registry.ValueExists('Height') then
Height:=Registry.ReadInteger('Height');
if Registry.ValueExists('Maximized') then
begin
if Registry.ReadBool('Maximized') then WindowState:=wsMaximized
else WindowState:=wsNormal;
end;
end;
Registry.free;
end;
procedure TForm1.SaveForm(Name:string);
var
Registry:TRegistry;
begin
Registry :=TRegistry.Create;
Registry.RootKey:=HKEY_CURRENT_USER;
if Registry.OpenKey(StringReg+'\'+Name,true) then
begin
Registry.WriteBool('Maximized',WindowState=wsMaximized);
if WindowState=wsMaximized then WindowState:=wsNormal;
Registry.WriteInteger('Top',Top);
Registry.WriteInteger('Left',Left);
Registry.WriteInteger('Width',Width);
Registry.WriteInteger('Height',Height);
end;
Registry.free;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
end;
{
Функция для получение
имени проекта из
полного пути к файлу проекта
который лежит в реестре
}
function GetProjectName:String;
var
projName:String;
tempStr:String;
slashPos:Integer;
Registry:TRegistry;
begin
projName := '';
Registry :=TRegistry.Create;
Registry.RootKey:=HKEY_CURRENT_USER;
if Registry.OpenKey(StringReg, true) then
begin
if Registry.ValueExists('InputFileName') then
begin
// Получаем полный путь до файла проекта
tempStr:=Registry.ReadString('InputFileName');
// Получаем только имя файла проекта
while(Pos('\',tempStr) <> 0) do
begin
slashPos:= Pos('\',tempStr);
Delete(tempStr,1,slashPos);
end;
Delete(tempStr,Pos('.',tempStr),Length(tempStr));
// Удаляем расширение и получаем имя проекта
projName:= tempStr;
end;
end;
Result := projName;
End;
procedure TForm1.FormCreate(Sender: TObject);
var i:integer;
begin
//******ИЮНЬ 2012
// доступ к файлу с хранящимися данными о конфигурации проекта, заданной пользователем
SigmaIni:=TIniFile.Create(ExtractFilePath(ParamStr(0))+IniFileName);
for i := 1 to MsgCount do
begin
// отображать пункты в меню согласно файлу конфигурации
with SigmaIni do
if SigmaIni.ReadString('FortranPrint',InttoStr(i),'NO')= 'YES' then
begin
ListBox2.Items.Add(CheckHints[i]);
// заполнить вспомогательный список, границами разделов между отдельными блоками текстового результата
ListBox3.Items.Add(ResultSets[2*i-1]);
ListBox3.Items.Add(ResultSets[2*i]);
end;
end;
SigmaIni.Free;
//******ИЮНЬ 2012
Caption:= Caption + ' ' + GetProjectName;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
Form1:=nil;
end;
procedure TForm1.FormResize(Sender: TObject);
var
dop :integer;
cfF: TIniFile;
SigmaLocation:string;
i:integer;
begin
{c:=0;
top:=0;
//определение места расположения Сигмы
SigmaLocation :=LowerCase(ExtractFilePath(ParamStr(0)));
i:=pos('\bin',SigmaLocation);
if i>0 then SetLength(SigmaLocation,i);
cfF:=TIniFile.Create(SigmaLocation+'bin\sforms.ini');
// cfF:=TIniFile.Create('sforms.ini');
try
dop:=CfF.ReadInteger('Главная','Высота',top);
top:=dop-StatusBar1.Height-8;
left:=0;
Height:=Screen.Height-dop;
cfF.Free;
except
MessageDlg('Не могу прочитать файл sforms.ini!',mtError,[mbOk],0);
end;
Constraints.MaxHeight:=Screen.Height-dop;
top:=dop-StatusBar1.Height-8;
}
end;
procedure TForm1.SpeedButton2Click(Sender: TObject);
var ttt:TPrintService;
begin
ttt.PrinterSetupDialog;
end;
{************************************************}
//Сохранение выделенного раздела
procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
if SaveDlg.Execute then
begin
Memo1.Lines.SaveToFile(SaveDlg.FileName);
end;
end;
procedure TForm1.SpeedButton3Click(Sender: TObject);
var
stroka: system.text;
i: integer;
begin
AssignPrn(Stroka);
rewrite(Stroka);
printer.Canvas.Font:=Memo1.Font;
for i:=0 to Memo1.Lines.Count-1 do Writeln(Stroka, Memo1.lines[i]);
System.Close(Stroka);
end;
//******ИЮНЬ 2012
procedure TForm1.ListBox2Click(Sender: TObject);
var
cur:Integer;
s:string;
Handle:TextFile;
start:boolean;
st,fn:string;
IniFile:TIniFile;
begin
cur:=ListBox2.ItemIndex;
Memo1.Lines.Clear;
if FileExists(FileName) then
begin
if (cur=0) then Memo1.Lines.LoadFromFile(FileName)
else begin
st := ListBox3.Items[(ListBox2.ItemIndex)*2-1];
//fn := ReadString('ResultSets','Finish'+IntToStr(cur),'');
fn := ListBox3.Items[(ListBox2.ItemIndex)*2];
Memo1.Lines.BeginUpdate;
AssignFile(Handle,FileName);
Reset(Handle);
Start:=false;
While not EOF(Handle) do
begin
ReadLn(Handle,s);
if (pos(st,s)<>0) then Start:=True;
if (Start) then Memo1.lines.Add(s);
if (pos(fn,s)<>0) then Start:=False;
end;
CloseFile(Handle);
Memo1.Lines.EndUpdate;
end;
end;
end;
//******ИЮНЬ 2012
end.
|
{Textures v1.0 28.01.2000 by ArrowSoft-VMP}
unit Textures;
interface
type
TColorRGB = packed record
r, g, b : BYTE;
end;
PColorRGB = ^TColorRGB;
TRGBList = packed array[0..0] of TColorRGB;
PRGBList = ^TRGBList;
TColorRGBA = packed record
r, g, b, a : BYTE;
end;
PColorRGBA = ^TColorRGBA;
TRGBAList = packed array[0..0] of TColorRGBA;
PRGBAList = ^TRGBAList;
TTexture=class(tobject)
ID, width, height:integer;
pixels: pRGBlist;
constructor Load(tID:integer;filename:string);
destructor destroy; override;
end;
TVoidTexture=class(tobject)
ID, width, height:integer;
pixels: pRGBlist;
constructor create(tid, twidth, theight:integer);
destructor destroy; override;
end;
TTextureRGBA= class(TTexture)
pixels: pRGBAlist;
end;
TVoidTextureRGBA=class(tobject)
ID, width, height:integer;
pixels: pRGBAlist;
constructor create(tid, twidth, theight:integer);
destructor destroy; override;
end;
implementation
uses dialogs, sysutils, graphics, jpeg;
constructor tTexture.Load(tID:integer; filename:string);
var f:file;
dims: array[0..3] of byte;
actread:integer;
fext:string;
bmp:tbitmap; jpg:tjpegimage;
i,j:integer;
pixline: pRGBlist;
r,g,b:byte;
begin
inherited create;
if not fileexists(filename) then begin messagedlg(filename+' not found',mterror,[mbabort],0); halt(1);end;
fExt:=uppercase(ExtractFileExt(filename));
ID:=tID;
if fext='.RGBA' then
begin
assign(f,filename);
{$i-}
reset(f,4);
blockread(f,dims,1);
{$i+}
if ioresult<>0 then begin messagedlg(filename+' not found',mterror,[mbabort],0); halt(1);end;
Width:=dims[0]+dims[1]*256; Height:=dims[2]+dims[3]*256;
getmem(pixels,(filesize(f)-1)*4);
blockread(f,pixels^,width*height,actread);
closefile(f);
end
else
if fext='.RGB' then
begin
assign(f,filename);
{$i-}
reset(f,1);
blockread(f,dims,4);
{$i+}
if ioresult<>0 then begin messagedlg(filename+' not found',mterror,[mbabort],0); halt(1);end;
Width:=dims[0]+dims[1]*256; Height:=dims[2]+dims[3]*256;
getmem(pixels,filesize(f)-4);
blockread(f,pixels^,width*height*3,actread);
closefile(f);
end
else
if fext='.BMP' then
begin
bmp:=TBitmap.Create;
bmp.HandleType:=bmDIB;
bmp.PixelFormat:=pf24bit;
bmp.LoadFromFile(filename);
Width:=bmp.Width;
Height:=bmp.Height;
getmem(pixels,width*height*3);
for i:=0 to height-1 do
begin
pixline:=bmp.ScanLine[i];
for j:=0 to width-1 do
begin
r:=pixline[j].b;
g:=pixline[j].g;
b:=pixline[j].r;
pixels[i*width+j].r:=r;
pixels[i*width+j].g:=g;
pixels[i*width+j].b:=b;
end;
end;
bmp.Free;
end
else
if fext='.JPG' then
begin
jpg:=tjpegimage.Create;
jpg.LoadFromFile(filename);
bmp:=TBitmap.Create;
bmp.HandleType:=bmDIB;
bmp.PixelFormat:=pf24bit;
Width:=jpg.Width;
Height:=jpg.Height;
bmp.Width:=Width;
bmp.Height:=Height;
bmp.Assign(jpg);
getmem(pixels,width*height*3);
for i:=0 to height-1 do
begin
pixline:=bmp.ScanLine[i];
for j:=0 to width-1 do
begin
r:=pixline[j].b;
g:=pixline[j].g;
b:=pixline[j].r;
pixels[i*width+j].r:=r;
pixels[i*width+j].g:=g;
pixels[i*width+j].b:=b;
end;
end;
bmp.Free;
jpg.Free;
end;
end;
destructor TTexture.destroy;
begin
freemem(pixels);
inherited destroy;
end;
constructor tvoidtexture.create(tid, twidth, theight:integer);
begin
inherited create;
id:=tid;
width:=twidth; height:=theight;
getmem(pixels,width*height*3);
end;
destructor tvoidtexture.destroy;
begin
freemem(pixels);
inherited destroy;
end;
constructor tvoidtextureRGBA.create(tid, twidth, theight:integer);
begin
inherited create;
id:=tid;
width:=twidth; height:=theight;
getmem(pixels,width*height*4);
end;
destructor tvoidtextureRGBA.destroy;
begin
freemem(pixels);
inherited destroy;
end;
end.
|
unit FormMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CommonConnection.Intf, Vcl.StdCtrls,
Vcl.ExtCtrls, Spring.Container, Spring.Services, FrameConnectDB, Data.DB,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async,
FireDAC.Phys, FireDAC.Phys.MSSQL, FireDAC.Phys.MSSQLDef, FireDAC.VCLUI.Wait,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, Data.Win.ADODB, Vcl.Grids,
Vcl.DBGrids, NGFDMemTable, Datasnap.DBClient;
type
TForm1 = class(TForm)
pnLeft: TPanel;
pnLeftTop: TPanel;
btnFDOpen1: TButton;
btnFDLoop: TButton;
btnFDLoop2: TButton;
DBGrid1: TDBGrid;
pnRight: TPanel;
pnRightTop: TPanel;
btnADOOpen1: TButton;
btnADOLoop: TButton;
btnADOLoop2: TButton;
DBGrid2: TDBGrid;
ADOQuery1: TADOQuery;
DataSource1: TDataSource;
DataSource2: TDataSource;
FDQuery1: TFDQuery;
btnCdsOpen: TButton;
cds: TClientDataSet;
mtb: TNGFDMemTable;
btnMTBOpen: TButton;
btnOpen: TButton;
btnApplyChanges: TButton;
btnAODOpen: TButton;
btnCdsApplayChanges: TButton;
procedure FormCreate(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure btnFDOpen1Click(Sender: TObject);
procedure btnADOOpen1Click(Sender: TObject);
procedure btnFDLoopClick(Sender: TObject);
procedure btnADOLoopClick(Sender: TObject);
procedure btnCdsOpenClick(Sender: TObject);
procedure btnMTBOpenClick(Sender: TObject);
procedure btnOpenClick(Sender: TObject);
procedure btnApplyChangesClick(Sender: TObject);
procedure btnAODOpenClick(Sender: TObject);
procedure btnCdsApplayChangesClick(Sender: TObject);
private
FFDDBConnectFrame, FADODBConnectFrame: TDBConnectFrame;
FSQLString: string;
FStartTime: DWORD;
procedure ShowButtonCaption(Sender: TObject; iCount: Integer);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
// if rgConnectType.ItemIndex = 0 then
// FDBConnectFrame.DBConnectType := dctFD
// else
// FDBConnectFrame.DBConnectType := dctADO;
procedure TForm1.btnADOLoopClick(Sender: TObject);
begin
ADOQuery1.First;
FStartTime := GetTickCount;
while not ADOQuery1.EOF do
ADOQuery1.Next;
ShowButtonCaption(Sender, ADOQuery1.RecordCount);
end;
procedure TForm1.btnADOOpen1Click(Sender: TObject);
begin
ADOQuery1.Close;
FStartTime := GetTickCount;
ADOQuery1.Open();
ShowButtonCaption(Sender, ADOQuery1.RecordCount);
end;
procedure TForm1.btnAODOpenClick(Sender: TObject);
begin
cds.CommandText := 'select * from Area';
// ADOQuery1.SQL.Text := cds.CommandText;
// ADOQuery1.Open;
cdpADOGlobal.cdsOpen(cds, True, False, False);
end;
procedure TForm1.btnCdsApplayChangesClick(Sender: TObject);
begin
cdpADOGlobal.cdsApplyUpdatesTable(cds, 'Area', '', '', 'AreaID');
end;
procedure TForm1.btnCdsOpenClick(Sender: TObject);
begin
FStartTime := GetTickCount;
cds.CommandText := 'select * from TaskList';
cdpADOGlobal.cdsOpen(cds, True, False, True);
ShowButtonCaption(Sender, cds.RecordCount);
end;
procedure TForm1.btnFDLoopClick(Sender: TObject);
begin
FDQuery1.First;
FStartTime := GetTickCount;
while not FDQuery1.EOF do
FDQuery1.Next;
ShowButtonCaption(Sender, FDQuery1.RecordCount);
end;
procedure TForm1.btnFDOpen1Click(Sender: TObject);
begin
FDQuery1.Close;
FStartTime := GetTickCount;
FDQuery1.Open();
ShowButtonCaption(Sender, FDQuery1.RecordCount);
end;
procedure TForm1.btnMTBOpenClick(Sender: TObject);
begin
FStartTime := GetTickCount;
mtb.SQL.Text := 'select * from TaskList';
cdpFDGlobal.cdsOpen(mtb, True);
ShowButtonCaption(Sender, mtb.RecordCount);
end;
procedure TForm1.btnOpenClick(Sender: TObject);
begin
mtb.SQL.Text := 'select * from Area';
FDQuery1.Open(mtb.SQL.Text);
mtb.Close;
mtb.Data := FDQuery1.Data;
mtb.MergeChangeLog;
end;
procedure TForm1.btnApplyChangesClick(Sender: TObject);
begin
cdpFDGlobal.cdsApplyUpdates(mtb);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ReleaseGlobalDataProvider;
cdpFDGlobal := ServiceLocator.GetService<IFDMemTableProvider>(CDP_IDENT_FD);
cdpADOGlobal := ServiceLocator.GetService<IClientDataSetProvider>(CDP_IDENT_ADO);
FFDDBConnectFrame := TDBConnectFrame.Create(Self);
FFDDBConnectFrame.DBConnectType := dctFD;
FFDDBConnectFrame.Name := 'FD_DBConnectFrame';
FFDDBConnectFrame.Parent := pnLeftTop;
FFDDBConnectFrame.Align := alLeft;
FFDDBConnectFrame.btnSQLServerConnectClick(nil);
FDQuery1.Connection := TFDConnection(cdpFDGlobal.DBConnection.Connection);
FADODBConnectFrame := TDBConnectFrame.Create(Self);
FADODBConnectFrame.DBConnectType := dctADO;
FADODBConnectFrame.Name := 'ADO_DBConnectFrame';
FADODBConnectFrame.Parent := pnRightTop;
FADODBConnectFrame.Align := alLeft;
FADODBConnectFrame.btnSQLServerConnectClick(nil);
ADOQuery1.Connection := TADOConnection(cdpADOGlobal.DBConnection.Connection);
FSQLString := 'select * from TaskList'; //Row_Number() over(order by id) as RowID,
FDQuery1.SQL.Text := FSQLString;
ADOQuery1.SQL.Text := FSQLString;
width := 1500;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
pnLeft.Width := width div 2;
end;
procedure TForm1.ShowButtonCaption(Sender: TObject; iCount: Integer);
begin
TButton(Sender).Caption := Format('%s-%d ms-%d Records', [TButton(Sender).Name, (GetTickCount - FStartTime), iCount]);
end;
end.
|
{ Definitions for GNU multiple precision functions: arithmetic with
integer, rational and real numbers of arbitrary size and
precision.
Translation of the C header (gmp.h) of the GMP library. Tested
with GMP 3.x and 4.x.
To use the GMP unit, you will need the GMP library which can be
found in http://www.gnu-pascal.de/libs/
Copyright (C) 1998-2005 Free Software Foundation, Inc.
Author: Frank Heckenbach <frank@pascal.gnu.de>
This file is part of GNU Pascal.
GNU Pascal is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2, or (at your
option) any later version.
GNU Pascal is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Pascal; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
As a special exception, if you link this file with files compiled
with a GNU compiler to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public
License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU
General Public License.
Please also note the license of the GMP library. }
{$gnu-pascal,I-}
{$if __GPC_RELEASE__ < 20030303}
{$error This unit requires GPC release 20030303 or newer.}
{$endif}
{$nested-comments}
{ If HAVE_GMP4 is set (the default unless HAVE_GMP3 is set, some
interface changes made in GMP 4 are taken into account.
I.e., if this is set wrong, programs might fail. However, this
only affects a few routines related to random numbers. }
{$if not defined (HAVE_GMP3)}
{$define HAVE_GMP4}
{$endif}
{$undef GMP} { in case it's set by the user }
unit GMP;
interface
uses GPC;
{$if defined (__mips) and defined (_ABIN32) and defined (HAVE_GMP3)}
{ Force the use of 64-bit limbs for all 64-bit MIPS CPUs if ABI
permits. }
{$define _LONG_LONG_LIMB}
{$endif}
type
{$ifdef _SHORT_LIMB}
mp_limb_t = CCardinal;
mp_limb_signed_t = CInteger;
{$elif defined (_LONG_LONG_LIMB)}
mp_limb_t = LongCard;
mp_limb_signed_t = LongInt;
{$else}
mp_limb_t = MedCard;
mp_limb_signed_t = MedInt;
{$endif}
mp_ptr = ^mp_limb_t;
{$if defined (_CRAY) and not defined (_CRAYMPP)}
mp_size_t = CInteger;
mp_exp_t = CInteger;
{$else}
mp_size_t = MedInt;
mp_exp_t = MedInt;
{$endif}
mpz_t = record
mp_alloc,
mp_size: CInteger;
mp_d: mp_ptr
end;
mpz_array_ptr = ^mpz_array;
mpz_array = array [0 .. MaxVarSize div SizeOf (mpz_t) - 1] of mpz_t;
mpq_t = record
mp_num,
mp_den: mpz_t
end;
mpf_t = record
mp_prec,
mp_size: CInteger;
mp_exp: mp_exp_t;
mp_d: mp_ptr
end;
TAllocFunction = function (Size: SizeType): Pointer;
TReAllocFunction = function (var Dest: Pointer; OldSize, NewSize: SizeType): Pointer;
TDeAllocProcedure = procedure (Src: Pointer; Size: SizeType);
var
mp_bits_per_limb: CInteger; attribute (const); external name '__gmp_bits_per_limb';
procedure mp_set_memory_functions (AllocFunction: TAllocFunction;
ReAllocFunction: TReAllocFunction;
DeAllocProcedure: TDeAllocProcedure); external name '__gmp_set_memory_functions';
{ Integer (i.e. Z) routines }
procedure mpz_init (var Dest: mpz_t); external name '__gmpz_init';
procedure mpz_clear (var Dest: mpz_t); external name '__gmpz_clear';
function mpz_realloc (var Dest: mpz_t; NewAlloc: mp_size_t): Pointer; external name '__gmpz_realloc';
procedure mpz_array_init (Dest: mpz_array_ptr; ArraySize, FixedNumBits: mp_size_t); external name '__gmpz_array_init';
procedure mpz_set (var Dest: mpz_t; protected var Src: mpz_t); external name '__gmpz_set';
procedure mpz_set_ui (var Dest: mpz_t; Src: MedCard); external name '__gmpz_set_ui';
procedure mpz_set_si (var Dest: mpz_t; Src: MedInt); external name '__gmpz_set_si';
procedure mpz_set_d (var Dest: mpz_t; Src: Real); external name '__gmpz_set_d';
procedure mpz_set_q (var Dest: mpz_t; Src: mpq_t); external name '__gmpz_set_q';
procedure mpz_set_f (var Dest: mpz_t; Src: mpf_t); external name '__gmpz_set_f';
function mpz_set_str (var Dest: mpz_t; Src: CString; Base: CInteger): CInteger; external name '__gmpz_set_str';
procedure mpz_init_set (var Dest: mpz_t; protected var Src: mpz_t); external name '__gmpz_init_set';
procedure mpz_init_set_ui (var Dest: mpz_t; Src: MedCard); external name '__gmpz_init_set_ui';
procedure mpz_init_set_si (var Dest: mpz_t; Src: MedInt); external name '__gmpz_init_set_si';
procedure mpz_init_set_d (var Dest: mpz_t; Src: Real); external name '__gmpz_init_set_d';
function mpz_init_set_str (var Dest: mpz_t; Src: CString; Base: CInteger): CInteger; external name '__gmpz_init_set_str';
function mpz_get_ui (protected var Src: mpz_t): MedCard; external name '__gmpz_get_ui';
function mpz_get_si (protected var Src: mpz_t): MedInt; external name '__gmpz_get_si';
function mpz_get_d (protected var Src: mpz_t): Real; external name '__gmpz_get_d';
{ Pass nil for Dest to let the function allocate memory for it }
function mpz_get_str (Dest: CString; Base: CInteger; protected var Src: mpz_t): CString; external name '__gmpz_get_str';
procedure mpz_add (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_add';
procedure mpz_add_ui (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard); external name '__gmpz_add_ui';
procedure mpz_sub (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_sub';
procedure mpz_sub_ui (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard); external name '__gmpz_sub_ui';
procedure mpz_mul (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_mul';
procedure mpz_mul_ui (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard); external name '__gmpz_mul_ui';
procedure mpz_mul_2exp (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard); external name '__gmpz_mul_2exp';
procedure mpz_neg (var Dest: mpz_t; protected var Src: mpz_t); external name '__gmpz_neg';
procedure mpz_abs (var Dest: mpz_t; protected var Src: mpz_t); external name '__gmpz_abs';
procedure mpz_fac_ui (var Dest: mpz_t; Src: MedCard); external name '__gmpz_fac_ui';
procedure mpz_tdiv_q (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_tdiv_q';
procedure mpz_tdiv_q_ui (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard); external name '__gmpz_tdiv_q_ui';
procedure mpz_tdiv_r (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_tdiv_r';
procedure mpz_tdiv_r_ui (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard); external name '__gmpz_tdiv_r_ui';
procedure mpz_tdiv_qr (var DestQ, DestR: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_tdiv_qr';
procedure mpz_tdiv_qr_ui (var DestQ, DestR: mpz_t; protected var Src1: mpz_t; Src2: MedCard); external name '__gmpz_tdiv_qr_ui';
procedure mpz_fdiv_q (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_fdiv_q';
function mpz_fdiv_q_ui (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard): MedCard; external name '__gmpz_fdiv_q_ui';
procedure mpz_fdiv_r (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_fdiv_r';
function mpz_fdiv_r_ui (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard): MedCard; external name '__gmpz_fdiv_r_ui';
procedure mpz_fdiv_qr (var DestQ, DestR: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_fdiv_qr';
function mpz_fdiv_qr_ui (var DestQ, DestR: mpz_t; protected var Src1: mpz_t; Src2: MedCard): MedCard; external name '__gmpz_fdiv_qr_ui';
function mpz_fdiv_ui (protected var Src1: mpz_t; Src2: MedCard): MedCard; external name '__gmpz_fdiv_ui';
procedure mpz_cdiv_q (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_cdiv_q';
function mpz_cdiv_q_ui (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard): MedCard; external name '__gmpz_cdiv_q_ui';
procedure mpz_cdiv_r (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_cdiv_r';
function mpz_cdiv_r_ui (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard): MedCard; external name '__gmpz_cdiv_r_ui';
procedure mpz_cdiv_qr (var DestQ, DestR: mpz_t; protected var Src1,Src2: mpz_t); external name '__gmpz_cdiv_qr';
function mpz_cdiv_qr_ui (var DestQ, DestR: mpz_t; protected var Src1: mpz_t; Src2: MedCard): MedCard; external name '__gmpz_cdiv_qr_ui';
function mpz_cdiv_ui (protected var Src1: mpz_t; Src2:MedCard): MedCard; external name '__gmpz_cdiv_ui';
procedure mpz_mod (var Dest: mpz_t; protected var Src1,Src2: mpz_t); external name '__gmpz_mod';
procedure mpz_divexact (var Dest: mpz_t; protected var Src1,Src2: mpz_t); external name '__gmpz_divexact';
procedure mpz_tdiv_q_2exp (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard); external name '__gmpz_tdiv_q_2exp';
procedure mpz_tdiv_r_2exp (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard); external name '__gmpz_tdiv_r_2exp';
procedure mpz_fdiv_q_2exp (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard); external name '__gmpz_fdiv_q_2exp';
procedure mpz_fdiv_r_2exp (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard); external name '__gmpz_fdiv_r_2exp';
procedure mpz_powm (var Dest: mpz_t; protected var Base, Exponent, Modulus: mpz_t); external name '__gmpz_powm';
procedure mpz_powm_ui (var Dest: mpz_t; protected var Base: mpz_t; Exponent: MedCard; protected var Modulus: mpz_t); external name '__gmpz_powm_ui';
procedure mpz_pow_ui (var Dest: mpz_t; protected var Base: mpz_t; Exponent: MedCard); external name '__gmpz_pow_ui';
procedure mpz_ui_pow_ui (var Dest: mpz_t; Base, Exponent: MedCard); external name '__gmpz_ui_pow_ui';
procedure mpz_sqrt (var Dest: mpz_t; protected var Src: mpz_t); external name '__gmpz_sqrt';
procedure mpz_sqrtrem (var Dest, DestR: mpz_t; protected var Src: mpz_t); external name '__gmpz_sqrtrem';
function mpz_perfect_square_p (protected var Src: mpz_t): CInteger; external name '__gmpz_perfect_square_p';
function mpz_probab_prime_p (protected var Src: mpz_t; Repetitions: CInteger): CInteger; external name '__gmpz_probab_prime_p';
procedure mpz_gcd (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_gcd';
function mpz_gcd_ui (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard): MedCard; external name '__gmpz_gcd_ui';
procedure mpz_gcdext (var Dest, DestA, DestB: mpz_t; protected var SrcA, SrcB: mpz_t); external name '__gmpz_gcdext';
function mpz_invert (var Dest: mpz_t; protected var Src, Modulus: mpz_t): CInteger; external name '__gmpz_invert';
function mpz_jacobi (protected var Src1, Src2: mpz_t): CInteger; external name '__gmpz_jacobi';
function mpz_cmp (protected var Src1, Src2: mpz_t): CInteger; external name '__gmpz_cmp';
function mpz_cmp_ui (protected var Src1: mpz_t; Src2: MedCard): CInteger; external name '__gmpz_cmp_ui';
function mpz_cmp_si (protected var Src1: mpz_t; Src2: MedInt): CInteger; external name '__gmpz_cmp_si';
function mpz_sgn (protected var Src: mpz_t): CInteger; attribute (inline);
procedure mpz_and (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_and';
procedure mpz_ior (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_ior';
procedure mpz_com (var Dest: mpz_t; protected var Src: mpz_t); external name '__gmpz_com';
function mpz_popcount (protected var Src: mpz_t): MedCard; external name '__gmpz_popcount';
function mpz_hamdist (protected var Src1, Src2: mpz_t): MedCard; external name '__gmpz_hamdist';
function mpz_scan0 (protected var Src: mpz_t; StartingBit: MedCard): MedCard; external name '__gmpz_scan0';
function mpz_scan1 (protected var Src: mpz_t; StartingBit: MedCard): MedCard; external name '__gmpz_scan1';
procedure mpz_setbit (var Dest: mpz_t; BitIndex: MedCard); external name '__gmpz_setbit';
procedure mpz_clrbit (var Dest: mpz_t; BitIndex: MedCard); external name '__gmpz_clrbit';
procedure mpz_random (var Dest: mpz_t; MaxSize: mp_size_t); external name '__gmpz_random';
procedure mpz_random2 (var Dest: mpz_t; MaxSize: mp_size_t); external name '__gmpz_random2';
function mpz_sizeinbase (protected var Src: mpz_t; Base: CInteger): SizeType; external name '__gmpz_sizeinbase';
{ Rational (i.e. Q) routines }
procedure mpq_canonicalize (var Dest: mpq_t); external name '__gmpq_canonicalize';
procedure mpq_init (var Dest: mpq_t); external name '__gmpq_init';
procedure mpq_clear (var Dest: mpq_t); external name '__gmpq_clear';
procedure mpq_set (var Dest: mpq_t; protected var Src: mpq_t); external name '__gmpq_set';
procedure mpq_set_z (var Dest: mpq_t; protected var Src: mpz_t); external name '__gmpq_set_z';
procedure mpq_set_ui (var Dest: mpq_t; Nom, Den: MedCard); external name '__gmpq_set_ui';
procedure mpq_set_si (var Dest: mpq_t; Nom: MedInt; Den: MedCard); external name '__gmpq_set_si';
procedure mpq_add (var Dest: mpq_t; protected var Src1, Src2: mpq_t); external name '__gmpq_add';
procedure mpq_sub (var Dest: mpq_t; protected var Src1, Src2: mpq_t); external name '__gmpq_sub';
procedure mpq_mul (var Dest: mpq_t; protected var Src1, Src2: mpq_t); external name '__gmpq_mul';
procedure mpq_div (var Dest: mpq_t; protected var Src1, Src2: mpq_t); external name '__gmpq_div';
procedure mpq_neg (var Dest: mpq_t; protected var Src: mpq_t); external name '__gmpq_neg';
procedure mpq_inv (var Dest: mpq_t; protected var Src: mpq_t); external name '__gmpq_inv';
function mpq_cmp (protected var Src1, Src2: mpq_t): CInteger; external name '__gmpq_cmp';
function mpq_cmp_ui (protected var Src1: mpq_t; Nom2, Den2: MedCard): CInteger; external name '__gmpq_cmp_ui';
function mpq_sgn (protected var Src: mpq_t): CInteger; attribute (inline);
function mpq_equal (protected var Src1, Src2: mpq_t): CInteger; external name '__gmpq_equal';
function mpq_get_d (protected var Src: mpq_t): Real; external name '__gmpq_get_d';
procedure mpq_set_num (var Dest: mpq_t; protected var Src: mpz_t); external name '__gmpq_set_num';
procedure mpq_set_den (var Dest: mpq_t; protected var Src: mpz_t); external name '__gmpq_set_den';
procedure mpq_get_num (var Dest: mpz_t; protected var Src: mpq_t); external name '__gmpq_get_num';
procedure mpq_get_den (var Dest: mpz_t; protected var Src: mpq_t); external name '__gmpq_get_den';
{ Floating point (i.e. R) routines }
procedure mpf_set_default_prec (Precision: MedCard); external name '__gmpf_set_default_prec';
procedure mpf_init (var Dest: mpf_t); external name '__gmpf_init';
procedure mpf_init2 (var Dest: mpf_t; Precision: MedCard); external name '__gmpf_init2';
procedure mpf_clear (var Dest: mpf_t); external name '__gmpf_clear';
procedure mpf_set_prec (var Dest: mpf_t; Precision: MedCard); external name '__gmpf_set_prec';
function mpf_get_prec (protected var Src: mpf_t): MedCard; external name '__gmpf_get_prec';
procedure mpf_set_prec_raw (var Dest: mpf_t; Precision: MedCard); external name '__gmpf_set_prec_raw';
procedure mpf_set (var Dest: mpf_t; protected var Src: mpf_t); external name '__gmpf_set';
procedure mpf_set_ui (var Dest: mpf_t; Src: MedCard); external name '__gmpf_set_ui';
procedure mpf_set_si (var Dest: mpf_t; Src: MedInt); external name '__gmpf_set_si';
procedure mpf_set_d (var Dest: mpf_t; Src: Real); external name '__gmpf_set_d';
procedure mpf_set_z (var Dest: mpf_t; protected var Src: mpz_t); external name '__gmpf_set_z';
procedure mpf_set_q (var Dest: mpf_t; protected var Src: mpq_t); external name '__gmpf_set_q';
function mpf_set_str (var Dest: mpf_t; Src: CString; Base: CInteger): CInteger; external name '__gmpf_set_str';
procedure mpf_init_set (var Dest: mpf_t; protected var Src: mpf_t); external name '__gmpf_init_set';
procedure mpf_init_set_ui (var Dest: mpf_t; Src: MedCard); external name '__gmpf_init_set_ui';
procedure mpf_init_set_si (var Dest: mpf_t; Src: MedInt); external name '__gmpf_init_set_si';
procedure mpf_init_set_d (var Dest: mpf_t; Src: Real); external name '__gmpf_init_set_d';
function mpf_init_set_str (var Dest: mpf_t; Src: CString; Base: CInteger): CInteger; external name '__gmpf_init_set_str';
function mpf_get_d (protected var Src: mpf_t): Real; external name '__gmpf_get_d';
{ Pass nil for Dest to let the function allocate memory for it }
function mpf_get_str (Dest: CString; var Exponent: mp_exp_t; Base: CInteger;
NumberOfDigits: SizeType; protected var Src: mpf_t): CString; external name '__gmpf_get_str';
procedure mpf_add (var Dest: mpf_t; protected var Src1, Src2: mpf_t); external name '__gmpf_add';
procedure mpf_add_ui (var Dest: mpf_t; protected var Src1: mpf_t; Src2: MedCard); external name '__gmpf_add_ui';
procedure mpf_sub (var Dest: mpf_t; protected var Src1, Src2: mpf_t); external name '__gmpf_sub';
procedure mpf_ui_sub (var Dest: mpf_t; Src1: MedCard; protected var Src2: mpf_t); external name '__gmpf_ui_sub';
procedure mpf_sub_ui (var Dest: mpf_t; protected var Src1: mpf_t; Src2: MedCard); external name '__gmpf_sub_ui';
procedure mpf_mul (var Dest: mpf_t; protected var Src1, Src2: mpf_t); external name '__gmpf_mul';
procedure mpf_mul_ui (var Dest: mpf_t; protected var Src1: mpf_t; Src2: MedCard); external name '__gmpf_mul_ui';
procedure mpf_div (var Dest: mpf_t; protected var Src1, Src2: mpf_t); external name '__gmpf_div';
procedure mpf_ui_div (var Dest: mpf_t; Src1: MedCard; protected var Src2: mpf_t); external name '__gmpf_ui_div';
procedure mpf_div_ui (var Dest: mpf_t; protected var Src1: mpf_t; Src2: MedCard); external name '__gmpf_div_ui';
procedure mpf_sqrt (var Dest: mpf_t; protected var Src: mpf_t); external name '__gmpf_sqrt';
procedure mpf_sqrt_ui (var Dest: mpf_t; Src: MedCard); external name '__gmpf_sqrt_ui';
procedure mpf_neg (var Dest: mpf_t; protected var Src: mpf_t); external name '__gmpf_neg';
procedure mpf_abs (var Dest: mpf_t; protected var Src: mpf_t); external name '__gmpf_abs';
procedure mpf_mul_2exp (var Dest: mpf_t; protected var Src1: mpf_t; Src2: MedCard); external name '__gmpf_mul_2exp';
procedure mpf_div_2exp (var Dest: mpf_t; protected var Src1: mpf_t; Src2: MedCard); external name '__gmpf_div_2exp';
function mpf_cmp (protected var Src1, Src2: mpf_t): CInteger; external name '__gmpf_cmp';
function mpf_cmp_si (protected var Src1: mpf_t; Src2: MedInt): CInteger; external name '__gmpf_cmp_si';
function mpf_cmp_ui (protected var Src1: mpf_t; Src2: MedCard): CInteger; external name '__gmpf_cmp_ui';
function mpf_eq (protected var Src1, Src2: mpf_t; NumberOfBits: MedCard): CInteger; external name '__gmpf_eq';
procedure mpf_reldiff (var Dest: mpf_t; protected var Src1, Src2: mpf_t); external name '__gmpf_reldiff';
function mpf_sgn (protected var Src: mpf_t): CInteger; attribute (inline);
procedure mpf_random2 (var Dest: mpf_t; MaxSize: mp_size_t; MaxExp: mp_exp_t); external name '__gmpf_random2';
{$if False} { @@ commented out because they use C file pointers }
function mpz_inp_str (var Dest: mpz_t; Src: CFilePtr; Base: CInteger): SizeType; external name '__gmpz_inp_str';
function mpz_inp_raw (var Dest: mpz_t; Src: CFilePtr): SizeType; external name '__gmpz_inp_raw';
function mpz_out_str (Dest: CFilePtr; Base: CInteger; protected var Src: mpz_t): SizeType; external name '__gmpz_out_str';
function mpz_out_raw (Dest: CFilePtr; protected var Src: mpz_t): SizeType ; external name '__gmpz_out_raw';
{ @@ mpf_out_str has a bug in GMP 2.0.2: it writes a spurious #0 before the exponent for negative numbers }
function mpf_out_str (Dest: CFilePtr; Base: CInteger; NumberOfDigits: SizeType; protected var Src: mpf_t): SizeType; external name '__gmpf_out_str';
function mpf_inp_str (var Dest: mpf_t; Src: CFilePtr; Base: CInteger): SizeType; external name '__gmpf_inp_str';
{$endif}
{ Available random number generation algorithms. }
type
gmp_randalg_t = (GMPRandAlgLC { Linear congruential. });
const
GMPRandAlgDefault = GMPRandAlgLC;
{ Linear congruential data struct. }
type
gmp_randata_lc = record
a: mpz_t; { Multiplier. }
c: MedCard; { Adder. }
m: mpz_t; { Modulus (valid only if M2Exp = 0). }
M2Exp: MedCard; { If <> 0, modulus is 2 ^ M2Exp. }
end;
type
gmp_randstate_t = record
Seed: mpz_t; { Current seed. }
Alg: gmp_randalg_t; { Algorithm used. }
AlgData: record { Algorithm specific data. }
case gmp_randalg_t of
GMPRandAlgLC: (lc: ^gmp_randata_lc) { Linear congruential. }
end
end;
procedure gmp_randinit (var State: gmp_randstate_t; Alg: gmp_randalg_t; ...); external name '__gmp_randinit';
procedure gmp_randinit_lc (var State: gmp_randstate_t; {$ifdef HAVE_GMP4} protected var {$endif} a: mpz_t; c: MedCard; {$ifdef HAVE_GMP4} protected var {$endif} m: mpz_t); external name '__gmp_randinit_lc';
procedure gmp_randinit_lc_2exp (var State: gmp_randstate_t; {$ifdef HAVE_GMP4} protected var {$endif} a: mpz_t; c: MedCard; M2Exp: MedCard); external name '__gmp_randinit_lc_2exp';
procedure gmp_randseed (var State: gmp_randstate_t; Seed: mpz_t); external name '__gmp_randseed';
procedure gmp_randseed_ui (var State: gmp_randstate_t; Seed: MedCard); external name '__gmp_randseed_ui';
procedure gmp_randclear (var State: gmp_randstate_t); external name '__gmp_randclear';
procedure mpz_addmul_ui (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard); external name '__gmpz_addmul_ui';
procedure mpz_bin_ui (var Dest: mpz_t; protected var Src1: mpz_t; Src2: MedCard); external name '__gmpz_bin_ui';
procedure mpz_bin_uiui (var Dest: mpz_t; Src1, Src2: MedCard); external name '__gmpz_bin_uiui';
function mpz_cmpabs (protected var Src1, Src2: mpz_t): CInteger; external name '__gmpz_cmpabs';
function mpz_cmpabs_ui (protected var Src1: mpz_t; Src2: MedCard): CInteger; external name '__gmpz_cmpabs_ui';
procedure mpz_dump (protected var Src: mpz_t); external name '__gmpz_dump';
procedure mpz_fib_ui (var Dest: mpz_t; Src: MedCard); external name '__gmpz_fib_ui';
function mpz_fits_sint_p (protected var Src: mpz_t): CInteger; external name '__gmpz_fits_sint_p';
function mpz_fits_slong_p (protected var Src: mpz_t): CInteger; external name '__gmpz_fits_slong_p';
function mpz_fits_sshort_p (protected var Src: mpz_t): CInteger; external name '__gmpz_fits_sshort_p';
function mpz_fits_uint_p (protected var Src: mpz_t): CInteger; external name '__gmpz_fits_uint_p';
function mpz_fits_ulong_p (protected var Src: mpz_t): CInteger; external name '__gmpz_fits_ulong_p';
function mpz_fits_ushort_p (protected var Src: mpz_t): CInteger; external name '__gmpz_fits_ushort_p';
procedure mpz_lcm (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_lcm';
procedure mpz_nextprime (var Dest: mpz_t; protected var Src: mpz_t); external name '__gmpz_nextprime';
function mpz_perfect_power_p (protected var Src: mpz_t): CInteger; external name '__gmpz_perfect_power_p';
function mpz_remove (var Dest: mpz_t; protected var Src1, Src2: mpz_t): MedCard; external name '__gmpz_remove';
function mpz_root (var Dest: mpz_t; protected var Src: mpz_t; n: MedCard): CInteger; external name '__gmpz_root';
procedure mpz_rrandomb (var ROP: mpz_t; var State: gmp_randstate_t; n: MedCard); external name '__gmpz_rrandomb';
procedure mpz_swap (var v1, v2: mpz_t); external name '__gmpz_swap';
function mpz_tdiv_ui (protected var Src1: mpz_t; Src2: MedCard): MedCard; external name '__gmpz_tdiv_ui';
function mpz_tstbit (protected var Src1: mpz_t; Src2: MedCard): CInteger; external name '__gmpz_tstbit';
procedure mpz_urandomb ({$ifdef HAVE_GMP4} var {$endif} ROP: mpz_t; var State: gmp_randstate_t; n: MedCard); external name '__gmpz_urandomb';
procedure mpz_urandomm ({$ifdef HAVE_GMP4} var {$endif} ROP: mpz_t; var State: gmp_randstate_t; {$ifdef HAVE_GMP4} protected var {$endif} n: mpz_t); external name '__gmpz_urandomm';
procedure mpz_xor (var Dest: mpz_t; protected var Src1, Src2: mpz_t); external name '__gmpz_xor';
procedure mpq_set_d (var Dest: mpq_t; Src: Real); external name '__gmpq_set_d';
procedure mpf_ceil (var Dest: mpf_t; protected var Src: mpf_t); external name '__gmpf_ceil';
procedure mpf_floor (var Dest: mpf_t; protected var Src: mpf_t); external name '__gmpf_floor';
{$ifdef HAVE_GMP4}
function mpf_get_si (protected var Src: mpf_t): MedInt; external name '__gmpf_get_si';
function mpf_get_ui (protected var Src: mpf_t): MedCard; external name '__gmpf_get_ui';
function mpf_get_d_2exp (var Exp: MedInt; protected var Src: mpf_t): Real; external name '__gmpf_get_d_2exp';
{$endif}
procedure mpf_pow_ui (var Dest: mpf_t; protected var Src1: mpf_t; Src2: MedCard); external name '__gmpf_pow_ui';
procedure mpf_trunc (var Dest: mpf_t; protected var Src: mpf_t); external name '__gmpf_trunc';
procedure mpf_urandomb (ROP: mpf_t; var State: gmp_randstate_t; n: MedCard); external name '__gmpf_urandomb';
const
GMPErrorNone = 0;
GMPErrorUnsupportedArgument = 1;
GMPErrorDivisionByZero = 2;
GMPErrorSqrtOfNegative = 4;
GMPErrorInvalidArgument = 8;
GMPErrorAllocate = 16;
var
gmp_errno: CInteger; external name '__gmp_errno';
{ Extensions to the GMP library, implemented in this unit }
procedure mpf_exp (var Dest: mpf_t; protected var Src: mpf_t);
procedure mpf_ln (var Dest: mpf_t; protected var Src: mpf_t);
procedure mpf_pow (var Dest: mpf_t; protected var Src1, Src2: mpf_t);
procedure mpf_sin (var Dest: mpf_t; protected var Src: mpf_t);
procedure mpf_cos (var Dest: mpf_t; protected var Src: mpf_t);
procedure mpf_arctan (var Dest: mpf_t; protected var Src: mpf_t);
procedure mpf_pi (var Dest: mpf_t);
implementation
{$L gmp}
{ @@ Should rather be inline and in the interface }
function mpz_sgn (protected var Src: mpz_t): CInteger;
begin
if Src.mp_size < 0 then
mpz_sgn := -1
else if Src.mp_size > 0 then
mpz_sgn := 1
else
mpz_sgn := 0
end;
function mpq_sgn (protected var Src: mpq_t): CInteger;
begin
if Src.mp_num.mp_size < 0 then
mpq_sgn := -1
else if Src.mp_num.mp_size > 0 then
mpq_sgn := 1
else
mpq_sgn := 0
end;
function mpf_sgn (protected var Src: mpf_t) : CInteger;
begin
if Src.mp_size < 0 then
mpf_sgn := -1
else if Src.mp_size > 0 then
mpf_sgn := 1
else
mpf_sgn := 0
end;
{$ifndef HAVE_GMP4}
function GetExp (protected var x: mpf_t) = Exp: mp_exp_t; attribute (inline);
{ @@ This is a kludge, but how to get the exponent (of base 2) in a better way? }
begin
Dispose (mpf_get_str (nil, Exp, 2, 0, x))
end;
{$else}
function GetExp (protected var x: mpf_t) = Exp: MedInt; attribute (inline);
begin
Discard (mpf_get_d_2exp (Exp, x))
end;
{$endif}
procedure mpf_exp (var Dest: mpf_t; protected var Src: mpf_t);
{ $$ \exp x = \sum_{n = 0}^{\infty} \frac{x^n}{n!} $$
The series is used for $x \in [0, 1]$, other values of $x$ are scaled. }
var
y, s, c0: mpf_t;
Precision, n: MedCard;
Exp, i: mp_exp_t;
Negative: Boolean;
begin
Precision := mpf_get_prec (Dest);
mpf_init2 (y, Precision);
mpf_set (y, Src);
mpf_set_ui (Dest, 1);
Negative := mpf_sgn (y) < 0;
if Negative then mpf_neg (y, y);
Exp := GetExp (y);
if Exp > 0 then mpf_div_2exp (y, y, Exp);
mpf_init2 (c0, Precision);
mpf_init2 (s, Precision);
mpf_set_ui (s, 1);
n := 1;
repeat
mpf_mul (s, s, y);
mpf_div_ui (s, s, n);
mpf_set (c0, Dest);
mpf_add (Dest, Dest, s);
Inc (n)
until mpf_eq (c0, Dest, Precision) <> 0;
for i := 1 to Exp do mpf_mul (Dest, Dest, Dest);
if Negative then mpf_ui_div (Dest, 1, Dest);
mpf_clear (s);
mpf_clear (c0);
mpf_clear (y)
end;
procedure mpf_ln (var Dest: mpf_t; protected var Src: mpf_t);
{ $$ \ln x = \sum_{n = 1}^{\infty} - \frac{(1-x)^n}{n}, \quad x \in ]0, 2] \Rightarrow $$
$$ \ln 2^i y = -i \ln \frac{1}{2} + \sum_{n = 1}^{\infty} - \frac{(1-y)^n}{n},
\quad y \in \left[ \frac{1}{2}, 1 \right], i \in \mathbf{Z} $$ }
var
y, s, p, c0, Half: mpf_t;
LnHalf: mpf_t; attribute (static);
LnHalfInited: Boolean = False; attribute (static);
n, Precision: MedCard;
Exp: mp_exp_t;
begin
if mpf_sgn (Src) <= 0 then
begin
Discard (Ln (0)); { Generate an error }
Exit
end;
Precision := mpf_get_prec (Dest);
mpf_init2 (y, Precision);
mpf_set (y, Src);
mpf_set_ui (Dest, 0);
Exp := GetExp (y);
if Exp <> 0 then
begin
if not LnHalfInited or (mpf_get_prec (LnHalf) < Precision) then
begin
if LnHalfInited then mpf_clear (LnHalf);
LnHalfInited := True;
mpf_init2 (LnHalf, Precision);
mpf_init2 (Half, Precision);
mpf_set_d (Half, 0.5);
mpf_ln (LnHalf, Half);
mpf_clear (Half)
end;
mpf_set (Dest, LnHalf);
mpf_mul_ui (Dest, Dest, Abs (Exp));
if Exp > 0 then
begin
mpf_neg (Dest, Dest);
mpf_div_2exp (y, y, Exp)
end
else
mpf_mul_2exp (y, y, - Exp)
end;
mpf_ui_sub (y, 1, y);
mpf_init2 (c0, Precision);
mpf_init2 (s, Precision);
mpf_init2 (p, Precision);
mpf_set_si (p, -1);
n := 1;
repeat
mpf_mul (p, p, y);
mpf_div_ui (s, p, n);
mpf_set (c0, Dest);
mpf_add (Dest, Dest, s);
Inc (n)
until mpf_eq (c0, Dest, Precision) <> 0;
mpf_clear (p);
mpf_clear (s);
mpf_clear (c0);
mpf_clear (y)
end;
procedure mpf_pow (var Dest: mpf_t; protected var Src1, Src2: mpf_t);
var Temp: mpf_t;
begin
mpf_init2 (Temp, mpf_get_prec (Src1));
mpf_ln (Temp, Src1);
mpf_mul (Temp, Temp, Src2);
mpf_exp (Dest, Temp);
mpf_clear (Temp)
end;
procedure mpf_sin (var Dest: mpf_t; protected var Src: mpf_t);
{ $$ \sin x = \sum_{n = 0}^{\infty} (-1)^n \frac{x^{2n+1}}{(2n+1)!} $$
after reduction to range $[0, \pi/2[$ }
var
Precision, Quadrant, n: MedCard;
Sign: CInteger;
a, b, z, xx, c0: mpf_t;
begin
Precision := mpf_get_prec (Dest);
mpf_init2 (a, Precision);
mpf_init2 (b, Precision);
mpf_init2 (z, Precision);
mpf_init2 (xx, Precision);
mpf_init2 (c0, Precision);
Sign := mpf_sgn (Src);
mpf_abs (xx, Src);
mpf_pi (z);
mpf_div_2exp (z, z, 1);
mpf_div (a, xx, z);
mpf_floor (xx, a);
if mpf_cmp_ui (xx, 4) >= 0 then
begin
mpf_div_2exp (b, xx, 2);
mpf_floor (b, b);
mpf_mul_2exp (b, b, 2);
mpf_sub (b, xx, b)
end
else
mpf_set (b, xx);
{$ifdef HAVE_GMP4}
Quadrant := mpf_get_ui (b);
{$else}
Quadrant := Round (mpf_get_d (b));
{$endif}
mpf_sub (b, a, xx);
mpf_mul (xx, z, b);
if Quadrant > 1 then
Sign := -Sign;
if Odd (Quadrant) then
mpf_sub (xx, z, xx);
mpf_mul (z, xx, xx);
mpf_neg (z, z);
n := 1;
mpf_set_ui (b, 1);
mpf_set_ui (Dest, 1);
repeat
Inc (n);
mpf_div_ui (b, b, n);
Inc (n);
mpf_div_ui (b, b, n);
mpf_mul (b, b, z);
mpf_set (c0, Dest);
mpf_add (Dest, Dest, b)
until mpf_eq (c0, Dest, Precision) <> 0;
mpf_mul (Dest, Dest, xx);
if Sign < 0 then
mpf_neg (Dest, Dest);
mpf_clear (a);
mpf_clear (b);
mpf_clear (z);
mpf_clear (xx);
mpf_clear (c0)
end;
procedure mpf_cos (var Dest: mpf_t; protected var Src: mpf_t);
var Temp: mpf_t;
begin
mpf_init2 (Temp, mpf_get_prec (Dest));
mpf_pi (Temp);
mpf_div_2exp (Temp, Temp, 1);
mpf_sub (Temp, Temp, Src);
mpf_sin (Dest, Temp);
mpf_clear (Temp)
end;
procedure mpf_arctan (var Dest: mpf_t; protected var Src: mpf_t);
{ $$\arctan x = \sum_{n=0}^{\infty} (-1)^n \frac{x^{2n+1}}{2n+1}$$
after double range reduction
around $\tan(3\pi/8) = \sqrt{2}+1$ with $\arctan x = \pi/2+\arctan(-1/x)$
around $\tan(\pi/8) = \sqrt{2}-1$ with $\arctan x = \pi/4+\arctan((x-1)/(x+1))$ }
var
Precision, n: MedCard;
xx, mx2, a, b: mpf_t;
SqRtTwo: mpf_t; attribute (static);
SqRtTwoInited: Boolean = False; attribute (static);
begin
Precision := mpf_get_prec (Dest);
mpf_init2 (xx, Precision);
mpf_init2 (mx2, Precision);
mpf_init2 (a, Precision);
mpf_init2 (b, Precision);
mpf_abs (xx, Src);
if not SqRtTwoInited or (mpf_get_prec (SqRtTwo) < Precision) then
begin
if SqRtTwoInited then mpf_clear (SqRtTwo);
SqRtTwoInited := True;
mpf_init2 (SqRtTwo, Precision);
mpf_sqrt_ui (SqRtTwo, 2)
end;
mpf_add_ui (a, SqRtTwo, 1);
if mpf_cmp (xx, a) > 0 then
begin
mpf_pi (Dest);
mpf_div_2exp (Dest, Dest, 1);
mpf_ui_div (xx, 1, xx);
mpf_neg (xx, xx)
end
else
begin
mpf_sub_ui (b, SqRtTwo, 1);
if mpf_cmp (xx, b) > 0 then
begin
mpf_pi (Dest);
mpf_div_2exp (Dest, Dest, 2);
mpf_sub_ui (a, xx, 1);
mpf_add_ui (b, xx, 1);
mpf_div (xx, a, b)
end
else
mpf_set_ui (Dest, 0)
end;
mpf_mul (mx2, xx, xx);
mpf_neg (mx2, mx2);
mpf_add (Dest, Dest, xx);
n := 1;
repeat
mpf_mul (xx, xx, mx2);
mpf_div_ui (a, xx, 2 * n + 1);
mpf_set (b, Dest);
mpf_add (Dest, Dest, a);
Inc (n)
until mpf_eq (b, Dest, Precision) <> 0;
if mpf_sgn (Src) < 0 then
mpf_neg (Dest, Dest);
mpf_clear (xx);
mpf_clear (mx2);
mpf_clear (a);
mpf_clear (b)
end;
procedure mpf_pi (var Dest: mpf_t);
{ 4 arctan 1/5 - arctan 1/239 = pi/4 }
var
b: mpf_t;
Precision: MedCard;
Pi: mpf_t; attribute (static);
PiInited: Boolean = False; attribute (static);
begin
Precision := mpf_get_prec (Dest);
if not PiInited or (mpf_get_prec (Pi) < Precision) then
begin
if PiInited then mpf_clear (Pi);
PiInited := True;
mpf_init2 (Pi, Precision);
mpf_set_ui (Pi, 1);
mpf_div_ui (Pi, Pi, 5);
mpf_arctan (Pi, Pi);
mpf_mul_ui (Pi, Pi, 4);
mpf_init2 (b, Precision);
mpf_set_ui (b, 1);
mpf_div_ui (b, b, 239);
mpf_arctan (b, b);
mpf_sub (Pi, Pi, b);
mpf_mul_ui (Pi, Pi, 4);
mpf_clear (b)
end;
mpf_set (Dest, Pi)
end;
end.
|
(*************************************************************************
Copyright (c) 2007, Sergey Bochkanov (ALGLIB project).
>>> SOURCE LICENSE >>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation (www.fsf.org); either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
A copy of the GNU General Public License is available at
http://www.fsf.org/licensing/licenses
>>> END OF LICENSE >>>
*************************************************************************)
unit correlationtests;
interface
uses Math, Sysutils, Ap, gammafunc, normaldistr, ibetaf, studenttdistr, correlation;
procedure PearsonCorrelationSignificance(R : AlglibFloat;
N : AlglibInteger;
var BothTails : AlglibFloat;
var LeftTail : AlglibFloat;
var RightTail : AlglibFloat);
procedure SpearmanRankCorrelationSignificance(R : AlglibFloat;
N : AlglibInteger;
var BothTails : AlglibFloat;
var LeftTail : AlglibFloat;
var RightTail : AlglibFloat);
implementation
function SpearmanTail5(S : AlglibFloat):AlglibFloat;forward;
function SpearmanTail6(S : AlglibFloat):AlglibFloat;forward;
function SpearmanTail7(S : AlglibFloat):AlglibFloat;forward;
function SpearmanTail8(S : AlglibFloat):AlglibFloat;forward;
function SpearmanTail9(S : AlglibFloat):AlglibFloat;forward;
function SpearmanTail(T : AlglibFloat; N : AlglibInteger):AlglibFloat;forward;
(*************************************************************************
Pearson's correlation coefficient significance test
This test checks hypotheses about whether X and Y are samples of two
continuous distributions having zero correlation or whether their
correlation is non-zero.
The following tests are performed:
* two-tailed test (null hypothesis - X and Y have zero correlation)
* left-tailed test (null hypothesis - the correlation coefficient is
greater than or equal to 0)
* right-tailed test (null hypothesis - the correlation coefficient is
less than or equal to 0).
Requirements:
* the number of elements in each sample is not less than 5
* normality of distributions of X and Y.
Input parameters:
R - Pearson's correlation coefficient for X and Y
N - number of elements in samples, N>=5.
Output parameters:
BothTails - p-value for two-tailed test.
If BothTails is less than the given significance level
the null hypothesis is rejected.
LeftTail - p-value for left-tailed test.
If LeftTail is less than the given significance level,
the null hypothesis is rejected.
RightTail - p-value for right-tailed test.
If RightTail is less than the given significance level
the null hypothesis is rejected.
-- ALGLIB --
Copyright 09.04.2007 by Bochkanov Sergey
*************************************************************************)
procedure PearsonCorrelationSignificance(R : AlglibFloat;
N : AlglibInteger;
var BothTails : AlglibFloat;
var LeftTail : AlglibFloat;
var RightTail : AlglibFloat);
var
T : AlglibFloat;
P : AlglibFloat;
begin
//
// Some special cases
//
if AP_FP_Greater_Eq(R,1) then
begin
BothTails := 0.0;
LeftTail := 1.0;
RightTail := 0.0;
Exit;
end;
if AP_FP_Less_Eq(R,-1) then
begin
BothTails := 0.0;
LeftTail := 0.0;
RightTail := 1.0;
Exit;
end;
if N<5 then
begin
BothTails := 1.0;
LeftTail := 1.0;
RightTail := 1.0;
Exit;
end;
//
// General case
//
T := R*Sqrt((N-2)/(1-AP_Sqr(R)));
P := StudentTDistribution(N-2, T);
BothTails := 2*Min(P, 1-P);
LeftTail := P;
RightTail := 1-P;
end;
(*************************************************************************
Spearman's rank correlation coefficient significance test
This test checks hypotheses about whether X and Y are samples of two
continuous distributions having zero correlation or whether their
correlation is non-zero.
The following tests are performed:
* two-tailed test (null hypothesis - X and Y have zero correlation)
* left-tailed test (null hypothesis - the correlation coefficient is
greater than or equal to 0)
* right-tailed test (null hypothesis - the correlation coefficient is
less than or equal to 0).
Requirements:
* the number of elements in each sample is not less than 5.
The test is non-parametric and doesn't require distributions X and Y to be
normal.
Input parameters:
R - Spearman's rank correlation coefficient for X and Y
N - number of elements in samples, N>=5.
Output parameters:
BothTails - p-value for two-tailed test.
If BothTails is less than the given significance level
the null hypothesis is rejected.
LeftTail - p-value for left-tailed test.
If LeftTail is less than the given significance level,
the null hypothesis is rejected.
RightTail - p-value for right-tailed test.
If RightTail is less than the given significance level
the null hypothesis is rejected.
-- ALGLIB --
Copyright 09.04.2007 by Bochkanov Sergey
*************************************************************************)
procedure SpearmanRankCorrelationSignificance(R : AlglibFloat;
N : AlglibInteger;
var BothTails : AlglibFloat;
var LeftTail : AlglibFloat;
var RightTail : AlglibFloat);
var
T : AlglibFloat;
P : AlglibFloat;
begin
//
// Special case
//
if N<5 then
begin
BothTails := 1.0;
LeftTail := 1.0;
RightTail := 1.0;
Exit;
end;
//
// General case
//
if AP_FP_Greater_Eq(R,1) then
begin
T := 1.0E10;
end
else
begin
if AP_FP_Less_Eq(R,-1) then
begin
T := -1.0E10;
end
else
begin
T := R*Sqrt((N-2)/(1-AP_Sqr(R)));
end;
end;
if AP_FP_Less(T,0) then
begin
P := SpearmanTail(T, N);
BothTails := 2*P;
LeftTail := P;
RightTail := 1-P;
end
else
begin
P := SpearmanTail(-T, N);
BothTails := 2*P;
LeftTail := 1-P;
RightTail := P;
end;
end;
(*************************************************************************
Tail(S, 5)
*************************************************************************)
function SpearmanTail5(S : AlglibFloat):AlglibFloat;
begin
if AP_FP_Less(S,0.000e+00) then
begin
Result := StudentTDistribution(3, -S);
Exit;
end;
if AP_FP_Greater_Eq(S,3.580e+00) then
begin
Result := 8.304e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,2.322e+00) then
begin
Result := 4.163e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,1.704e+00) then
begin
Result := 6.641e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,1.303e+00) then
begin
Result := 1.164e-01;
Exit;
end;
if AP_FP_Greater_Eq(S,1.003e+00) then
begin
Result := 1.748e-01;
Exit;
end;
if AP_FP_Greater_Eq(S,7.584e-01) then
begin
Result := 2.249e-01;
Exit;
end;
if AP_FP_Greater_Eq(S,5.468e-01) then
begin
Result := 2.581e-01;
Exit;
end;
if AP_FP_Greater_Eq(S,3.555e-01) then
begin
Result := 3.413e-01;
Exit;
end;
if AP_FP_Greater_Eq(S,1.759e-01) then
begin
Result := 3.911e-01;
Exit;
end;
if AP_FP_Greater_Eq(S,1.741e-03) then
begin
Result := 4.747e-01;
Exit;
end;
if AP_FP_Greater_Eq(S,0.000e+00) then
begin
Result := 5.248e-01;
Exit;
end;
Result := 0;
end;
(*************************************************************************
Tail(S, 6)
*************************************************************************)
function SpearmanTail6(S : AlglibFloat):AlglibFloat;
begin
if AP_FP_Less(S,1.001e+00) then
begin
Result := StudentTDistribution(4, -S);
Exit;
end;
if AP_FP_Greater_Eq(S,5.663e+00) then
begin
Result := 1.366e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,3.834e+00) then
begin
Result := 8.350e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,2.968e+00) then
begin
Result := 1.668e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.430e+00) then
begin
Result := 2.921e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.045e+00) then
begin
Result := 5.144e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,1.747e+00) then
begin
Result := 6.797e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,1.502e+00) then
begin
Result := 8.752e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,1.295e+00) then
begin
Result := 1.210e-01;
Exit;
end;
if AP_FP_Greater_Eq(S,1.113e+00) then
begin
Result := 1.487e-01;
Exit;
end;
if AP_FP_Greater_Eq(S,1.001e+00) then
begin
Result := 1.780e-01;
Exit;
end;
Result := 0;
end;
(*************************************************************************
Tail(S, 7)
*************************************************************************)
function SpearmanTail7(S : AlglibFloat):AlglibFloat;
begin
if AP_FP_Less(S,1.001e+00) then
begin
Result := StudentTDistribution(5, -S);
Exit;
end;
if AP_FP_Greater_Eq(S,8.159e+00) then
begin
Result := 2.081e-04;
Exit;
end;
if AP_FP_Greater_Eq(S,5.620e+00) then
begin
Result := 1.393e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,4.445e+00) then
begin
Result := 3.398e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,3.728e+00) then
begin
Result := 6.187e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,3.226e+00) then
begin
Result := 1.200e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.844e+00) then
begin
Result := 1.712e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.539e+00) then
begin
Result := 2.408e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.285e+00) then
begin
Result := 3.320e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.068e+00) then
begin
Result := 4.406e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,1.879e+00) then
begin
Result := 5.478e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,1.710e+00) then
begin
Result := 6.946e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,1.559e+00) then
begin
Result := 8.331e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,1.420e+00) then
begin
Result := 1.001e-01;
Exit;
end;
if AP_FP_Greater_Eq(S,1.292e+00) then
begin
Result := 1.180e-01;
Exit;
end;
if AP_FP_Greater_Eq(S,1.173e+00) then
begin
Result := 1.335e-01;
Exit;
end;
if AP_FP_Greater_Eq(S,1.062e+00) then
begin
Result := 1.513e-01;
Exit;
end;
if AP_FP_Greater_Eq(S,1.001e+00) then
begin
Result := 1.770e-01;
Exit;
end;
Result := 0;
end;
(*************************************************************************
Tail(S, 8)
*************************************************************************)
function SpearmanTail8(S : AlglibFloat):AlglibFloat;
begin
if AP_FP_Less(S,2.001e+00) then
begin
Result := StudentTDistribution(6, -S);
Exit;
end;
if AP_FP_Greater_Eq(S,1.103e+01) then
begin
Result := 2.194e-05;
Exit;
end;
if AP_FP_Greater_Eq(S,7.685e+00) then
begin
Result := 2.008e-04;
Exit;
end;
if AP_FP_Greater_Eq(S,6.143e+00) then
begin
Result := 5.686e-04;
Exit;
end;
if AP_FP_Greater_Eq(S,5.213e+00) then
begin
Result := 1.138e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,4.567e+00) then
begin
Result := 2.310e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,4.081e+00) then
begin
Result := 3.634e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,3.697e+00) then
begin
Result := 5.369e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,3.381e+00) then
begin
Result := 7.708e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,3.114e+00) then
begin
Result := 1.087e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.884e+00) then
begin
Result := 1.397e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.682e+00) then
begin
Result := 1.838e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.502e+00) then
begin
Result := 2.288e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.340e+00) then
begin
Result := 2.883e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.192e+00) then
begin
Result := 3.469e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.057e+00) then
begin
Result := 4.144e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.001e+00) then
begin
Result := 4.804e-02;
Exit;
end;
Result := 0;
end;
(*************************************************************************
Tail(S, 9)
*************************************************************************)
function SpearmanTail9(S : AlglibFloat):AlglibFloat;
begin
if AP_FP_Less(S,2.001e+00) then
begin
Result := StudentTDistribution(7, -S);
Exit;
end;
if AP_FP_Greater_Eq(S,9.989e+00) then
begin
Result := 2.306e-05;
Exit;
end;
if AP_FP_Greater_Eq(S,8.069e+00) then
begin
Result := 8.167e-05;
Exit;
end;
if AP_FP_Greater_Eq(S,6.890e+00) then
begin
Result := 1.744e-04;
Exit;
end;
if AP_FP_Greater_Eq(S,6.077e+00) then
begin
Result := 3.625e-04;
Exit;
end;
if AP_FP_Greater_Eq(S,5.469e+00) then
begin
Result := 6.450e-04;
Exit;
end;
if AP_FP_Greater_Eq(S,4.991e+00) then
begin
Result := 1.001e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,4.600e+00) then
begin
Result := 1.514e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,4.272e+00) then
begin
Result := 2.213e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,3.991e+00) then
begin
Result := 2.990e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,3.746e+00) then
begin
Result := 4.101e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,3.530e+00) then
begin
Result := 5.355e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,3.336e+00) then
begin
Result := 6.887e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,3.161e+00) then
begin
Result := 8.598e-03;
Exit;
end;
if AP_FP_Greater_Eq(S,3.002e+00) then
begin
Result := 1.065e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.855e+00) then
begin
Result := 1.268e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.720e+00) then
begin
Result := 1.552e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.595e+00) then
begin
Result := 1.836e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.477e+00) then
begin
Result := 2.158e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.368e+00) then
begin
Result := 2.512e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.264e+00) then
begin
Result := 2.942e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.166e+00) then
begin
Result := 3.325e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.073e+00) then
begin
Result := 3.800e-02;
Exit;
end;
if AP_FP_Greater_Eq(S,2.001e+00) then
begin
Result := 4.285e-02;
Exit;
end;
Result := 0;
end;
(*************************************************************************
Tail(T,N), accepts T<0
*************************************************************************)
function SpearmanTail(T : AlglibFloat; N : AlglibInteger):AlglibFloat;
begin
if N=5 then
begin
Result := SpearmanTail5(-T);
Exit;
end;
if N=6 then
begin
Result := SpearmanTail6(-T);
Exit;
end;
if N=7 then
begin
Result := SpearmanTail7(-T);
Exit;
end;
if N=8 then
begin
Result := SpearmanTail8(-T);
Exit;
end;
if N=9 then
begin
Result := SpearmanTail9(-T);
Exit;
end;
Result := StudentTDistribution(N-2, T);
end;
end. |
program GameShow;
CONST
Trials = 10000;
Switch = TRUE {switch picked door when offered? };
DoorCount = 3;
TYPE
DoorSet = Set Of 0..DoorCount;
VAR
DoorWithPrize,
DoorPicked,
NewDoorPicked,
i,j, WinCount : WORD;
DoorsLeft : DoorSet;
Done : BOOLEAN;
BEGIN
Randomize;
WinCount := 0;
FOR i := 1 to Trials DO
BEGIN
{ what doors can be chosen ? }
DoorsLeft := [1,2,3];
{ hide the prize behind a door }
DoorWithPrize := Random(DoorCount)+1;
{ contestant picks a door }
DoorPicked := Random(DoorCount)+1;
DoorsLeft := DoorsLeft - [DoorPicked];
IF Switch THEN
BEGIN
{ host opens door without prize and not picked}
Done := FALSE;
j := 0;
REPEAT
inc(j);
IF NOT (j= DoorPicked) AND NOT (j = DoorWithPrize) THEN
BEGIN
DoorsLeft := DoorsLeft - [j];
Done := TRUE;
END;
UNTIL Done;
{ host lets contestant switch }
DoorPicked := 1;
WHILE NOT (DoorPicked IN DoorsLeft) DO
INC(DoorPicked);
END {SWITCH};
{ Does contestant win? }
IF DoorPicked = DoorWithPrize THEN
INC(WinCount);
END {trial};
Writeln(WinCount:5);
END. |
unit ACorrigeNotasSpedFiscal;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, StdCtrls, Buttons,
Componentes1, ExtCtrls, PainelGradiente, UnSpedfiscal, ComCtrls, UnDados, Localizacao,
Mask, numericos;
type
TFCorrigeNotasSpedFiscal = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
PanelColor2: TPanelColor;
BCorrigir: TBitBtn;
BFechar: TBitBtn;
StatusBar1: TStatusBar;
Label1: TLabel;
Label2: TLabel;
SpeedButton1: TSpeedButton;
Label3: TLabel;
Label4: TLabel;
EDatInicio: TCalendario;
EDatFim: TCalendario;
ECodFilial: TEditLocaliza;
Bevel1: TBevel;
Label5: TLabel;
Label6: TLabel;
Bevel2: TBevel;
CRecalcularICMSeST: TCheckBox;
CLimparIPI: TCheckBox;
CBaseCalculoProdutosNotaEntrada: TCheckBox;
Label7: TLabel;
ENota: Tnumerico;
CBaseCalculoNotaSaida: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure BCorrigirClick(Sender: TObject);
private
{ Private declarations }
VprDSpedFiscal : TRBDSpedFiscal;
FunSpedFiscal : TRBFuncoesSpedFiscal;
procedure CarDClasse;
procedure CarDTela;
public
{ Public declarations }
procedure CorrigeNotas(VpaDSpedFiscal:TRBDSpedFiscal);
end;
var
FCorrigeNotasSpedFiscal: TFCorrigeNotasSpedFiscal;
implementation
uses APrincipal;
{$R *.DFM}
{ **************************************************************************** }
procedure TFCorrigeNotasSpedFiscal.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
FunSpedFiscal := TRBFuncoesSpedFiscal.cria(FPrincipal.BaseDados);
end;
{ *************************************************************************** }
procedure TFCorrigeNotasSpedFiscal.BCorrigirClick(Sender: TObject);
begin
CarDClasse;
if CRecalcularICMSeST.Checked then
FunSpedFiscal.CorrigeNotasValICMSeST(VprDSpedFiscal,StatusBar1);
if CLimparIPI.Checked then
FunSpedFiscal.CorrigeNotaLimpaIPI(VprDSpedFiscal,StatusBar1);
if CBaseCalculoProdutosNotaEntrada.Checked then
FunSpedFiscal.CorrigeBaseCalculoNotaEntrada(VprDSpedFiscal,StatusBar1);
if CBaseCalculoNotaSaida.Checked then
FunSpedFiscal.CorrigeBaseCalculoNotaSaida(VprDSpedFiscal,StatusBar1);
end;
{******************************************************************************}
procedure TFCorrigeNotasSpedFiscal.BFecharClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFCorrigeNotasSpedFiscal.CarDClasse;
begin
VprDSpedFiscal.DatInicio := EDatInicio.Date;
VprDSpedFiscal.NumNota := ENota.AsInteger;
end;
{******************************************************************************}
procedure TFCorrigeNotasSpedFiscal.CarDTela;
begin
ECodFilial.AInteiro := VprDSpedFiscal.CodFilial;
ECodFilial.Atualiza;
EDatInicio.Date := VprDSpedFiscal.DatInicio;
EDatFim.Date := VprDSpedFiscal.DatFinal;
end;
procedure TFCorrigeNotasSpedFiscal.CorrigeNotas(VpaDSpedFiscal: TRBDSpedFiscal);
begin
VprDSpedFiscal := VpaDSpedFiscal;
CarDTela;
ShowModal;
end;
{******************************************************************************}
procedure TFCorrigeNotasSpedFiscal.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
FunSpedFiscal.Free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFCorrigeNotasSpedFiscal]);
end.
|
{*******************************************************}
{ }
{ Delphi VCL Extensions (RX) }
{ }
{ Copyright (c) 1995, 1996 AO ROSNO }
{ Copyright (c) 1997 Master-Bank }
{ }
{*******************************************************}
unit rxDBIndex;
interface
{$I RX.INC}
uses
SysUtils, Windows, Messages, Classes, Controls, Forms,
Graphics, Menus, StdCtrls, ExtCtrls, DB, DBTables;
type
TIdxDisplayMode = (dmFieldLabels, dmFieldNames, dmIndexName);
{ TDBIndexCombo }
TDBIndexCombo = class(TCustomComboBox)
private
FDataLink: TDataLink;
FUpdate: Boolean;
{$IFDEF RX_D4} // Polaris
FNoIndexItem: String;
{$ELSE}
FNoIndexItem: PString;
{$ENDIF}
FEnableNoIndex: Boolean;
FChanging: Boolean;
FDisplayMode: TIdxDisplayMode;
function GetDataSource: TDataSource;
procedure SetDataSource(Value: TDataSource);
function GetIndexFieldName(var AName: string): Boolean;
procedure SetNoIndexItem(const Value: string);
function GetNoIndexItem: string;
procedure SetEnableNoIndex(Value: Boolean);
procedure SetDisplayMode(Value: TIdxDisplayMode);
procedure ActiveChanged;
procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
protected
procedure Loaded; override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure FillIndexList(List: TStrings);
procedure Change; override;
procedure UpdateList; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ published properties }
property DataSource: TDataSource read GetDataSource write SetDataSource;
property NoIndexItem: string read GetNoIndexItem write SetNoIndexItem;
property EnableNoIndex: Boolean read FEnableNoIndex write SetEnableNoIndex default False;
property DisplayMode: TIdxDisplayMode read FDisplayMode write SetDisplayMode default dmFieldLabels;
property DragCursor;
property DragMode;
property Enabled;
property Color;
property Ctl3D;
property DropDownCount;
property Font;
{$IFDEF RX_D4}
property Anchors;
property BiDiMode;
property Constraints;
property DragKind;
property ParentBiDiMode;
{$ENDIF}
{$IFNDEF VER90}
property ImeMode;
property ImeName;
{$ENDIF}
property ItemHeight;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property Sorted;
property TabOrder;
property TabStop;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
{$IFDEF RX_D5}
property OnContextPopup;
{$ENDIF}
property OnStartDrag;
{$IFDEF RX_D4}
property OnEndDock;
property OnStartDock;
{$ENDIF}
end;
implementation
uses
Bde,
DBConsts, rxStrUtils, rxDBUtils, rxBdeUtils;
{ TKeyDataLink }
type
TKeyDataLink = class(TDataLink)
private
FCombo: TDBIndexCombo;
protected
procedure ActiveChanged; override;
procedure DataSetChanged; override;
procedure DataSetScrolled(Distance: Integer); override;
public
constructor Create(ACombo: TDBIndexCombo);
destructor Destroy; override;
end;
constructor TKeyDataLink.Create(ACombo: TDBIndexCombo);
begin
inherited Create;
FCombo := ACombo;
end;
destructor TKeyDataLink.Destroy;
begin
FCombo := nil;
inherited Destroy;
end;
procedure TKeyDataLink.ActiveChanged;
begin
if FCombo <> nil then FCombo.ActiveChanged;
end;
procedure TKeyDataLink.DataSetChanged;
begin
if FCombo <> nil then FCombo.ActiveChanged;
end;
procedure TKeyDataLink.DataSetScrolled(Distance: Integer);
begin
{ ignore this data event }
end;
{ TDBIndexCombo }
constructor TDBIndexCombo.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDataLink := TKeyDataLink.Create(Self);
Style := csDropDownList;
FUpdate := False;
{$IFDEF RX_D4} // Polaris
FNoIndexItem := EmptyStr;
{$ELSE}
FNoIndexItem := NullStr;
{$ENDIF}
FEnableNoIndex := False;
end;
destructor TDBIndexCombo.Destroy;
begin
FDataLink.Free;
FDataLink := nil;
{$IFNDEF RX_D4} // Polaris
DisposeStr(FNoIndexItem);
FNoIndexItem := NullStr;
{$ENDIF}
inherited Destroy;
end;
procedure TDBIndexCombo.SetNoIndexItem(const Value: string);
begin
{$IFDEF RX_D4} // Polaris
if Value <> FNoIndexItem then begin
FNoIndexItem := Value;
{$ELSE}
if Value <> FNoIndexItem^ then begin
AssignStr(FNoIndexItem, Value);
{$ENDIF}
if not (csLoading in ComponentState) then ActiveChanged;
end;
end;
procedure TDBIndexCombo.SetEnableNoIndex(Value: Boolean);
begin
if FEnableNoIndex <> Value then begin
FEnableNoIndex := Value;
if not (csLoading in ComponentState) then ActiveChanged;
end;
end;
procedure TDBIndexCombo.SetDisplayMode(Value: TIdxDisplayMode);
begin
if (Value <> FDisplayMode) then begin
FDisplayMode := Value;
if not (csLoading in ComponentState) then UpdateList;
end;
end;
function TDBIndexCombo.GetNoIndexItem: string;
begin
{$IFDEF RX_D4} // Polaris
Result := FNoIndexItem;
{$ELSE}
Result := FNoIndexItem^;
{$ENDIF}
end;
function TDBIndexCombo.GetDataSource: TDataSource;
begin
if FDataLink <> nil then Result := FDataLink.DataSource
else Result := nil;
end;
procedure TDBIndexCombo.SetDataSource(Value: TDataSource);
begin
FDataLink.DataSource := Value;
if Value <> nil then Value.FreeNotification(Self);
if not (csLoading in ComponentState) then ActiveChanged;
end;
procedure TDBIndexCombo.ActiveChanged;
begin
if not (Enabled and FDataLink.Active and
FDataLink.DataSet.InheritsFrom(TTable)) then
begin
Clear;
ItemIndex := -1;
end
else UpdateList;
end;
procedure TDBIndexCombo.Loaded;
begin
inherited Loaded;
ActiveChanged;
end;
procedure TDBIndexCombo.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (FDataLink <> nil) and
(AComponent = DataSource) then DataSource := nil;
end;
procedure TDBIndexCombo.CMEnabledChanged(var Message: TMessage);
begin
inherited;
if not (csLoading in ComponentState) then ActiveChanged;
end;
function TDBIndexCombo.GetIndexFieldName(var AName: string): Boolean;
begin
Result := True;
if ItemIndex >= 0 then begin
if EnableNoIndex and (Items[ItemIndex] = NoIndexItem) then AName := ''
else begin
AName := TIndexDef(Items.Objects[ItemIndex]).Fields;
if AName = '' then begin
AName := TIndexDef(Items.Objects[ItemIndex]).Name;
Result := False;
end;
end;
end
else AName := '';
end;
procedure TDBIndexCombo.FillIndexList(List: TStrings);
var
AFld: string;
Pos: Integer;
I: Integer;
begin
List.Clear;
if not FDataLink.Active then Exit;
with FDataLink.DataSet as TTable do begin
for I := 0 to IndexDefs.Count - 1 do
with IndexDefs[I] do
if not (ixExpression in Options) then begin
if FDisplayMode = dmIndexName then AFld := Name
else begin
AFld := '';
Pos := 1;
while Pos <= Length(Fields) do begin
if AFld <> '' then AFld := AFld + '; ';
case FDisplayMode of
dmFieldLabels:
AFld := AFld + FieldByName(ExtractFieldName(Fields, Pos)).DisplayLabel;
dmFieldNames:
AFld := AFld + FieldByName(ExtractFieldName(Fields, Pos)).FieldName;
end;
end;
end;
if List.IndexOf(AFld) < 0 then List.AddObject(AFld, IndexDefs[I]);
end;
end;
if EnableNoIndex then
if List.IndexOf(NoIndexItem) < 0 then List.AddObject(NoIndexItem, nil);
end;
procedure TDBIndexCombo.Change;
var
ABookmark: TBookmark;
AName: string;
begin
if Enabled and FDataLink.Active and not FChanging and
FDataLink.DataSet.InheritsFrom(TTable) and
not (csLoading in ComponentState) then
begin
ABookmark := nil;
with FDataLink.DataSet as TTable do begin
if Database.IsSQLBased then ABookmark := GetBookmark;
try
if GetIndexFieldName(AName) then begin
IndexFieldNames := AName;
if (AName = '') and (IndexDefs.Count > 0) then
IndexName := '';
end
else begin
if AName = '' then IndexFieldNames := '';
IndexName := AName;
end;
if (ABookmark <> nil) then
SetToBookmark(TTable(Self.FDataLink.DataSet), ABookmark);
finally
if ABookmark <> nil then FreeBookmark(ABookmark);
end;
end;
end;
inherited Change;
end;
procedure TDBIndexCombo.UpdateList;
function FindIndex(Table: TTable): Integer;
var
I: Integer;
IdxFields: string;
begin
Result := -1;
IdxFields := '';
if Table.IndexFieldNames <> '' then
for I := 0 to Table.IndexFieldCount - 1 do begin
if IdxFields <> '' then IdxFields := IdxFields + ';';
IdxFields := IdxFields + Table.IndexFields[I].FieldName;
end;
for I := 0 to Items.Count - 1 do begin
if (Items.Objects[I] <> nil) and
(((IdxFields <> '') and
(AnsiCompareText(TIndexDef(Items.Objects[I]).Fields, IdxFields) = 0)) or
((Table.IndexName <> '') and
(AnsiCompareText(TIndexDef(Items.Objects[I]).Name, Table.IndexName) = 0))) then
begin
Result := I;
Exit;
end;
end;
if EnableNoIndex and FDataLink.Active then
if (Table.IndexFieldNames = '') and (Table.IndexName = '') then
Result := Items.IndexOf(NoIndexItem);
end;
begin
if Enabled and FDataLink.Active then
try
Items.BeginUpdate;
try
if FDataLink.DataSet.InheritsFrom(TTable) then begin
TTable(FDataLink.DataSet).IndexDefs.Update;
FillIndexList(Items);
ItemIndex := FindIndex(TTable(FDataLink.DataSet));
FChanging := True;
end
else Items.Clear;
finally
Items.EndUpdate;
end;
finally
FChanging := False;
end;
end;
end. |
{******************************************}
{ TFastLineSeries Editor Dialog }
{ Copyright (c) 1996-2004 by David Berneda }
{******************************************}
unit TeeFLineEdi;
{$I TeeDefs.inc}
interface
uses
{$IFNDEF LINUX}
Windows,
{$ENDIF}
{$IFDEF CLX}
QGraphics, QForms, QControls, QStdCtrls, QComCtrls,
{$ELSE}
Graphics, Forms, Controls, StdCtrls, ComCtrls,
{$ENDIF}
Classes, TeePenDlg, TeCanvas, Series;
type
TFastLineSeriesEditor = class(TPenDialog)
CBDrawAll: TCheckBox;
GBStair: TGroupBox;
CBStairs: TCheckBox;
CBInvStairs: TCheckBox;
CBNulls: TCheckBox;
procedure FormShow(Sender: TObject);
procedure BColorClick(Sender: TObject);
procedure CBDrawAllClick(Sender: TObject);
procedure CBStairsClick(Sender: TObject);
procedure CBInvStairsClick(Sender: TObject);
procedure CBNullsClick(Sender: TObject);
private
{ Private declarations }
FastLine : TFastLineSeries;
public
{ Public declarations }
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
procedure TFastLineSeriesEditor.FormShow(Sender: TObject);
begin
FastLine:=TFastLineSeries(Tag);
if Assigned(FastLine) then
begin
ThePen:=FastLine.Pen;
CBDrawAll.Checked:=FastLine.DrawAllPoints;
CBStairs.Checked:=FastLine.Stairs;
CBInvStairs.Checked:=FastLine.InvertedStairs;
CBInvStairs.Enabled:=CBStairs.Checked;
CBNulls.Checked:=FastLine.IgnoreNulls;
end;
inherited;
end;
procedure TFastLineSeriesEditor.BColorClick(Sender: TObject);
begin
inherited;
FastLine.SeriesColor:=ThePen.Color;
CBStyle.Repaint;
end;
procedure TFastLineSeriesEditor.CBDrawAllClick(Sender: TObject);
begin
FastLine.DrawAllPoints:=CBDrawAll.Checked;
end;
procedure TFastLineSeriesEditor.CBStairsClick(Sender: TObject);
begin
FastLine.Stairs:=CBStairs.Checked;
CBInvStairs.Enabled:=CBStairs.Checked;
end;
procedure TFastLineSeriesEditor.CBInvStairsClick(Sender: TObject);
begin
FastLine.InvertedStairs:=CBInvStairs.Checked;
end;
procedure TFastLineSeriesEditor.CBNullsClick(Sender: TObject);
begin
FastLine.IgnoreNulls:=CBNulls.Checked;
end;
initialization
RegisterClass(TFastLineSeriesEditor);
end.
|
unit ReleaseRecipientDetail;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopupDetail, RzEdit, RzBtnEdt,
Vcl.DBCtrls, RzDBCmbo, Vcl.StdCtrls, Vcl.Mask, RzDBEdit, RzButton, RzTabs,
RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, DB;
type
TfrmReleaseRecipientDetail = class(TfrmBasePopupDetail)
edAmount: TRzDBNumericEdit;
dbluMethod: TRzDBLookupComboBox;
bteRecipient: TRzButtonEdit;
dteDateReleased: TRzDBDateTimeEdit;
dbluBranch: TRzDBLookupComboBox;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
procedure FormCreate(Sender: TObject);
procedure bteRecipientButtonClick(Sender: TObject);
private
{ Private declarations }
procedure PopulateUnboundFields;
public
{ Public declarations }
protected
procedure Save; override;
procedure Cancel; override;
procedure BindToObject; override;
function ValidEntry: boolean; override;
end;
var
frmReleaseRecipientDetail: TfrmReleaseRecipientDetail;
implementation
{$R *.dfm}
uses
LoanData, LoansAuxData, FormsUtil, RecipientSearch, Recipient, ReleaseRecipient,
Loan, IFinanceDialogs;
procedure TfrmReleaseRecipientDetail.PopulateUnboundFields;
begin
with dmLoan.dstLoanRelease do
begin
if State <> dsInsert then
bteRecipient.Text := rrp.Recipient.Name;
end;
end;
procedure TfrmReleaseRecipientDetail.FormCreate(Sender: TObject);
begin
inherited;
OpenDropdownDataSources(tsDetail);
PopulateUnboundFields;
end;
procedure TfrmReleaseRecipientDetail.Save;
begin
with dmLoan.dstLoanRelease do
begin
if State in [dsInsert,dsEdit] then
begin
FieldByName('recipient').AsString := rrp.Recipient.Id;
Post;
end;
rrp.Date := dteDateReleased.Date;
rrp.LocationCode := dbluBranch.GetKeyValue;
rrp.LocationName := dbluBranch.Text;
rrp.Amount := edAmount.Value;
rrp.ReleaseMethod := TReleaseMethod.Create(dbluMethod.GetKeyValue,dbluMethod.Text);
ln.AddReleaseRecipient(rrp,true);
end;
end;
procedure TfrmReleaseRecipientDetail.BindToObject;
begin
inherited;
end;
procedure TfrmReleaseRecipientDetail.bteRecipientButtonClick(Sender: TObject);
begin
with TfrmRecipientSearch.Create(self) do
begin
try
try
rcp := TRecipient.Create;
ShowModal;
if ModalResult = mrOK then
begin
bteRecipient.Text := rcp.Name;
rrp.Recipient := rcp;
end;
except
on e: Exception do
ShowErrorBox(e.Message);
end;
finally
Free;
end;
end;
end;
procedure TfrmReleaseRecipientDetail.Cancel;
begin
with dmLoan.dstMonExp do
if State in [dsInsert,dsEdit] then
Cancel;
end;
function TfrmReleaseRecipientDetail.ValidEntry: boolean;
var
error: string;
begin
with dmLoan.dstLoanRelease do
begin
if Trim(dteDateReleased.Text) = '' then
error := 'Please enter date release.'
else if bteRecipient.Text = '' then
error := 'Please enter recipient.'
else if dbluBranch.Text = '' then
error := 'Please select a branch.'
else if dbluMethod.Text = '' then
error := 'Please select a release method.'
else if edAmount.Value <= 0 then
error := 'Invalid value for amount.'
else if (State = dsInsert) and
(ln.ReleaseRecipientExists(rrp.Recipient.Id,dbluBranch.GetKeyValue,dbluMethod.GetKeyValue)) then
error := 'Recipient and release method already exists.';
end;
Result := error = '';
if not Result then ShowErrorBox(error);
end;
end.
|
Unit ARCH_REG_Provincia;
interface
uses FUNC_REG_Provincias;
const
limite = 23;
Directorio_provincia = '.\Datos\Datos Provincias.dat';
type
ARCHIVO_Provincia = File Of REG_provincia;
procedure Cargar_todas_las_provincias_en_el_archivo_provincias(VAR ARCH_Provincia: ARCHIVO_Provincia; VAR Provincia : REG_provincia);
function tomar_y_devolver_reg_provincia_del_archivo(VAR ARCH_Provincia: ARCHIVO_Provincia; VAR Provincia : REG_provincia; POS: LongWord) : REG_provincia;
implementation
procedure Abrir_archivo_provincia_para_lectura_escritura(VAR ARCH_Provincia: ARCHIVO_Provincia);
const
Directorio = Directorio_provincia;
begin
assign(ARCH_Provincia, Directorio);
{$I-} reset(ARCH_Provincia); {$I+}
end;
procedure Guarda_Registro_Provincias(VAR ARCH_Provincia: ARCHIVO_Provincia; Provincia : REG_provincia);
begin
Abrir_archivo_provincia_para_lectura_escritura(ARCH_Provincia);
if ioresult <> 0 then
begin
rewrite(ARCH_Provincia);
seek(ARCH_Provincia,0);
write(ARCH_Provincia, Provincia);
end
else
begin
seek(ARCH_Provincia,filesize(ARCH_Provincia));
write(ARCH_Provincia, Provincia);
end;
Close(ARCH_Provincia);
end;
procedure Cargar_todas_las_provincias_en_el_archivo_provincias(VAR ARCH_Provincia: ARCHIVO_Provincia; VAR Provincia : REG_provincia);
const
arreglo_Provincias: array [1..limite] of REG_provincia = (
(Nombre_Provincia: 'Salta'; Codigo_de_provincia: 1; Telefono_de_contacto: '911'),
(Nombre_Provincia: 'Provincia de Buenos Aires'; Codigo_de_provincia: 2; Telefono_de_contacto: '148'),
(Nombre_Provincia: 'San Luis'; Codigo_de_provincia: 3; Telefono_de_contacto: '107'),
(Nombre_Provincia: 'Entre Rios'; Codigo_de_provincia: 4; Telefono_de_contacto: '0800-777-8476'),
(Nombre_Provincia: 'La Rioja'; Codigo_de_provincia: 5; Telefono_de_contacto: '107'),
(Nombre_Provincia: 'Santiago del Estero'; Codigo_de_provincia: 6; Telefono_de_contacto: '0800-888-6737'),
(Nombre_Provincia: 'Chaco'; Codigo_de_provincia: 7; Telefono_de_contacto: '0800-444-0829'),
(Nombre_Provincia: 'San Juan'; Codigo_de_provincia: 8; Telefono_de_contacto: '107'),
(Nombre_Provincia: 'Catamarca'; Codigo_de_provincia: 9; Telefono_de_contacto: '383-15-423-8872'),
(Nombre_Provincia: 'La Pampa'; Codigo_de_provincia: 10; Telefono_de_contacto: '0800-333-1135'),
(Nombre_Provincia: 'Mendoza'; Codigo_de_provincia: 11; Telefono_de_contacto: '0800-800-26843'),
(Nombre_Provincia: 'Misiones'; Codigo_de_provincia: 12; Telefono_de_contacto: '0800-444-3400'),
(Nombre_Provincia: 'Formosa'; Codigo_de_provincia: 13; Telefono_de_contacto: '107'),
(Nombre_Provincia: 'Neuquen'; Codigo_de_provincia: 14; Telefono_de_contacto: '0800-333-1002'),
(Nombre_Provincia: 'Rio Negro'; Codigo_de_provincia: 15; Telefono_de_contacto: '911'),
(Nombre_Provincia: 'Santa Fe'; Codigo_de_provincia: 16; Telefono_de_contacto: '0800-555-6549'),
(Nombre_Provincia: 'Tucuman'; Codigo_de_provincia: 17; Telefono_de_contacto: '0800-555-8478'),
(Nombre_Provincia: 'Chubut'; Codigo_de_provincia: 18; Telefono_de_contacto: '0800-222-2676'),
(Nombre_Provincia: 'Tierra del Fuego'; Codigo_de_provincia: 19; Telefono_de_contacto: '107'),
(Nombre_Provincia: 'Corrientes'; Codigo_de_provincia: 20; Telefono_de_contacto: '0379-497-4811'),
(Nombre_Provincia: 'Cordoba'; Codigo_de_provincia: 21; Telefono_de_contacto: '0800-122-1444'),
(Nombre_Provincia: 'Jujuy'; Codigo_de_provincia: 22; Telefono_de_contacto: '0800-888-4767'),
(Nombre_Provincia: 'Santa Cruz'; Codigo_de_provincia: 23; Telefono_de_contacto: '0800-222-2676')
);
VAR
i: Integer;
begin
for i:= 0 to 22 do
begin
Provincia:= arreglo_Provincias[i+1];
Guarda_Registro_Provincias(ARCH_Provincia, Provincia);
end;
end;
function tomar_y_devolver_reg_provincia_del_archivo(VAR ARCH_Provincia: ARCHIVO_Provincia; VAR Provincia : REG_provincia; POS: LongWord) : REG_provincia;
BEGIN
Abrir_archivo_provincia_para_lectura_escritura(ARCH_Provincia);
if ioresult <> 0 then
begin
Cargar_todas_las_provincias_en_el_archivo_provincias(ARCH_Provincia, Provincia);
Abrir_archivo_provincia_para_lectura_escritura(ARCH_Provincia);
Seek(ARCH_Provincia, POS);
Read(ARCH_Provincia, Provincia);
Close(ARCH_Provincia);
end
else
begin
Seek(ARCH_Provincia, POS);
Read(ARCH_Provincia, Provincia);
Close(ARCH_Provincia);
end;
tomar_y_devolver_reg_provincia_del_archivo:= Provincia;
END;
end. |
unit taExcel;
interface
uses
Excel2010, taTypes, System.DateUtils, System.SysUtils;
type
TTaExcel = class(TObject)
strict private
private
FBook: ExcelWorkbook;
FExcel: TExcelApplication;
protected
public
constructor Create;
destructor Destroy; override;
function EofRow(ASheet: ExcelWorksheet; ARow: Integer): Boolean;
procedure GetCorrections(ACorrections: TTimePeriodList; var ALastStart:
TDatetime);
function GetSheet(AIndex: Integer): ExcelWorksheet;
procedure GetTomatoes(ATomatoes: TTimePeriodList);
procedure InitExcelBook(APath, ATemplatePath: string);
function MonthToNumber(AName: string; const AFormat: TFormatSettings): Integer;
procedure PrintPeriods(APeriods: TTimePeriodList);
function TomatoDateToDateTime(AValue: string): TDateTime;
end;
implementation
uses
Winapi.Windows, System.Variants, System.Classes, taGlobals;
constructor TTaExcel.Create;
begin
inherited Create;
FExcel := TExcelApplication.Create(nil);
end;
destructor TTaExcel.Destroy;
begin
FreeAndNil(FExcel);
inherited Destroy;
end;
function TTaExcel.EofRow(ASheet: ExcelWorksheet; ARow: Integer): Boolean;
begin
Result := VarToStrDef(ASheet.Cells.Item[ARow, 1], '').IsEmpty;
end;
procedure TTaExcel.GetCorrections(ACorrections: TTimePeriodList; var
ALastStart: TDatetime);
const
COLIDX_DATE = 'A';
COLIDX_DURATION = 'B';
COLIDX_TAGS = 'C';
var
LIdx: Integer;
LRow: Integer;
LSheet: ExcelWorksheet;
begin
ACorrections.Clear;
LSheet := GetSheet(2);
LRow := 1;
try
while not EofRow(LSheet, LRow) do
begin
LIdx := ACorrections.Add(
TTimePeriod.Create(
StrToDateTime(LSheet.Cells.Item[LRow, COLIDX_DATE]),
StrToInt(LSheet.Cells.Item[LRow, COLIDX_DURATION]) * SECONDSINMINUTE,
VarToStrDef(LSheet.Cells.Item[LRow, COLIDX_TAGS], '')
)
);
ACorrections[LIdx] := ACorrections[LIdx].TimeShift(-ACorrections[LIdx].Duration);
Inc(LRow);
end;
except on e:Exception do
begin
e.RaiseOuterException(
Exception.CreateFmt('%s LRow = %d', [e.Message, LRow])
);
end;
end;
ACorrections.ClearUntil(ALastStart);
if ACorrections.Count > 0 then
ALastStart := ACorrections.Last.Start;
end;
function TTaExcel.GetSheet(AIndex: Integer): ExcelWorksheet;
begin
Result := FBook.Worksheets.Item[AIndex] as ExcelWorksheet;
end;
procedure TTaExcel.GetTomatoes(ATomatoes: TTimePeriodList);
const
COLIDX_DATE = 'A';
COLIDX_TAGS = 'B';
var
LRow: Integer;
LSheet: ExcelWorksheet;
begin
ATomatoes.Clear;
LSheet := GetSheet(1);
LRow := 1;
try
while not EofRow(LSheet, LRow) do
begin
ATomatoes.Add(
TTimePeriod.Create(
TomatoDateToDateTime(LSheet.Cells.Item[LRow, COLIDX_DATE]),
TOMATODURATION,
VarToStrDef(LSheet.Cells.Item[LRow, COLIDX_TAGS], '')
)
);
Inc(LRow);
end;
except on e:Exception do
begin
e.RaiseOuterException(
Exception.CreateFmt('%s LRow = %d', [e.Message, LRow])
);
end;
end;
ATomatoes.Reverse;
ATomatoes.Check;
end;
procedure TTaExcel.InitExcelBook(APath, ATemplatePath: string);
begin
FExcel.Visible[GetUserDefaultLCID] := True;
//TODO: WorkbookCreateFromTemplate
//FExcel.Workbooks.Add(ATemplatePath, GetUserDefaultLCID);
//FExcel.Workbooks.Add('', GetUserDefaultLCID);
FBook := FExcel.Workbooks.Open(APath, EmptyParam, EmptyParam, EmptyParam, EmptyParam,
EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam,
EmptyParam, EmptyParam, EmptyParam, EmptyParam, 0);
{
FBook := FExcel.Workbooks.Open(APath, varNull, nil, nil, nil,
nil, nil, nil, nil, nil, nil,
nil, nil, nil, nil, 0);
}
end;
function TTaExcel.MonthToNumber(AName: string; const AFormat: TFormatSettings):
Integer;
var
I: Integer;
begin
Result := -1;
for I := Low(AFormat.LongMonthNames) to High(AFormat.LongMonthNames) do
if AFormat.LongMonthNames[i] = AName then
Exit(I);
end;
procedure TTaExcel.PrintPeriods(APeriods: TTimePeriodList);
const
STimeFormat = 'h:mm:ss;@';
var
I: Integer;
LRow: Integer;
LSheet: ExcelWorksheet;
begin
LSheet := GetSheet(3);
LSheet.Cells.ClearContents;
//LSheet.Columns.Item[1, 2].NumberFormat := STimeFormat;
//LSheet.Columns.Item[1, 2].NumberFormat := STimeFormat;
for I := 0 to APeriods.Count - 1 do
begin
LRow := I + 1;
LSheet.Cells.Item[LRow, 'A'] := DateOf(APeriods[I].Start);
LSheet.Cells.Item[LRow, 'B'] := TimeOf(APeriods[I].Start);
LSheet.Cells.Item[LRow, 'C'] := TimeOf(APeriods[I].Finish);
LSheet.Cells.Item[LRow, 'E'] := APeriods[I].Tags;
end;
end;
function TTaExcel.TomatoDateToDateTime(AValue: string): TDateTime;
const
IDXDAY = 1;
var
LFormat: TFormatSettings;
LStrings: TStringList;
begin
LFormat := LFormat.Create('en_US');
LStrings := TStringList.Create();
try
LStrings.Delimiter := ' ';
LStrings.DelimitedText := AValue;
LStrings.Strings[IDXDAY] := StringReplace(LStrings.Strings[IDXDAY], ',','', []);
AValue := Format('%d/%s/%s %s', [
MonthToNumber(LStrings.Strings[0], LFormat),
LStrings.Strings[IDXDAY],
LStrings.Strings[2],
LStrings.Strings[3]
]);
finally
FreeAndNil(LStrings);
end;
// DateTimeToString(AValue, 'mmmm dd, yyyy hh:nn', Now, LFormat);
Result := StrToDateTime(AValue, LFormat);
end;
end.
|
unit Support.Toshiba;
interface
uses
SysUtils,
Support, Device.SMART.List;
type
TToshibaNSTSupport = class sealed(TNSTSupport)
private
InterpretingSMARTValueList: TSMARTValueList;
function GetEraseError: TReadEraseError;
function GetFullSupport: TSupportStatus;
function IsModelHasToshibaString: Boolean;
function IsProductOfToshiba: Boolean;
function IsTHNSNF: Boolean;
function IsTHNSNH: Boolean;
function IsTHNSNJ: Boolean;
public
function GetSupportStatus: TSupportStatus; override;
function GetSMARTInterpreted(SMARTValueList: TSMARTValueList):
TSMARTInterpreted; override;
end;
implementation
{ TToshibaNSTSupport }
function TToshibaNSTSupport.IsModelHasToshibaString: Boolean;
begin
result := Pos('TOSHIBA', Identify.Model) > 0;
end;
function TToshibaNSTSupport.IsTHNSNF: Boolean;
begin
result := Pos('THNSNF', Identify.Model) > 0;
end;
function TToshibaNSTSupport.IsTHNSNH: Boolean;
begin
result := Pos('THNSNH', Identify.Model) > 0;
end;
function TToshibaNSTSupport.IsTHNSNJ: Boolean;
begin
result := Pos('THNSNJ', Identify.Model) > 0;
end;
function TToshibaNSTSupport.IsProductOfToshiba: Boolean;
begin
result := IsModelHasToshibaString and
(IsTHNSNF or IsTHNSNH or IsTHNSNJ);
end;
function TToshibaNSTSupport.GetFullSupport: TSupportStatus;
begin
result.Supported := Supported;
result.FirmwareUpdate := true;
result.TotalWriteType := TTotalWriteType.WriteNotSupported;
end;
function TToshibaNSTSupport.GetSupportStatus: TSupportStatus;
begin
result.Supported := NotSupported;
if IsProductOfToshiba then
result := GetFullSupport;
end;
function TToshibaNSTSupport.GetEraseError: TReadEraseError;
const
IDOfEraseErrorElse = 1;
begin
result.TrueReadErrorFalseEraseError := true;
result.Value :=
InterpretingSMARTValueList.GetRAWByID(IDOfEraseErrorElse);
end;
function TToshibaNSTSupport.GetSMARTInterpreted(
SMARTValueList: TSMARTValueList): TSMARTInterpreted;
const
IDOfReplacedSector = 5;
IDofUsedHour = 9;
ReplacedSectorThreshold = 50;
EraseErrorThreshold = 10;
begin
InterpretingSMARTValueList := SMARTValueList;
result.TotalWrite.InValue.ValueInMiB := 0;
result.UsedHour :=
InterpretingSMARTValueList.GetRAWByID(IDOfUsedHour);
result.ReadEraseError := GetEraseError;
result.SMARTAlert.ReadEraseError :=
result.ReadEraseError.Value >= EraseErrorThreshold;
result.ReplacedSectors :=
InterpretingSMARTValueList.GetRAWByID(IDOfReplacedSector);
result.SMARTAlert.ReplacedSector :=
result.ReplacedSectors >= ReplacedSectorThreshold;
end;
end.
|
unit ncCompression;
// To disable as much of RTTI as possible (Delphi 2009/2010),
// Note: There is a bug if $RTTI is used before the "unit <unitname>;" section of a unit, hence the position
{$IF CompilerVersion >= 21.0}
{$WEAKLINKRTTI ON}
{$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])}
{$ENDIF}
interface
uses System.ZLib, System.Classes, System.SysUtils;
type
TncCompressionLevel = TZCompressionLevel;
function CompressBytes(const aBytes: TBytes; aCompressionLevel: TncCompressionLevel = zcDefault): TBytes;
function DecompressBytes(const aBytes: TBytes): TBytes;
implementation
function CompressBytes(const aBytes: TBytes; aCompressionLevel: TncCompressionLevel = zcDefault): TBytes;
begin
if Length(aBytes) > 0 then
ZCompress(aBytes, Result, aCompressionLevel)
else
SetLength(Result, 0);
end;
function DecompressBytes(const aBytes: TBytes): TBytes;
begin
if Length(aBytes) > 0 then
ZDecompress(aBytes, Result)
else
SetLength(Result, 0);
end;
end.
|
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------}
unit untImagesSelect;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ImgList, untEasyButtons;
type
TfrmImagesSelect = class(TForm)
ListView1: TListView;
imgVW: TImageList;
procedure FormCreate(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
procedure ListView1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
FControlFlag: Integer;
end;
var
frmImagesSelect: TfrmImagesSelect;
implementation
uses untTvDirectoryOper;
{$R *.dfm}
procedure TfrmImagesSelect.FormCreate(Sender: TObject);
var
ABmp: TBitmap;
I : Integer;
ATmpListItem: TListItem;
begin
ListView1.Items.Clear;
ABmp := TBitmap.Create;
ABmp.LoadFromFile(ExtractFilePath(Application.ExeName) + 'images\Tree.bmp');
imgVW.Add(ABmp, nil);
ABmp.Free;
for I := 0 to imgVW.Count - 1 do
begin
ATmpListItem := ListView1.Items.Add;
ATmpListItem.Caption := IntToStr(I);
ATmpListItem.ImageIndex := I;
end;
end;
procedure TfrmImagesSelect.FormDeactivate(Sender: TObject);
begin
Close;
end;
procedure TfrmImagesSelect.ListView1Click(Sender: TObject);
begin
if ListView1.Selected = nil then Exit;
if FControlFlag = 1 then
frmTvDirectoryOper.edtImage1.Text := IntToStr(ListView1.Selected.Index)
else if FControlFlag = 2 then
frmTvDirectoryOper.edtImage2.Text := IntToStr(ListView1.Selected.Index);
Close;
end;
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit REST.Backend.PushTypes;
interface
uses System.Generics.Collections, System.SysUtils, System.Classes, System.JSON, System.PushNotification,
REST.Backend.Providers, REST.Backend.MetaTypes, REST.Backend.ServiceTypes;
type
TPushData = class;
TDeviceRegisteredAtProviderEvent = procedure(const AService: TPushService) of object;
IBackendPushApi = interface;
IBackendPushDeviceApi = interface;
IBackendPushDeviceService = interface(IBackendService)
['{1810D21D-BF97-4DF0-B39A-DECA2A8A6F07}']
function GetPushDeviceAPI: IBackendPushDeviceApi;
function CreatePushDeviceApi: IBackendPushDeviceApi;
property PushDeviceAPI: IBackendPushDeviceApi read GetPushDeviceAPI;
end;
// Service must implement this
IBackendPushDeviceApi = interface
['{2F1A3600-8C92-4C74-9D20-E800FD275482}']
function GetPushService: TPushService; // May raise exception
function HasPushService: Boolean;
procedure RegisterDevice(AOnRegistered: TDeviceRegisteredAtProviderEvent);
procedure UnregisterDevice;
end;
/// <summary>Providers may implement this interface in order to allow a device
/// to register customer installation properties, such as {"channels":["a", "b"]}
/// </summary>
IBackendPushDeviceApi2 = interface
['{3A78B2C1-233B-485D-9616-049A66E374B3}']
/// <summary>Register a device. Include the properties that will be written to the installation object</summary>
procedure RegisterDevice(const AProperties: TJSONObject; AOnRegistered: TDeviceRegisteredAtProviderEvent);
/// <summary>Get the identify of the installation object after a device has been registered. True is returned if the identity
/// is available. Use the TBackendEntityValue.ObjectID property to retrieve the object id of the installation object.
/// </summary>
function TryGetInstallationValue(out AValue: TBackendEntityValue): Boolean;
end;
// Wrapper
TBackendPushDeviceApi = class(TBackendAuthenticationApi)
private
FServiceApi: IBackendPushDeviceApi;
FService: IBackendPushDeviceService;
function GetServiceAPI: IBackendPushDeviceApi;
protected
function GetAuthenticationApi: IBackendAuthenticationApi; override;
public
constructor Create(const AApi: IBackendPushDeviceApi); overload;
constructor Create(const AService: IBackendPushDeviceService); overload;
function GetPushService: TPushService; // May raise exception
function HasPushService: Boolean;
procedure RegisterDevice(AOnRegistered: TDeviceRegisteredAtProviderEvent); overload;
procedure RegisterDevice(const AProperties: TJSONObject; AOnRegistered: TDeviceRegisteredAtProviderEvent); overload;
procedure UnregisterDevice;
/// <summary>Get the identify of the installation object after a device has been registered. True is returned if the identity
/// is available. Use the TBackendEntityValue.ObjectID property to retrieve the object id of the installation object.
/// </summary>
function TryGetInstallationValue(out AValue: TBackendEntityValue): Boolean;
property ProviderAPI: IBackendPushDeviceApi read FServiceAPI;
end;
IBackendPushService = interface(IBackendService)
['{34547227-6E40-40F7-A59D-4961FDBD499B}']
function GetPushAPI: IBackendPushApi;
function CreatePushApi: IBackendPushApi;
property PushAPI: IBackendPushApi read GetPushAPI;
end;
// Service must implement this
IBackendPushApi = interface(IBackendApi)
['{F7FAC938-CE46-42A9-B4D2-8620365A64B0}']
procedure PushBroadcast(const AData: TPushData);
end;
/// <summary>Providers may implement this interface to support broadcasing a JSON payload.
/// </summary>
IBackendPushApi2 = interface
['{E9E1859D-1C35-4266-A335-490508A2C6EE}']
/// <summary>Broadcast a notification</summary>
procedure PushBroadcast(const AData: TJSONObject); overload;
/// <summary>Create a TJSONObject that represents TPushData</summary>
function PushDataAsJSON(const AData: TPushData): TJSONObject;
end;
/// <summary>Providers may implement this interface to support broadcasting a notification
/// to a target, such as {"channels": ["a"]}. The format of the target is provider specific.
/// </summary>
IBackendPushApi3 = interface
['{E0B215B3-8709-4D80-A2DE-8847A69D1773}']
/// <summary>Send a notification to a target</summary>
procedure PushToTarget(const AData: TPushData; const ATarget: TJSONObject); overload;
procedure PushToTarget(const AData: TJSONObject; const ATarget: TJSONObject); overload;
end;
// Wrapper
TBackendPushApi = class(TBackendAuthenticationApi)
private
FService: IBackendPushService;
FServiceAPI: IBackendPushAPI;
function GetServiceAPI: IBackendPushApi;
protected
function GetAuthenticationApi: IBackendAuthenticationApi; override;
public
constructor Create(const AService: IBackendPushService); overload;
constructor Create(const AServiceAPI: IBackendPushAPI); overload;
procedure PushBroadcast(const AData: TPushData); overload;
/// <summary>Send a notification to a target</summary>
procedure PushToTarget(const AData: TPushData; const ATarget: TJSONObject); overload;
procedure PushToTarget(const AData: TJSONObject; const ATarget: TJSONObject); overload;
/// <summary>Create a TJSONObject that represents TPushData</summary>
function PushDataAsJSON(const AData: TPushData): TJSONObject;
property ProviderAPI: IBackendPushApi read GetServiceAPI;
end;
TPushData = class
public type
TChangeMethod = TProc;
TDataGroup = class(TPersistent)
private
FOnChange: TChangeMethod;
protected
procedure DoChange;
public
procedure Load(const AJSONObject: TJSONObject; const ARoot: string); virtual; abstract;
procedure Save(const AJSONObject: TJSONObject; const ARoot: string); virtual; abstract;
property OnChange: TChangeMethod read FOnChange write FOnChange;
end;
TAPS = class(TDataGroup)
public type
TNames = record
public
const ApsRoot = 'aps';
const Alert = 'alert';
const Badge = 'badge';
const Sound = 'sound';
end;
private
FAlert: string;
FBadge: string;
FSound: string;
procedure SetAlert(const Value: string);
procedure SetBadge(const Value: string);
procedure SetSound(const Value: string);
protected
procedure AssignTo(APersistent: TPersistent); override;
public
procedure Load(const AJSONObject: TJSONObject; const ARoot: string); override;
procedure Save(const AJSONObject: TJSONObject; const ARoot: string); override;
published
property Alert: string read FAlert write SetAlert;
property Badge: string read FBadge write SetBadge;
property Sound: string read FSound write SetSound;
end;
TGCM = class(TDataGroup)
private
FAction: string;
FTitle: string;
FMessage: string;
FMsg: string;
public type
TNames = record
public
const Action = 'action';
const Msg = 'msg';
const Message = 'message';
const Title = 'title';
end;
private
procedure SetAction(const Value: string);
procedure SetTitle(const Value: string);
procedure SetMessage(const Value: string);
procedure SetMsg(const Value: string);
protected
procedure AssignTo(APersistent: TPersistent); override;
public
procedure Load(const AJSONObject: TJSONObject; const ARoot: string); override;
procedure Save(const AJSONObject: TJSONObject; const ARoot: string); override;
published
property Action: string read FAction write SetAction;
property Title: string read FTitle write SetTitle;
property Message: string read FMessage write SetMessage;
property Msg: string read FMsg write SetMsg;
end;
TExtras = class(TDataGroup)
public type
TExtrasPair = TPair<string, string>;
TExtrasList = TList<TExtrasPair>;
private
function GetCount: Integer;
function GetItem(I: Integer): TExtrasPair;
protected
FList: TExtrasList;
procedure AssignTo(APersistent: TPersistent); override;
public
constructor Create;
destructor Destroy; override;
procedure Add(const AName, AValue: string);
function IndexOf(const AName: string): Integer;
procedure Clear;
procedure Remove(const AName: string);
procedure Delete(AIndex: Integer);
function GetEnumerator: TEnumerator<TExtrasPair>;
procedure Load(const AJSONObject: TJSONObject; const ARoot: string); override;
procedure Save(const AJSONObject: TJSONObject; const ARoot: string); override;
property Count: Integer read GetCount;
property Items[I: Integer]: TExtrasPair read GetItem; default;
published
end;
private
class function GetString(const AJSON: TJSONObject; const ARoot, AName: string): string; overload; static;
class procedure SetString(const AJSON: TJSONObject; const ARoot, AName: string; const AValue: string); overload; static;
class procedure SetValue(const AJSON: TJSONObject; const ARoot, AName: string; const AValue: TJSONValue); overload; static;
class procedure SetString(const AJSON: TJSONObject; const AName: string; const AValue: string); overload; static;
private
FAPS: TAPS;
FGCM: TGCM;
FExtras: TExtras;
FOnChange: TChangeMethod;
FMessage: string;
procedure SetMessage(const Value: string);
procedure SetAPS(const Value: TAPS);
procedure SetGCM(const Value: TGCM);
procedure DoChange;
procedure SetExtras(const Value: TExtras);
public
constructor Create; overload;
destructor Destroy; override;
procedure Load(const AJSON: TJSONObject);
procedure SaveMessage(const AJSON: TJSONObject; const AName: string);
property Message: string read FMessage write SetMessage;
property APS: TAPS read FAPS write SetAPS;
property GCM: TGCM read FGCM write SetGCM;
property Extras: TExtras read FExtras write SetExtras;
property OnChange: TChangeMethod read FOnChange write FOnChange;
end;
implementation
{$IFDEF LOGGING}
uses FMX.Types;
{$ENDIF}
{ TPushNotification }
constructor TPushData.Create;
begin
FAPS := TAPS.Create;
FAPS.OnChange :=
procedure
begin
DoChange;
end;
FGCM := TGCM.Create;
FGCM.OnChange :=
procedure
begin
DoChange;
end;
FExtras := TExtras.Create;
FExtras.OnChange :=
procedure
begin
DoChange;
end;
end;
destructor TPushData.Destroy;
begin
FAPS.Free;
FGCM.Free;
FExtras.Free;
inherited;
end;
procedure TPushData.DoChange;
begin
if Assigned(FOnChange) then
FOnChange;
end;
procedure TPushData.SaveMessage(const AJSON: TJSONObject; const AName: string);
begin
TPushData.SetString(AJSON, AName, FMessage);
end;
procedure TPushData.SetAPS(const Value: TAPS);
begin
FAPS.Assign(Value);
end;
procedure TPushData.SetExtras(const Value: TExtras);
begin
FExtras.Assign(Value);
end;
procedure TPushData.SetGCM(const Value: TGCM);
begin
FGCM.Assign(Value);
end;
procedure TPushData.SetMessage(const Value: string);
begin
if Value <> Message then
begin
FMessage := Value;
DoChange;
end;
end;
procedure GetRoot(const AFullName: string; out ARoot, AName: string);
var
I: Integer;
begin
I := AFullName.IndexOf('.');
if I >= 0 then
begin
ARoot := AFullName.Substring(0, I);
AName := AFullName.Substring(I+1);
Assert(AName.IndexOf('.') < 0, AName);
end
else
begin
ARoot := '';
AName := AFullName;
end;
end;
class function TPushData.GetString(const AJSON: TJSONObject; const ARoot, AName: string): string;
var
LJSONValue: TJSONValue;
LJSONObject: TJSONObject;
begin
if ARoot <> '' then
LJSONObject := AJSON.GetValue(ARoot) as TJSONObject
else
LJSONObject := AJSON;
if LJSONObject <> nil then
begin
LJSONValue := LJSONObject.GetValue(AName);
if LJSONValue <> nil then
Result := LJSONValue.Value
else
Result := '';
end;
end;
procedure TPushData.Load(const AJSON: TJSONObject);
const
sAps = 'aps';
sGcm = 'gcm';
sMsg = 'msg';
sData = 'data';
sAlert = 'alert';
var
LJSONValue: TJSONValue;
LJSONObject: TJSONObject;
LJSONGCM: TJSONObject;
LJSONAPS: TJSONObject;
LTemp: TJSONValue;
S: string;
LGCMName: string;
begin
LTemp := nil;
LJSONObject := AJSON.Clone as TJSONObject;
try
LJSONValue := LJSONObject.GetValue(sAps);
if LJSONValue is TJSONObject then
LJSONAPS := TJSONObject(LJSONValue)
else
LJSONAPS := LJSONObject;
FAPS.Load(LJSONAPS, '');
// Clear values
with TPushData.TAPS.Create do
try
Save(LJSONAPS, '');
finally
Free;
end;
LGCMName := sGCM;
LJSONValue := LJSONObject.GetValue(LGCMName);
if LJSONValue = nil then
begin
// Kinvey puts android payload here
LGCMName := sMsg;
LJSONValue := LJSONObject.GetValue(LGCMName);
end;
if LJSONValue = nil then
begin
// Parse puts android payload here
LGCMName := sData;
LJSONValue := LJSONObject.GetValue(LGCMName);
end;
LJSONGCM := LJSONObject;
if LJSONValue is TJSONObject then
LJSONGCM := TJSONObject(LJSONValue)
else if LJSONValue is TJSONString then
begin
S := TJSONString(LJSONValue).Value;
if (S.Length > 0) and (S.Chars[0] = '{') then
try
LTemp := TJSONObject.ParseJSONValue(S); // Freed later
if LTemp is TJSONObject then
LJSONGCM := TJSONObject(LTemp);
if LGCMName <> '' then
TPushData.SetString(LJSONObject, '', LGCMName, ''); // Clear
except
end;
end;
FGCM.Load(LJSONGCM, '');
// Clear values
with TPushData.TGCM.Create do
try
Save(LJSONGCM, '');
finally
Free;
end;
// Load remaining elements in GCM into extras
FExtras.Load(LJSONGCM, '');
if LJSONGCM <> LJSONObject then
// Load remaining elements into extras
FExtras.Load(LJSONObject, '');
if FAPS.Alert <> '' then
FMessage := FAPS.Alert
else if FGCM.Message <> '' then
FMessage := FGCM.Message
else if FGCM.Msg <> '' then
FMessage := FGCM.Msg
else if LJSONGCM.TryGetValue<string>(sAlert, S) then
FMessage := S; // Parse puts GCM message here
finally
LTemp.Free;
LJSONObject.Free;
end;
end;
class procedure TPushData.SetString(const AJSON: TJSONObject; const ARoot, AName: string;
const AValue: string);
var
LJSONObject: TJSONObject;
LPair: TJSONPair;
begin
if ARoot <> '' then
begin
LJSONObject := AJSON.GetValue(ARoot) as TJSONObject;
if LJSONObject = nil then
if AValue <> '' then
begin
LJSONObject := TJSONObject.Create;
AJSON.AddPair(ARoot, LJSONObject);
end;
end
else
LJSONObject := AJSON;
if LJSONObject <> nil then
begin
if AValue = '' then
begin
LPair := LJSONObject.RemovePair(AName);
LPair.Free;
end
else
begin
if LJSONObject.GetValue(AName) <> nil then
begin
LPair := LJSONObject.RemovePair(AName);
LPair.Free;
end;
LJSONObject.AddPair(AName, AValue);
end;
end;
end;
class procedure TPushData.SetString(const AJSON: TJSONObject; const AName: string;
const AValue: string);
begin
SetString(AJSON, '', AName, AValue);
end;
class procedure TPushData.SetValue(const AJSON: TJSONObject; const ARoot,
AName: string; const AValue: TJSONValue);
var
LJSONObject: TJSONObject;
begin
if ARoot <> '' then
begin
LJSONObject := AJSON.GetValue(ARoot) as TJSONObject;
if LJSONObject = nil then
if AValue <> nil then
begin
LJSONObject := TJSONObject.Create;
AJSON.AddPair(ARoot, LJSONObject);
end;
end
else
LJSONObject := AJSON;
if LJSONObject <> nil then
begin
if AValue = nil then
LJSONObject.RemovePair(AName)
else
begin
if LJSONObject.GetValue(AName) <> nil then
LJSONObject.RemovePair(AName);
LJSONObject.AddPair(AName, AValue);
end;
end;
end;
{ TBackendPushDeviceApi }
constructor TBackendPushDeviceApi.Create(const AApi: IBackendPushDeviceApi);
begin
FServiceApi := AApi;
end;
constructor TBackendPushDeviceApi.Create(
const AService: IBackendPushDeviceService);
begin
FService := AService;
end;
function TBackendPushDeviceApi.GetServiceAPI: IBackendPushDeviceApi;
begin
if FServiceApi <> nil then
Result := FServiceAPI
else
Result := FService.GetPushDeviceApi
end;
function TBackendPushDeviceApi.GetAuthenticationApi: IBackendAuthenticationApi;
begin
Result := GetServiceApi as IBackendAuthenticationApi;
end;
function TBackendPushDeviceApi.GetPushService: TPushService;
begin
Result := GetServiceApi.GetPushService;
end;
function TBackendPushDeviceApi.HasPushService: Boolean;
begin
Result := GetServiceApi.HasPushService;
end;
procedure TBackendPushDeviceApi.RegisterDevice(
AOnRegistered: TDeviceRegisteredAtProviderEvent);
begin
GetServiceApi.RegisterDevice(AOnRegistered);
end;
procedure TBackendPushDeviceApi.RegisterDevice(
const AProperties: TJSONObject; AOnRegistered: TDeviceRegisteredAtProviderEvent);
var
LIntf: IBackendPushDeviceApi2;
begin
if (AProperties <> nil) and Supports(GetServiceApi, IBackendPushDeviceApi2, LIntf) then
LIntf.RegisterDevice(AProperties, AOnRegistered)
else
// Provider does not support AProperties
GetServiceApi.RegisterDevice(AOnRegistered)
end;
function TBackendPushDeviceApi.TryGetInstallationValue(
out AValue: TBackendEntityValue): Boolean;
var
LIntf: IBackendPushDeviceApi2;
begin
if Supports(GetServiceApi, IBackendPushDeviceApi2, LIntf) then
Result := LIntf.TryGetInstallationValue(AValue)
else
Result := False;
end;
procedure TBackendPushDeviceApi.UnregisterDevice;
begin
GetServiceApi.UnregisterDevice;
end;
{ TBackendPushApi }
constructor TBackendPushApi.Create(const AService: IBackendPushService);
begin
FService := AService;
end;
constructor TBackendPushApi.Create(const AServiceAPI: IBackendPushAPI);
begin
FServiceAPI := AServiceAPI;
end;
function TBackendPushApi.GetAuthenticationApi: IBackendAuthenticationApi;
begin
Result := GetServiceApi as IBackendAuthenticationApi;
end;
function TBackendPushApi.GetServiceAPI: IBackendPushApi;
begin
if FServiceApi <> nil then
Result := FServiceAPI
else
Result := FService.GetPushApi
end;
procedure TBackendPushApi.PushBroadcast(
const AData: TPushData);
begin
GetServiceApi.PushBroadcast(AData);
end;
function TBackendPushApi.PushDataAsJSON(const AData: TPushData): TJSONObject;
var
LIntf: IBackendPushApi2;
begin
if Supports(GetServiceApi, IBackendPushApi2, LIntf) then
Result := LIntf.PushDataAsJSON(AData)
else
raise ENotSupportedException.Create('Provider does not support this operation');
end;
procedure TBackendPushApi.PushToTarget(const AData: TPushData;
const ATarget: TJSONObject);
var
LIntf: IBackendPushApi3;
begin
if Supports(GetServiceApi, IBackendPushApi3, LIntf) then
LIntf.PushToTarget(AData, ATarget)
else if ATarget = nil then
GetServiceApi.PushBroadcast(AData)
else
raise ENotSupportedException.Create('Provider does not support this operation');
end;
procedure TBackendPushApi.PushToTarget(const AData, ATarget: TJSONObject);
var
LIntf: IBackendPushApi3;
begin
if Supports(GetServiceApi, IBackendPushApi3, LIntf) then
LIntf.PushToTarget(AData, ATarget)
else
raise ENotSupportedException.Create('Provider does not support this operation');
end;
{ TPushData.TDataGroup }
procedure TPushData.TDataGroup.DoChange;
begin
if Assigned(FOnChange) then
FOnChange;
end;
{ TPushData.TAPS }
procedure TPushData.TAPS.AssignTo(APersistent: TPersistent);
begin
if APersistent is TAPS then
begin
TAPS(APersistent).Alert := Alert;
TAPS(APersistent).Badge := Badge;
TAPS(APersistent).Sound := Sound;
end
else
inherited;
end;
procedure TPushData.TAPS.Load(const AJSONObject: TJSONObject; const ARoot: string);
begin
Alert := TPushData.GetString(AJSONObject, ARoot, TNames.Alert);
Badge := TPushData.GetString(AJSONObject, ARoot, TNames.Badge);
Sound := TPushData.GetString(AJSONObject, ARoot, TNames.Sound);
end;
procedure TPushData.TAPS.Save(const AJSONObject: TJSONObject; const ARoot: string);
var
LBadge: Integer;
begin
TPushData.SetString(AJSONObject, ARoot, TNames.Alert, Alert);
if TryStrToInt(Badge, LBadge) then
TPushData.SetValue(AJSONObject, ARoot, TNames.Badge, TJSONNumber.Create(LBadge))
else
// Badge may not be a number. For, example "Increment" may be used with Parse
TPushData.SetString(AJSONObject, ARoot, TNames.Badge, Badge);
TPushData.SetString(AJSONObject, ARoot, TNames.Sound, Sound);
end;
procedure TPushData.TAPS.SetAlert(const Value: string);
begin
if Value <> Alert then
begin
FAlert := Value;
DoChange;
end;
end;
procedure TPushData.TAPS.SetBadge(const Value: string);
begin
if Value <> Badge then
begin
FBadge := Value;
DoChange;
end;
end;
procedure TPushData.TAPS.SetSound(const Value: string);
begin
if Value <> Sound then
begin
FSound := Value;
DoChange;
end;
end;
{ TPushData.TGCM }
procedure TPushData.TGCM.AssignTo(APersistent: TPersistent);
begin
if APersistent is TGCM then
begin
TGCM(APersistent).Action := Action;
TGCM(APersistent).Title := Title;
TGCM(APersistent).Msg := Msg;
TGCM(APersistent).Message := Message;
end
else
inherited;
end;
procedure TPushData.TGCM.Load(const AJSONObject: TJSONObject; const ARoot: string);
begin
Action := TPushData.GetString(AJSONObject, ARoot, TNames.Action);
Message := TPushData.GetString(AJSONObject, ARoot, TNames.Message);
Msg := TPushData.GetString(AJSONObject, ARoot, TNames.Msg);
Title := TPushData.GetString(AJSONObject, ARoot, TNames.Title);
end;
procedure TPushData.TGCM.Save(const AJSONObject: TJSONObject; const ARoot: string);
begin
TPushData.SetString(AJSONObject, ARoot, TNames.Action, Action);
TPushData.SetString(AJSONObject, ARoot, TNames.Message, Message);
TPushData.SetString(AJSONObject, ARoot, TNames.Msg, Msg);
TPushData.SetString(AJSONObject, ARoot, TNames.Title, Title);
end;
procedure TPushData.TGCM.SetAction(const Value: string);
begin
if Value <> Action then
begin
FAction := Value;
DoChange;
end;
end;
procedure TPushData.TGCM.SetMessage(const Value: string);
begin
if Value <> Message then
begin
FMessage := Value;
DoChange;
end;
end;
procedure TPushData.TGCM.SetMsg(const Value: string);
begin
if Value <> Msg then
begin
FMsg := Value;
DoChange;
end;
end;
procedure TPushData.TGCM.SetTitle(const Value: string);
begin
if Value <> Title then
begin
FTitle := Value;
DoChange;
end;
end;
{ TPushData.TExtras }
procedure TPushData.TExtras.Add(const AName, AValue: string);
begin
FList.Add(TExtrasPair.Create(AName, AValue))
end;
procedure TPushData.TExtras.AssignTo(APersistent: TPersistent);
begin
if APersistent is TExtras then
begin
TExtras(APersistent).Clear;
TExtras(APersistent).FList.AddRange(FList.ToArray);
end
else
inherited;
end;
procedure TPushData.TExtras.Clear;
begin
FList.Clear;
end;
constructor TPushData.TExtras.Create;
begin
FList := TExtrasList.Create;
end;
procedure TPushData.TExtras.Delete(AIndex: Integer);
begin
FList.Delete(AIndex);
end;
destructor TPushData.TExtras.Destroy;
begin
inherited;
FList.Free;
end;
function TPushData.TExtras.GetCount: Integer;
begin
Result := FList.Count;
end;
function TPushData.TExtras.GetEnumerator: TEnumerator<TExtrasPair>;
begin
Result := FList.GetEnumerator;
end;
function TPushData.TExtras.GetItem(I: Integer): TExtrasPair;
begin
Result := FList[I];
end;
function TPushData.TExtras.IndexOf(const AName: string): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to Count - 1 do
if Items[I].Key = AName then
begin
Result := I;
break;
end;
end;
procedure TPushData.TExtras.Load(const AJSONObject: TJSONObject;
const ARoot: string);
var
LJSONObject: TJSONObject;
LJSONPair: TJSONPair;
LValue: TJSONValue;
begin
if ARoot = '' then
LJSONObject := AJSONObject
else
LJSONObject := AJSONObject.GetValue(ARoot) as TJSONObject;
if LJSONObject <> nil then
for LJSONPair in LJSONObject do
begin
LValue := LJSONPair.JsonValue;
if (not (LValue is TJSONObject)) and (not (LValue is TJSONArray)) then
Add(LJSONPair.JsonString.Value, TJSONString(LValue).Value)
end;
end;
procedure TPushData.TExtras.Remove(const AName: string);
var
I: Integer;
begin
I := IndexOf(AName);
if I >= 0 then
Delete(I);
end;
procedure TPushData.TExtras.Save(const AJSONObject: TJSONObject;
const ARoot: string);
var
LPair: TExtrasPair;
begin
for LPair in FList do
if LPair.Key <> '' then
TPushData.SetString(AJSONObject, ARoot, LPair.Key, LPair.Value);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC binary streaming implementation }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Stan.StorageBin;
interface
uses
System.Classes;
type
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDStanStorageBinLink = class(TComponent)
end;
implementation
uses
System.SysUtils, System.TypInfo,
Data.FMTBcd, Data.SQLTimSt, Data.DB,
FireDAC.Stan.Intf, FireDAC.Stan.Util, FireDAC.Stan.Storage, FireDAC.Stan.SQLTimeInt,
FireDAC.Stan.Factory, FireDAC.Stan.Error, FireDAC.Stan.Consts;
type
TFDBinStorage = class(TFDStorage, IFDStanStorage)
private
FDictionary: TFDStringList;
FDictionaryIndex: Integer;
procedure InternalReadProperty(var AName: String);
procedure InternalWriteProperty(const APropName: String;
ApValue: Pointer; ALen: Cardinal);
function InternalReadObject(var AName: String): Boolean;
function InternalReadObjectEnd: Boolean;
function LookupName(const AName: String): Word;
public
constructor Create; override;
destructor Destroy; override;
procedure Close; override;
function IsObjectEnd(const AObjectName: String): Boolean;
procedure Open(AResOpts: TObject; AEncoder: TObject;
const AFileName: String; AStream: TStream; AMode: TFDStorageMode); override;
function ReadBoolean(const APropName: String; ADefValue: Boolean): Boolean;
function ReadDate(const APropName: String; ADefValue: TDateTime): TDateTime;
function ReadFloat(const APropName: String; ADefValue: Double): Double;
function ReadInteger(const APropName: String; ADefValue: Integer): Integer;
function ReadLongWord(const APropName: String; ADefValue: Cardinal): Cardinal;
function ReadInt64(const APropName: String; ADefValue: Int64): Int64;
function ReadObjectBegin(const AObjectName: String; AStyle: TFDStorageObjectStyle): String; override;
procedure ReadObjectEnd(const AObjectName: String; AStyle: TFDStorageObjectStyle); override;
function ReadAnsiString(const APropName: String; const ADefValue: TFDAnsiString): TFDAnsiString;
function ReadString(const APropName: String; const ADefValue: UnicodeString): UnicodeString;
function ReadValue(const APropName: String; APropIndex: Word; ADataType: TFDDataType;
out ABuff: Pointer; out ALen: Cardinal): Boolean;
function ReadEnum(const APropName: String; ATypeInfo: PTypeInfo; ADefValue: Integer): Integer;
function TestObject(const AObjectName: String): Boolean;
function TestAndReadObjectBegin(const AObjectName: String; AStyle: TFDStorageObjectStyle): Boolean;
function TestProperty(const APropName: String): Boolean;
function TestAndReadProperty(const APropName: String): Boolean;
procedure WriteBoolean(const APropName: String; const AValue, ADefValue: Boolean);
procedure WriteDate(const APropName: String; const AValue, ADefValue: TDateTime);
procedure WriteFloat(const APropName: String; const AValue, ADefValue: Double);
procedure WriteInteger(const APropName: String; const AValue, ADefValue: Integer);
procedure WriteLongWord(const APropName: String; const AValue, ADefValue: Cardinal);
procedure WriteInt64(const APropName: String; const AValue, ADefValue: Int64);
procedure WriteObjectBegin(const AObjectName: String; AStyle: TFDStorageObjectStyle);
procedure WriteObjectEnd(const AObjectName: String; AStyle: TFDStorageObjectStyle);
procedure WriteAnsiString(const APropName: String; const AValue, ADefValue: TFDAnsiString);
procedure WriteString(const APropName: String; const AValue, ADefValue: UnicodeString);
procedure WriteValue(const APropName: String; APropIndex: Word; ADataType: TFDDataType;
ABuff: Pointer; ALen: Cardinal);
procedure WriteEnum(const APropName: String; ATypeInfo: PTypeInfo; const AValue,
ADefValue: Integer);
function GetBookmark: TObject;
procedure SetBookmark(const AValue: TObject);
end;
{-------------------------------------------------------------------------------}
{ TFDBinStorage }
{-------------------------------------------------------------------------------}
type
TFDBinStorageHeader = record
FMagic: array[0..3] of Byte;
FVersion: Word;
FDictionaryOffset: Cardinal;
end;
const
C_Magic: array[0..3] of Byte = (Ord('A'), Ord('D'), Ord('B'), Ord('S'));
C_ObjBegin = 255;
C_ObjEnd = 254;
constructor TFDBinStorage.Create;
begin
inherited Create;
FDictionary := TFDStringList.Create(dupIgnore, False, True);
FDictionary.UseLocale := False;
end;
{-------------------------------------------------------------------------------}
destructor TFDBinStorage.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FDictionary);
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.Open(AResOpts: TObject; AEncoder: TObject;
const AFileName: String; AStream: TStream; AMode: TFDStorageMode);
var
rHdr: TFDBinStorageHeader;
iLen: Word;
s: String;
begin
inherited Open(AResOpts, AEncoder, AFileName, AStream, AMode);
if FMode = smWrite then begin
FillChar(rHdr, SizeOf(rHdr), 0);
FStream.Write(rHdr, SizeOf(rHdr));
FDictionary.Sorted := True;
FDictionaryIndex := 0;
end
else begin
if (FStream.Read(rHdr, SizeOf(rHdr)) <> SizeOf(rHdr)) or
not CompareMem(@rHdr.FMagic[0], @C_Magic[0], SizeOf(C_Magic)) then
FDException(Self, [S_FD_LStan], er_FD_StanStrgInvBinFmt, []);
FStreamVersion := rHdr.FVersion;
FStream.Seek(rHdr.FDictionaryOffset, soBeginning);
FDictionary.Sorted := False;
iLen := 0;
while FStream.Read(iLen, SizeOf(iLen)) = SizeOf(iLen) do begin
SetLength(s, iLen div SizeOf(WideChar));
if iLen > 0 then
FStream.Read(s[1], iLen);
FDictionary.Add(s);
end;
FStream.Seek(SizeOf(rHdr), soBeginning);
CheckBuffer(C_FD_MaxFixedSize);
end;
end;
{-------------------------------------------------------------------------------}
function DoCompareObjects(List: TStringList; Index1, Index2: Integer): Integer;
begin
Result := Integer(TFDStringList(List).Ints[Index1]) -
Integer(TFDStringList(List).Ints[Index2]);
end;
procedure TFDBinStorage.Close;
var
i: Integer;
iLen: Word;
iPos: int64;
rHdr: TFDBinStorageHeader;
s: String;
begin
if (FStream <> nil) and (FMode = smWrite) then begin
iPos := FStream.Position;
FDictionary.Sorted := False;
FDictionary.CustomSort(DoCompareObjects);
for i := 0 to FDictionary.Count - 1 do begin
iLen := Word(Length(FDictionary[i]) * SizeOf(WideChar));
FStream.Write(iLen, SizeOf(iLen));
if iLen > 0 then begin
s := FDictionary[i];
FStream.Write(s[1], iLen);
end;
end;
Move(C_Magic[0], rHdr.FMagic[0], SizeOf(C_Magic));
rHdr.FVersion := FStreamVersion;
rHdr.FDictionaryOffset := Cardinal(iPos);
FStream.Seek(0, soBeginning);
FStream.Write(rHdr, SizeOf(rHdr));
FStream.Seek(0, soEnd);
end;
FDictionary.Clear;
inherited Close;
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.InternalReadProperty(var AName: String);
var
iDict: Word;
begin
iDict := 0;
FStream.Read(iDict, SizeOf(iDict));
if (iDict and $FF) < C_ObjEnd then
AName := FDictionary[iDict];
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.TestProperty(const APropName: String): Boolean;
var
iPos: Int64;
sName: String;
begin
iPos := FStream.Position;
InternalReadProperty(sName);
Result := CompareText(sName, APropName) = 0;
FStream.Position := iPos;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.TestAndReadProperty(const APropName: String): Boolean;
var
iPos: Int64;
sName: String;
begin
iPos := FStream.Position;
InternalReadProperty(sName);
Result := CompareText(sName, APropName) = 0;
if not Result then
FStream.Position := iPos;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.ReadBoolean(const APropName: String;
ADefValue: Boolean): Boolean;
begin
if TestAndReadProperty(APropName) then
FStream.Read(Result, SizeOf(Result))
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.ReadDate(const APropName: String;
ADefValue: TDateTime): TDateTime;
begin
if TestAndReadProperty(APropName) then
FStream.Read(Result, SizeOf(Result))
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.ReadEnum(const APropName: String; ATypeInfo: PTypeInfo;
ADefValue: Integer): Integer;
function DoReadEnum1: Integer;
begin
if TestAndReadProperty(APropName) then begin
FStream.Read(Result, SizeOf(Result));
if (FStreamVersion = 1) and (ATypeInfo = TypeInfo(TFDDataType)) then begin
if Result >= Integer(dtXML) then
Inc(Result);
if Result >= Integer(dtTimeIntervalFull) then
Inc(Result, 3);
if Result >= Integer(dtExtended) then
Inc(Result);
if Result >= Integer(dtSingle) then
Inc(Result);
end;
end
else
Result := ADefValue;
end;
function DoReadEnum3: Integer;
var
sStr: String;
begin
sStr := ReadString(APropName, '');
if sStr = '' then
Result := ADefValue
else
Result := GetEnumValue(ATypeInfo, Copy(
GetCachedEnumName(ATypeInfo, Integer(ADefValue)), 1, 2) + sStr);
end;
var
iDict: Word;
begin
if FStreamVersion >= 5 then begin
if TestAndReadProperty(APropName) then begin
FStream.Read(iDict, SizeOf(iDict));
Result := GetEnumValue(ATypeInfo, FDictionary[iDict]);
end
else
Result := ADefValue;
end
else if FStreamVersion >= 3 then
Result := DoReadEnum3
else
Result := DoReadEnum1;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.ReadFloat(const APropName: String;
ADefValue: Double): Double;
begin
if TestAndReadProperty(APropName) then
FStream.Read(Result, SizeOf(Result))
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.ReadInteger(const APropName: String;
ADefValue: Integer): Integer;
begin
if TestAndReadProperty(APropName) then
FStream.Read(Result, SizeOf(Result))
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.ReadLongWord(const APropName: String;
ADefValue: Cardinal): Cardinal;
begin
if TestAndReadProperty(APropName) then
FStream.Read(Result, SizeOf(Result))
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.ReadInt64(const APropName: String; ADefValue: Int64): Int64;
begin
if TestAndReadProperty(APropName) then
FStream.Read(Result, SizeOf(Result))
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.TestObject(const AObjectName: String): Boolean;
var
sName: String;
iPos: Int64;
begin
iPos := FStream.Position;
Result := InternalReadObject(sName);
if Result then
Result := CompareText(AObjectName, sName) = 0;
FStream.Position := iPos;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.TestAndReadObjectBegin(const AObjectName: String;
AStyle: TFDStorageObjectStyle): Boolean;
var
sName: String;
iPos: Int64;
begin
iPos := FStream.Position;
Result := InternalReadObject(sName);
if Result then
Result := CompareText(AObjectName, sName) = 0;
if not Result then
FStream.Position := iPos;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.ReadObjectBegin(const AObjectName: String; AStyle: TFDStorageObjectStyle): String;
begin
if not InternalReadObject(Result) then
FDException(Self, [S_FD_LStan], er_FD_StanStrgCantReadObj, ['<unknown>']);
if (Result <> '') and (AObjectName <> '') and (CompareText(Result, AObjectName) <> 0) then
FDException(Self, [S_FD_LStan], er_FD_StanStrgCantReadObj, [AObjectName]);
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.InternalReadObject(var AName: String): Boolean;
var
b: Byte;
iDict: Byte;
begin
Result := (FStream.Read(b, SizeOf(Byte)) = SizeOf(Byte)) and (b = C_ObjBegin);
if Result then begin
FStream.Read(iDict, SizeOf(iDict));
AName := FDictionary[iDict];
end;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.InternalReadObjectEnd: Boolean;
var
b: Byte;
begin
Result := (FStream.Read(b, SizeOf(Byte)) = SizeOf(Byte)) and (b = C_ObjEnd);
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.IsObjectEnd(const AObjectName: String): Boolean;
var
iPos: Int64;
begin
iPos := FStream.Position;
Result := InternalReadObjectEnd;
FStream.Position := iPos;
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.ReadObjectEnd(const AObjectName: String; AStyle: TFDStorageObjectStyle);
begin
InternalReadObjectEnd;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.ReadAnsiString(const APropName: String;
const ADefValue: TFDAnsiString): TFDAnsiString;
var
iLen: Cardinal;
begin
if TestAndReadProperty(APropName) then begin
FStream.Read(iLen, SizeOf(iLen));
SetLength(Result, iLen div SizeOf(TFDAnsiChar));
if iLen <> 0 then
FStream.Read(PFDAnsiString(Result)^, iLen);
end
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.ReadString(const APropName: String;
const ADefValue: UnicodeString): UnicodeString;
var
iLen: Cardinal;
begin
if TestAndReadProperty(APropName) then begin
FStream.Read(iLen, SizeOf(iLen));
SetLength(Result, iLen div SizeOf(WideChar));
if iLen <> 0 then
FStream.Read(Result[1], iLen);
end
else
Result := ADefValue;
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.ReadValue(const APropName: String; APropIndex: Word;
ADataType: TFDDataType; out ABuff: Pointer; out ALen: Cardinal): Boolean;
var
oMS: TMemoryStream;
iProp: Word;
iLen: Byte;
iBmk: Int64;
begin
ABuff := nil;
ALen := 0;
Result := False;
if FStreamVersion >= 4 then begin
iBmk := FStream.Position;
FStream.Read(iProp, SizeOf(iProp));
if iProp <> APropIndex then begin
FStream.Position := iBmk;
Exit;
end;
end
else begin
if not TestAndReadProperty(APropName) then
Exit;
end;
Result := True;
case ADataType of
dtObject,
dtRowSetRef,
dtCursorRef,
dtRowRef,
dtArrayRef:
ALen := 0;
dtMemo,
dtHMemo,
dtWideMemo,
dtXML,
dtWideHMemo,
dtByteString,
dtBlob,
dtHBlob,
dtHBFile,
dtAnsiString,
dtWideString:
FStream.Read(ALen, SizeOf(Cardinal));
dtBoolean:
ALen := SizeOf(WordBool);
dtSByte:
ALen := SizeOf(ShortInt);
dtInt16:
ALen := SizeOf(SmallInt);
dtInt32:
ALen := SizeOf(Integer);
dtInt64:
ALen := SizeOf(Int64);
dtByte:
ALen := SizeOf(Byte);
dtUInt16:
ALen := SizeOf(Word);
dtUInt32,
dtParentRowRef:
ALen := SizeOf(Cardinal);
dtUInt64:
ALen := SizeOf(UInt64);
dtSingle:
ALen := SizeOf(Single);
dtDouble:
ALen := SizeOf(Double);
dtExtended:
begin
ALen := SizeOf(Extended);
{$IF SizeOf(Extended) = 8}
oMS := CheckBuffer(SizeOf(TExtended80Rec));
ABuff := oMS.Memory;
FStream.Read(ABuff^, SizeOf(TExtended80Rec));
PExtended(ABuff)^ := Extended(PExtended80Rec(ABuff)^);
Exit;
{$ENDIF}
end;
dtCurrency:
ALen := SizeOf(Currency);
dtBCD,
dtFmtBCD:
if FStreamVersion >= 4 then begin
FStream.Read(iLen, SizeOf(iLen));
ALen := SizeOf(TBcd);
oMS := CheckBuffer(ALen);
ABuff := oMS.Memory;
if iLen <> 0 then
FStream.Read(ABuff^, iLen);
FillChar((PByte(ABuff) + iLen)^, ALen - iLen, 0);
Exit;
end
else
ALen := SizeOf(TBcd);
dtDateTime:
ALen := SizeOf(TDateTimeAlias);
dtDateTimeStamp:
ALen := SizeOf(TSQLTimeStamp);
dtTimeIntervalFull,
dtTimeIntervalYM,
dtTimeIntervalDS:
ALen := SizeOf(TFDSQLTimeInterval);
dtTime,
dtDate:
ALen := SizeOf(Integer);
dtGUID:
ALen := SizeOf(TGUID);
end;
oMS := CheckBuffer(ALen);
if ALen <> 0 then
FStream.Read(oMS.Memory^, ALen);
ABuff := oMS.Memory;
if ADataType in [dtWideMemo, dtXML, dtWideHMemo, dtWideString] then
ALen := ALen div SizeOf(WideChar);
end;
{-------------------------------------------------------------------------------}
function TFDBinStorage.LookupName(const AName: String): Word;
var
i: Integer;
begin
i := FDictionary.IndexOf(AName);
if i = -1 then begin
if FDictionaryIndex >= $FFFF then
FDException(Self, [S_FD_LStan], er_FD_StanStrgDictOverflow, []);
FDictionary.AddInt(AName, LongWord(FDictionaryIndex));
Result := Word(FDictionaryIndex);
Inc(FDictionaryIndex);
if FDictionaryIndex = C_ObjEnd then begin
LookupName('<end>');
LookupName('<begin>');
end;
end
else
Result := Word(LongWord(FDictionary.Ints[i]));
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.InternalWriteProperty(const APropName: String;
ApValue: Pointer; ALen: Cardinal);
var
iDict: Word;
begin
iDict := LookupName(APropName);
FStream.Write(iDict, SizeOf(iDict));
if ApValue <> nil then
FStream.Write(ApValue^, ALen);
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.WriteBoolean(const APropName: String; const AValue,
ADefValue: Boolean);
begin
if AValue <> ADefValue then
InternalWriteProperty(APropName, @AValue, SizeOf(AValue));
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.WriteDate(const APropName: String; const AValue,
ADefValue: TDateTime);
begin
if AValue <> ADefValue then
InternalWriteProperty(APropName, @AValue, SizeOf(AValue));
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.WriteEnum(const APropName: String; ATypeInfo: PTypeInfo;
const AValue, ADefValue: Integer);
procedure DoWriteEnum1;
var
iVal: Integer;
begin
iVal := AValue;
if (FStreamVersion = 1) and (ATypeInfo = TypeInfo(TFDDataType)) then begin
if iVal > Integer(dtWideMemo) then
Dec(iVal);
if iVal > Integer(dtDateTimeStamp) then
Dec(iVal, 3);
end;
InternalWriteProperty(APropName, @iVal, SizeOf(iVal));
end;
procedure DoWriteEnum3;
begin
WriteString(APropName, Copy(GetCachedEnumName(ATypeInfo, AValue), 3, MAXINT),
Copy(GetCachedEnumName(ATypeInfo, ADefValue), 3, MAXINT))
end;
var
iDict: Word;
begin
if AValue <> ADefValue then
if FStreamVersion >= 5 then begin
iDict := LookupName(GetCachedEnumName(ATypeInfo, AValue));
InternalWriteProperty(APropName, @iDict, SizeOf(iDict));
end
else if FStreamVersion >= 3 then
DoWriteEnum3()
else
DoWriteEnum1();
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.WriteFloat(const APropName: String; const AValue,
ADefValue: Double);
begin
if AValue <> ADefValue then
InternalWriteProperty(APropName, @AValue, SizeOf(AValue));
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.WriteInteger(const APropName: String; const AValue,
ADefValue: Integer);
begin
if AValue <> ADefValue then
InternalWriteProperty(APropName, @AValue, SizeOf(AValue));
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.WriteLongWord(const APropName: String;
const AValue, ADefValue: Cardinal);
var
uiVal: Cardinal;
begin
if AValue <> ADefValue then begin
uiVal := AValue;
InternalWriteProperty(APropName, @uiVal, SizeOf(uiVal));
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.WriteInt64(const APropName: String; const AValue,
ADefValue: Int64);
begin
if AValue <> ADefValue then
InternalWriteProperty(APropName, @AValue, SizeOf(AValue));
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.WriteObjectBegin(const AObjectName: String; AStyle: TFDStorageObjectStyle);
var
b: Byte;
iDict: Byte;
begin
b := C_ObjBegin;
FStream.Write(b, SizeOf(Byte));
iDict := LookupName(AObjectName);
FStream.Write(iDict, SizeOf(iDict));
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.WriteObjectEnd(const AObjectName: String; AStyle: TFDStorageObjectStyle);
var
b: Byte;
begin
b := C_ObjEnd;
FStream.Write(b, SizeOf(Byte));
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.WriteAnsiString(const APropName: String; const AValue,
ADefValue: TFDAnsiString);
var
iLen: Cardinal;
begin
if AValue <> ADefValue then begin
InternalWriteProperty(APropName, nil, 0);
iLen := Length(AValue) * SizeOf(TFDAnsiChar);
FStream.Write(iLen, SizeOf(iLen));
if iLen <> 0 then
FStream.Write(PFDAnsiString(AValue)^, iLen);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.WriteString(const APropName: String;
const AValue, ADefValue: UnicodeString);
var
iLen: Cardinal;
begin
if AValue <> ADefValue then begin
InternalWriteProperty(APropName, nil, 0);
iLen := Length(AValue) * SizeOf(WideChar);
FStream.Write(iLen, SizeOf(iLen));
if iLen <> 0 then
FStream.Write(AValue[1], iLen);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.WriteValue(const APropName: String; APropIndex: Word;
ADataType: TFDDataType; ABuff: Pointer; ALen: Cardinal);
var
iLen: Byte;
{$IF SizeOf(Extended) = 8}
rExt80: TExtended80Rec;
{$ENDIF}
begin
if ABuff = nil then
Exit;
if FStreamVersion >= 4 then
FStream.Write(APropIndex, SizeOf(APropIndex))
else
InternalWriteProperty(APropName, nil, 0);
case ADataType of
dtObject,
dtRowSetRef,
dtCursorRef,
dtRowRef,
dtArrayRef:
;
dtMemo,
dtHMemo,
dtWideMemo,
dtXML,
dtWideHMemo,
dtByteString,
dtBlob,
dtHBlob,
dtHBFile,
dtAnsiString,
dtWideString:
begin
if ADataType in [dtWideMemo, dtXML, dtWideHMemo, dtWideString] then
ALen := ALen * SizeOf(WideChar);
FStream.Write(ALen, SizeOf(ALen));
FStream.Write(ABuff^, ALen);
end;
dtBCD,
dtFmtBCD:
if FStreamVersion >= 4 then begin
iLen := 2 + (PBcd(ABuff)^.Precision + 1) div 2;
FStream.Write(iLen, SizeOf(iLen));
FStream.Write(ABuff^, iLen);
end
else
FStream.Write(ABuff^, ALen);
{$IF SizeOf(Extended) = 8}
dtExtended:
begin
rExt80 := TExtended80Rec(PExtended(ABuff)^);
FStream.Write(rExt80, SizeOf(rExt80));
end;
{$ENDIF}
else
FStream.Write(ABuff^, ALen);
end;
end;
{-------------------------------------------------------------------------------}
type
TFDBinStorageBmk = class(TObject)
private
FPos: Int64;
end;
function TFDBinStorage.GetBookmark: TObject;
begin
Result := TFDBinStorageBmk.Create;
TFDBinStorageBmk(Result).FPos := FStream.Position;
end;
{-------------------------------------------------------------------------------}
procedure TFDBinStorage.SetBookmark(const AValue: TObject);
begin
FStream.Position := TFDBinStorageBmk(AValue).FPos;
end;
{-------------------------------------------------------------------------------}
var
oFact: TFDFactory;
initialization
oFact := TFDMultyInstanceFactory.Create(TFDBinStorage, IFDStanStorage,
'BIN;.FDS;.FDB;.BIN;.DAT;');
finalization
FDReleaseFactory(oFact);
end.
|
unit TItems_U;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TItems = class
private
{ Private declarations }
itemType : string ;
itemDescription : string ;
itemCost : real ;
public
{ Public declarations }
Constructor Create (pItemType, pItemDescription : string ; pItemCost : real );
Function GetItemType : string ;
Function GetItemDescription : string ;
Function GetItemCost : real ;
end;
implementation
{ TItems }
constructor TItems.Create(pItemType, pItemDescription: string; pItemCost: real);
begin
itemType := pItemType ;
itemDescription := pItemDescription ;
itemCost := pItemCost ;
end;
function TItems.GetItemCost: real;
begin
Result := itemCost ;
end;
function TItems.GetItemDescription: string;
begin
Result := itemDescription ;
end;
function TItems.GetItemType: string;
begin
Result := itemType ;
end;
end.
|
(*
AVR Basic Compiler
Copyright 1997-2002 Silicon Studio Ltd.
Copyright 2008 Trioflex OY
http://www.trioflex.com
*)
unit coff;
interface
Uses
Classes;
{$A-}
Type
T_FILHDR = Record // COFF File Header
f_magic: WORD; //* magic number */
f_nscns: WORD; //* number of sections */
f_timdat: CARDINAL; //* time & date stamp */
f_symptr: CARDINAL; //* file pointer to symtab */
f_nsyms: CARDINAL; //* number of symtab entries */
f_opthdr: WORD; //* sizeof(optional hdr) */
f_flags: WORD; //* flags */
End;
Const
F_RELFLG = $0001;
F_EXEC = $0002;
F_LNNO = $0004;
F_LSYMS = $0008;
F_AR32WR = $0100;
Type
T_SCNHDR = Record
s_name: Array[0..7] Of Char; //* section name */
s_paddr: CARDINAL; //* physical address, aliased s_nlib */
s_vaddr: CARDINAL; //* virtual address */
s_size: CARDINAL; //* section size */
s_scnptr: CARDINAL; //* file ptr to raw data for section */
s_relptr: CARDINAL; //* file ptr to relocation */
s_lnnoptr: CARDINAL; //* file ptr to line numbers */
s_nreloc: WORD; //* number of relocation entries */
s_nlnno: WORD; //* number of line number entries */
s_flags: CARDINAL; //* flags */
End;
Const
STYP_TEXT = $0020;
STYP_DATA = $0040;
STYP_BSS = $0080;
Type
T_SYM_NAM = Record
Case integer of
0: (e_zeroes, e_offset: CARDINAL);
1: (e_name: Array[0..7] Of Char);
End;
T_SYMENT = Record
e: T_SYM_NAM; // ??
e_value: CARDINAL;
e_scnum: SmallInt; // 16 Bit Int
e_type: Word;
e_sclass: Byte;
e_numaux: Byte;
End;
T_RELOC = Record
r_vaddr,
r_symndx: CARDINAL;
r_type: WORD;
r_etype: WORD; // FAKE For MPASM !
End;
T_BBF = Record
res1: Cardinal;
snum: Word;
res2,
res3: Cardinal;
next: Word;
res4: Word;
End;
T_EBF = Record
res1: Cardinal;
snum: Word;
res2,
res3,
res4: Cardinal;
End;
T_AVR_LNUM = Record
l_paddr: Cardinal;
l_lnno: Word;
End;
//
// My Stuff
//
Type
PCOFF_LdSymbol = ^TCOFF_LdSymbol;
TCOFF_LdSymbol = Record
e_name: String; // Loaded from String Table if Reguired
e_rvalue, // Adjusted Value
// T_SYMENT
e_value: CARDINAL;
e_scnum: SmallInt; // 16 Bit Int
e_type: Word;
e_sclass: Byte;
e_numaux: Byte;
End;
Var
COFF_FileHeader: T_FILHDR;
COFF_SectionHeader: T_SCNHDR;
COFF_SymbolEntry: T_SYMENT;
COFF_AuxEntry: Array[0..17] Of Byte;
COFF_Reloc: T_RELOC;
//
COFF_Stream: TFileStream;
//
COFF_LdSymbol: PCOFF_LdSymbol;
COFF_SymList: TList; // List of TCOFF_LdSymbol
implementation
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1999-2001 Borland Software Corp. }
{ }
{*******************************************************}
unit WbmConst;
interface
resourcestring
sDataSetFieldBlank = 'Data set field is blank';
sDataSetFieldNotFound = 'Data set field not found: %s';
sNotDataSetField = 'Field is not a dataset field: %s';
ScriptTableName = '%s_Table';
sNoXMLBroker = '%s: missing XMLBroker';
sFieldNotFound = '%0:s: Field "%1:s" not found';
sXMLBrokerNotDefined = '%s.XMLBroker = nil';
sSubmitQuery = 'Submit';
sResetQuery = 'Reset';
sApplyUpdates = 'Apply Updates';
sFieldNameBlank = '%s.FieldName = ''''';
sXMLComponentNotDefined = '%s.XMLComponent = nil';
ScriptNamesVar = '%s_Names';
ScriptIDsVar = '%s_IDs';
ScriptXMLDisplayName = '%s_Disp';
sInvalidParent = 'Invalid parent';
sInvalidParentClass = 'Invalid parent class: %s';
sDuplicateStatusField = 'Field %s ignored, only one status field allowed';
sFirstButton = '|<';
sLastButton = '>|';
sPriorButton = '<';
sNextButton = '>';
sPriorPageButton = '<<';
sNextPageButton = '>>';
sDeleteButton = ' - ';
sInsertButton = ' + ';
sUndoButton = 'Undo';
sPostButton = 'Post';
sWarningsBody = '<TABLE BORDER=1 CELLPADDING=4>'#13#10 +
'<TR><TD><P ALIGN=CENTER>Design-time Warnings<P>'#13#10 +
'%s'#13#10 +
'</TD></TD>'#13#10 +
'</TABLE>'#13#10;
ScriptDocumentVarName = '%s_Doc';
ScriptXMLVarName = '%s_XML';
sInvalidWebComponentsCreation = 'Invalid Web component creation';
ScriptRowSetVarName = '%s_RS';
sApplyUpdatesError = 'ApplyUpdates error. Error count: %d.';
sDeltaNotFound = 'Missing Delta Packet';
sXMLBrokerNotConnected = 'XMLBroker: %s is not connected';
sDataSetNotActive = 'DataSet: %s is not active';
implementation
end.
|
unit WordFinder.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, System.Generics.Collections,
Vcl.ComCtrls, HGM.Button, Vcl.Grids, HGM.Controls.VirtualTable, HGM.License;
type
//Матрица символов из полей
TChars = array[1..5, 1..5] of Char;
//Состояние символа соответственно матрице символов. Занят или нет и порядковый номер
TCharState = record
State:Boolean;
Ord:Integer;
end;
//Матрица состояния символов
TCharsState = array[1..5, 1..5] of TCharState;
//Данные слова
TWordData = record
Text:string; //Слово
Gifts:Integer;
Mask:TCharsState;//Матрица состояний, чтоб отобразить при выборе
end;
//Список найденных слов
TWords = class(TTableData<TWordData>)
//Поиск слова в списке
function IndexOf(Text:string):Integer;
end;
TFormMain = class(TForm)
Panel1: TPanel;
PanelPad: TPanel;
EditLet1: TEdit;
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
Edit4: TEdit;
Edit5: TEdit;
Edit6: TEdit;
Edit7: TEdit;
Edit8: TEdit;
Edit9: TEdit;
Edit10: TEdit;
Edit11: TEdit;
Edit12: TEdit;
Edit13: TEdit;
Edit14: TEdit;
Edit15: TEdit;
Edit16: TEdit;
Edit17: TEdit;
Edit18: TEdit;
Edit19: TEdit;
Edit20: TEdit;
Edit21: TEdit;
Edit22: TEdit;
Edit23: TEdit;
Edit24: TEdit;
Label1: TLabel;
LabelWrdCount: TLabel;
ButtonFind: TButtonFlat;
ButtonRandom: TButtonFlat;
ButtonClose: TButtonFlat;
ButtonAbout: TButtonFlat;
ButtonClear: TButtonFlat;
TableExWords: TTableEx;
Label2: TLabel;
hTrue: ThTrue;
procedure EditLet1Click(Sender: TObject);
procedure EditLet1KeyPress(Sender: TObject; var Key: Char);
procedure ButtonFindClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure ListViewWordsChange(Sender: TObject; Item: TListItem; Change: TItemChange);
procedure EditFieldChange(Sender: TObject);
procedure ButtonRandomClick(Sender: TObject);
procedure ButtonCloseClick(Sender: TObject);
procedure ButtonAboutClick(Sender: TObject);
procedure ButtonClearClick(Sender: TObject);
procedure TableExWordsGetData(FCol, FRow: Integer; var Value: string);
procedure TableExWordsItemClick(Sender: TObject; MouseButton: TMouseButton;
const Index: Integer);
procedure TableExWordsDblClick(Sender: TObject);
private
FChars:TChars;
FCharsState:TCharsState;
Dict:TStringList;
FWords:TWords;
FFieldGifts:TCharsState;
procedure UpdateGifts;
function CalcGifts(Item:TWordData):Integer;
public
destructor Destroy; override;
end;
var
FormMain: TFormMain;
implementation
uses Math, HGM.Common.Utils, ShellApi;
{$R *.dfm}
function CharState(AState:Boolean; AOrd:Integer):TCharState;
begin
Result.State:=AState;
Result.Ord:=AOrd;
end;
//Очистка состояния символов
procedure ClearState(var States:TCharsState);
var x, y:Integer;
begin
for x:= 1 to 5 do
for y:= 1 to 5 do
States[x, y]:=CharState(False, 0);
end;
procedure TFormMain.ButtonAboutClick(Sender: TObject);
begin
MessageBox(Handle,
'Разработчик: Геннадий Малинин aka HemulGM'+#13+#10+
'Delphi, 2019 год'+#13+#10+
'Программа для поиска слов в матрице символов 5х5'+#13+#10+
'Сайт: www.hemulgm.ru',
'', MB_ICONINFORMATION or MB_OK);
end;
procedure TFormMain.ButtonClearClick(Sender: TObject);
begin
ClearState(FFieldGifts);
UpdateGifts;
end;
procedure TFormMain.ButtonCloseClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TFormMain.ButtonFindClick(Sender: TObject);
var i, y, x: Integer;
Wrd:string;
Item:TWordData;
//Проверка координаты на корректность и доступность
function CheckCoord(xv, yv:Integer):Boolean;
begin
Result:=False;
//Проверка границ
if (xv < 1) or (yv < 1) then Exit;
if (xv > 5) or (yv > 5) then Exit;
//Проверка на доступность
Result:=not FCharsState[xv, yv].State;
end;
//Поиск следующего символа относительно текущей позиции
function FindNext(x1, y1, c:Integer):Boolean;
var nx, ny, vr:Integer;
begin
//Если длина слова равна текущему символу, то слово собрано, выходим
if Wrd.Length = c then Exit(True);
Result:=False;
nx:=0;
ny:=0;
//8 вариантов направления //5 2 8
for vr:= 1 to 8 do //3 x 6
begin //4 1 7
case vr of
1: begin nx:=x1; ny:=y1+1; end;
2: begin nx:=x1; ny:=y1-1; end;
3: begin nx:=x1-1; ny:=y1; end;
4: begin nx:=x1-1; ny:=y1-1; end;
5: begin nx:=x1-1; ny:=y1+1; end;
6: begin nx:=x1+1; ny:=y1; end;
7: begin nx:=x1+1; ny:=y1+1; end;
8: begin nx:=x1+1; ny:=y1-1; end;
end;
//Проверяем полученное смещение на границы массива и на не занятость
if CheckCoord(nx, ny) then
begin
//Если наш символ как раз совпадает со следующим символом в слове,
if FChars[nx, ny] = Wrd[c+1] then
begin
FCharsState[nx, ny]:=CharState(True, c+1); //То устанавливаем состояние - занят и его порядок в слове
Result:=FindNext(nx, ny, c+1); //И передаем далее рекурсивно
if not Result then //Если дальше не нашли ничего
FCharsState[nx, ny]:=CharState(False, 0)//То текущий символ освобождаем
else Exit; //А если всё нашли, то далее можно не продолжать
end;
end;
end;
end;
begin
//Собираем данные из полей в массив
for i:= 0 to PanelPad.ControlCount-1 do
begin
if PanelPad.Controls[i] is TEdit then
begin
x:=(PanelPad.Controls[i] as TEdit).Tag;
FChars[(x-1) mod 5+1, (x-1) div 5+1]:=AnsiLowerCase((PanelPad.Controls[i] as TEdit).Text)[1];
end;
end;
//Основной цикл поиска слов
FWords.BeginUpdate;
FWords.Clear; //Очистим список слов
if Dict.Count > 0 then
begin
for i:= 0 to Dict.Count-1 do
begin
Wrd:=AnsiLowerCase(Dict[i]); //Берём слово из словаря
if Wrd.Length < 3 then Continue; //Если оно менее 3, то пропускаем
ClearState(FCharsState); //Очищаем состояние матрицы отмеченных символов
for y:= 1 to 5 do //Идём по матрице символов
for x := 1 to 5 do
begin //Если символ в матрице является началом слова
if Wrd[1] = AnsiLowerCase(FChars[x, y])[1] then
begin
FCharsState[x, y]:=CharState(True, 1); //То, устанвляиваем состояние текущего символа - занят
if FindNext(x, y, 1) then //Передаем на поиск следующих символов слова
begin //Если нашли всё слово
if FWords.IndexOf(Wrd) < 0 then //И его уже нет в списке
begin //То добавляем его в список
Item.Text:=Wrd; //Слово
Item.Mask:=FCharsState; //Состояние символов
FWords.Add(Item); //
end;
end;
ClearState(FCharsState); //Каждый раз очищаем состояние, чтоб ничего не осталось
end;
end;
end;
for x:=0 to FWords.Count-1 do
begin
Item:=FWords[x];
Item.Gifts:=CalcGifts(Item);
FWords[x]:=Item;
end; {
//Процесс поиска закончен, отображаем результат
//Сортируем по количеству символов в слове
for x:=0 to FWords.Count-1 do
begin
for i:=0 to FWords.Count-2 do
if FWords[i].Text.Length < FWords[i+1].Text.Length then
begin
Item:=FWords[i];
FWords[i]:=FWords[i+1];
FWords[i+1]:=Item;
end;
end; }
//Процесс поиска закончен, отображаем результат
//Сортируем по количеству символов в слове
for x:=0 to FWords.Count-1 do
for i:=0 to FWords.Count-2 do
if (FWords[i].Gifts < FWords[i+1].Gifts) and (FWords[i+1].Text.Length > 2) then
begin
Item:=FWords[i];
FWords[i]:=FWords[i+1];
FWords[i+1]:=Item;
end;
end
else
MessageBox(Handle, 'Необходим файл словаря dict.txt в каталоге с программой!', 'Внимание', MB_ICONWARNING or MB_OK);
FWords.EndUpdate;
//Если хоть одно слово нашли,
if FWords.Count > 0 then
begin
TableExWords.ItemIndex:=0; //то выбираем первое
end;
//Покажем, сколько слов нашли
LabelWrdCount.Caption:=IntToStr(FWords.Count);
TableExWords.DoItemClick; //И выделяем его в полях
end;
procedure TFormMain.ButtonRandomClick(Sender: TObject);
var i:Integer;
begin
for i:= 0 to PanelPad.ControlCount-1 do
if PanelPad.Controls[i] is TEdit then
(PanelPad.Controls[i] as TEdit).Text:=AnsiChar(RandomRange(Ord('А'), Ord('Я')+1));
ClearState(FFieldGifts);
UpdateGifts;
ButtonFindClick(nil);
end;
function TFormMain.CalcGifts(Item: TWordData): Integer;
var y, x: Integer;
c2, c3:Integer;
begin
Result:=0;
c2:=0;
c3:=0;
for y:= 1 to 5 do
for x:= 1 to 5 do
if Item.Mask[x, y].State then
begin
case FFieldGifts[x, y].Ord of
0: Inc(Result, Item.Mask[x, y].Ord);
1: Inc(Result, Item.Mask[x, y].Ord * 2);
2: Inc(Result, Item.Mask[x, y].Ord * 3);
3: begin
Inc(Result, Item.Mask[x, y].Ord);
Inc(c2);
end;
4: begin
Inc(Result, Item.Mask[x, y].Ord);
Inc(c3);
end;
end;
end;
for y:= 1 to c2 do Result:=Result*2;
for y:= 1 to c3 do Result:=Result*3;
end;
destructor TFormMain.Destroy;
begin
Dict.Free;
FWords.Free;
inherited;
end;
procedure TFormMain.EditFieldChange(Sender: TObject);
begin
//Если наша ячейка последняя, то выполним поиск автоматически
if (Sender as TEdit).Tag = 25 then ButtonFindClick(nil);
end;
procedure TFormMain.EditLet1Click(Sender: TObject);
begin
(Sender as TEdit).SelectAll;
end;
procedure TFormMain.EditLet1KeyPress(Sender: TObject; var Key: Char);
var x:Integer;
Item:TCharState;
begin
case Key of
#13: Key:=#0;
'1'..'9':
begin
x:=(Sender as TEdit).Tag;
Item:=FFieldGifts[(x-1) mod 5+1, (x-1) div 5+1];
Item.Ord:=StrToInt(Key);
FFieldGifts[(x-1) mod 5+1, (x-1) div 5+1]:=Item;
UpdateGifts;
Key:=#0;
Exit;
end;
' ':
begin
Key:=#0;
x:=(Sender as TEdit).Tag;
Item:=FFieldGifts[(x-1) mod 5+1, (x-1) div 5+1];
Item.Ord:=0;
FFieldGifts[(x-1) mod 5+1, (x-1) div 5+1]:=Item;
UpdateGifts;
Exit;
end;
#8:
begin
Key:=#0;
SelectNext((Sender as TEdit), False, True);
Exit;
end;
end;
//Следующее поле по TabOrder
SelectNext((Sender as TEdit), True, True);
end;
procedure TFormMain.FormCreate(Sender: TObject);
var i:Integer;
begin
ClientHeight:=480;
ClientWidth:=530;
//Создаем и загружаем словарь
Dict:=TStringList.Create;
if not hTrue.IsCreated then Halt;
if FileExists('dict.txt') then
try
Dict.LoadFromFile('dict.txt')
except
MessageBox(Handle, 'Необходим файл словаря dict.txt в каталоге с программой!', 'Внимание', MB_ICONWARNING or MB_OK);
end
else
MessageBox(Handle, 'Необходим файл словаря dict.txt в каталоге с программой!', 'Внимание', MB_ICONWARNING or MB_OK);
//Список найденных слов
FWords:=TWords.Create(TableExWords);
end;
procedure TFormMain.ListViewWordsChange(Sender: TObject; Item: TListItem; Change: TItemChange);
begin
TableExWords.DoItemClick;
end;
procedure TFormMain.TableExWordsDblClick(Sender: TObject);
begin
if IndexInList(TableExWords.ItemIndex, FWords.Count) then
begin
ShellExecute(Handle, 'open', PWideChar('http://gramota.ru/slovari/dic/?word='+FWords[TableExWords.ItemIndex].Text+'&all=x'), nil, nil, SW_NORMAL);
end;
end;
procedure TFormMain.TableExWordsGetData(FCol, FRow: Integer; var Value: string);
begin
if not IndexInList(FRow, FWords.Count) then Exit;
case FCol of
0: Value:=AnsiUpperCase(FWords[FRow].Text);
1: Value:=FWords[FRow].Gifts.ToString +' ';
end;
end;
procedure TFormMain.TableExWordsItemClick(Sender: TObject;
MouseButton: TMouseButton; const Index: Integer);
var x, y, t: Integer;
Item:TWordData;
begin
//Очищаем цвет полей
for x:= 0 to PanelPad.ControlCount-1 do
if PanelPad.Controls[x] is TEdit then
(PanelPad.Controls[x] as TEdit).Color:=clWhite;
//Если выбран элемент
if IndexInList(TableExWords.ItemIndex, FWords.Count) then
begin
//Выбранный элемент
Item:=FWords[TableExWords.ItemIndex];
//Идём по матрице символов
for y:= 1 to 5 do
for x:= 1 to 5 do
begin
//Если символ использовался, то ищем нужное поле
//и указываем цвет выделения и степень его насыщенности в зависимости от порядкового номера в слове
if Item.Mask[x, y].State then
for t:= 0 to PanelPad.ControlCount-1 do
if PanelPad.Controls[t] is TEdit then //Координаты в номер
if (PanelPad.Controls[t] as TEdit).Tag = (y-1) * 5 + 1 + (x-1) then
begin
(PanelPad.Controls[t] as TEdit).Color:=ColorLighter($00A85400, Item.Mask[x, y].Ord * 8);
end;
end;
end;
end;
procedure TFormMain.UpdateGifts;
var x, y, t: Integer;
begin
//Очищаем цвет полей
for x:= 0 to PanelPad.ControlCount-1 do
if PanelPad.Controls[x] is TEdit then
(PanelPad.Controls[x] as TEdit).Font.Color:=clBlack;
for y:= 1 to 5 do
for x:= 1 to 5 do
begin
if FFieldGifts[x, y].Ord > 0 then
for t:= 0 to PanelPad.ControlCount-1 do
if PanelPad.Controls[t] is TEdit then //Координаты в номер
if (PanelPad.Controls[t] as TEdit).Tag = (y-1) * 5 + 1 + (x-1) then
begin
case FFieldGifts[x, y].Ord of
1:(PanelPad.Controls[t] as TEdit).Font.Color:=$00FF1298;
2:(PanelPad.Controls[t] as TEdit).Font.Color:=$00FF1298;
3:(PanelPad.Controls[t] as TEdit).Font.Color:=$000033CC;
4:(PanelPad.Controls[t] as TEdit).Font.Color:=$000033CC;
end;
end;
end;
end;
{ TWords }
function TWords.IndexOf(Text: string): Integer;
var i: Integer;
begin
Result:=-1;
for i:= 0 to Count-1 do
if Items[i].Text = Text then Exit(i);
end;
end.
|
program BIOSInfo;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, uSMBIOS;
procedure GetBIOSInfo;
Var
SMBios: TSMBios;
LBIOS: TBiosInformation;
OEMStr: TOEMStringsInformation;
i: Integer;
begin
SMBios:=TSMBios.Create;
try
LBIOS:=SMBios.BiosInfo;
WriteLn('Bios Information');
WriteLn('Vendor '+LBIOS.VendorStr);
WriteLn('Version '+LBIOS.VersionStr);
WriteLn('Start Segment '+IntToHex(LBIOS.RAWBiosInformation^.StartingSegment,4));
WriteLn('ReleaseDate '+LBIOS.ReleaseDateStr);
WriteLn(Format('Bios Rom Size %d k',[64*(LBIOS.RAWBiosInformation^.BiosRomSize+1)]));
if LBIOS.RAWBiosInformation^.SystemBIOSMajorRelease<>$ff then
WriteLn(Format('System BIOS Major Release %d',[LBIOS.RAWBiosInformation^.SystemBIOSMajorRelease]));
if LBIOS.RAWBiosInformation^.SystemBIOSMinorRelease<>$ff then
WriteLn(Format('System BIOS Minor Release %d',[LBIOS.RAWBiosInformation^.SystemBIOSMinorRelease]));
//If the system does not have field upgradeable embedded controller firmware, the value is 0FFh.
if LBIOS.RAWBiosInformation^.EmbeddedControllerFirmwareMajorRelease<>$ff then
WriteLn(Format('Embedded Controller Firmware Major Release %d',[LBIOS.RAWBiosInformation^.EmbeddedControllerFirmwareMajorRelease]));
if LBIOS.RAWBiosInformation^.EmbeddedControllerFirmwareMinorRelease<>$ff then
WriteLn(Format('Embedded Controller Firmware Minor Releasee %d',[LBIOS.RAWBiosInformation^.EmbeddedControllerFirmwareMinorRelease]));
WriteLn;
if SMBios.HasOEMStringsInfo then
begin
Writeln('OEM Strings');
Writeln('-----------');
for OEMStr in SMBios.OEMStringsInfo do
for i:=1 to OEMStr.RAWOEMStringsInformation^.Count do
Writeln(OEMStr.GetOEMString(i));
end;
finally
SMBios.Free;
end;
end;
begin
try
GetBIOSInfo;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln;
Writeln('Press Enter to exit');
Readln;
end.
|
{*******************************************************}
{ }
{ Delphi REST Client Framework }
{ }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit REST.Backend.Consts;
interface
resourcestring
sUnknownQueryCondition = 'Unknown query condition';
sMissingClassForQuery = 'Missing class for query';
sMissingExpressionForQuery = 'Missing expression for query';
sObjectNotAttachedToBackend = 'Object not attached to backend';
sFormatParseError = 'Parse Error: %0:s (%1:d)';
sFormatKinveyError = 'Kinvey Error: %0:s. %1:s';
sSessionIDRequired = 'SessionID required';
sAPIKeyRequired = 'APIKey required';
sBackendClassNameRequired = 'BackendClassName required';
sJSONObjectRequired = 'JSON object required';
sInvalidAuthenticationForThisOperation = 'Invalid authentication (%0:s) for this operation. %1:s';
sUseValidAuthentication = 'Use %s.';
sUseValidAuthentications = 'Use %0:s or %1:s.';
sAccessDenied = 'Access denied';
sJSONObjectExpected = 'JSON object expected';
sChannelNamesExpected = 'Channel names expected';
sDeviceNamesExpected = 'Device names expected';
sOneUserExpected = 'One user expected';
sNoBackendService = 'Cannot complete operation because a service is not available. %s.Provider property must not be nil.';
sObjectIDRequired = 'ObjectID required';
sMasterKeyRequired = 'MasterKey required';
sAuthTokenRequired = 'AuthToken required';
sBackendCollectionNameRequired = 'BackendCollectionName required';
sAppKeyRequired = 'AppKey required';
sAppSecretRequired = 'AppSecret required';
sMasterSecretRequired = 'MasterSecret required';
sUserNameRequired = 'User name required';
sGroupNameRequired = 'Group name required';
sNoMetaFactory = 'No meta type factory';
sObjectNotFound = 'Object not found';
sPushEventsProviderRequired = 'Provider is nil. A provider is required to use push events';
sPushEventsNotSupportByProvider = 'Push events are not supported by the "%s" provider on this platform';
sPushEventsPushServiceConnectionRequired = 'Application is not connected to push service. Push service connection is required to register or unregister an application';
sPushDeviceNoPushService = 'No %0:s compatible push service available for device "%1:s"';
sPushDevicePushServiceNotFound = 'Push service "%1:s" not found. %0:s requires this service.';
sPushDeviceGCMAppIDBlank = 'GCM AppID is blank. Specify a GCM AppID.';
sServiceNotSupportedByProvider = 'Service not supported by %s provider';
sDuplicateProviderID = 'Duplicatate ProviderID: %s';
sProviderNotFound = 'Provider not found: %s';
sDuplicateService = 'Duplicate service for provider: %s';
sUnregisterServiceNotFound = 'Unregister error. Service not found for provider: %s';
sUnregisterProviderNotFound = 'Unregister error. Provider "%s" not registered.';
sBackendThreadRunning = 'A backend thread can''t be started because it is already running.';
sUnsupportedBackendQueryType = 'Unsupported Backend query type: %s';
sCreateAtRequired = 'CreatedAt required';
sDownloadUrlRequired = 'Download URL required';
sExpiresAtRequired = 'ExpiresAt required';
sUpdatedAtRequired = 'UpdatedAt required';
sFileNameRequired = 'Filename required';
sFileIDRequired = 'FileID required';
sDataTypeNameRequired = 'Data type name required';
sUnexpectedDeleteObjectCount = 'Unexpected delete count: %d';
sParameterNotMetaType = 'Parameter is not meta type';
sPushDeviceParseInstallationIDBlankDelete = 'Installation ID is blank. Installation ID is required to delete a Parse installation';
sKinveyRequiresCustomEndpoint = 'Kinvey push service requires a custom endpoint.';
sExtrasName = 'Name';
sExtrasValue = 'Value';
sDeviceIDUnavailable = 'DeviceID is not available. This application may not be configured to support push notifications';
sDeviceTokenUnavailable = 'DeviceToken is not available. This application may not be configured to support push notifications';
sDeviceTokenRequestFailed = 'DeviceToken request failed: %s';
sOperationRequiresAuthentication = 'Request requires %s authentication';
sAuthenticationNotSupported = 'Authentication type, %s, is not supported.';
sParameterNotLogin = 'Login parameter does not identify a logged in user';
sBackendAuthMultipleProviders = 'In order to Login or Signup, all components must be connected to the same provider';
sBackendAuthMismatchedProvider = 'Auth component and connected components must use the same provider';
sLoginRequired = 'Operation cannot be completed because a user is not logged in.';
sWrongProvider = 'Wrong provider';
implementation
end.
|
var
a,b,Sum,Difference, Product, Quotient: Real;
begin
Write('Введите число a: ');
Readln(a);
Write('Введите число b: ');
Readln(b);
Sum:=sqr(a)+sqr(b);
Writeln('Сумма квадратов a и b равна: ',Sum);
Difference:=sqr(a)-sqr(b);
Writeln('Разность квадратов a и b равна: ',Difference);
Product:=sqr(a)*sqr(b);
Writeln('Произведение квадратов a и b равна: ',Product);
Quotient:=sqr(a)/sqr(b);
Writeln('Частное квадратов a и b равна: ',Quotient);
end. |
{ *********************************************************************** }
{ }
{ Delphi 通用 Hook 库,支持 Windows x86/x64, Ansi/Unicode }
{ }
{ 设计:Lsuper 2016.10.01 }
{ 备注: }
{ 审核: }
{ }
{ Copyright (c) 1998-2016 Super Studio }
{ }
{ *********************************************************************** }
{ }
{ 注意: }
{ }
{ 1、Hook/Unhook 放到单元,初始化、析构中做,否则可能因改写内存没挂起 }
{ 其他线程的调用而造成错误 }
{ }
{ 限制: }
{ }
{ 1、限制:不能 Hook 代码大小小于 5 个字节的函数 }
{ 2、限制:不能 Hook 前 5 个字节中有跳转指令的函数 }
{ }
{ 希望使用的朋友们自己也具有一定的汇编或者逆向知识,Hook 函数前请确定 }
{ 该函数不属于上面两种情况 }
{ }
{ 另外钩 COM 对象有一个技巧,如果你想在最早时机勾住某个 COM 对象可以在 }
{ 你要钩的 COM 对象创建前自己先创建一个该对象,Hook 住然后释放你自己的 }
{ 对象,这样这个函数已经被下钩子了,而且是钩在这个 COM 对象创建前的 }
{ }
{ *********************************************************************** }
{ }
{ 2016.10.01 - Lsuper }
{ }
{ 1、参考 wr960204 武稀松 的原始实现: }
{ https://code.google.com/p/delphi-hook-library }
{ 2、修改 BeaEngine 引擎为 LDE64 长度反编译引擎,大幅降低大小 }
{ https://github.com/BeaEngine/lde64 }
{ http://www.beaengine.org/download/LDE64-x86.zip }
{ http://www.beaengine.org/download/LDE64-x64.rar }
{ 3、去除原始实现对多线程冻结的处理,通常建议 Hook/Unhook 放到单元 }
{ 初始化、析构中做,否则可能因改写内存没挂起其他线程造成错误 }
{ }
{ *********************************************************************** }
{ }
{ 2012.02.01 - wr960204 武稀松,http://www.raysoftware.cn }
{ }
{ 1、使用了开源的 BeaEngine 反汇编引擎,BeaEngine 的好处是可以用 BCB 编 }
{ 译成 OMF 格式的 Obj,直接链接进 dcu 或目标文件中,无须额外的 DLL }
{ 2、BeaEngine 引擎: }
{ https://github.com/BeaEngine/beaengine }
{ http://beatrix2004.free.fr/BeaEngine/index1.php }
{ http://www.beaengine.org/ }
{ }
{ *********************************************************************** }
unit HookUtils;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{.$DEFINE USEINT3} { 在机器指令中插入 INT3,断点指令方便调试 }
interface
function HookProc(ATargetProc, ANewProc: Pointer;
out AOldProc: Pointer): Boolean; overload;
function HookProc(const ATargetModule, ATargetProc: string; ANewProc: Pointer;
out AOldProc: Pointer): Boolean; overload;
function UnHookProc(var AOldProc: Pointer): Boolean;
implementation
{$IFDEF CPUX64}
{$DEFINE USELONGJMP}
{$ENDIF}
uses
Windows;
const
defAllocMemPageSize = 4096;
type
{$IFNDEF FPC} {$IF CompilerVersion < 23}
NativeUInt = LongWord;
{$IFEND} {$ENDIF}
TJMPCode = packed record
{$IFDEF USELONGJMP}
JMP: Word;
JmpOffset: Int32;
Addr: UIntPtr;
{$ELSE}
JMP: Byte;
Addr: UINT_PTR;
{$ENDIF}
end;
PJMPCode = ^TJMPCode;
TOldProc = packed record
{$IFDEF USEINT3}
Int3OrNop: Byte;
{$ENDIF}
BackCode: array[0..$20 - 1] of Byte;
JmpRealFunc: TJMPCode;
JmpHookFunc: TJMPCode;
BackUpCodeSize: Integer;
OldFuncAddr: Pointer;
end;
POldProc = ^TOldProc;
TNewProc = packed record
JMP: Byte;
Addr: Integer;
end;
PNewProc = ^TNewProc;
////////////////////////////////////////////////////////////////////////////////
//修改:Lsuper 2016.10.01
//功能:引入 LDE64 长度反编译引擎 ShellCode
//参数:
////////////////////////////////////////////////////////////////////////////////
const
{$IFDEF CPUX64}
{$I 'HookUtils.64.inc'}
{$ELSE}
{$I 'HookUtils.32.inc'}
{$ENDIF}
////////////////////////////////////////////////////////////////////////////////
//修改:Lsuper 2016.10.01
//功能:LDE64 长度反编译引擎函数定义
//参数:
//注意:x64 下需要处理 DEP 问题
////////////////////////////////////////////////////////////////////////////////
function LDE(lpData: Pointer; arch: LongWord): NativeUInt;
var
D: Pointer;
F: LongWord;
M: TMemoryBasicInformation;
P: function (lpData: Pointer; arch: LongWord): NativeUInt; stdcall;
begin
D := @defLde64ShellCode;
if VirtualQuery(D, M, SizeOf(M)) <> 0 then
if M.Protect <> PAGE_EXECUTE_WRITECOPY then
VirtualProtect(D, SizeOf(defLde64ShellCode), PAGE_EXECUTE_WRITECOPY, @F);
P := D;
Result := P(lpData, arch);
end;
////////////////////////////////////////////////////////////////////////////////
//修改:Lsuper 2016.10.01
//功能:计算需要覆盖的机器指令大小,借助了 LDE64 反汇编引擎以免指令被从中间切开
//参数:
////////////////////////////////////////////////////////////////////////////////
function CalcHookProcSize(AFunc: Pointer): Integer;
const
lde_archi_32 = 0;
lde_archi_64 = 64;
{$IFDEF CPUX64}
lde_archi_default = lde_archi_64;
{$ELSE}
lde_archi_default = lde_archi_32;
{$ENDIF}
var
nLen: LongInt;
pCode: PByte;
begin
Result := 0;
pCode := AFunc;
while Result < SizeOf(TNewProc) do
begin
nLen := LDE(pCode, lde_archi_default);
Inc(pCode, nLen);
Inc(Result, nLen);
end;
end;
////////////////////////////////////////////////////////////////////////////////
//修改:Lsuper 2016.10.01
//功能:
//参数:
//注意:尝试在指定指针 APtr 的正负 2Gb 以内分配内存,32 位肯定是这样的
// 64 位 JMP 都是相对的,操作数是 32 位整数,所以必须保证新的函数在旧函数
// 的正负2GB内,否则没法跳转到或者跳转回来
////////////////////////////////////////////////////////////////////////////////
function TryAllocMem(APtr: Pointer; ASize: LongWord): Pointer;
const
{$IFDEF CPUX64}
defAllocationType = MEM_COMMIT or MEM_RESERVE or MEM_TOP_DOWN;
{$ELSE}
defAllocationType = MEM_COMMIT or MEM_RESERVE;
{$ENDIF}
KB: Int64 = 1024;
MB: Int64 = 1024 * 1024;
GB: Int64 = 1024 * 1024 * 1024;
var
mbi: TMemoryBasicInformation;
Min, Max: Int64;
pbAlloc: Pointer;
sSysInfo: TSystemInfo;
begin
GetSystemInfo(sSysInfo);
Min := NativeUInt(APtr) - 2 * GB;
if Min <= 0 then
Min := 1;
Max := NativeUInt(APtr) + 2 * GB;
Result := nil;
pbAlloc := Pointer(Min);
while NativeUInt(pbAlloc) < Max do
begin
if (VirtualQuery(pbAlloc, mbi, SizeOf(mbi)) = 0) then
Break;
if ((mbi.State or MEM_FREE) = MEM_FREE) and (mbi.RegionSize >= ASize) and
(mbi.RegionSize >= sSysInfo.dwAllocationGranularity) then
begin
pbAlloc := PByte(NativeUInt((NativeUInt(pbAlloc) + (sSysInfo.dwAllocationGranularity - 1)) div
sSysInfo.dwAllocationGranularity) * sSysInfo.dwAllocationGranularity);
Result := VirtualAlloc(pbAlloc, ASize, defAllocationType, PAGE_EXECUTE_READWRITE);
if Result <> nil then
Break;
end;
pbAlloc := Pointer(NativeUInt(mbi.BaseAddress) + mbi.RegionSize);
end;
end;
////////////////////////////////////////////////////////////////////////////////
//设计:Lsuper 2016.10.01
//功能:挂接 API
//参数:
//注意:如果 ATargetModule 没有被 LoadLibrary 下 Hook 会失败,建议先手工 Load
////////////////////////////////////////////////////////////////////////////////
function HookProc(const ATargetModule, ATargetProc: string; ANewProc: Pointer;
out AOldProc: Pointer): Boolean;
var
nHandle: THandle;
pProc: Pointer;
begin
Result := False;
nHandle := GetModuleHandle(PChar(ATargetModule));
if nHandle = 0 then
Exit;
pProc := GetProcAddress(nHandle, PChar(ATargetProc));
if pProc = nil then
Exit;
Result := HookProc(pProc, ANewProc, AOldProc);
end;
////////////////////////////////////////////////////////////////////////////////
//设计: Lsuper 2016.10.01
//功能: 替换原有过程指针,并保留原有指针
//参数:ATargetProc:被替换过程指针, NewProc:新的过程指针。
// OldProc: 被替换过程的备份过程指针(和原来的不是一个)
//注意:对 Delphi 的 bpl 类函数需要 FixFunc 查找真正的函数地址
//注意:需要判断是否 Win8 的 jmp xxx; int 3; ... 的特殊精简模式
//注意:64 位中会有一种情况失败,就是 VirtualAlloc 不能在被Hook函数地址正负 2Gb
// 范围内分配到内存。不过这个可能微乎其微,几乎不可能发生
////////////////////////////////////////////////////////////////////////////////
function HookProc(ATargetProc, ANewProc: Pointer; out AOldProc: Pointer): Boolean;
procedure FixFunc();
type
TJmpCode = packed record
Code: Word; // 间接跳转指定,为 $25FF
{$IFDEF CPUX64}
RelOffset: Int32; // JMP QWORD PTR [RIP + RelOffset]
{$ELSE}
Addr: PPointer; // JMP DWORD PTR [JMPPtr] 跳转指针地址,指向保存目标地址的指针
{$ENDIF}
end;
PJmpCode = ^TJmpCode;
const
csJmp32Code = $25FF;
var
P: PPointer;
begin
if PJmpCode(ATargetProc)^.Code = csJmp32Code then
begin
{$IFDEF CPUX64}
P := Pointer(NativeUInt(ATargetProc) + PJmpCode(ATargetProc)^.RelOffset + SizeOf(TJmpCode));
ATargetProc := P^;
{$ELSE}
P := PJmpCode(ATargetProc)^.Addr;
ATargetProc := P^;
{$ENDIF}
FixFunc();
end;
end;
var
oldProc: POldProc;
newProc: PNewProc;
backCodeSize: Integer;
newProtected, oldProtected: DWORD;
{$IFDEF USELONGJMP}
JmpAfterBackCode: PJMPCode;
{$ENDIF}
begin
Result := False;
if (ATargetProc = nil) or (ANewProc = nil) then
Exit;
FixFunc();
newProc := PNewProc(ATargetProc);
backCodeSize := CalcHookProcSize(ATargetProc);
if backCodeSize < 0 then
Exit;
if not VirtualProtect(ATargetProc, backCodeSize, PAGE_EXECUTE_READWRITE,
oldProtected) then
Exit;
AOldProc := TryAllocMem(ATargetProc, defAllocMemPageSize);
// AOldProc := VirtualAlloc(nil, defAllocMemPageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
if AOldProc = nil then
Exit;
FillMemory(AOldProc, SizeOf(TOldProc), $90);
oldProc := POldProc(AOldProc);
{$IFDEF USEINT3}
oldProc.Int3OrNop := $CC;
{$ENDIF}
oldProc.BackUpCodeSize := backCodeSize;
oldProc.OldFuncAddr := ATargetProc;
CopyMemory(@oldProc^.BackCode, ATargetProc, backCodeSize);
{$IFDEF USELONGJMP}
JmpAfterBackCode := PJMPCode(@oldProc^.BackCode[backCodeSize]);
oldProc^.JmpRealFunc.JMP := $25FF;
oldProc^.JmpRealFunc.JmpOffset := 0;
oldProc^.JmpRealFunc.Addr := UIntPtr(Int64(ATargetProc) + backCodeSize);
JmpAfterBackCode^.JMP := $25FF;
JmpAfterBackCode^.JmpOffset := 0;
JmpAfterBackCode^.Addr := UIntPtr(Int64(ATargetProc) + backCodeSize);
oldProc^.JmpHookFunc.JMP := $25FF;
oldProc^.JmpHookFunc.JmpOffset := 0;
oldProc^.JmpHookFunc.Addr := UIntPtr(ANewProc);
{$ELSE}
oldProc^.JmpRealFunc.JMP := $E9;
oldProc^.JmpRealFunc.Addr := (NativeInt(ATargetProc) + backCodeSize) -
(NativeInt(@oldProc^.JmpRealFunc) + 5);
oldProc^.JmpHookFunc.JMP := $E9;
oldProc^.JmpHookFunc.Addr := NativeInt(ANewProc) -
(NativeInt(@oldProc^.JmpHookFunc) + 5);
{$ENDIF}
// Init
FillMemory(ATargetProc, backCodeSize, $90);
newProc^.JMP := $E9;
newProc^.Addr := NativeInt(@oldProc^.JmpHookFunc) -
(NativeInt(@newProc^.JMP) + 5);;
// NativeInt(ANewProc) - (NativeInt(@newProc^.JMP) + 5);
if not VirtualProtect(ATargetProc, backCodeSize, oldProtected, newProtected) then
Exit;
// 刷新处理器中的指令缓存,以免这部分指令被缓存执行的时候不一致
FlushInstructionCache(GetCurrentProcess(), newProc, backCodeSize);
FlushInstructionCache(GetCurrentProcess(), oldProc, defAllocMemPageSize);
Result := True;
end;
////////////////////////////////////////////////////////////////////////////////
//设计: Lsuper 2016.10.01
//功能: 解除钩子
//参数:OldProc:在 HookProc 中保存的指针
////////////////////////////////////////////////////////////////////////////////
function UnHookProc(var AOldProc: Pointer): Boolean;
var
oldProc: POldProc absolute AOldProc;
newProc: PNewProc;
backCodeSize: Integer;
newProtected, oldProtected: DWORD;
begin
Result := False;
if AOldProc = nil then
Exit;
backCodeSize := oldProc^.BackUpCodeSize;
newProc := PNewProc(oldProc^.OldFuncAddr);
if not VirtualProtect(newProc, backCodeSize, PAGE_EXECUTE_READWRITE, oldProtected) then
Exit;
CopyMemory(newProc, @oldProc^.BackCode, oldProc^.BackUpCodeSize);
if not VirtualProtect(newProc, backCodeSize, oldProtected, newProtected) then
Exit;
VirtualFree(oldProc, defAllocMemPageSize, MEM_FREE);
// 刷新处理器中的指令缓存,以免这部分指令被缓存执行的时候不一致
FlushInstructionCache(GetCurrentProcess(), newProc, backCodeSize);
AOldProc := nil;
Result := True;
end;
end.
|
unit Ap;
interface
uses Math;
/////////////////////////////////////////////////////////////////////////
// constants
/////////////////////////////////////////////////////////////////////////
const
MachineEpsilon = 5E-16;
MaxRealNumber = 1E300;
MinRealNumber = 1E-300;
/////////////////////////////////////////////////////////////////////////
// arrays
/////////////////////////////////////////////////////////////////////////
type
Complex = record
X, Y: Double;
end;
TInteger1DArray = array of LongInt;
TReal1DArray = array of Double;
TComplex1DArray = array of Complex;
TBoolean1DArray = array of Boolean;
TInteger2DArray = array of array of LongInt;
TReal2DArray = array of array of Double;
TComplex2DArray = array of array of Complex;
TBoolean2DArray = array of array of Boolean;
/////////////////////////////////////////////////////////////////////////
// Functions/procedures
/////////////////////////////////////////////////////////////////////////
function AbsReal(X : Extended):Extended;
function AbsInt (I : Integer):Integer;
function RandomReal():Extended;
function RandomInteger(I : Integer):Integer;
function Sign(X:Extended):Integer;
function DynamicArrayCopy(const A: TInteger1DArray):TInteger1DArray;overload;
function DynamicArrayCopy(const A: TReal1DArray):TReal1DArray;overload;
function DynamicArrayCopy(const A: TComplex1DArray):TComplex1DArray;overload;
function DynamicArrayCopy(const A: TBoolean1DArray):TBoolean1DArray;overload;
function DynamicArrayCopy(const A: TInteger2DArray):TInteger2DArray;overload;
function DynamicArrayCopy(const A: TReal2DArray):TReal2DArray;overload;
function DynamicArrayCopy(const A: TComplex2DArray):TComplex2DArray;overload;
function DynamicArrayCopy(const A: TBoolean2DArray):TBoolean2DArray;overload;
function AbsComplex(const Z : Complex):Double;
function Conj(const Z : Complex):Complex;
function CSqr(const Z : Complex):Complex;
function C_Complex(const X : Double):Complex;
function C_Opposite(const Z : Complex):Complex;
function C_Add(const Z1 : Complex; const Z2 : Complex):Complex;
function C_Mul(const Z1 : Complex; const Z2 : Complex):Complex;
function C_AddR(const Z1 : Complex; const R : Double):Complex;
function C_MulR(const Z1 : Complex; const R : Double):Complex;
function C_Sub(const Z1 : Complex; const Z2 : Complex):Complex;
function C_SubR(const Z1 : Complex; const R : Double):Complex;
function C_RSub(const R : Double; const Z1 : Complex):Complex;
function C_Div(const Z1 : Complex; const Z2 : Complex):Complex;
function C_DivR(const Z1 : Complex; const R : Double):Complex;
function C_RDiv(const R : Double; const Z2 : Complex):Complex;
function C_Equal(const Z1 : Complex; const Z2 : Complex):Boolean;
function C_NotEqual(const Z1 : Complex; const Z2 : Complex):Boolean;
function C_EqualR(const Z1 : Complex; const R : Double):Boolean;
function C_NotEqualR(const Z1 : Complex; const R : Double):Boolean;
implementation
/////////////////////////////////////////////////////////////////////////
// Functions/procedures
/////////////////////////////////////////////////////////////////////////
function AbsReal(X : Extended):Extended;
begin
Result := Abs(X);
end;
function AbsInt (I : Integer):Integer;
begin
Result := Abs(I);
end;
function RandomReal():Extended;
begin
Result := Random;
end;
function RandomInteger(I : Integer):Integer;
begin
Result := Random(I);
end;
function Sign(X:Extended):Integer;
begin
if X>0 then
Result := 1
else if X<0 then
Result := -1
else
Result := 0;
end;
/////////////////////////////////////////////////////////////////////////
// dynamical arrays copying
/////////////////////////////////////////////////////////////////////////
function DynamicArrayCopy(const A: TInteger1DArray):TInteger1DArray;overload;
var
I: Integer;
begin
SetLength(Result, High(A)+1);
for I:=Low(A) to High(A) do
Result[I]:=A[I];
end;
function DynamicArrayCopy(const A: TReal1DArray):TReal1DArray;overload;
var
I: Integer;
begin
SetLength(Result, High(A)+1);
for I:=Low(A) to High(A) do
Result[I]:=A[I];
end;
function DynamicArrayCopy(const A: TComplex1DArray):TComplex1DArray;overload;
var
I: Integer;
begin
SetLength(Result, High(A)+1);
for I:=Low(A) to High(A) do
Result[I]:=A[I];
end;
function DynamicArrayCopy(const A: TBoolean1DArray):TBoolean1DArray;overload;
var
I: Integer;
begin
SetLength(Result, High(A)+1);
for I:=Low(A) to High(A) do
Result[I]:=A[I];
end;
function DynamicArrayCopy(const A: TInteger2DArray):TInteger2DArray;overload;
var
I,J: Integer;
begin
SetLength(Result, High(A)+1);
for I:=Low(A) to High(A) do
begin
SetLength(Result[I], High(A[I])+1);
for J:=Low(A[I]) to High(A[I]) do
Result[I,J]:=A[I,J];
end;
end;
function DynamicArrayCopy(const A: TReal2DArray):TReal2DArray;overload;
var
I,J: Integer;
begin
SetLength(Result, High(A)+1);
for I:=Low(A) to High(A) do
begin
SetLength(Result[I], High(A[I])+1);
for J:=Low(A[I]) to High(A[I]) do
Result[I,J]:=A[I,J];
end;
end;
function DynamicArrayCopy(const A: TComplex2DArray):TComplex2DArray;overload;
var
I,J: Integer;
begin
SetLength(Result, High(A)+1);
for I:=Low(A) to High(A) do
begin
SetLength(Result[I], High(A[I])+1);
for J:=Low(A[I]) to High(A[I]) do
Result[I,J]:=A[I,J];
end;
end;
function DynamicArrayCopy(const A: TBoolean2DArray):TBoolean2DArray;overload;
var
I,J: Integer;
begin
SetLength(Result, High(A)+1);
for I:=Low(A) to High(A) do
begin
SetLength(Result[I], High(A[I])+1);
for J:=Low(A[I]) to High(A[I]) do
Result[I,J]:=A[I,J];
end;
end;
/////////////////////////////////////////////////////////////////////////
// complex numbers
/////////////////////////////////////////////////////////////////////////
function AbsComplex(const Z : Complex):Double;
var
W : Double;
XABS : Double;
YABS : Double;
V : Double;
begin
XABS := AbsReal(Z.X);
YABS := AbsReal(Z.Y);
W := Max(XABS, YABS);
V := Min(XABS, YABS);
if V=0 then
begin
Result := W;
end
else
begin
Result := W*SQRT(1+Sqr(V/W));
end;
end;
function Conj(const Z : Complex):Complex;
begin
Result.X := Z.X;
Result.Y := -Z.Y;
end;
function CSqr(const Z : Complex):Complex;
begin
Result.X := Sqr(Z.X)-Sqr(Z.Y);
Result.Y := 2*Z.X*Z.Y;
end;
function C_Complex(const X : Double):Complex;
begin
Result.X := X;
Result.Y := 0;
end;
function C_Opposite(const Z : Complex):Complex;
begin
Result.X := -Z.X;
Result.Y := -Z.Y;
end;
function C_Add(const Z1 : Complex; const Z2 : Complex):Complex;
begin
Result.X := Z1.X+Z2.X;
Result.Y := Z1.Y+Z2.Y;
end;
function C_Mul(const Z1 : Complex; const Z2 : Complex):Complex;
begin
Result.X := Z1.X*Z2.X-Z1.Y*Z2.Y;
Result.Y := Z1.X*Z2.Y+Z1.Y*Z2.X;
end;
function C_AddR(const Z1 : Complex; const R : Double):Complex;
begin
Result.X := Z1.X+R;
Result.Y := Z1.Y;
end;
function C_MulR(const Z1 : Complex; const R : Double):Complex;
begin
Result.X := Z1.X*R;
Result.Y := Z1.Y*R;
end;
function C_Sub(const Z1 : Complex; const Z2 : Complex):Complex;
begin
Result.X := Z1.X-Z2.X;
Result.Y := Z1.Y-Z2.Y;
end;
function C_SubR(const Z1 : Complex; const R : Double):Complex;
begin
Result.X := Z1.X-R;
Result.Y := Z1.Y;
end;
function C_RSub(const R : Double; const Z1 : Complex):Complex;
begin
Result.X := R-Z1.X;
Result.Y := -Z1.Y;
end;
function C_Div(const Z1 : Complex; const Z2 : Complex):Complex;
var
A : Double;
B : Double;
C : Double;
D : Double;
E : Double;
F : Double;
begin
A := Z1.X;
B := Z1.Y;
C := Z2.X;
D := Z2.Y;
if AbsReal(D)<AbsReal(C) then
begin
E := D/C;
F := C+D*E;
Result.X := (A+B*E)/F;
Result.Y := (B-A*E)/F;
end
else
begin
E := C/D;
F := D+C*E;
Result.X := (B+A*E)/F;
Result.Y := (-A+B*E)/F;
end;
end;
function C_DivR(const Z1 : Complex; const R : Double):Complex;
begin
Result.X := Z1.X/R;
Result.Y := Z1.Y/R;
end;
function C_RDiv(const R : Double; const Z2 : Complex):Complex;
var
A : Double;
C : Double;
D : Double;
E : Double;
F : Double;
begin
A := R;
C := Z2.X;
D := Z2.Y;
if AbsReal(D)<AbsReal(C) then
begin
E := D/C;
F := C+D*E;
Result.X := A/F;
Result.Y := -A*E/F;
end
else
begin
E := C/D;
F := D+C*E;
Result.X := A*E/F;
Result.Y := -A/F;
end;
end;
function C_Equal(const Z1 : Complex; const Z2 : Complex):Boolean;
begin
Result := (Z1.X=Z2.X) and (Z1.Y=Z2.Y);
end;
function C_NotEqual(const Z1 : Complex; const Z2 : Complex):Boolean;
begin
Result := (Z1.X<>Z2.X) or (Z1.Y<>Z2.Y);
end;
function C_EqualR(const Z1 : Complex; const R : Double):Boolean;
begin
Result := (Z1.X=R) and (Z1.Y=0);
end;
function C_NotEqualR(const Z1 : Complex; const R : Double):Boolean;
begin
Result := (Z1.X<>R) or (Z1.Y<>0);
end;
end.
|
{*******************************************************}
{ }
{ Delphi VCL Extensions (RX) }
{ }
{ Copyright (c) 1995, 1996 AO ROSNO }
{ Copyright (c) 1997, 1998 Master-Bank }
{ }
{ Patched by Polaris Software }
{*******************************************************}
unit rxObjStr;
interface
{$I RX.INC}
uses
SysUtils, Classes;
type
{ TObjectStrings }
TDestroyEvent = procedure(Sender, AObject: TObject) of object;
TObjectSortCompare = function (const S1, S2: string;
Item1, Item2: TObject): Integer of object;
TObjectStrings = class(TStringList)
private
FOnDestroyObject: TDestroyEvent;
protected
procedure DestroyObject(AObject: TObject); virtual;
procedure PutObject(Index: Integer; AObject: TObject); override;
public
procedure Clear; override;
procedure Delete(Index: Integer); override;
procedure Move(CurIndex, NewIndex: Integer); override;
procedure Remove(Index: Integer);
procedure ParseStrings(const Values: string);
procedure SortList(Compare: TObjectSortCompare);
property OnDestroyObject: TDestroyEvent read FOnDestroyObject
write FOnDestroyObject;
end;
{ THugeList class }
const
MaxHugeListSize = MaxListSize;
type
THugeList = class(TList);
implementation
uses
Consts,
{$IFDEF RX_D6} RTLConsts, {$ENDIF} // Polaris
rxStrUtils;
{ TObjectStrings }
procedure QuickSort(SortList: TStrings; L, R: Integer;
SCompare: TObjectSortCompare);
var
I, J: Integer;
P: TObject;
S: string;
begin
repeat
I := L;
J := R;
P := SortList.Objects[(L + R) shr 1];
S := SortList[(L + R) shr 1];
repeat
while SCompare(SortList[I], S, SortList.Objects[I], P) < 0 do Inc(I);
while SCompare(SortList[J], S, SortList.Objects[J], P) > 0 do Dec(J);
if I <= J then begin
SortList.Exchange(I, J);
Inc(I);
Dec(J);
end;
until I > J;
if L < J then QuickSort(SortList, L, J, SCompare);
L := I;
until I >= R;
end;
procedure TObjectStrings.DestroyObject(AObject: TObject);
begin
if Assigned(FOnDestroyObject) then FOnDestroyObject(Self, AObject)
else if AObject <> nil then AObject.Free;
end;
procedure TObjectStrings.Clear;
var
I: Integer;
begin
if Count > 0 then begin
Changing;
for I := 0 to Count - 1 do Objects[I] := nil;
BeginUpdate;
try
inherited Clear;
finally
EndUpdate;
end;
Changed;
end;
end;
procedure TObjectStrings.Delete(Index: Integer);
begin
Objects[Index] := nil;
inherited Delete(Index);
end;
procedure TObjectStrings.Remove(Index: Integer);
begin
inherited Delete(Index);
end;
procedure TObjectStrings.Move(CurIndex, NewIndex: Integer);
var
TempObject: TObject;
TempString: string;
begin
if CurIndex <> NewIndex then
begin
TempString := Get(CurIndex);
TempObject := GetObject(CurIndex);
inherited Delete(CurIndex);
try
InsertObject(NewIndex, TempString, TempObject);
except
DestroyObject(TempObject);
raise;
end;
end;
end;
procedure TObjectStrings.PutObject(Index: Integer; AObject: TObject);
begin
Changing;
BeginUpdate;
try
if (Index < Self.Count) and (Index >= 0) then
DestroyObject(Objects[Index]);
inherited PutObject(Index, AObject);
finally
EndUpdate;
end;
Changed;
end;
procedure TObjectStrings.ParseStrings(const Values: string);
var
Pos: Integer;
begin
Pos := 1;
BeginUpdate;
try
while Pos <= Length(Values) do Add(ExtractSubstr(Values, Pos, [';']));
finally
EndUpdate;
end;
end;
procedure TObjectStrings.SortList(Compare: TObjectSortCompare);
begin
if Sorted then
{$IFDEF RX_D3}
Error(SSortedListError, 0);
{$ELSE}
raise EListError.Create(LoadStr(SSortedListError));
{$ENDIF}
if Count > 0 then begin
BeginUpdate;
try
QuickSort(Self, 0, Count - 1, Compare);
finally
EndUpdate;
end;
end;
end;
end.
|
unit uCadastroBase;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Data.DB,
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, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TfrmCadBase = class(TForm)
pcPrincipal: TPageControl;
tsGrid: TTabSheet;
tsEdits: TTabSheet;
pn: TPanel;
btInserir: TButton;
btEditar: TButton;
btExcluir: TButton;
pnEditsButtons: TPanel;
btSalvar: TButton;
btCancelar: TButton;
grDados: TDBGrid;
qrDados: TFDQuery;
dsDados: TDataSource;
procedure FormShow(Sender: TObject);
procedure btCancelarClick(Sender: TObject);
procedure btSalvarClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btEditarClick(Sender: TObject);
procedure btExcluirClick(Sender: TObject);
procedure btInserirClick(Sender: TObject);
private
{ Private declarations }
procedure EsconderAbas;
protected
function ValidarObrigatorios: boolean; virtual;
public
{ Public declarations }
end;
var
frmCadBase: TfrmCadBase;
implementation
{$R *.dfm}
uses uSystemutils, udmPrincipal;
{ TfrmCadBase }
procedure TfrmCadBase.btCancelarClick(Sender: TObject);
begin
qrDados.Cancel;
pcPrincipal.ActivePage := tsGrid;
end;
procedure TfrmCadBase.btEditarClick(Sender: TObject);
begin
pcPrincipal.ActivePage := tsEdits;
qrDados.Edit;
end;
procedure TfrmCadBase.btExcluirClick(Sender: TObject);
begin
if MsgConfirm('Tem certeza ue deseja excluir o registro?') then
qrDados.Delete;
end;
procedure TfrmCadBase.btInserirClick(Sender: TObject);
begin
pcPrincipal.ActivePage := tsEdits;
qrDados.Insert;
end;
procedure TfrmCadBase.btSalvarClick(Sender: TObject);
begin
if ValidarObrigatorios then
begin
try
qrDados.Post;
qrDados.Refresh;
pcPrincipal.ActivePage := tsGrid;
except
on E: Exception do
begin
if E.Message.Contains('PRIMARY') then
MsgWarning('Registro duplicado')
else
MsgWarning('Ocorreu um erro: ' + E.Message);
end;
end;
end;
end;
procedure TfrmCadBase.EsconderAbas;
var
I: Integer;
begin
for I := 0 to pcPrincipal.PageCount - 1 do
pcPrincipal.Pages[I].TabVisible := False;
pcPrincipal.ActivePage := tsGrid;
end;
procedure TfrmCadBase.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TfrmCadBase.FormShow(Sender: TObject);
begin
EsconderAbas;
qrDados.Open;
end;
function TfrmCadBase.ValidarObrigatorios: boolean;
begin
Result := true;
end;
end.
|
unit LLVM.Imports.TargetMachine;
interface
//based on TargetMachine.h
uses
LLVM.Imports,
LLVM.Imports.Target,
LLVM.Imports.Types;
type
TLLVMTargetMachineRef = type TLLVMRef;
TLLVMTargetRef = type TLLVMRef;
{$MINENUMSIZE 4}
TLLVMCodeGenOptLevel = (
LLVMCodeGenLevelNone,
LLVMCodeGenLevelLess,
LLVMCodeGenLevelDefault,
LLVMCodeGenLevelAggressive
);
TLLVMRelocMode = (
LLVMRelocDefault,
LLVMRelocStatic,
LLVMRelocPIC,
LLVMRelocDynamicNoPic,
LLVMRelocROPI,
LLVMRelocRWPI,
LLVMRelocROPI_RWPI
);
TLLVMCodeModel = (
LLVMCodeModelDefault,
LLVMCodeModelJITDefault,
LLVMCodeModelTiny,
LLVMCodeModelSmall,
LLVMCodeModelKernel,
LLVMCodeModelMedium,
LLVMCodeModelLarge
);
TLLVMCodeGenFileType = (
LLVMAssemblyFile,
LLVMObjectFile
);
function LLVMGetFirstTarget: TLLVMTargetRef; cdecl; external CLLVMLibrary;
function LLVMGetNextTarget(T: TLLVMTargetRef): TLLVMTargetRef; cdecl; external CLLVMLibrary;
(*===-- Target ------------------------------------------------------------===*)
function LLVMGetTargetFromName(const Name: PLLVMChar): TLLVMTargetRef; cdecl; external CLLVMLibrary;
function LLVMGetTargetFromTriple(const Triple: PLLVMChar; out T: TLLVMTargetRef; out ErrorMessage: PLLVMChar): LongBool; cdecl; external CLLVMLibrary;
function LLVMGetTargetName(T: TLLVMTargetRef): PLLVMChar; cdecl; external CLLVMLibrary;
function LLVMGetTargetDescription(T: TLLVMTargetRef): PLLVMChar; cdecl; external CLLVMLibrary;
function LLVMTargetHasJIT(T: TLLVMTargetRef): LongBool; cdecl; external CLLVMLibrary;
function LLVMTargetHasTargetMachine(T: TLLVMTargetRef): LongBool; cdecl; external CLLVMLibrary;
function LLVMTargetHasAsmBackend(T: TLLVMTargetRef): LongBool; cdecl; external CLLVMLibrary;
(*===-- Target Machine ----------------------------------------------------===*)
function LLVMCreateTargetMachine(T: TLLVMTargetRef; const Triple: PLLVMChar; const CPU: PLLVMChar; const Features: PLLVMChar; Level: TLLVMCodeGenOptLevel; Reloc: TLLVMRelocMode; CodeModel: TLLVMCodeModel): TLLVMTargetMachineRef; cdecl; external CLLVMLibrary;
procedure LLVMDisposeTargetMachine(T: TLLVMTargetMachineRef); cdecl; external CLLVMLibrary;
function LLVMGetTargetMachineTarget(T: TLLVMTargetMachineRef): TLLVMTargetRef; cdecl; external CLLVMLibrary;
function LLVMGetTargetMachineTriple(T: TLLVMTargetMachineRef): PLLVMChar; cdecl; external CLLVMLibrary;
function LLVMGetTargetMachineCPU(T: TLLVMTargetMachineRef): PLLVMChar; cdecl; external CLLVMLibrary;
function LLVMGetTargetMachineFeatureString(T: TLLVMTargetMachineRef): PLLVMChar; cdecl; external CLLVMLibrary;
function LLVMCreateTargetDataLayout(T: TLLVMTargetMachineRef): TLLVMTargetDataRef; cdecl; external CLLVMLibrary;
procedure LLVMSetTargetMachineAsmVerbosity(T: TLLVMTargetMachineRef; VerboseAsm: LongBool); cdecl; external CLLVMLibrary;
function LLVMTargetMachineEmitToFile(T: TLLVMTargetMachineRef; M: TLLVMModuleRef; Filename: PLLVMChar; codegen: TLLVMCodeGenFileType; out ErrorMessage: PLLVMChar): TLLVMBool; cdecl; external CLLVMLibrary;
function LLVMTargetMachineEmitToMemoryBuffer(T: TLLVMTargetMachineRef; M: TLLVMModuleRef; codegen: TLLVMCodeGenFileType; out ErrorMessage: PLLVMChar; out OutMemBuf: TLLVMMemoryBufferRef): TLLVMBool; cdecl; external CLLVMLibrary;
(*===-- Triple ------------------------------------------------------------===*)
{/** Get a triple for the host machine as a string. The result needs to be disposed with LLVMDisposeMessage. */}
function LLVMGetDefaultTargetTriple: PLLVMChar; cdecl; external CLLVMLibrary;
{/** Normalize a target triple. The result needs to be disposed with LLVMDisposeMessage. */}
function LLVMNormalizeTargetTriple(const triple: PLLVMChar):PLLVMChar;cdecl; external CLLVMLibrary;
{/** Get the host CPU as a string. The result needs to be disposed with LLVMDisposeMessage. */}
function LLVMGetHostCPUName:PLLVMChar; cdecl; external CLLVMLibrary;
{/** Get the host CPU's features as a string. The result needs to be disposed with LLVMDisposeMessage. */}
function LLVMGetHostCPUFeatures:PLLVMChar; cdecl; external CLLVMLibrary;
procedure LLVMAddAnalysisPasses(T: TLLVMTargetMachineRef; PM: TLLVMPassManagerRef); cdecl; external CLLVMLibrary;
implementation
end.
|
unit acCustomParametroSistemaDataUn;
interface
uses
SysUtils, Classes, FMTBcd, DB, Provider, osSQLDataSetProvider, SqlExpr,
osCustomDataSetProvider, osUtils, osSQLQuery, osSQLDataSet, DBClient,
osClientDataset, acCustomReportUn;
type
TacCustomParametroSistemaData = class(TDataModule)
MasterDataSet: TosSQLDataset;
MasterProvider: TosSQLDataSetProvider;
ParamQuery: TosSQLQuery;
MasterClientDataset: TosClientDataset;
procedure DataModuleCreate(Sender: TObject);
// procedure MasterClientDatasetCalcFields(DataSet: TDataSet);
private
public
// procedure Validate(PDataSet: TDataSet);
// function GetNextOrcamento : integer;
function getNomeImpressoraClasse(nomeClasseImpressora: string): string; virtual;
function getConfigImpressora(PID: Integer; var config: TConfigImpressao): Boolean; virtual;
end;
var
acCustomParametroSistemaData: TacCustomParametroSistemaData;
implementation
uses acCustomSQLMainDataUn, osErrorHandler, osCIC;
{$R *.dfm}
{function TacCustomParametroSistemaData.GetNextOrcamento: integer;
var
sp: TSQLStoredProc;
iNumOrcamento : integer;
begin
sp := TSQLStoredProc.Create(nil);
try
sp.SQLConnection := MainData.SQLConnection;
sp.StoredProcName := 'OS_PROTOCOLO';
sp.ExecProc;
iNumOrcamento := sp.Params[0].AsInteger;
finally
freeAndNil(sp);
end;
Result := (iNumOrcamento * 10) + CalcDV_Modulo11(iNumOrcamento);
end;
{procedure TacCustomParametroSistemaData.Validate(PDataSet: TDataSet);
begin
with PDataSet, HError do
begin
Clear;
CheckEmpty(FieldByName('IDEmpresa'));
Check;
end;
end;}
procedure TacCustomParametroSistemaData.DataModuleCreate(Sender: TObject);
begin
acCustomSQLMainData.RegisterRefreshTable(tnParametroSistema, MasterClientDataset);
// MainData.RegisterRefreshTable(tnFeriado, FeriadoClientDataSet);
end;
{procedure TacCustomParametroSistemaData.MasterClientDatasetCalcFields(DataSet: TDataSet);
begin
MasterClientDatasetBairroCidadeUF.Value := MasterClientDatasetBAIRRO.Value + ' - '
+ MasterClientDatasetCIDADE.Value + ' - '
+ MasterClientDatasetUF.Value;
end;
initialization
OSRegisterClass(TacCustomParametroSistemaData);}
function TacCustomParametroSistemaData.getConfigImpressora(PID: Integer;
var config: TConfigImpressao): Boolean;
begin
Result := False;
end;
function TacCustomParametroSistemaData.getNomeImpressoraClasse(
nomeClasseImpressora: string): string;
begin
result := '';
end;
end.
|
unit amqp.tcp_socket;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{$INCLUDE config.inc}
//DEFINE EAGAIN Operation would have caused the process to be suspended.
interface
uses AMQP.Types, amqp.socket,
{$IFNDEF FPC}
{$IFDEF _WIN32}
Net.Winsock2, Net.Wship6,
{$ELSE}
Net.SocketAPI,
{$ENDIF}
System.SysUtils;
{$ELSE}
winsock2, SysUtils;
{$ENDIF}
function amqp_tcp_socket_new( state : Pamqp_connection_state):Pamqp_socket;
function amqp_tcp_socket_recv(base: Pointer; buf: Pointer; len : size_t; flags : integer):ssize_t;
function amqp_tcp_socket_open( base: Pointer; const host : PAnsiChar; port : integer;const timeout: Ptimeval):integer;
function amqp_tcp_socket_get_sockfd(base: Pointer):int;
function amqp_tcp_socket_close(base: Pointer; force: Tamqp_socket_close_enum):integer;
function amqp_tcp_socket_send(base: Pointer;const buf: Pointer; len : size_t; flags : integer):ssize_t;
procedure amqp_tcp_socket_set_sockfd(base : Pamqp_socket; sockfd : integer);
procedure amqp_tcp_socket_delete(base: Pointer);
const
//Record Constants Record constants cannot contain file-type values at any level.
amqp_tcp_socket_class: Tamqp_socket_class = (
send : amqp_tcp_socket_send;
recv : amqp_tcp_socket_recv;
open : amqp_tcp_socket_open;
close : amqp_tcp_socket_close;
get_sockfd : amqp_tcp_socket_get_sockfd;
delete : amqp_tcp_socket_delete);
implementation
(*TCP_CORK is Linux only; TCP_NOPUSH is BSD only; Windows does its own thing:
https://baus.net/on-tcp_cork/
https://docs.microsoft.com/en-us/windows/win32/winsock/ipproto-tcp-socket-options
*)
procedure amqp_tcp_socket_set_sockfd(base : Pamqp_socket; sockfd : integer);
var
self : Pamqp_tcp_socket;
s: string;
begin
if base.klass <> @amqp_tcp_socket_class then
begin
s := Format('<%p> is not of type Tamqp_tcp_socket', [base]);
raise Exception.Create(s);
end;
self := Pamqp_tcp_socket(base);
self.sockfd := sockfd;
end;
procedure amqp_tcp_socket_delete(base: Pointer);
var
self : Pamqp_tcp_socket;
begin
self := Pamqp_tcp_socket(base);
if Assigned(self) then
begin
amqp_tcp_socket_close(self, AMQP_SC_NONE);
freeMem(self);
end;
end;
function amqp_tcp_socket_get_sockfd(base: Pointer):int;
var
self : Pamqp_tcp_socket;
begin
self := Pamqp_tcp_socket(base);
Result := self.sockfd;
end;
function amqp_tcp_socket_close(base: Pointer; force: Tamqp_socket_close_enum):integer;
var
self : Pamqp_tcp_socket;
begin
self := Pamqp_tcp_socket(base);
if -1 = self.sockfd then
Exit(Int(AMQP_STATUS_SOCKET_CLOSED));
if amqp_os_socket_close(self.sockfd) > 0 then
Exit(Int(AMQP_STATUS_SOCKET_ERROR));
self.sockfd := -1;
Result := Int(AMQP_STATUS_OK);
end;
function amqp_tcp_socket_open( base: Pointer; const host : PAnsiChar; port : integer;const timeout: Ptimeval):integer;
var
Lself : Pamqp_tcp_socket;
err : integer;
begin
Lself := Pamqp_tcp_socket(base);
if -1 <> Lself.sockfd then
Exit(Int(AMQP_STATUS_SOCKET_INUSE));
Lself.sockfd := amqp_open_socket_noblock(host, port, timeout);
if 0 > Lself.sockfd then
begin
err := Lself.sockfd;
Lself.sockfd := -1;
Exit(err);
end;
Result := Int(AMQP_STATUS_OK);
end;
function amqp_tcp_socket_recv(base: Pointer; buf: Pointer; len : size_t; flags : integer):ssize_t;
var
self : Pamqp_tcp_socket;
ret : ssize_t;
Level: int;
s: string;
label start;
begin
Inc(gLevel);
Level := gLevel;
{$IFDEF _DEBUG_}
DebugOut(Level, 'step into amqp.tcp_socket::amqp_tcp_socket_recv!');
{$ENDIF}
self := Pamqp_tcp_socket(base);
if -1 = self.sockfd then
Exit(Int(AMQP_STATUS_SOCKET_CLOSED));
start:
{$IFDEF _WIN32}
ret := recv(self.sockfd, Pbyte(buf)^, Int(len), flags);
{$ELSE}
ret = recv(self.sockfd, buf, len, flags);
{$ENDIF}
if 0 > ret then
begin
self.internal_error := amqp_os_socket_error();
{$IFDEF _DEBUG_}
s := Format('step over amqp.tcp_socket::recv, ret=%d os_socket_error=%d', [ret, self.internal_error] );
DebugOut(Level, s);
{$ENDIF}
case self.internal_error of
WSAEINTR: goto start;
{$IFDEF _WIN32}
WSAEWOULDBLOCK,
{$ELSE}
EWOULDBLOCK:
{$ENDIF}
{$IF EAGAIN <> 10035}//EWOULDBLOCK}
EAGAIN:
{$IFEND}
ret := Int(AMQP_PRIVATE_STATUS_SOCKET_NEEDREAD);
else
ret := Int(AMQP_STATUS_SOCKET_ERROR);
end;
end
else
if (0 = ret) then
ret := Int(AMQP_STATUS_CONNECTION_CLOSED);
Result := ret;
end;
function amqp_tcp_socket_send(base: Pointer;const buf: Pointer; len : size_t; flags : integer):ssize_t;
var
Lself : Pamqp_tcp_socket;
res : ssize_t;
flagz, one, zero : integer;
LBuffer : Puint8_t;
LArray: array of AnsiChar;
label start;
begin
{$POINTERMATH ON}
Lself := Pamqp_tcp_socket(base);
flagz := 0;
//sockfd=-1 表示socket 已经closed
if -1 = Lself.sockfd then
Exit(Int(AMQP_STATUS_SOCKET_CLOSED));
{$IFDEF MSG_NOSIGNAL}
flagz := flagz or MSG_NOSIGNAL;
{$ENDIF}
{$IF defined(MSG_MORE)}
if flags and AMQP_SF_MORE then begin
flagz := flagz or MSG_MORE;
end;
{ Cygwin defines TCP_NOPUSH, but trying to use it will return not
* implemented. Disable it here. }
{$ELSEIF defined(TCP_NOPUSH) and not defined(__CYGWIN__)}
if ( (flags and Int(AMQP_SF_MORE))>0 ) and
(0> (self.state and Int(AMQP_SF_MORE) )) then
begin
one := 1;
res := setsockopt(self.sockfd, IPPROTO_TCP, TCP_NOPUSH, &one, sizeof(one));
if 0 <> res then
begin
self.internal_error := res;
Exit(AMQP_STATUS_SOCKET_ERROR);
end;
self.state := self.state or AMQP_SF_MORE;
end
else
if ( 0= (flags and AMQP_SF_MORE) ) and ((self.state and AMQP_SF_MORE)>0) then
begin
zero := 0;
res := setsockopt(self.sockfd, IPPROTO_TCP, TCP_NOPUSH, &zero, sizeof(&zero));
if 0 <> res then
begin
self.internal_error := res;
res := AMQP_STATUS_SOCKET_ERROR;
end
else
begin
self.state &= ~AMQP_SF_MORE;
end;
end;
{$IFEND}
start:
{$IFDEF _WIN32}
//LBuffer := Puint8_t(buf);
{SetLength(LArray, len);
for var I := 0 to Len - 1 do
Larray[I] := AnsiChar(LBuffer[I]); }
{$IFNDEF FPC}
res := send(Lself.sockfd, buf^, Int(len), flagz);
{$ELSE}
res := send(Lself.sockfd, buf^, len, flagz);
{$ENDIF}
{$ELSE}
res := send(Lself.sockfd, buf, len, flagz);
{$ENDIF}
if res < 0 then
begin
Lself.internal_error := amqp_os_socket_error();
case Lself.internal_error of
WSAEINTR: goto start;
{$IFDEF _WIN32}
WSAEWOULDBLOCK,
{$ELSE }
EWOULDBLOCK:
{$ENDIF}
{$if EAGAIN <> 10035}//EWOULDBLOCK}
EAGAIN:
{$IFEND}
res := int(AMQP_PRIVATE_STATUS_SOCKET_NEEDWRITE);
else
res := Int(AMQP_STATUS_SOCKET_ERROR);
end;
end
else
Lself.internal_error := 0;
Result := res;
{$POINTERMATH ON}
end;
function amqp_tcp_socket_new( state : Pamqp_connection_state):Pamqp_socket;
var
Lself : Pamqp_tcp_socket;
begin
Lself := calloc(1, sizeof(Tamqp_tcp_socket));
if not Assigned(Lself) then
Exit(nil);
Lself.klass := @amqp_tcp_socket_class;
Lself.sockfd := -1;
//amqp_set_socket(state, Pamqp_socket(Lself));
state.socket := Pamqp_socket(Lself);
Result := Pamqp_socket(Lself);
end;
initialization
end.
|
unit JD.Weather.Maps;
interface
uses
System.Classes, System.SysUtils, System.Generics.Collections,
JD.Weather.Intf;
type
TWeatherMap = class;
TWeatherMapItem = class;
TWeatherMapEvent = procedure(Sender: TObject; const Map: TWeatherMapItem) of object;
TWeatherMapItem = class(TObject)
private
FOwner: TWeatherMap;
FImage: IWeatherGraphic;
FTimestamp: TDateTime;
public
constructor Create(AOwner: TWeatherMap); overload;
constructor Create(AOwner: TWeatherMap; const Image: IWeatherGraphic); overload;
destructor Destroy; override;
property Timestamp: TDateTime read FTimestamp;
end;
TWeatherMap = class(TComponent)
private
FItems: TObjectList<TWeatherMapItem>;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
end;
implementation
{ TWeatherMapItem }
constructor TWeatherMapItem.Create(AOwner: TWeatherMap);
begin
FOwner:= AOwner;
end;
constructor TWeatherMapItem.Create(AOwner: TWeatherMap;
const Image: IWeatherGraphic);
begin
FOwner:= AOwner;
FImage:= Image;
end;
destructor TWeatherMapItem.Destroy;
begin
if Assigned(FImage) then begin
FImage._Release;
FImage:= nil;
end;
inherited;
end;
{ TWeatherMap }
constructor TWeatherMap.Create(AOwner: TComponent);
begin
inherited;
FItems:= TObjectList<TWeatherMapItem>.Create(True);
end;
destructor TWeatherMap.Destroy;
begin
FItems.Free;
inherited;
end;
end.
|
unit unitParserObj;
interface
uses System.SysUtils, frmModel;
type
{-----------------------------------------------------------------------------
Vertex - 'v ' - список вершин
Texture - 'vt' - текстурные координаты
Normals - 'vn' - нормали
Faces - 'f ' - определения поверхности(сторон)
нет - 'vp' - параметры вершин в пространстве
Object - 'o ' - название нового объекта
-----------------------------------------------------------------------------}
TModelType = class
function parseString(var temp: string): string;
function parseFaces(var Fase: string): string;
procedure objLoaderCount(FileName: string);
procedure objLoader(FileName: string);
public
VertexCount: integer;
TextureCount: integer;
NormalsCount: integer;
FacesCount : integer;
Vertex : array of array of real;
Texture : array of array of real;
Normals : array of array of real;
FacesVertex : array of array of integer;
FacesTexture: array of array of integer;
FacesNormals: array of array of integer;
iVertex: integer;
iNormals: integer;
iFaces: integer;
iTexture: integer;
end;
implementation
// разбор строки
function TModelType.parseString(var temp: string): string;
var
i: integer;
s: string;
begin
for i:=1 to Length(temp) do
begin
if (temp[i] = ' ') then
begin
s := Copy(temp, 1, i-1);
Delete(temp, 1, i);
break;
end;
if (i = Length(temp)) then
begin
s := Copy(temp, 1, i);
Delete(temp, 1, i);
break;
end;
end;
Result := s;
end;
// разбор строки полигонов
function TModelType.parseFaces(var Fase: string): string;
var
i: integer;
s: string;
begin
for i:=1 to Length(Fase) do
begin
if (Fase[i] = '/') then
begin
s := Copy(Fase, 1, i-1);
Delete(Fase, 1, i);
break;
end;
if (i = Length(Fase)) then
begin
s := Copy(Fase, 1, i);
Delete(Fase, 1, i);
break;
end;
end;
Result := s;
end;
// загрузка количества элементов из файла и
// выделение памяти для массивов
procedure TModelType.objLoaderCount(FileName: string);
var
f : TextFile;
key: string;
temp: string;
code: integer;
begin
AssignFile(f,FileName);
Reset(f);
while not eof(f) do
begin
ReadLn(f, temp);
key := Copy(temp, 1, 2);
// v - вершины
if key = 'v ' then
begin
VertexCount := VertexCount + 1;
Continue;
end;
// vt - текстурные координаты
if key = 'vt' then
begin
TextureCount := TextureCount + 1;
Continue;
end;
// vn - нормали
if key = 'vn' then
begin
NormalsCount := NormalsCount + 1;
Continue;
end;
// f - полигоны
if key = 'f ' then
begin
FacesCount := FacesCount + 1;
Continue;
end;
end;
CloseFile(f);
// выделение памяти для массивов
SetLength(Vertex, 3, VertexCount);
SetLength(Texture, 2, TextureCount);
SetLength(Normals, 3, NormalsCount);
SetLength(FacesVertex, 4, FacesCount);
SetLength(FacesNormals, 4, FacesCount);
SetLength(FacesTexture, 4, FacesCount);
end;
// загрузка значений из файла и
// заполнение массивов
procedure TModelType.objLoader(FileName: string);
var
f : TextFile;
key: string;
temp: string;
code: integer;
i: integer;
c: char;
slash: boolean;
Fase, FaseTemp: string;
begin
slash := false;
AssignFile(f,FileName);
Reset(f);
while not eof(f) do
begin
ReadLn(f, temp);
key := Copy(temp, 1, 2);
//--------------------------------------------------------------------------
//v - вершины
//--------------------------------------------------------------------------
if key = 'v ' then
begin
Delete(temp, 1, 2); // удаление 'v '
Val(parseString(temp), Vertex[0,iVertex], code);
Val(parseString(temp), Vertex[1,iVertex], code);
Val(parseString(temp), Vertex[2,iVertex], code);
iVertex := iVertex+1;
Continue;
end;
//--------------------------------------------------------------------------
//vt - текстурные координаты
//--------------------------------------------------------------------------
if key = 'vt' then
begin
Delete(temp, 1, 3); // удаление 'vt '
Val(parseString(temp), Texture[0,iTexture], code);
Val(parseString(temp), Texture[1,iTexture], code);
iTexture := iTexture+1;
Continue;
end;
//--------------------------------------------------------------------------
//vn - нормали
//--------------------------------------------------------------------------
if key = 'vn' then
begin
Delete(temp, 1, 3); // удаление 'vn '
Val(parseString(temp), Normals[0,iNormals], code);
Val(parseString(temp), Normals[1,iNormals], code);
Val(parseString(temp), Normals[2,iNormals], code);
iNormals := iNormals+1;
Continue;
end;
//--------------------------------------------------------------------------
// f - полигоны
//--------------------------------------------------------------------------
if key = 'f ' then
begin
Delete(temp, 1, 2); // удаление 'f '
// проверяем на наличие '/' в строке
for i := 1 to Length(temp) do
begin
c := temp[i];
if c = '/' then
begin
slash := true;
break;
end;
end;
if slash then // если "/" есть
begin
// 1 face
Fase := parseString(temp);
FacesVertex[0,iFaces] := StrToInt(parseFaces(Fase));
if Fase <> '' then
begin
FaseTemp := parseFaces(Fase);
if FaseTemp <> '' then
FacesTexture[0,iFaces] := StrToInt(FaseTemp);
end
else
FacesTexture[0,iFaces] := 0;
if Fase <> '' then
FacesNormals[0,iFaces] := StrToInt(parseFaces(Fase))
else
FacesNormals[0,iFaces] := 0;
// 2 face
Fase := parseString(temp);
FacesVertex[1,iFaces] := StrToInt(parseFaces(Fase));
if Fase <> '' then
begin
FaseTemp := parseFaces(Fase);
if FaseTemp <> '' then
FacesTexture[1,iFaces] := StrToInt(FaseTemp);
end
else
FacesTexture[1,iFaces] := 0;
if Fase <> '' then
FacesNormals[1,iFaces] := StrToInt(parseFaces(Fase))
else
FacesNormals[1,iFaces] := 0;
// 3 face
Fase := parseString(temp);
FacesVertex[2,iFaces] := StrToInt(parseFaces(Fase));
if Fase <> '' then
begin
FaseTemp := parseFaces(Fase);
if FaseTemp <> '' then
FacesTexture[2,iFaces] := StrToInt(FaseTemp);
end
else
FacesTexture[2,iFaces] := 0;
if Fase <> '' then
FacesNormals[2,iFaces] := StrToInt(parseFaces(Fase))
else
FacesNormals[2,iFaces] := 0;
// 4 face
if temp <> '' then
begin
Fase := parseString(temp);
FacesVertex[3,iFaces] := StrToInt(parseFaces(Fase));
if Fase <> '' then
begin
FaseTemp := parseFaces(Fase);
if FaseTemp <> '' then
FacesTexture[3,iFaces] := StrToInt(FaseTemp);
end
else
FacesTexture[3,iFaces] := 0;
if Fase <> '' then
FacesNormals[3,iFaces] := StrToInt(parseFaces(Fase))
else
FacesNormals[3,iFaces] := 0;
end
else
begin
FacesVertex[3,iFaces] := 0;
FacesTexture[3,iFaces] := 0;
FacesNormals[3,iFaces] := 0;
end;
end
// если "/" нет
else
begin
FacesVertex[0,iFaces] := StrToInt(parseString(temp));
FacesVertex[1,iFaces] := StrToInt(parseString(temp));
FacesVertex[2,iFaces] := StrToInt(parseString(temp));
if temp <> '' then
FacesVertex[3,iFaces] := StrToInt(parseString(temp))
else
FacesVertex[3,iFaces] := 0;
FacesNormals[0,iFaces] := 0;
FacesTexture[0,iFaces] := 0;
end;
iFaces := iFaces+1;
Continue;
end;
//--------------------------------------------------------------------------
end;
CloseFile(f);
end;
end.
|
unit EditFrm;
{ This unit implements TEditForm, the MDI child form class, and TMemoDoc,
the automation object for a memo editor form. TMemoDoc implements the
following automated methods and properties:
procedure Clear;
Clears the contents of the memo.
procedure Insert(const Text: string);
Inserts the given string at the current cursor position.
procedure Save;
Saves the contents of the memo.
procedure Close;
Closes the memo.
property FileName: string;
The name of the file associated with the memo. The memo can be renamed
by assigning to this property.
property Modified: WordBool;
True if the memo has been modified since it was loaded or last saved.
OLE Automation controllers obtain instances of TMemoDoc using the NewMemo
and OpenMemo methods of the "MemoApp.Application" OLE class. Since
instances of TMemoDoc cannot be created through OLE, there is no need to
register the class. }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Menus, ComObj, Memo_TLB;
type
TMemoDoc = class;
TEditForm = class(TForm)
Memo: TMemo;
MainMenu: TMainMenu;
FileMenu: TMenuItem;
FileNewItem: TMenuItem;
FileOpenItem: TMenuItem;
FileSaveItem: TMenuItem;
FileSaveAsItem: TMenuItem;
FileCloseItem: TMenuItem;
FileExitItem: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FileNewItemClick(Sender: TObject);
procedure FileOpenItemClick(Sender: TObject);
procedure FileSaveItemClick(Sender: TObject);
procedure FileSaveAsItemClick(Sender: TObject);
procedure FileCloseItemClick(Sender: TObject);
procedure FileExitItemClick(Sender: TObject);
procedure MemoChange(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FMemoDoc: TMemoDoc;
FFileName: string;
FModified: Boolean;
FUnnamed: Boolean;
function GetOleObject: Variant;
procedure Rename(const NewName: string);
function Save(ChangeName, ForceSave: Boolean): Boolean;
procedure SaveToFile;
public
property OleObject: Variant read GetOleObject;
end;
TMemoDoc = class(TAutoObject, IMemoDoc)
private
FEditForm: TEditForm;
protected
function Get_FileName: WideString; safecall;
function Get_Modified: WordBool; safecall;
procedure Clear; safecall;
procedure Close; safecall;
procedure Insert(const Text: WideString); safecall;
procedure Save; safecall;
procedure Set_FileName(const Value: WideString); safecall;
end;
implementation
{$R *.DFM}
uses MainFrm, ComServ;
{ TEditForm }
procedure TEditForm.FormCreate(Sender: TObject);
begin
if not MainForm.Local then
begin
FMemoDoc := TMemoDoc.Create;
FMemoDoc.FEditForm := Self;
end;
if MainForm.NewFileName = '' then
begin
FFileName := 'Untitled.txt';
FUnnamed := True;
end else
begin
FFileName := MainForm.NewFileName;
Memo.Lines.LoadFromFile(FFileName);
FUnnamed := False;
end;
Caption := FFileName;
FModified := False;
MainForm.Local := False;
end;
procedure TEditForm.FormDestroy(Sender: TObject);
begin
if FMemoDoc <> nil then
begin
FMemoDoc.FEditForm := nil;
FMemoDoc := nil;
end;
end;
procedure TEditForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := Save(False, False);
end;
procedure TEditForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TEditForm.FileNewItemClick(Sender: TObject);
begin
MainForm.FileNewItemClick(Sender);
end;
procedure TEditForm.FileOpenItemClick(Sender: TObject);
begin
MainForm.FileOpenItemClick(Sender);
end;
procedure TEditForm.FileSaveItemClick(Sender: TObject);
begin
Save(False, True);
end;
procedure TEditForm.FileSaveAsItemClick(Sender: TObject);
begin
Save(True, True);
end;
procedure TEditForm.FileCloseItemClick(Sender: TObject);
begin
Close;
end;
procedure TEditForm.FileExitItemClick(Sender: TObject);
begin
MainForm.Close;
end;
procedure TEditForm.MemoChange(Sender: TObject);
begin
FModified := True;
end;
function TEditForm.GetOleObject: Variant;
begin
Result := FMemoDoc as IDispatch;
end;
procedure TEditForm.Rename(const NewName: string);
begin
FFileName := ExpandFileName(NewName);
FUnnamed := False;
Caption := FFileName;
end;
function TEditForm.Save(ChangeName, ForceSave: Boolean): Boolean;
begin
Result := False;
if not ForceSave and FModified then
case MessageDlg(Format('Save changes to %s?',
[ExtractFileName(FFileName)]), mtConfirmation, mbYesNoCancel, 0) of
mrYes: ForceSave := True;
mrCancel: Exit;
end;
if ForceSave then
begin
if ChangeName or FUnnamed then
with MainForm.SaveDialog do
begin
FileName := FFileName;
DefaultExt := #0;
if not Execute then Exit;
Rename(FileName);
end;
SaveToFile;
end;
Result := True;
end;
procedure TEditForm.SaveToFile;
begin
Memo.Lines.SaveToFile(FFileName);
FModified := False;
end;
{ TMemoDoc }
procedure TMemoDoc.Clear;
begin
if FEditForm <> nil then
begin
FEditForm.Memo.Clear;
FEditForm.FModified := True;
end;
end;
procedure TMemoDoc.Close;
begin
FEditForm.Free;
end;
function TMemoDoc.Get_FileName: WideString;
begin
if FEditForm <> nil then
Result := FEditForm.FFileName else
Result := '';
end;
function TMemoDoc.Get_Modified: WordBool;
begin
if FEditForm <> nil then
Result := FEditForm.FModified else
Result := False;
end;
procedure TMemoDoc.Insert(const Text: WideString);
begin
if FEditForm <> nil then FEditForm.Memo.SelText := Text;
end;
procedure TMemoDoc.Save;
begin
if FEditForm <> nil then FEditForm.SaveToFile;
end;
procedure TMemoDoc.Set_FileName(const Value: WideString);
begin
if FEditForm <> nil then FEditForm.Rename(Value);
end;
initialization
TAutoObjectFactory.Create(ComServer, TMemoDoc, Class_MemoDoc, ciInternal);
end.
|
unit uNomeClasse;
interface
uses
Classes, SysUtils,
mCollection, mCollectionItem;
type
TNomeClasse = class;
TNomeClasseClass = class of TNomeClasse;
TNomeClasseList = class;
TNomeClasseListClass = class of TNomeClasseList;
TNomeClasse = class(TmCollectionItem)
private
fU_Version: String;
fCd_Operador: Integer;
fDt_Cadastro: TDateTime;
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
published
property U_Version : String read fU_Version write fU_Version;
property Cd_Operador : Integer read fCd_Operador write fCd_Operador;
property Dt_Cadastro : TDateTime read fDt_Cadastro write fDt_Cadastro;
end;
TNomeClasseList = class(TmCollection)
private
function GetItem(Index: Integer): TNomeClasse;
procedure SetItem(Index: Integer; Value: TNomeClasse);
public
constructor Create(AOwner: TPersistent);
function Add: TNomeClasse;
property Items[Index: Integer]: TNomeClasse read GetItem write SetItem; default;
end;
implementation
{ TNomeClasse }}
constructor TNomeClasse.Create(ACollection: TCollection);
begin
inherited;
end;
destructor TNomeClasse.Destroy;
begin
inherited;
end;
{ TNomeClasseList }}
constructor TNomeClasseList.Create(AOwner: TPersistent);
begin
inherited Create(TNomeClasse);
end;
function TNomeClasseList.Add: TNomeClasse;
begin
Result := TNomeClasse(inherited Add);
Result.create(Self);
end;
function TNomeClasseList.GetItem(Index: Integer): TNomeClasse;
begin
Result := TNomeClasse(inherited GetItem(Index));
end;
procedure TNomeClasseList.SetItem(Index: Integer; Value: TNomeClasse);
begin
inherited SetItem(Index, Value);
end;
end. |
(*
* Unit owner: D10.Mofen
* homePage: http://www.diocp.org
* blog: http://www.cnblogs.com/dksoft
* 1. 扩展服务器TDiocpExTcpServer, 可以定义开始标志和结束标志(也可以只设定结束标志),然后自动进行解包触发OnContextDataAction事件。
* 2. 字符串服务器TDiocpStringTcpServer, 可以设定开始字符串和结束字符串(也可以只设定结束字符串),然后自动进行解包触发OnContextStringAction事件。
* 2015-07-15 09:00:09
*
* 3. 修复ex.server编码问题,发送大数据时,无法解码的bug
* 2015-08-17 14:25:56
*)
unit diocp.ex.server;
interface
uses
diocp.tcp.server, utilsBuffer, utilsSafeLogger, SysUtils, Classes;
type
TDiocpExContext = class;
TDiocpStringContext = class;
TContextDataActionEvent = procedure(pvContext:TDiocpExContext; pvData: Pointer;
pvDataLen: Integer) of object;
TContextStringActionEvent = procedure(pvContext:TDiocpStringContext;
pvDataString:String) of object;
TDiocpExContext = class(TIocpClientContext)
private
FCacheBuffer: TBufferLink;
FRecvData: array of Byte;
protected
procedure OnRecvBuffer(buf: Pointer; len: Cardinal; ErrCode: WORD); override;
procedure OnDataAction(pvData: Pointer; pvDataLen: Integer);
procedure DoCleanUp;override;
public
constructor Create; override;
destructor Destroy; override;
/// <summary>
/// 自动添加前后标志
/// </summary>
procedure WriteData(pvData: Pointer; pvDataLen: Integer);
end;
TDiocpExTcpServer = class(TDiocpTcpServer)
private
FStartData: array [0..254] of Byte;
FStartDataLen:Byte;
FEndData:array [0..254] of Byte;
FEndDataLen: Byte;
/// 设置最大的数据包长度
FMaxDataLen:Integer;
FOnContextDataAction: TContextDataActionEvent;
protected
procedure DoDataAction(pvContext: TDiocpExContext; pvData: Pointer; pvDataLen:
Integer);virtual;
public
constructor Create(AOwner: TComponent); override;
procedure SetStart(pvData:Pointer; pvDataLen:Byte);
procedure SetEnd(pvData:Pointer; pvDataLen:Byte);
/// <summary>
/// 设置最大的数据包长度
/// 不能设置小于0的数字
/// 10M (1024 * 1024 * 10)
/// </summary>
procedure SetMaxDataLen(pvDataLen:Integer);
property OnContextDataAction: TContextDataActionEvent read FOnContextDataAction write FOnContextDataAction;
end;
TDiocpStringContext = class(TDiocpExContext)
public
procedure WriteAnsiString(pvData:AnsiString);
end;
TDiocpStringTcpServer = class(TDiocpExTcpServer)
private
FOnContextStringAction: TContextStringActionEvent;
protected
procedure DoDataAction(pvContext: TDiocpExContext; pvData: Pointer; pvDataLen:
Integer); override;
public
constructor Create(AOwner: TComponent); override;
procedure SetPackEndStr(pvEndStr:AnsiString);
procedure SetPackStartStr(pvStartStr:AnsiString);
property OnContextStringAction: TContextStringActionEvent read FOnContextStringAction write FOnContextStringAction;
end;
implementation
uses
utilsStrings;
constructor TDiocpExContext.Create;
begin
inherited Create;
FCacheBuffer := TBufferLink.Create();
end;
destructor TDiocpExContext.Destroy;
begin
FCacheBuffer.Free;
inherited Destroy;
end;
procedure TDiocpExContext.DoCleanUp;
begin
inherited DoCleanUp;
FCacheBuffer.clearBuffer;
end;
procedure TDiocpExContext.OnRecvBuffer(buf: Pointer; len: Cardinal; ErrCode: WORD);
var
j, i, x, r:Integer;
str:AnsiString;
pstr, pbuf, prsearch:PAnsiChar;
lvStartData:Pointer;
lvStartDataLen:Byte;
lvEndData:Pointer;
lvEndDataLen:Byte;
lvOwner:TDiocpExTcpServer;
begin
lvOwner := TDiocpExTcpServer(Owner);
lvStartData := @lvOwner.FStartData[0];
lvStartDataLen := lvOwner.FStartDataLen;
lvEndData := @lvOwner.FEndData[0];
lvEndDataLen := lvOwner.FEndDataLen;
FCacheBuffer.AddBuffer(buf, len);
while FCacheBuffer.validCount > 0 do
begin
// 标记读取的开始位置,如果数据不够,进行恢复,以便下一次解码
FCacheBuffer.markReaderIndex;
if lvStartDataLen > 0 then
begin
// 不够数据,跳出
if FCacheBuffer.validCount < lvStartDataLen + lvEndDataLen then Break;
j := FCacheBuffer.SearchBuffer(lvStartData, lvStartDataLen);
if j = -1 then
begin // 没有搜索到开始标志
FCacheBuffer.clearBuffer();
Exit;
end else
begin
// 跳过开头标志
FCacheBuffer.Skip(j + lvStartDataLen);
end;
end;
// 不够数据,跳出
if FCacheBuffer.validCount < lvEndDataLen then
begin
FCacheBuffer.restoreReaderIndex;
Break;
end;
j := FCacheBuffer.SearchBuffer(lvEndData, lvEndDataLen);
if j <> -1 then
begin
SetLength(FRecvData, j);
FCacheBuffer.readBuffer(@FRecvData[0], j);
OnDataAction(@FRecvData[0], j);
FCacheBuffer.Skip(lvEndDataLen);
end else
begin // 没有结束符
FCacheBuffer.restoreReaderIndex;
Break;
end;
end;
FCacheBuffer.clearHaveReadBuffer();
// pbuf := PAnsiChar(buf);
// r := len;
//
//
//
// // 已经有数据了
// if (FCacheBuffer.validCount > 0) then
// begin
// // 不够数据
// if FCacheBuffer.validCount < lvEndDataLen then Exit;
//
// // 查找结束字符串
// prsearch := SearchPointer(pbuf, len, 0, lvEndData, lvEndDataLen);
// if prsearch = nil then
// begin // 没有结束标志
// FCacheBuffer.AddBuffer(buf, len);
// Exit;
// end else
// begin // 有结束标志了,拼包
// j := prsearch-pbuf;
// i := self.FCacheBuffer.validCount;
// if i > 0 then
// begin
// SetLength(FRecvData, i + j);
// pstr := PAnsiChar(@FRecvData[0]);
// FCacheBuffer.readBuffer(pstr, i);
// pstr := pstr + i;
// Move(pbuf^, pstr^, j);
// Inc(pbuf, j);
// Dec(r, j);
//
// FCacheBuffer.clearBuffer();
// OnDataAction(@FRecvData[0], i + j);
// end;
// end;
// end;
//
// while r > 0 do
// begin
// if lvStartDataLen > 0 then
// begin
// prsearch := SearchPointer(pbuf, r, 0, lvStartData, lvStartDataLen);
// if prsearch = nil then
// begin // 没有开始标志buf无效
// Break;
// end else
// begin
// j := prsearch - pbuf;
// // 丢弃到开始标志之前的数据
// Inc(pbuf, j + lvStartDataLen); // 跳过开始标志
// Dec(r, j + lvStartDataLen);
// end;
// end;
//
// prsearch := SearchPointer(pbuf, r, 0, lvEndData, lvEndDataLen);//(pbuf, r, 0);
// if prsearch <> nil then
// begin
// j := prsearch - pbuf;
// if j = 0 then
// begin // 只有一个结束标志
//
// end else
// begin
// SetLength(FRecvData, j);
// pstr := PAnsiChar(@FRecvData[0]);
// Move(pbuf^, pstr^, j);
// Inc(pbuf, j);
// Dec(r, j);
// OnDataAction(pstr, j);
// end;
// Inc(pbuf, lvEndDataLen); // 跳过结束标志
// Dec(r, lvEndDataLen);
// end else
// begin // 剩余数据处理
// if r > 0 then FCacheBuffer.AddBuffer(pbuf, r);
// if FCacheBuffer.validCount > lvOwner.FMaxDataLen then
// begin // 超过最大数据包大小
// FCacheBuffer.clearBuffer();
// end;
//
// Break;
// end;
// end;
end;
procedure TDiocpExContext.OnDataAction(pvData: Pointer; pvDataLen: Integer);
var
lvOwner:TDiocpExTcpServer;
begin
lvOwner := TDiocpExTcpServer(Owner);
lvOwner.DoDataAction(self, pvData, pvDataLen);
end;
procedure TDiocpExContext.WriteData(pvData: Pointer; pvDataLen: Integer);
var
j, i, x, r:Integer;
str:AnsiString;
pstr, pbuf, prsearch:PAnsiChar;
lvStartData:Pointer;
lvStartDataLen:Byte;
lvEndData:Pointer;
lvEndDataLen:Byte;
lvOwner:TDiocpExTcpServer;
lvSendBuffer:array of byte;
begin
lvOwner := TDiocpExTcpServer(Owner);
lvStartData := @lvOwner.FStartData[0];
lvStartDataLen := lvOwner.FStartDataLen;
lvEndData := @lvOwner.FEndData[0];
lvEndDataLen := lvOwner.FEndDataLen;
j := lvStartDataLen + pvDataLen + lvEndDataLen;
SetLength(lvSendBuffer, j);
if lvStartDataLen > 0 then
begin
Move(lvStartData^, lvSendBuffer[0], lvStartDataLen);
end;
Move(pvData^, lvSendBuffer[lvStartDataLen], pvDataLen);
if lvEndDataLen > 0 then
begin
Move(lvEndData^, lvSendBuffer[lvStartDataLen + pvDatalen], lvEndDataLen);
end;
PostWSASendRequest(@lvSendBuffer[0], j);
end;
{ TDiocpExTcpServer }
constructor TDiocpExTcpServer.Create(AOwner: TComponent);
begin
inherited;
RegisterContextClass(TDiocpExContext);
FMaxDataLen := 1024 * 1024 * 10; // 10M
end;
procedure TDiocpExTcpServer.DoDataAction(pvContext: TDiocpExContext; pvData:
Pointer; pvDataLen: Integer);
begin
if Assigned(FOnContextDataAction) then
begin
FOnContextDataAction(pvContext, pvData, pvDataLen);
end;
end;
procedure TDiocpExTcpServer.SetEnd(pvData:Pointer; pvDataLen:Byte);
begin
Move(pvData^, FEndData[0], pvDataLen);
FEndDataLen := pvDataLen;
end;
procedure TDiocpExTcpServer.SetMaxDataLen(pvDataLen:Integer);
begin
FMaxDataLen := pvDataLen;
Assert(FMaxDataLen > 0);
end;
procedure TDiocpExTcpServer.SetStart(pvData:Pointer; pvDataLen:Byte);
begin
Move(pvData^, FStartData[0], pvDataLen);
FStartDataLen := pvDataLen;
end;
constructor TDiocpStringTcpServer.Create(AOwner: TComponent);
begin
inherited;
end;
procedure TDiocpStringTcpServer.DoDataAction(pvContext: TDiocpExContext; pvData:
Pointer; pvDataLen: Integer);
var
ansiStr:AnsiString;
begin
inherited;
SetLength(ansiStr, pvDataLen);
Move(pvData^, PAnsiChar(ansiStr)^, pvDataLen);
if Assigned(FOnContextStringAction) then
begin
FOnContextStringAction(TDiocpStringContext(pvContext), ansiStr);
end;
end;
procedure TDiocpStringTcpServer.SetPackEndStr(pvEndStr:AnsiString);
begin
SetEnd(PAnsiChar(pvEndStr), Length(pvEndStr));
end;
procedure TDiocpStringTcpServer.SetPackStartStr(pvStartStr:AnsiString);
begin
SetStart(PAnsiChar(pvStartStr), Length(pvStartStr));
end;
procedure TDiocpStringContext.WriteAnsiString(pvData:AnsiString);
begin
WriteData(PAnsiChar(pvData), Length(pvData));
end;
end.
|
unit AsciiImage;
interface
uses
Classes,
{$if CompilerVersion > 22}
System.Types,
System.UITypes,
{$Else}
Types,
{$IfEnd}
SysUtils,
Graphics,
Generics.Collections,
AsciiImage.RenderContext.Types,
{$if Framework = 'VCL'}
Windows,
{$IfEnd}
AsciiImage.Shapes,
AsciiImage.RenderContext.Factory,
AsciiImage.RenderContext.Intf;
type
TAsciiImagePaintContext = record
FillColor: TColorValue;
StrokeColor: TColorValue;
PenSize: Integer;
end;
TAsciiImagePaintCallBack = reference to procedure(const Index: Integer; var Context: TAsciiImagePaintContext);
TDownSampling = (dsNone, dsX2, dsX4, dsX8);
{$if Framework = 'VCL'}
TAsciiImage = class(TGraphic)
{$ELSE}
TAsciiImage = class(TInterfacedPersistent)
{$IfEnd}
private
FRawData: TArray<string>;
FDots: array of TList<TPointF>;
FShapes: TObjectList<TAsciiShape>;
FIndexLookup: TDictionary<Char, Integer>;
FWidth: Integer;
FHeight: Integer;
FOnDraw: TAsciiImagePaintCallBack;
FOnCreateRenderContext: TCreateRenderContextHook;
protected
procedure Clear();
procedure ScanShapes(); virtual;
procedure AddDot(APoint: TPointF); virtual;
procedure AddEllipsis(const APoints: array of TPointF); virtual;
procedure AddPath(const APoints: array of TPointF); virtual;
procedure AddLine(const AFrom, ATo: TPointF); virtual;
function CreateRenderContext(ACanvas: TCanvas; AWidth, AHeight: Single): IRenderContext;
{$If Framework = 'VCL'}
function GetEmpty: Boolean; override;
function GetHeight: Integer; override;
function GetWidth: Integer; override;
procedure SetHeight(Value: Integer); override;
procedure SetWidth(Value: Integer); override;
{$Else}
function GetEmpty: Boolean;
function GetHeight: Integer;
function GetWidth: Integer;
procedure SetHeight(Value: Integer);
procedure SetWidth(Value: Integer);
{$IfEnd}
public
{$if Framework = 'VCL'}
constructor Create(); override;
{$Else}
constructor Create();
{$IfEnd}
destructor Destroy(); override;
procedure LoadFromAscii(const AAsciiImage: array of string);
procedure SaveToAscii(var AAsciiImage: TArray<string>);
{$If Framework = 'VCL'}
procedure DrawDebugGrid(const ACanvas: TCanvas);
procedure Draw(ACanvas: TCanvas; const ARect: TRect); override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
procedure LoadFromClipboardFormat(AFormat: Word; AData: THandle;
APalette: HPALETTE); override;
procedure SaveToClipboardFormat(var AFormat: Word; var AData: THandle;
var APalette: HPALETTE); override;
{$Else}
procedure Draw(ACanvas: TCanvas; const ARect: TRect);
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
procedure LoadFromFile(const AFileName: string);
procedure SaveToFile(const AFileName: string);
{$IfEnd}
procedure Assign(Source: TPersistent); override;
property OnDraw: TAsciiImagePaintCallBack read FOnDraw write FOnDraw;
property OnCreateRenderContext: TCreateRenderContextHook read FOnCreateRenderContext write FOnCreateRenderContext;
{$If Framework = 'FM'}
property Width: Integer read GetWidth write SetWidth;
property Height: Integer read GetHeight write SetHeight;
property Empty: Boolean read GetEmpty;
{$IfEnd}
end;
implementation
uses
Math;
{ TAsciiImage }
const
CCharSet = ['1'..'9', 'A'..'Z', 'a'..'z'];
procedure TAsciiImage.AddDot(APoint: TPointF);
var
LDot: TAsciiDot;
begin
LDot := TAsciiDot.Create();
LDot.Points.Add(APoint);
FShapes.Add(LDot);
end;
procedure TAsciiImage.AddEllipsis(const APoints: array of TPointF);
var
LEllipsis: TAsciiEllipsis;
begin
LEllipsis := TAsciiEllipsis.Create();
LEllipsis.Points.AddRange(APoints);
FShapes.Add(LEllipsis);
end;
procedure TAsciiImage.AddLine(const AFrom, ATo: TPointF);
var
LLine: TAsciiLine;
begin
LLine := TAsciiLine.Create();
LLine.Points.Add(AFrom);
LLine.Points.Add(ATo);
FShapes.Add(LLine);
end;
procedure TAsciiImage.AddPath(const APoints: array of TPointF);
var
LPath: TAsciiPath;
begin
LPath := TAsciiPath.Create();
LPath.Points.AddRange(APoints);
FShapes.Add(LPath);
end;
procedure TAsciiImage.Assign(Source: TPersistent);
var
LSource: TAsciiImage;
begin
if Source is TAsciiImage then
begin
LSource := TAsciiImage(Source);
OnDraw := LSource.OnDraw;
LoadFromAscii(LSource.FRawData);
end
else
begin
inherited;
end;
end;
procedure TAsciiImage.Clear;
begin
FShapes.Clear;
end;
constructor TAsciiImage.Create;
var
i: Integer;
LChar: Char;
begin
inherited;
FShapes := TObjectList<TAsciiShape>.Create(True);
FIndexLookup := TDictionary<Char, Integer>.Create();
i := 0;
for LChar in CCharSet do
begin
FIndexLookup.Add(LChar, i);
Inc(i);
end;
SetLength(FDots, FIndexLookup.Count);
for i := 0 to Length(FDots) - 1 do
begin
FDots[i] := TList<TPointF>.Create();
end;
FWidth := 0;
FHeight := 0;
end;
function TAsciiImage.CreateRenderContext(ACanvas: TCanvas; AWidth,
AHeight: Single): IRenderContext;
begin
if Assigned(FOnCreateRenderContext) then
begin
Result := FOnCreateRenderContext(ACanvas, AWidth, AHeight);
end
else
begin
Result := TRenderContextFactory.CreateDefaultRenderContext(ACanvas, AWidth, AHeight);
end;
end;
destructor TAsciiImage.Destroy;
var
LDotList: TList<TPointF>;
begin
for LDotList in FDots do
LDotList.Free;
SetLength(FDots, 0);
FShapes.Free();
FIndexLookup.Free();
inherited;
end;
procedure TAsciiImage.Draw(ACanvas: TCanvas; const ARect: TRect);
var
LContext: IRenderContext;
i: Integer;
LScaleX, LScaleY: Single;
LPaintContext: TAsciiImagePaintContext;
begin
if Empty then Exit;
LScaleX := (ARect.Right - ARect.Left) / FWidth;
LScaleY := (ARect.Bottom - ARect.Top) / FHeight;
LContext := CreateRenderContext(ACanvas, Width*LScaleX, Height*LScaleY);
LContext.BeginScene(ARect);
{$If Framework = 'VCL'}
LContext.Clear(ACanvas.Brush.Color);
{$Else}
LContext.Clear(ACanvas.Fill.Color);
{$IfEnd}
for i := 0 to FShapes.Count - 1 do
begin
LPaintContext.FillColor := clNone;
LPaintContext.StrokeColor := clNone;
LPaintContext.PenSize :=1;
if Assigned(FOnDraw) then
begin
FOnDraw(i, LPaintContext);
end
else
begin
//some defaultvalues to see something
LPaintContext.FillColor := clBlack;
LPaintContext.StrokeColor := clBlack;
end;
LContext.Brush.Color := LPaintContext.FillColor;
LContext.Pen.Color := LPaintContext.StrokeColor;
LContext.Pen.Size := Round(LPaintContext.PenSize*LScaleX);
LContext.Brush.Visible := LContext.Brush.Color <> clNone;
LContext.Pen.Visible := LContext.Pen.Color <> clNone;
FShapes[i].ScaleX := LScaleX;
FShapes[i].ScaleY := LScaleY;
FShapes[i].Draw(LContext);
end;
LContext.EndScene();
end;
{$If FrameWork = 'VCL'}
procedure TAsciiImage.DrawDebugGrid(const ACanvas: TCanvas);
var
LScaleX, LScaleY: Single;
i: Integer;
LMode: TPenMode;
LColor: TColorValue;
begin
LScaleX := (ACanvas.ClipRect.Right - ACanvas.ClipRect.Left) / FWidth;
LScaleY := (ACanvas.ClipRect.Bottom - ACanvas.ClipRect.Top) / FHeight;
LMode := ACanvas.Pen.Mode;
ACanvas.Pen.Mode := pmXor;
LColor := ACanvas.Pen.Color;
ACanvas.Pen.Color := clRed;
for i := 1 to FWidth do
begin
ACanvas.MoveTo(Round(i*LScaleX), ACanvas.ClipRect.Top);
ACanvas.LineTo(Round(i*LScaleX), ACanvas.ClipRect.Bottom);
end;
for i := 1 to FHeight do
begin
ACanvas.MoveTo(ACanvas.ClipRect.Left, Round(i*LScaleY));
ACanvas.LineTo(ACanvas.ClipRect.Right, Round(i*LScaleY));
end;
ACanvas.Pen.Mode := LMode;
ACanvas.Pen.Color := LColor;
end;
procedure TAsciiImage.LoadFromClipboardFormat(AFormat: Word; AData: THandle;
APalette: HPALETTE);
begin
raise ENotSupportedException.Create('Loading form Clippboard not supported');
end;
procedure TAsciiImage.SaveToClipboardFormat(var AFormat: Word; var AData: THandle;
var APalette: HPALETTE);
begin
raise ENotSupportedException.Create('Saving to Clippboard not supported');
end;
{$IfEnd}
function TAsciiImage.GetEmpty: Boolean;
begin
Result := FShapes.Count = 0;
end;
function TAsciiImage.GetHeight: Integer;
begin
Result := FHeight;
end;
function TAsciiImage.GetWidth: Integer;
begin
Result := FWidth;
end;
procedure TAsciiImage.LoadFromAscii(const AAsciiImage: array of string);
var
LLineIndex: Integer;
LFirstLineLength, LCurrentLineLength: Integer;
LCharIndex: Integer;
LChar: Char;
i: Integer;
begin
SetLength(FRawData, Length(AAsciiImage));
for i := 0 to Length(AAsciiImage) - 1 do
begin
FRawData[i] := AAsciiImage[i];
end;
LFirstLineLength := -1;
for LLineIndex := 0 to Length(AAsciiImage) - 1 do
begin
LCurrentLineLength := 0;
for LChar in AAsciiImage[LLineIndex] do
begin
if LChar <> ' ' then
begin
if FIndexLookup.TryGetValue(LChar, LCharIndex) then
begin
FDots[LCharIndex].Add(PointF(LCurrentLineLength, LLineIndex));
end;
Inc(LCurrentLineLength);
end;
end;
if LFirstLineLength < 0 then
begin
LFirstLineLength := LCurrentLineLength;
end
else
begin
if LFirstLineLength <> LCurrentLineLength then
raise Exception.Create('Length of line ' + IntToStr(LLineIndex) + '(' + IntToStr(LFirstLineLength)
+ ') does not match length of first line (' + IntToStr(LFirstLineLength) + ')');
end;
end;
FWidth := LFirstLineLength;
FHeight := Length(AAsciiImage);
ScanShapes();
end;
{$if Framework = 'FM'}
procedure TAsciiImage.LoadFromFile(const AFileName: string);
var
LStream: TStream;
begin
LStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(LStream);
finally
LStream.Free;
end;
end;
procedure TAsciiImage.SaveToFile(const AFileName: string);
var
LStream: TStream;
begin
LStream := TFileStream.Create(AFileName, fmCreate);
try
SaveToStream(LStream);
finally
LStream.Free;
end;
end;
{$IfEnd}
procedure TAsciiImage.LoadFromStream(Stream: TStream);
var
LAscii: TStringList;
begin
LAscii := TStringList.Create();
try
LAscii.LoadFromStream(Stream);
LoadFromAscii(LAscii.ToStringArray);
finally
LAscii.Free();
end;
end;
procedure TAsciiImage.SaveToAscii(var AAsciiImage: TArray<string>);
var
i: Integer;
begin
SetLength(AAsciiImage, Length(FRawData));
for i := 0 to Length(FRawData) - 1 do
begin
AAsciiImage[i] := FRawData[i];
end;
end;
procedure TAsciiImage.SaveToStream(Stream: TStream);
var
LAscii: TStringList;
begin
LAscii := TStringList.Create();
try
LAscii.AddStrings(FRawData);
LAscii.SaveToStream(Stream);
finally
LAscii.Free;
end;
end;
procedure TAsciiImage.ScanShapes;
var
LPathStart, LPathLength: Integer;
i, k: Integer;
LPoints: array of TPointF;
begin
LPathStart := -1;
for i := 0 to Length(FDots) - 1 do
begin
//we have one dot for this char and haven't started a path yet?
//mark it as path-start
if FDots[i].Count = 1 then
begin
if LPathStart = -1 then
LPathStart := i;
end
else
begin
if FDots[i].Count = 2 then
AddLine(FDots[i][0], FDots[i][1]);
if FDots[i].Count > 2 then
AddEllipsis(FDots[i].ToArray);
end;
//did we start a path? Is the current dot not part of a path?(Marks end) or is it the last dot?
if (LPathStart > -1) and ((FDots[i].Count <> 1) or (i = Length(FDots) - 1)) then
begin
//in case the final point is simply a path of length 1, pathlength is 0, because
//i = LPathStart
//anything with more than 1 point is a path, anything below is just a dot
LPathLength := i - LPathStart;
if LPathLength < 2 then
begin
AddDot(FDots[LPathStart][0]);
end
else
begin
SetLength(LPoints, Max(LPathLength, 1));
for k := 0 to Length(LPoints) - 1 do
begin
LPoints[k] := FDots[k + LPathStart][0];
end;
AddPath(LPoints);
end;
LPathStart := -1;
end;
end;
end;
procedure TAsciiImage.SetHeight(Value: Integer);
begin
inherited;
if FHeight <> Value then
begin
FHeight := Value;
Clear();
end;
end;
procedure TAsciiImage.SetWidth(Value: Integer);
begin
inherited;
if FWidth <> Value then
begin
FWidth := Value;
Clear();
end;
end;
{$if Framework = 'VCL'}
initialization
TPicture.RegisterFileFormat('AIMG', 'Ascii Image Graphic', TAsciiImage);
TPicture.RegisterFileFormat('AsciiImage', 'Ascii Image Graphic', TAsciiImage);
finalization
TPicture.UnregisterGraphicClass(TAsciiImage);
{$IfEnd}
end.
|
{*******************************************************}
{ }
{ 无边框窗体大小控制单元 }
{ }
{ 版权所有 (C) 2017 by YangYxd }
{ }
{*******************************************************}
{
使用方法: 将需要控制大小的无边框窗口的基类设置为 TSizeForm 即可
}
unit UI.SizeForm;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Windows, Winapi.Messages, FMX.Platform.Win, Winapi.MultiMon,
{$ENDIF}
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, UI.Base,
FMX.StdCtrls, FMX.Effects;
type
TResizeMode = (Normal, LTop, RTop, LBottom, RBottom, Top, Bottom, Left, Right);
TSizeForm = class(TForm)
{$IFDEF MSWINDOWS}
private
FHwnd: HWND;
FWndHandle: HWND;
FObjectInstance: Pointer;
FDefWindowProc: Pointer;
procedure MainWndProc(var Message: TMessage);
procedure HookWndProc;
procedure UnHookWndProc;
procedure WMGetMinMaxInfo(var AMsg: TWMGetMinMaxInfo); message WM_GETMINMAXINFO;
protected
procedure WndProc(var Message: TMessage); virtual;
{$ENDIF}
private
{ Private declarations }
FShadowForm: TCustomForm;
FCaptureDragForm: Boolean;
FMouseDraging: Boolean;
FShowShadow: Boolean;
FResizable: Boolean;
FMinSize: TSize;
procedure SetShowShadow(const Value: Boolean);
function GetMonitorIndex: Integer;
function GetIsDestroy: Boolean;
protected
FSizeWH: Single; // 可调节区域大小
FMousePos, FDownPos, FResizeSize, FDownSize: TPointF;
FResizeMode: TResizeMode;
function PointInDragBorder(const X, Y: Single): Boolean;
function CalcResizeMode(const X, Y: Single): TResizeMode;
procedure UpdateCurror(const AResizeMode: TResizeMode);
procedure DoShow; override;
function GetShadowColor: TAlphaColor; virtual;
function GetShadowBackgroundColor: TAlphaColor; virtual;
function GetSceneScale: Single;
procedure InitShadowForm();
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ObjectAtPoint(AScreenPoint: TPointF): IControl; override;
procedure MouseMove(Shift: TShiftState; X, Y: Single); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single; DoClick: Boolean = True); override;
/// <summary>
/// 最小化
/// </summary>
procedure ShowMin; virtual;
/// <summary>
/// 最大化
/// </summary>
procedure ShowMax; virtual;
/// <summary>
/// 恢复
/// </summary>
procedure ShowReSize; virtual;
/// <summary>
/// 双击标题栏
/// </summary>
procedure DBClickTitle(Sender: TObject);
property ShadowForm: TCustomForm read FShadowForm;
property MonitorIndex: Integer read GetMonitorIndex;
/// <summary>
/// 是否已经释放
/// </summary>
property IsDestroy: Boolean read GetIsDestroy;
published
property CaptureDragForm: Boolean read FCaptureDragForm write FCaptureDragForm;
property SizeWH: Single read FSizeWH write FSizeWH;
/// <summary>
/// 是否显示阴影
/// </summary>
property ShowShadow: Boolean read FShowShadow write SetShowShadow default False;
/// <summary>
/// 是否可以改变大小
/// </summary>
property Resizable: Boolean read FResizable write FResizable default True;
/// <summary>
/// 窗口限制最小尺寸,为0则不限制
/// </summary>
property MinSize: TSize read FMinSize write FMinSize;
end;
implementation
uses
System.Generics.Collections;
type
TColorView = class(TControl)
protected
FColor: TAlphaColor;
procedure Paint; override;
end;
TShadowForm = class(TCustomForm)
private
[Weak] FOwner: TSizeForm;
FShadowSize: Integer;
FView: TColorView;
FShadow: TShadowEffect;
FIsShow: Boolean;
{$IFDEF MSWINDOWS}
FHwnd, FMHwnd: HWND; // 保存窗口句柄
{$ENDIF}
protected
procedure InitializeNewForm; override;
procedure InitView(const BgColor, ShadowColor: TAlphaColor);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{$IFDEF MSWINDOWS}
procedure ParentWindowProc(var message: TMessage);
{$ENDIF}
procedure DoShow; override;
procedure UpdateBounds(ALeft, ATop, AWidth, AHeight: Integer;
AUpdateSize: Boolean = True; AUpdateZOrder: Boolean = False);
property Owner: TSizeForm read FOwner;
property ShadowSize: Integer read FShadowSize write FShadowSize;
property Shadow: TShadowEffect read FShadow;
end;
{$IFDEF MSWINDOWS}
const
WM_SYNC_SIZE = WM_USER + 920;
type
TMonitor = record
Handle: HMONITOR;
MonitorNum: Integer;
end;
var
MonitorList: TList<TMonitor>;
function EnumMonitorsProc(hm: HMONITOR; dc: HDC; r: PRect; Data: Pointer): Boolean; stdcall;
var
M: TMonitor;
begin
M.Handle := hm;
M.MonitorNum := MonitorList.Count;
MonitorList.Add(M);
Result := True;
end;
procedure InitMonitorList();
begin
EnumDisplayMonitors(0, nil, @EnumMonitorsProc, 0);
end;
{$ENDIF}
function TSizeForm.CalcResizeMode(const X, Y: Single): TResizeMode;
begin
Result := TResizeMode.Normal;
if (X < 0) and (Y < 0) then
Exit;
if WindowState <> TWindowState.wsNormal then
Exit;
if (X > FSizeWH) and (X <= Width - FSizeWH) then begin
if (Y < FSizeWH) then
Result := TResizeMode.Top
else if (Y >= Height - FSizeWH) then
Result := TResizeMode.Bottom
end else if (Y > FSizeWH) and (Y < Height - FSizeWH) then begin
if X <= FSizeWH then
Result := TResizeMode.Left
else if X >= Width - FSizeWH then
Result := TResizeMode.Right
end else if (X <= FSizeWH) and (Y <= FSizeWH) then
Result := TResizeMode.LTop
else if (X >= Width - FSizeWH) and (Y <= FSizeWH) then
Result := TResizeMode.RTop
else if (X <= FSizeWH) and (Y >= Height - FSizeWH) then
Result := TResizeMode.LBottom
else if (X >= Width - FSizeWH) and (Y >= Height - FSizeWH) then
Result := TResizeMode.RBottom;
end;
constructor TSizeForm.Create(AOwner: TComponent);
begin
inherited;
FSizeWH := 10;
FShadowForm := nil;
FResizable := True;
FMinSize := TSize.Create(0, 0);
end;
procedure TSizeForm.DBClickTitle(Sender: TObject);
begin
if WindowState = TWindowState.wsNormal then begin
ShowMax();
end else begin
ShowReSize();
end;
end;
destructor TSizeForm.Destroy;
begin
FreeAndNil(FShadowForm);
{$IFDEF MSWINDOWS}
UnHookWndProc;
{$ENDIF}
inherited;
end;
procedure TSizeForm.DoShow;
begin
{$IFDEF MSWINDOWS}
HookWndProc;
{$ENDIF}
inherited DoShow;
{$IFDEF MSWINDOWS}
FHwnd := FmxHandleToHWND(Handle);
{$ENDIF}
InitShadowForm;
end;
function TSizeForm.GetIsDestroy: Boolean;
begin
Result := (not Assigned(Self)) or (csDestroying in ComponentState);
end;
function TSizeForm.GetMonitorIndex: Integer;
{$IFDEF MSWINDOWS}
var
HM: HMonitor;
I: Integer;
{$ENDIF}
begin
Result := 0;
{$IFDEF MSWINDOWS}
HM := MonitorFromWindow(FHwnd, MONITOR_DEFAULTTONEAREST);
for I := 0 to MonitorList.Count - 1 do
if MonitorList[I].Handle = HM then begin
Result := I;
Exit;
end;
{$ENDIF}
end;
procedure TSizeForm.InitShadowForm;
begin
if Assigned(FShadowForm) or (not FShowShadow) then
Exit;
if (csLoading in ComponentState) or (csDesigning in ComponentState) then
Exit;
if BorderStyle <> TFmxFormBorderStyle.None then
Exit;
FShadowForm := TShadowForm.Create(nil);
TShadowForm(FShadowForm).FOwner := Self;
TShadowForm(FShadowForm).InitView(GetShadowBackgroundColor, GetShadowColor);
FShadowForm.Show;
end;
procedure TSizeForm.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Single);
begin
inherited;
if (BorderStyle = TFmxFormBorderStyle.None) and (WindowState = TWindowState.wsNormal) then begin
if (csDesigning in ComponentState) then Exit;
if (Button = TMouseButton.mbLeft) and (Shift = [ssLeft]) then begin
if FullScreen then
Exit;
if not PointInDragBorder(X, Y) then begin
if FCaptureDragForm then begin
FMouseDraging := True;
StartWindowDrag;
end;
Exit;
end;
if FResizable then begin
FResizeMode := CalcResizeMode(X, Y);
UpdateCurror(FResizeMode);
if FResizeMode = TResizeMode.Normal then
Exit;
FMousePos := PointF(X, Y);
FDownPos := FMousePos;
FResizeSize := PointF(Width, Height);
FDownSize := FResizeSize;
FWinService.SetCapture(Self);
end;
end;
end;
end;
procedure TSizeForm.MouseMove(Shift: TShiftState; X, Y: Single);
var
P: TPointF;
{$IFDEF MSWINDOWS}
LScale: Single;
{$ENDIF}
begin
if FResizable and (FResizeMode <> TResizeMode.Normal) and (ssLeft in Shift) then begin
Engage;
try
P.X := Left;
P.Y := Top;
case FResizeMode of
TResizeMode.LTop:
begin
P.X := P.X + (X - FDownPos.X);
P.Y := P.Y + (Y - FDownPos.Y);
FResizeSize.X := Round(FResizeSize.X + (X - FMousePos.X - (X - FDownPos.X)));
FResizeSize.Y := Round(FResizeSize.Y + (Y - FMousePos.Y - (Y - FDownPos.Y)));
end;
TResizeMode.RTop:
begin
P.Y := P.Y + (Y - FDownPos.Y);
FResizeSize.X := Round(FResizeSize.X + (X - FMousePos.X));
FResizeSize.Y := Round(FResizeSize.Y + (Y - FMousePos.Y - (Y - FDownPos.Y)));
end;
TResizeMode.LBottom:
begin
P.X := P.X + (X - FDownPos.X);
FResizeSize.X := Round(FResizeSize.X + (X - FMousePos.X - (X - FDownPos.X)));
FResizeSize.Y := Round(FResizeSize.Y + (Y - FMousePos.Y));
end;
TResizeMode.RBottom:
begin
FResizeSize.X := Round(FResizeSize.X + (X - FMousePos.X));
FResizeSize.Y := Round(FResizeSize.Y + (Y - FMousePos.Y));
end;
TResizeMode.Top:
begin
P.Y := P.Y + (Y - FDownPos.Y);
FResizeSize.Y := Round(FResizeSize.Y + (Y - FMousePos.Y) - (Y - FDownPos.Y));
end;
TResizeMode.Bottom:
begin
FResizeSize.Y := Round(FResizeSize.Y + (Y - FMousePos.Y));
end;
TResizeMode.Left:
begin
P.X := P.X + (X - FDownPos.X);
FResizeSize.X := Round(FResizeSize.X + (X - FMousePos.X - (X - FDownPos.X)));
end;
TResizeMode.Right:
begin
FResizeSize.X := Round(FResizeSize.X + (X - FMousePos.X));
end;
end;
// 最小尺寸限制
if (FMinSize.cx <> 0) and (FResizeSize.X < FMinSize.cx) then
FResizeSize.X := FMinSize.cx;
if (FMinSize.cy <> 0) and (FResizeSize.Y < FMinSize.cy) then
FResizeSize.Y := FMinSize.cy;
{$IFDEF MSWINDOWS}
if Assigned(FShadowForm) then begin
LScale := GetSceneScale;
Lockwindowupdate(FHwnd);
SetWindowPos(FHwnd, HWND_TOP, Round(P.X), Round(P.Y), Round(FResizeSize.X * LScale), Round(FResizeSize.Y * LScale), SWP_NOREDRAW or SWP_NOACTIVATE or SWP_NOZORDER or SWP_DEFERERASE);
Lockwindowupdate(0);
TShadowForm(FShadowForm).UpdateBounds(Round(P.X), Round(P.Y), Round(FResizeSize.X), Round(FResizeSize.Y));
UpdateWindow(FHwnd);
end else
SetBounds(Round(P.X), Round(P.Y), Round(FResizeSize.X), Round(FResizeSize.Y));
{$ELSE}
SetBounds(Round(P.X), Round(P.Y), Round(FResizeSize.X), Round(FResizeSize.Y));
{$ENDIF}
FMousePos := PointF(X, Y);
finally
Disengage;
end;
end else begin
inherited;
if (BorderStyle = TFmxFormBorderStyle.None) then begin
if Shift = [] then
UpdateCurror(CalcResizeMode(X, Y))
else
Cursor := crArrow;
end else if Cursor <> crDefault then
Cursor := crDefault;
end;
end;
procedure TSizeForm.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single;
DoClick: Boolean);
begin
if FMouseDraging then begin
FMouseDraging := False;
ReleaseCapture;
end;
if FResizable and (FResizeMode <> TResizeMode.Normal) then begin
FResizeMode := TResizeMode.Normal;
ReleaseCapture;
end;
inherited;
end;
function TSizeForm.ObjectAtPoint(AScreenPoint: TPointF): IControl;
function Innder(const P: TPointF): IControl;
begin
if (P.X < 0) or (P.Y < 0) or PointInDragBorder(P.X, P.Y) then
Result := nil
else
Result := inherited;
end;
begin
if (BorderStyle = TFmxFormBorderStyle.None) and (WindowState = TWindowState.wsNormal) and (FSizeWH > 1) then
Result := Innder(ScreenToClient(AScreenPoint))
else
Result := inherited;
end;
function TSizeForm.PointInDragBorder(const X, Y: Single): Boolean;
begin
Result := (FSizeWH > 1) and ((X < FSizeWH) or (X >= Width - FSizeWH) or (Y < FSizeWH) or (Y >= Height - FSizeWH));
end;
procedure TSizeForm.SetShowShadow(const Value: Boolean);
begin
if FShowShadow <> Value then begin
FShowShadow := Value;
if (csDesigning in ComponentState) then
Exit;
if not Value then
FreeAndNil(FShadowForm);
end;
end;
procedure TSizeForm.ShowMax;
begin
Self.WindowState := TWindowState.wsMaximized;
{$IFDEF MSWINDOWS}
//PostMessage(FHwnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
{$ELSE}
{$ENDIF}
end;
procedure TSizeForm.ShowMin;
begin
{$IFDEF MSWINDOWS}
PostMessage(FHwnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);
{$ELSE}
Self.WindowState := TWindowState.wsMinimized;
{$ENDIF}
end;
procedure TSizeForm.ShowReSize;
begin
Self.WindowState := TWindowState.wsNormal;
end;
function TSizeForm.GetSceneScale: Single;
begin
if Handle <> nil then
Result := Handle.Scale
else
Result := 1;
end;
function TSizeForm.GetShadowBackgroundColor: TAlphaColor;
begin
Result := $ffffffff;
end;
function TSizeForm.GetShadowColor: TAlphaColor;
begin
Result := $7f000000;
end;
procedure TSizeForm.UpdateCurror(const AResizeMode: TResizeMode);
const
CCursor: array [TResizeMode] of Integer = (
crArrow, crSizeNWSE, crSizeNESW, crSizeNESW, crSizeNWSE, crSizeNS, crSizeNS, crSizeWE, crSizeWE
);
begin
Cursor := CCursor[AResizeMode]
end;
{$IFDEF MSWINDOWS}
procedure TSizeForm.HookWndProc;
begin
// 设计状态,不HOOK
if csDesigning in ComponentState then
Exit;
// 已HOOK
if FObjectInstance <> nil then
Exit;
if FWndHandle = 0 then
FWndHandle := FmxHandleToHWND(Handle);
if FWndHandle > 0 then
begin
if FObjectInstance = nil then
begin
FObjectInstance := MakeObjectInstance(MainWndProc);
if FObjectInstance <> nil then
begin
FDefWindowProc := Pointer(GetWindowLong(FWndHandle, GWL_WNDPROC));
SetWindowLong(FWndHandle, GWL_WNDPROC, IntPtr(FObjectInstance));
end;
end;
end;
end;
procedure TSizeForm.UnHookWndProc;
begin
if FDefWindowProc <> nil then
begin
SetWindowLong(FWndHandle, GWL_WNDPROC, IntPtr(FDefWindowProc));
FDefWindowProc := nil;
end;
if FObjectInstance <> nil then
begin
FreeObjectInstance(FObjectInstance);
FObjectInstance := nil;
end;
end;
procedure TSizeForm.WMGetMinMaxInfo(var AMsg: TWMGetMinMaxInfo);
var
LInfo: PMinMaxInfo;
begin
// 透明或者无边框下应用此规则
if (MonitorIndex = 0) and Transparency or (BorderStyle = TFmxFormBorderStyle.None) then
begin
LInfo := AMsg.MinMaxInfo;
if not Assigned(LInfo) then
Exit;
LInfo^.ptMaxSize.X := {$IF RTLVersion >= 35}Trunc{$ENDIF}(Screen.WorkAreaWidth);
LInfo^.ptMaxSize.Y := {$IF RTLVersion >= 35}Trunc{$ENDIF}(Screen.WorkAreaHeight);
AMsg.Result := 1;
end;
end;
procedure TSizeForm.WndProc(var Message: TMessage);
begin
// virtual method
end;
procedure TSizeForm.MainWndProc(var Message: TMessage);
begin
try
// 消息传递过程。
WndProc(Message);
// 消息派遣
if Message.Result = 0 then
Dispatch(Message);
except
Application.HandleException(Self);
end;
with Message do
begin
if Result = 0 then
Result := CallWindowProc(FDefWindowProc, FWndHandle, Msg, WParam, LParam);
end;
// 最后处理
// 如果需要显示阴影
if (Message.Msg <> WM_GETMINMAXINFO) and FShowShadow and Assigned(FShadowForm) then
TShadowForm(FShadowForm).ParentWindowProc(Message);
end;
{$ENDIF MSWINDOWS}
{ TShadowForm }
constructor TShadowForm.Create(AOwner: TComponent);
begin
FShadowSize := 12;
inherited;
SetDesigning(False, False);
Self.BorderStyle := TFmxFormBorderStyle.None;
Self.Visible := False;
Self.Transparency := True;
Self.WindowState := TWindowState.wsNormal;
end;
destructor TShadowForm.Destroy;
begin
inherited;
end;
procedure TShadowForm.DoShow;
begin
inherited;
FIsShow := True;
{$IFDEF MSWINDOWS}
FMHwnd := FmxHandleToHWND(Handle);
SetWindowLong(FMHwnd, GWL_EXSTYLE, GetWindowLong(FMHwnd, GWL_EXSTYLE)
or WS_EX_LAYERED or WS_EX_TRANSPARENT or WS_EX_TOPMOST or WS_EX_NOACTIVATE or WS_EX_TOOLWINDOW);
{$ENDIF}
if Assigned(FOwner) then begin
UpdateBounds(FOwner.Left, FOwner.Top, FOwner.Width, FOwner.Height);
{$IFDEF MSWINDOWS}
FHwnd := FmxHandleToHWND(FOwner.Handle);
{$ENDIF}
end;
end;
procedure TShadowForm.InitializeNewForm;
begin
inherited;
SetDesigning(True, False);
end;
procedure TShadowForm.InitView(const BgColor, ShadowColor: TAlphaColor);
begin
FView := TColorView.Create(Self);
FView.FColor := BgColor;
FView.Margins.Rect := RectF(FShadowSize, FShadowSize, FShadowSize, FShadowSize);
FView.Align := TAlignLayout.Client;
FView.Parent := Self;
FShadow := TShadowEffect.Create(Self);
FShadow.Direction := 90;
FShadow.Opacity := 1;
FShadow.Softness := 0.35;
FShadow.Distance := 0;
FShadow.ShadowColor := ShadowColor;
FShadow.Parent := FView;
FShadow.Enabled := True;
end;
procedure TShadowForm.UpdateBounds(ALeft, ATop, AWidth, AHeight: Integer;
AUpdateSize, AUpdateZOrder: Boolean);
function GetRect(AScale: Single): TRect;
begin
Result.Left := ALeft - Round(FShadowSize * AScale);
Result.Top := ATop - Round(FShadowSize * AScale);
Result.Right := Result.Left + Round((AWidth + FShadowSize * 2) * AScale);
Result.Bottom := Result.Top + Round((AHeight + FShadowSize * 2) * AScale);
end;
var
R: TRect;
{$IFDEF MSWINDOWS}
Flags: Integer;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
R := GetRect(FOwner.GetSceneScale);
Flags := SWP_NOREDRAW or SWP_NOACTIVATE or SWP_DEFERERASE;
if not AUpdateSize then
Flags := Flags or SWP_NOSIZE;
if not AUpdateZOrder then
Flags := Flags or SWP_NOZORDER;
SetWindowPos(FMHwnd, FHwnd, R.Left, R.Top, R.Width, R.Height, Flags);
//UpdateWindow(FMHwnd);
{$ELSE}
R := GetRect(1.0);
SetBounds(R);
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
procedure TShadowForm.ParentWindowProc(var message: TMessage);
var
LScale: Single;
begin
case message.Msg of
WM_MOVE:
begin
if (FOwner.WindowState = TWindowState.wsNormal) and (Abs(Self.Width - FOwner.Width) > FShadowSize * 2) then
UpdateBounds(FOwner.Left, FOwner.Top, FOwner.Width, FOwner.Height)
else
UpdateBounds(FOwner.Left, FOwner.Top, FOwner.Width, FOwner.Height, False);
end;
WM_ACTIVATE, WM_NCACTIVATE:
UpdateBounds(FOwner.Left, FOwner.Top, FOwner.Width, FOwner.Height, True, True);
WM_SHOWWINDOW:
SendMessage(FMHwnd, message.Msg, message.WParam, message.LParam);
end;
end;
{$ENDIF}
{ TColorView }
procedure TColorView.Paint;
begin
//inherited Paint;
Canvas.Fill.Color := FColor;
Canvas.Fill.Kind := TBrushKind.Solid;
Canvas.FillRect(ClipRect, 0, 0, [], 1);
end;
initialization
{$IFDEF MSWINDOWS}
MonitorList := TList<TMonitor>.Create;
InitMonitorList();
{$ENDIF}
finalization
{$IFDEF MSWINDOWS}
FreeAndNil(MonitorList);
{$ENDIF}
end.
|
unit DragDrop;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms,ShellApi;
type
TFilesDropped = Procedure(NumItems:Integer) of Object;
TDragDrop = class(TComponent)
private
//Define Event
FFilesDropped:TFilesDropped;
//Proc Pointers
OldWndProc : TFarProc;
NewWndProc : Pointer;
//Field Variables
FList:TStringList; // Store dropped files
FBTF:Boolean; // Bring to front?
FActive:Boolean; // Accept drops at all?
procedure HookParent;
procedure UnhookParent;
procedure HookWndProc(var Message: TMessage);
procedure SetActive(YesNo:Boolean);
protected
{ Protected declarations }
public
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
property DroppedFiles:TStringList Read FList;
published
procedure ClearList;
property Active:Boolean Read FActive Write SetActive;
property BringToFront:Boolean Read FBTF Write FBTF;
property OnFilesDropped:TFilesDropped Read FFilesDropped Write FFilesDropped;
end;
procedure Register;
implementation
constructor TDragDrop.Create(AOwner:TComponent);
Begin
Inherited Create(AOwner);
NewWndProc := Nil;
OldWndProc := Nil;
FList := TStringList.Create;
FBTF := False;
If ComponentState<>[csDesigning] Then
Begin
HookParent;
SetActive(FActive); //Activate (or don't) the capturing of WM_DROPFILES
End;
End;
destructor TDragDrop.Destroy;
begin
UnhookParent;
FList.Free;
inherited Destroy; // Call TComponent's default destroy meathod
end;
procedure TDragDrop.HookParent;
begin
// Exit if parent doesn't exist
if (Owner As TWinControl) = NIL then exit;
//Install Hook
OldWndProc := TFarProc(GetWindowLong((Owner As TWinControl).Handle, GWL_WNDPROC));
NewWndProc := MakeObjectInstance(HookWndProc);
SetWindowLong((Owner As TWinControl).Handle, GWL_WNDPROC, LongInt(NewWndProc));
end;
procedure TDragDrop.UnhookParent;
begin
if ( (Owner As TWinControl)<> NIL) And (Assigned(OldWndProc) ) then
SetWindowLong((Owner As TWinControl).Handle, GWL_WNDPROC, LongInt(OldWndProc));
if assigned(NewWndProc) then
FreeObjectInstance(NewWndProc);
NewWndProc := NIL;
OldWndProc := NIL;
end;
procedure TDragDrop.HookWndProc(var Message: TMessage);
var I,nl,nFiles:Integer;
fName:Array[1..255] of Char;
begin
if (Owner As TWinControl) = NIL then
Exit;
With Message Do
Begin
Result := CallWindowProc(OldWndProc, (Owner As TWinControl).Handle, Msg, wParam, lParam);
If (Msg = WM_DROPFILES) Then
Begin
If FBTF Then
SetForegroundWindow((Owner As TWinControl).Handle);
//Clear the internal list
FList.Clear;
//Using -1 in the index gives me the number of files
nFiles := DragQueryFile(wParam, $FFFFFFFF, Nil, 0);
For i:=0 to nFiles-1 do
Begin
//DragQueryFile returns the length of the given file
nl := DragQueryFile(wParam,i,@fName,255)+1;
//Append a character zero to make null-terminated string
fName[nl] := #0;
//Add the item
FList.Add(fName);
End;
If ((nFiles>0) And (Assigned(FFilesDropped))) Then
FFilesDropped(nFiles);
End;
End;
end;
procedure TDragDrop.ClearList;
Begin
Try
FList.Clear;
Except
End;
End;
procedure TDragDrop.SetActive(YesNo:Boolean);
Begin
//Set Private field
FActive := YesNo;
If ComponentState=[csDesigning] Then
Exit; //Don't hook to window at design time!
If FActive Then
DragAcceptFiles((Owner As TWinControl).Handle,True)
Else
DragAcceptFiles((Owner As TWinControl).Handle,False);
End;
procedure Register;
begin
RegisterComponents('System', [TDragDrop]);
end;
end.
|
(*Не рекомендуется часто использовать оператор (goto) т.к это ведёт к нечитаемости программы.
Распространённым случаем ипользования служит обработка ошибки неправельного ввода данных
с клавиатуры *)
program label_1;
label 12;
var N : integer ;
begin
12 : Write ('Введите значение N > 0 ' );
Readln(N);
if N <=0 then goto 12;
end.
(* - Именем метки служит идентифткатор или цифра
- Недопустимо использование одной метки для нескольких операторов или процедур.
- Метка, которая указывает в операторе перехода, должна находится в томже блоке
(поимённой части программы), что и сам оператор перехода. Недопустим выход из блока
или вход внутрь него извне.
- Недопустим вход внутрь структурного оператора.*)
|
unit uDataModule;
interface
uses
System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.SQLite,
FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, FireDAC.VCLUI.Wait,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TDM = class(TDataModule)
FDConnection1: TFDConnection;
TblEnemies: TFDTable;
DSEnemies: TDataSource;
FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink;
TblNotes: TFDTable;
FDQuery: TFDQuery;
TblPlayers: TFDTable;
DSPlayers: TDataSource;
TblCampaings: TFDTable;
DSCampaings: TDataSource;
TblLocations: TFDTable;
DSLocations: TDataSource;
TblNPCs: TFDTable;
DSNPCs: TDataSource;
TblQuests: TFDTable;
DSQuests: TDataSource;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
DM: TDM;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TDM.DataModuleCreate(Sender: TObject);
begin
FDConnection1.Connected := True;
TblEnemies.Active := True;
TblNotes.Active := True;
TblPlayers.Active := True;
TblLocations.Active := True;
TblCampaings.Active := True;
TblNPCs.Active := True;
TblQuests.Active := True;
FDQuery.Active := True;
end;
end.
|
unit fctf256;
(*************************************************************************
DESCRIPTION : File crypt/authenticate unit using Twofish 256
REQUIREMENTS : TP5-7, D1-D7/D9-D10, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : ---
REMARK :
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 10.03.16 G.Tani Based on W.Ehrhardt fcaes256 0.16 modified to use Twofish 256
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2003-2008 Wolfgang Ehrhardt, Giorgio Tani
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}
interface
uses
BTypes,
{$ifdef USEDLL}
{$ifdef VirtualPascal}
CH_INTV, TF_INTV;
{$else}
CH_INTF, TF_INTF;
{$endif}
{$else}
Hash, HMAC, Whirl512, KDF, TF_base, TF_CTR, TF_EAX;
{$endif}
const
C_FCF_Sig = $FC;
KeyIterations : word = 1000; {Iterations in KeyDeriv}
type
TFCF256Salt = array[0..2] of longint; {96 Bit salt}
TFCF256Hdr = packed record {same header format used in Fcrypt}
{a plus key size bit in Flag for 256 bit keys (bit 2)}
FCFsig: byte; {Sig $FC}
Flags : byte; {High $A0; Bit2: 0=128bit (as in Fcrypta)}
{1=256bit; Bit1: compression; Bit0: 1=EAX, 0=HMAC-CTR}
Salt : TFCF256Salt;
PW_Ver: word;
end;
TFCF256_AuthBlock = array[0..15] of byte;
type
TFCF_HMAC256_Context = record
TF_ctx : TTFContext; {crypt context}
hmac_ctx : THMAC_Context; {auth context}
end;
function FCF_EAX256_init(var cx: TTF_EAXContext; pPW: pointer; pLen: word; var hdr: TFCF256Hdr): integer;
{-Initialize crypt context using password pointer pPW and hdr.salt}
function FCF_EAX256_initS(var cx: TTF_EAXContext; sPW: Str255; var hdr: TFCF256Hdr): integer;
{-Initialize crypt context using password string sPW and hdr.salt}
function FCF_EAX256_encrypt(var cx: TTF_EAXContext; var data; dLen: word): integer;
{-encyrypt a block of data in place and update EAX}
function FCF_EAX256_decrypt(var cx: TTF_EAXContext; var data; dLen: word): integer;
{-decyrypt a block of data in place and update EAX}
procedure FCF_EAX256_final(var cx: TTF_EAXContext; var auth: TFCF256_AuthBlock);
{-return final EAX tag}
function FCF_HMAC256_init(var cx: TFCF_HMAC256_Context; pPW: pointer; pLen: word; var hdr: TFCF256Hdr): integer;
{-Initialize crypt context using password pointer pPW and hdr.salt}
function FCF_HMAC256_initS(var cx: TFCF_HMAC256_Context; sPW: Str255; var hdr: TFCF256Hdr): integer;
{-Initialize crypt context using password string sPW and hdr.salt}
function FCF_HMAC256_encrypt(var cx: TFCF_HMAC256_Context; var data; dLen: word): integer;
{-encyrypt a block of data in place and update HMAC}
function FCF_HMAC256_decrypt(var cx: TFCF_HMAC256_Context; var data; dLen: word): integer;
{-decyrypt a block of data in place and update HMAC}
procedure FCF_HMAC256_final(var cx: TFCF_HMAC256_Context; var auth: TFCF256_AuthBlock);
{-return final HMAC-Whirlpool-128 digest}
implementation
type
TX256Key = packed record {eXtended key for PBKDF}
ak: packed array[0..31] of byte; {TF 256 bit key }
hk: packed array[0..31] of byte; {HMAC key / EAX nonce }
pv: word; {password verifier }
end;
{---------------------------------------------------------------------------}
function FCF_HMAC256_init(var cx: TFCF_HMAC256_Context; pPW: pointer; pLen: word; var hdr: TFCF256Hdr): integer;
{-Initialize crypt context using password pointer pPW and hdr.salt}
var
XKey: TX256Key;
CTR : TTFBlock;
pwph: PHashDesc;
Err : integer;
begin
{CTR=0, random/uniqness from hdr.salt}
fillchar(CTR, sizeof(CTR), 0);
{derive the TF, HMAC keys and pw verifier}
pwph := FindHash_by_ID(_Whirlpool);
Err := pbkdf2(pwph, pPW, pLen, @hdr.salt, sizeof(TFCF256Salt), KeyIterations, XKey, sizeof(XKey));
{init TF CTR mode with ak}
if Err=0 then Err := TF_CTR_Init(XKey.ak, 8*sizeof(XKey.ak), CTR, cx.TF_ctx);
{exit if any error}
FCF_HMAC256_init := Err;
if Err<>0 then exit;
{initialise HMAC with hk, here pwph is valid}
hmac_init(cx.hmac_ctx, pwph, @XKey.hk, sizeof(XKey.hk));
{return pw verifier}
hdr.PW_Ver := XKey.pv;
hdr.FCFSig := C_FCF_Sig;
hdr.Flags := $A4;
{burn XKey}
fillchar(XKey, sizeof(XKey),0);
end;
{---------------------------------------------------------------------------}
function FCF_HMAC256_initS(var cx: TFCF_HMAC256_Context; sPW: Str255; var hdr: TFCF256Hdr): integer;
{-Initialize crypt context using password string sPW and hdr.salt}
begin
FCF_HMAC256_initS := FCF_HMAC256_init(cx, @sPW[1], length(sPW), hdr);
end;
{---------------------------------------------------------------------------}
function FCF_HMAC256_encrypt(var cx: TFCF_HMAC256_Context; var data; dLen: word): integer;
{-encyrypt a block of data in place and update HMAC}
begin
FCF_HMAC256_encrypt := TF_CTR_Encrypt(@data, @data, dLen, cx.TF_ctx);
hmac_update(cx.hmac_ctx, @data, dLen);
end;
{---------------------------------------------------------------------------}
function FCF_HMAC256_decrypt(var cx: TFCF_HMAC256_Context; var data; dLen: word): integer;
{-decyrypt a block of data in place and update HMAC}
begin
hmac_update(cx.hmac_ctx, @data, dLen);
FCF_HMAC256_decrypt := TF_CTR_Encrypt(@data, @data, dLen, cx.TF_ctx);
end;
{---------------------------------------------------------------------------}
procedure FCF_HMAC256_final(var cx: TFCF_HMAC256_Context; var auth: TFCF256_AuthBlock);
{-return final HMAC-Whirlpool-128 digest}
var
mac: THashDigest;
begin
hmac_final(cx.hmac_ctx,mac);
move(mac, auth, sizeof(auth));
end;
{---------------------------------------------------------------------------}
function FCF_EAX256_init(var cx: TTF_EAXContext; pPW: pointer; pLen: word; var hdr: TFCF256Hdr): integer;
{-Initialize crypt context using password pointer pPW and hdr.salt}
var
XKey: TX256Key;
Err : integer;
begin
{derive the EAX key / nonce and pw verifier}
Err := pbkdf2(FindHash_by_ID(_Whirlpool), pPW, pLen, @hdr.salt, sizeof(TFCF256Salt), KeyIterations, XKey, sizeof(XKey));
{init TF EAX mode with ak/hk}
if Err=0 then Err := TF_EAX_Init(XKey.ak, 8*sizeof(XKey.ak), xkey.hk, sizeof(XKey.hk), cx);;
{exit if any error}
FCF_EAX256_init := Err;
if Err<>0 then exit;
{return pw verifier}
hdr.PW_Ver := XKey.pv;
hdr.FCFSig := C_FCF_Sig;
hdr.Flags := $A5;
{burn XKey}
fillchar(XKey, sizeof(XKey),0);
end;
{---------------------------------------------------------------------------}
function FCF_EAX256_initS(var cx: TTF_EAXContext; sPW: Str255; var hdr: TFCF256Hdr): integer;
{-Initialize crypt context using password string sPW and hdr.salt}
begin
FCF_EAX256_initS := FCF_EAX256_init(cx, @sPW[1], length(sPW), hdr);
end;
{---------------------------------------------------------------------------}
function FCF_EAX256_encrypt(var cx: TTF_EAXContext; var data; dLen: word): integer;
{-encyrypt a block of data in place and update EAX}
begin
FCF_EAX256_encrypt := TF_EAX_Encrypt(@data, @data, dLen, cx);
end;
{---------------------------------------------------------------------------}
function FCF_EAX256_decrypt(var cx: TTF_EAXContext; var data; dLen: word): integer;
{-decyrypt a block of data in place and update EAX}
begin
FCF_EAX256_decrypt := TF_EAX_decrypt(@data, @data, dLen, cx);
end;
{---------------------------------------------------------------------------}
procedure FCF_EAX256_final(var cx: TTF_EAXContext; var auth: TFCF256_AuthBlock);
{-return final EAX tag}
begin
TF_EAX_Final(TTFBlock(auth), cx);
end;
end.
|
{ **********************************************************************}
{ }
{ DeskMetrics DLL - dskMetricsConsts.pas }
{ Copyright (c) 2010-2011 DeskMetrics Limited }
{ }
{ http://deskmetrics.com }
{ http://support.deskmetrics.com }
{ }
{ support@deskmetrics.com }
{ }
{ This code is provided under the DeskMetrics Modified BSD License }
{ A copy of this license has been distributed in a file called }
{ LICENSE with this source code. }
{ }
{ **********************************************************************}
unit dskMetricsConsts;
interface
uses
Windows;
const
{ DeskMetrics Server / HTTP Consts }
USERAGENT = 'DeskMetricsDLL';
DEFAULTSERVER = '.api.deskmetrics.com';
DEFAULTPORT = 443; {https}
DEFAULTPROXYPORT = 8080;
DEFAULTTIMEOUT = 8000; {8 seconds}
{ DeskMetrics Data }
MAXSTORAGEDATA = 51200; {50 KB}
MAXDAILYNETWORK = -1; {Unlimited}
{ DeskMetrics Strings Consts }
NULL_STR = 'null';
NONE_STR = 'none';
UNKNOWN_STR = 'Unknown';
ERROR_STR = 'Error';
{ DeskMetrics Registry Consts }
REGROOTKEY = DWORD($80000001); {HKEY_CURRENT_USER}
REGPATH = '\SOFTWARE\dskMetrics\';
{ DeskMetrics Test / Debug Consts }
LOGFILENAME = 'dskMetrics.log';
{ DeskMetrics - WebService API Calls }
API_SENDDATA = '/sendData';
{ DeskMetrics Wininet Consts }
READBUFFERSIZE = 4096;
WINETDLL = 'WININET.DLL';
INTERNET_PER_CONN_FLAGS = 1;
INTERNET_PER_CONN_PROXY_SERVER = 2;
INTERNET_PER_CONN_PROXY_BYPASS = 3;
INTERNET_PER_CONN_AUTOCONFIG_URL = 4;
INTERNET_PER_CONN_AUTODISCOVERY_FLAGS = 5;
PROXY_TYPE_DIRECT = $00000001; // direct to net
PROXY_TYPE_PROXY = $00000002; // via named proxy
INTERNET_OPTION_PER_CONNECTION_OPTION = 75;
{ DeskMetrics Wininet Types }
type
INTERNET_PER_CONN_OPTION = record
dwOption: DWORD;
Value: record
case Integer of
1: (dwValue: DWORD);
2: (pszValue: PAnsiChar);
3: (ftValue: TFileTime);
end;
end;
LPINTERNET_PER_CONN_OPTION = ^INTERNET_PER_CONN_OPTION;
INTERNET_PER_CONN_OPTION_LIST = record
dwSize: DWORD;
pszConnection: LPTSTR;
dwOptionCount: DWORD;
dwOptionError: DWORD;
pOptions: LPINTERNET_PER_CONN_OPTION;
end;
LPINTERNET_PER_CONN_OPTION_LIST = ^INTERNET_PER_CONN_OPTION_LIST;
implementation
end.
|
unit uWfxPluginListOperation;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
uFileSourceListOperation,
uWfxPluginFileSource,
uFileSource;
type
{ TWfxPluginListOperation }
TWfxPluginListOperation = class(TFileSourceListOperation)
private
FWfxPluginFileSource: IWfxPluginFileSource;
FCallbackDataClass: TCallbackDataClass;
FCurrentPath: String;
protected
function UpdateProgress(SourceName, TargetName: PAnsiChar; PercentDone: Integer): Integer;
public
constructor Create(aFileSource: IFileSource; aPath: String); override;
destructor Destroy; override;
procedure Initialize; override;
procedure MainExecute; override;
procedure Finalize; override;
end;
implementation
uses
DCFileAttributes, DCStrUtils, uFile, uFileSourceOperation, WfxPlugin,
uWfxModule, uLog, uLng;
function TWfxPluginListOperation.UpdateProgress(SourceName, TargetName: PAnsiChar;
PercentDone: Integer): Integer;
begin
if State = fsosStopping then // Cancel operation
Exit(1);
logWrite(rsMsgLoadingFileList + IntToStr(PercentDone) + '%', lmtInfo, False, False);
if CheckOperationStateSafe then
Result := 0
else begin
Result := 1;
end;
end;
constructor TWfxPluginListOperation.Create(aFileSource: IFileSource; aPath: String);
begin
FFiles := TFiles.Create(aPath);
FWfxPluginFileSource := aFileSource as IWfxPluginFileSource;
with FWfxPluginFileSource do
FCallbackDataClass:= TCallbackDataClass(WfxOperationList.Objects[PluginNumber]);
FCurrentPath:= ExcludeBackPathDelimiter(aPath);
inherited Create(aFileSource, aPath);
end;
destructor TWfxPluginListOperation.Destroy;
begin
inherited Destroy;
end;
procedure TWfxPluginListOperation.Initialize;
begin
with FWfxPluginFileSource do
begin
WfxModule.WfxStatusInfo(FCurrentPath, FS_STATUS_START, FS_STATUS_OP_LIST);
FCallbackDataClass.UpdateProgressFunction:= @UpdateProgress;
UpdateProgressFunction:= @UpdateProgress;
end;
end;
procedure TWfxPluginListOperation.MainExecute;
var
aFile: TFile;
Handle: THandle;
FindData : TWfxFindData;
HaveUpDir: Boolean = False;
begin
with FWfxPluginFileSource.WFXModule do
try
FFiles.Clear;
Handle := WfxFindFirst(FCurrentPath, FindData);
if Handle <> wfxInvalidHandle then
try
repeat
CheckOperationState;
if (FindData.FileName = '.') then Continue;
if (FindData.FileName = '..') then HaveUpDir:= True;
aFile := TWfxPluginFileSource.CreateFile(Path, FindData);
FFiles.Add(aFile);
until (not WfxFindNext(Handle, FindData));
finally
FsFindClose(Handle);
end;
finally
if not HaveUpDir then
begin
aFile := TWfxPluginFileSource.CreateFile(Path);
aFile.Name := '..';
aFile.Attributes := GENERIC_ATTRIBUTE_FOLDER;
FFiles.Insert(aFile, 0);
end;
end; // with
end;
procedure TWfxPluginListOperation.Finalize;
begin
with FWfxPluginFileSource do
begin
WfxModule.WfxStatusInfo(FCurrentPath, FS_STATUS_END, FS_STATUS_OP_LIST);
FCallbackDataClass.UpdateProgressFunction:= nil;
UpdateProgressFunction:= nil;
end;
end;
end.
|
program Prog1;
type matrix = array [1..40, 1..40] of integer;
var
m, n, i, j, maxi, maxj, maxij: Integer;
mat: matrix;
begin
{ Вводим данные }
write('Enter m: ');
readln(m);
write('Enter n: ');
readln(n);
writeln('Enter matrix');
for i := 1 to m do
for j := 1 to n do
read(mat[i,j]);
writeln;
maxi := 1;
maxj := 1;
maxij := mat[1,1]; { Вначале считаем наибольшим элемент [1,1] }
for i := 1 to m do
for j := 1 to n do begin { Проходим матрицу }
if mat[i,j] > maxij then begin
{ Если текущий элемент больше maxij -- запоминаем его координаты и значение }
maxij := mat[i,j];
maxi := i;
maxj := j;
end;
end;
{ Выводим результат }
writeln('Max element in [', maxi, ', ', maxj, '] ');
end.
|
{******************************************}
{ }
{ vtk GridReport library }
{ }
{ Copyright (c) 2003 by vtkTools }
{ }
{******************************************}
{Common functions, types, constants and variables definitions unit.
See also:
vgr_GUIFunctions}
unit vgr_Functions;
interface
{$I vtk.inc}
uses
Windows, Classes, SysUtils, TypInfo, {$IFDEF VTK_D6_OR_D7} Variants, {$ENDIF}
Clipbrd, Math, Graphics;
{$IFNDEF VTK_D7}
const
{number of hours in one day}
HoursPerDay = 24;
{number of minutes in one hour}
MinsPerHour = 60;
{number of seconds in one minute}
SecsPerMin = 60;
{number of milliseconds in one second}
MSecsPerSec = 1000;
{number of minutes in one day}
MinsPerDay = HoursPerDay * MinsPerHour;
{number of seconds in one day}
SecsPerDay = MinsPerDay * SecsPerMin;
{number of milliseconds in one day}
MSecsPerDay = SecsPerDay * MSecsPerSec;
{$ENDIF}
type
{$IFNDEF VTK_D6_OR_D7}
IInterface = interface(IUnknown)
end;
{$ENDIF}
{Array of TRect
Syntax:
TRectArray = array [0..0] of TRect;}
TRectArray = array [0..MaxInt div sizeof(TRect) div 2] of TRect;
{Pointer to a TRectArray array
Syntax:
PRectArray = ^TRectArray;}
PRectArray = ^TRectArray;
{Array of integer
Syntax:
TIntArray = array [0..0] of Integer;}
TIntArray = array [0..MaxInt div sizeof(Integer) div 2] of Integer;
{Pointer to a TIntArray array
Syntax:
PIntArray = ^TIntArray;}
PIntArray = ^TIntArray;
{Array of integer
Syntax:
TDynIntegerArray = array of Integer;}
TDynIntegerArray = array of Integer;
{Array of string
Syntax:
TvgrStringArray = array of string;}
TvgrStringArray = array of string;
{Represent position of border side
Syntax:
TvgrBorderSide = (vgrbsLeft, vgrbsTop, vgrbsRight, vgrbsBottom);
Items:
vgrbsLeft - Left
vgrbsTop - Top
vgrbsRight - Right
vgrbsBottom - Bottom
}
TvgrBorderSide = (vgrbsLeft, vgrbsTop, vgrbsRight, vgrbsBottom);
{ Represent units that measure size.
Syntax:
TvgrUnits = (vgruMms, vgruCentimeters, vgruInches, vgruTenthsMMs, vgruPixels);
Items:
vgruMms - millimeters
vgruCentimeters - centimeters
vgruInches - Inches
vgruTenthsMMs - 1/10 of millimeter
vgruPixels - device pixels }
TvgrUnits = (vgruMms, vgruCentimeters, vgruInches, vgruTenthsMMs, vgruPixels);
{Record containing information on lines with text
Syntax:
TvgrTextLineInfo = record
Start: Integer;
Length: Integer;
FullLength: Integer;
TextLength: Integer;
end;
}
TvgrTextLineInfo = record
Start: Integer;
Length: Integer;
FullLength: Integer;
TextLength: Integer;
CrLf: Boolean;
end;
/////////////////////////////////////////////////
//
// Functions
//
/////////////////////////////////////////////////
{$IFNDEF VTK_D6_OR_D7}
function IsZero(const A: Extended; Epsilon: Extended = 0): Boolean; overload;
function IsZero(const A: Double; Epsilon: Double = 0): Boolean; overload;
function IsZero(const A: Single; Epsilon: Single = 0): Boolean; overload;
{ DirectoryExists returns a boolean value that indicates whether the
specified directory exists (and is actually a directory)
Parameters:
Directory - string with path to directory.
Return value:
Boolean, true - if directory exists, false - if directory not exists}
function DirectoryExists(const Directory: string): Boolean;
{ Interface support routines }
function Supports(const Instance: IInterface; const IID: TGUID; out Intf): Boolean; overload;
function SupportsObject(const Instance: TObject; const IID: TGUID; out Intf): Boolean; overload;
function Supports(const Instance: IInterface; const IID: TGUID): Boolean; overload;
function Supports(const Instance: TObject; const IID: TGUID): Boolean; overload;
function Supports(const AClass: TClass; const IID: TGUID): Boolean; overload;
{$ENDIF}
{$IFNDEF VTK_D7}
function TryEncodeDate(Year, Month, Day: Word; out Date: TDateTime): Boolean;
function TryEncodeTime(Hour, Min, Sec, MSec: Word; out Time: TDateTime): Boolean;
function TryStrToTime(const S: string; out Value: TDateTime): Boolean;
function TryStrToDateTime(const S: string; out Value: TDateTime): Boolean;
function StrToDateTimeDef(const S: string; ADefDateTime: TDateTime): TDateTime;
{$ENDIF}
{ Returns caption of worksheet column by it number.
For example ColNumber = 27, Result = 'AB'
Parameters:
ColNumber - integer, number of column (from zero).
Return value:
String with caption of worksheet column.}
function GetWorksheetColCaption(ColNumber: integer): string;
{ Returns caption of worksheet row by it number.
For example RowNumber = 27, Result = '28'
Parameters:
RowNumber - number of row (from zero)
Return value:
String with caption of worksheet row.}
function GetWorksheetRowCaption(RowNumber: integer): string;
{ Creates a TSize structure from a sizes.
Parameters:
cx is the width
cy is the height
Return value:
Returns TSize structure which represents a width and height.
}
function Size(cx, cy: Integer): TSize;
{ This function determines whether ASmallRect placed within ALargeRect.
Parameters:
ASmallRect - TRect object
ALargeRect - TRect object
Return value:
Boolean, True - if ASmallRect placed within ALargeRect, False - if ASmallRect not placed within ALargeRect.
}
function RectInRect(const ASmallRect, ALargeRect: TRect): Boolean;
{ This function determines whether ASmallRect placed within ALargeRect.
Parameters:
ASmallRect - TRect object
ALargeRect - TRect object
Return value:
Boolean, True - if ASmallRect placed within ALargeRect, False - if ASmallRect not placed within ALargeRect.
}
function RectInSelRect(const ASmallRect, ALargeRect: TRect): Boolean;
{ Returns true if APoint placed within ARect, also this function returns
true if APoint placed on bounds of ARect.
Parameters:
APoint - TPoint object
ARect - TRect object
Return value:
Boolean.}
function PointInSelRect(const APoint: TPoint; ARect: TRect): Boolean;
{ The RectOverRect function determines whether any part of the
specified rectangle (r1) is within the boundaries of a over rectangle (r2).
Parameters:
r1 - TRect object
r2 - TRect object
Return value:
Boolean. True - if any part of the
specified rectangle (r1) is within the boundaries of a over rectangle (r2). False - if not.}
function RectOverRect(const r1: TRect; const r2: TRect): boolean;
{ This function normalizes a TRect structure so both the height and width are positive.
The method does a comparison of the top and bottom values,
swapping them if the bottom is greater than the top.
The same action is performed on the left and right values.
Parameters:
r - TRect object.
Return value:
Normalized TRect object.
}
function NormalizeRect(const r: TRect): TRect; overload;
{ This function creates a normalizated TRect structure so both the height and width
are positive.
The method does a comparison of the y1 (top) and y2 (bottom) values,
swapping them if the bottom is greater than the top.
The same action is performed on the (x1)left and (x2)right values.
Parameters:
x1 - left value.
y1 - top value.
x2 - right value.
y2 - bottom value.
Return value:
Normalized TRect object.}
function NormalizeRect(x1,y1,x2,y2: Integer): TRect; overload;
{ Returns horizontal center of the rect.
Result := ARect.Left + (ARect.Right - ARect.Left) div 2
Parameters:
ARect - TRect object
Return value:
Value of horizontal center of the rect}
function HorzCenterOfRect(const ARect: TRect): Integer;
{ Converts a string of hexadecimal digits to the corresponding binary value.
Parameters:
S - string of hexadecimal digits
AResult - integer in which is written resulting binary value.
Return value:
Boolean, return True if convert OK, otherwise return False.}
function HexToInt(const S: string; var AResult: Integer): Boolean;
{ Converts a string of hexadecimal digits to the corresponding binary value.
Parameters:
S - string of hexadecimal digits
ADefault - if S contains invalid string, ADefault returns.
Return value:
Integer with binary value.
}
function HexToIntDef(const S: string; ADefault: Integer = 0): Integer;
{ Returns names of enum items to TStrings object. }
procedure GetEnumNamesToStrings(ATypeInfo: PTypeInfo; AStrings: TStrings; ADeleteFirstCharCount: Integer = 0);
{ Call GetUniqueComponentName to get the unique name of the component within its owner.
Parameters:
AComponent - TComponent instance
Return value:
String with unique name of the component within its owner}
function GetUniqueComponentName(AComponent: TComponent): string;
{ Returns True if ANewName is a valid name for component AComponent.
ANewName not equals empty string and AComponent.Owner = nil or owner of AComponent
not contains child component with name ANewName.
Parameters:
AComponent - TComponent, component instance
ANewName - String, name for component AComponent
Return value:
Boolean value
}
function CheckComponentName(AComponent: TComponent; const ANewName: string): Boolean;
{ Format AValue based on its type. If AValue is a numeric value then FormatFloat function used.
If AValue is a TDateTime value then FormatDateTime function used.
If AValue is a string value returns AValue converted to string (VarToStr function used).
Parameters:
AFormat - string with specified format.
AValue - variant value to format.
Return value:
Formated string.
}
function FormatVariant(const AFormat: string; const AValue: Variant): string;
function PosToRowAndCol(AStrings: TStrings; APos: Integer; var ARow, ACol: Integer; AStringDelimiters: TSysCharSet): Boolean; overload;
function PosToRowAndCol(AStrings: TStrings; APos: Integer; var ARow, ACol: Integer): Boolean; overload;
procedure BeginEnumLines(const S: string; var ALineInfo: TvgrTextLineInfo);
function EnumLines(const S: string; var ALineInfo: TvgrTextLineInfo): Boolean;
procedure FindEndOfLineBreak(const S: string; ALen: Integer; var I: Integer);
{ Call IndexOf to obtain the position of the first occurrence of the string S.
This function is not case sensitive.
IndexOf returns the 0-based index of the string.
Parameters:
S - string for search
AList - list of strings
Return value:
Integer. If S matches the first string in the list, IndexOf returns 0,
if S is the second string, IndexOf returns 1, and so on.
If the string is not in the string list, IndexOf returns -1. }
function IndexInStrings(const S: string; AList: TStrings): Integer;
{ This procedure call destructor for all objects in then AList.
List AList must contains objects, all of its values should be not equal nil.
Parameters:
AList - TList, list of objects.}
procedure FreeListItems(AList: TList);
{$IFDEF VTK_D4}
procedure FreeAndNil(var AObject);
{$ENDIF}
{ This procedure call destructor for all objects in then AList.
List AList must contains objects, all of its values should be not equal nil.
Also this procedure free AList object.
Parameters:
AList - list of objects.}
procedure FreeList(var AList: TList);
{ Copying contents of AStream object to clipboard.
All contents of AStream are copied, irrespective of its property Position.
Parameters:
AClipboardFormat - Word number which represents clipboard format
AStream - TMemoryStream object
}
procedure StreamToClipboard(AClipboardFormat: Word; AStream: TMemoryStream);
{ Copying contents of clipboard to a AStream object.
Previos contents of AStream are discarded.
Parameters:
AClipboardFormat - Word number which represents clipboard format
AStream - TMemoryStream object}
procedure StreamFromClipboard(AClipboardFormat: Word; AStream: TMemoryStream);
function GetBorderPartSize(ASize: Integer; ASide: TvgrBorderSide): Integer;
{ Use this method to convert a value in twips to a value in pixels, based on value of ScreenPixelsPerInchX variable.
Parameters:
Twips - Number of twips
Return value:
Number of pixels}
function ConvertTwipsToPixelsX(Twips: integer): integer; overload;
{ Use this method to convert a value in twips to a value in pixels, based on value of ScreenPixelsPerInchY variable.
Parameters:
Twips - Number of twips
Return value:
Number of pixels}
function ConvertTwipsToPixelsY(Twips: integer): integer; overload;
{ Use this method to convert a value in twips to a value in pixels, based on value of PixelsPerX parameter.
Parameters:
Twips - Number of twips
PixelsPerX - indicates the number of device pixels that make up a logical inch in the horizontal direction.
Return value:
Number of pixels}
function ConvertTwipsToPixelsX(Twips: integer; PixelsPerX: Integer): integer; overload;
{Use this method to convert a value in twips to a value in pixels, based on value of PixelsPerY parameter.
Parameters:
Twips - Number of twips
PixelsPerY - parameter indicates the number of device pixels that make up a logical inch in the vertical direction.
Return value:
Number of pixels
}
function ConvertTwipsToPixelsY(Twips: integer; PixelsPerY: Integer): integer; overload;
{ Use this method to convert a value in pixels to a value in twips, based on value of ScreenPixelsPerInchX variable.
Parameters:
Integer, number of pixels
Return value:
Integer, number of twips
}
function ConvertPixelsToTwipsX(Pixels: integer): integer; overload;
{ Use this method to convert a value in pixels to a value in twips, based on value of ScreenPixelsPerInchY variable.
Parameters:
Integer, number of pixels
Return value:
Integer, number of twips
}
function ConvertPixelsToTwipsY(Pixels: integer): integer; overload;
{ Use this method to convert a value in pixels to a value in twips, based on value of PixelsPerX parameter.
Parameters:
Pixels - number of pixels
PixelsPerX - parameter indicates the number of device pixels that make up a logical inch in the horizontal direction.
Return value:
Integer, number of twips}
function ConvertPixelsToTwipsX(Pixels: integer; PixelsPerX: Integer): integer; overload;
{ Use this method to convert a value in pixels to a value in twips, based on value of PixelsPerY parameter.
Parameters:
Pixels - number of pixels
PixelsPerY - indicates the number of device pixels that make up a logical inch in the vertical direction.
Return value:
Integer, number of twips.
}
function ConvertPixelsToTwipsY(Pixels: integer; PixelsPerY: Integer): integer; overload;
{ Use this method to convert a value in units which specified a AUnits parameter to a value in twips.
Parameters:
AValue - Extended, value in units.
AUnits - TvgrUnits, type of units. If AUnits equals to vgruPixels,
ScreenPixelsPerInchY variable used in coversion.
Return value:
Integer, number of twips}
function ConvertUnitsToTwips(AValue: Extended; AUnits: TvgrUnits): Integer;
{ Use this method to covert a value in twips to a value in units which specified a AUnits parameter.
Parameters:
ATwips - Integer, number of twips.
AUnits - TvgrUnits, type of units. If AUnits equals to vgruPixels,
ScreenPixelsPerInchY variable used in coversion.
Return value:
Extended, value in units}
function ConvertTwipsToUnits(ATwips: Integer; AUnits: TvgrUnits): Extended;
{ Use this method to convert a value in twips to a value in units which specified a AUnits parameter.
Resulting value are formatted to string.
Parameters:
ATwips - Integer, number of twips.
AUnits - TvgrUnits, type of units. If AUnits equals to vgruPixels,
ScreenPixelsPerInchY variable used in coversion.
Return value:
String, value in units.
}
function ConvertTwipsToUnitsStr(ATwips: Integer; AUnits: TvgrUnits): string;
{ Returns True if a passed string is the list of pages, for example:
'1,3,6,10-13'.
Parameters:
S - String for checking
Return value:
Boolean
}
function CheckPageList(const S: string): Boolean;
{ This function are parsing string and form a list of numbers in this string.
Example:
S = '1,3,6,10-13'
APagesList contains these items: 1,3,6,10,11,12,13.
Parameters:
S - String for parsing
APagesList - TList containing resulting numbers
Return value:
Boolean. Returns True if successful.}
function TextToPageList(const S: string; APagesList: TList): Boolean;
{ Function GetCurrencyFormat returns the format string used to convert a numeric value to a string for display a currency value.
This string can be passed as format to a FormatFloat function.
Return value:
String with format.}
function GetCurrencyFormat: string;
{ Returns a path name with a trailing delimiter. If APathName not contains a backslahs at end,
the return value is APathName with the added backslahs symbol at end.
Parameters:
APathName - string with path name
Return value:
Path name with a trailing delimiter
}
function AddFlash(const APathName: string): string;
{ Search file with specified name and return its full name.<br>
The search goes in the following order:
<li>1. In program directory</li>
<li>2. In windows system directory</li>
<li>3. In windows directory</li><br>
If file not exists in previous paths return file in program directory. }
function GetFindFileName(const AFileName: string): string;
{ Returns full file name relative to specified directory.
Example:
AFileName = 'c:\temp\temp1\temp.tmp'
ADirectory = 'c:\temp'
Result = temp1\temp.tmp
AFileName = 'c:\temp\temp1\temp.tmp'
ADirectory = 'c:\temp\temp2'
Result = '..\temp1\temp.tmp'
Parameters:
AFileName - string with full path to file
ADirectory - string with full path to directory
Return value:
String, full file name relative to specified directory}
function GetRelativePathToFile(const AFileName: string; const ADirectory: string): string;
{ Write a string to specified stream at current position, in this format:
first four bytes - length of string
next chars - contents of the string without last zero character.
Parameters:
AStream - TStream object
S - string value for writing}
procedure WriteString(AStream: TStream; const S: string);
{ Write a string to specified stream at current position,
also this function add an end-of-line marker (line feed or carriage return/line feed) to the stream.
Parameters:
AStream - TStream object
S - string value for writing
}
procedure WriteLnString(AStream: TStream; const S: string);
{ Writes the Boolean value passed in Value to the current position of the stream.
Parameters:
AStream - TStream object
Value - boolean value for writing
}
procedure WriteBoolean(AStream: TStream; Value: Boolean);
{ Reads a string value written by WriteString from the stream and returns its contents.
Parameters:
AStream - TStream object
Return value:
String value written by WriteString.}
function ReadString(AStream: TStream): string;
{ Reads a boolean from the stream and returns that boolean value.
Parameters:
AStream - TStream object
Return value:
Boolean.}
function ReadBoolean(AStream: TStream): Boolean;
{ Obtains the name of a character set.
Call vgrCharsetToIdent to obtain the symbolic name for the character set of a font.
Parameters:
ACharset - TFontCharset
Return value:
String with symbolic name for the character set of a font.
}
function vgrCharsetToIdent(ACharset: TFontCharset): string;
{ Translates the name of a character set constant to the corresponding character set.
Parameters:
AIdent - string with name of a character set
Return value:
TFontCharset}
function vgrIdentToCharset(const AIdent: string): TFontCharset;
{ Extract new line from string from position [P]. Lines are delimited by #13#10 chars.
Parameters:
S - string from which is extracted new line
P - position of the initial symbol in string S
Return value:
String with new line}
function ExtractLine(const S: string; var P: Integer): string;
{ ExtractSubStr given a set of word delimiters, return the substring from S,
that started from position Pos.
Parameters:
S - string for processing
Pos - integer witch indicates started position
Delims - TSysCharSet, set of word delimiters.
Return value:
String
}
function ExtractSubStr(const S: string; var Pos: Integer; const Delims: TSysCharSet): string;
{Rounds a number to a specified number of digits.
Parameters:
AValue - Is the number you want to round.
ANumDigits - Specifies the number of digits to which you want to round number.}
function RoundEx(AValue: Extended; ANumDigits: Integer): Extended;
procedure JustifyArray(a: PIntArray;
aLen, NeededSize, RealSize: Integer; AUseSpaces: Boolean; S: PChar);
/////////////////////////////////////////////////
//
// DEBUG Functions
//
/////////////////////////////////////////////////
procedure DbgFileWriteString(const AFileName: string; const S: string); overload;
procedure DbgFileWriteString(const S: string); overload;
procedure DbgFileRect(const ADescRect: string; const ARect: TRect);
procedure DbgFileStr(const s: string);
procedure DbgFileStrFmt(const AMask: string; AParams: array of const);
procedure DbgRect(const ADescRect: string; const ARect: TRect);
procedure DbgStr(const s: string);
procedure DbgStrFmt(const AMask: string; AParams: array of const);
var
{ ScreenPixelsPerInchX global variable indicates the number of device pixels
that make up a logical inch in the horizontal direction. }
ScreenPixelsPerInchX: Integer;
{ ScreenPixelsPerInchY global variable indicates the number of device pixels
that make up a logical inch in the vertical direction. }
ScreenPixelsPerInchY: Integer;
DbgFileFileName: string = 'c:\CommonControlsDbgFile.txt';
implementation
uses
vgr_Consts;
const
{$IFNDEF VTK_D6_OR_D7}
FuzzFactor = 1000;
ExtendedResolution = 1E-19 * FuzzFactor;
DoubleResolution = 1E-15 * FuzzFactor;
SingleResolution = 1E-7 * FuzzFactor;
{$ENDIF}
RoundArray: array [1..5] of integer =(10, 100, 1000, 10000, 100000);
/////////////////////////////////////////////////
//
// Functions
//
/////////////////////////////////////////////////
procedure JustifyArray(a: PIntArray; aLen, NeededSize, RealSize: Integer; AUseSpaces: Boolean; S: PChar);
var
i,n,step,Delta,DeltaAbs, ASpacesCount : integer;
begin
if aLen = 0 then exit;
Delta := NeededSize - RealSize;
if AUseSpaces and (Delta > 0) then
begin
ASpacesCount := 0;
for I := 1 to Length(S) do
if S[I] = ' ' then
Inc(ASpacesCount);
if ASpacesCount = 0 then
exit;
if Delta >= ASpacesCount then
begin
N := Delta div ASpacesCount;
for I := 0 to aLen - 1 do
if S[I] = ' ' then
begin
Inc(a^[i], N);
Dec(Delta, N);
end;
end;
if Delta <> 0 then
begin
I := 0;
while (I < aLen) and (Delta > 0) do
begin
if S[I] = ' ' then
begin
Inc(a^[I], 1);
Dec(Delta);
end;
Inc(I);
end;
end;
end
else
begin
DeltaAbs := Abs(Delta);
if DeltaAbs >= aLen then
begin
n := Delta div aLen;
for I := 0 to aLen - 1 do
begin
Inc(a^[i], n);
Dec(Delta, n);
end;
DeltaAbs := Abs(Delta);
end;
if Delta <> 0 then
begin
if Delta > 0 then step := 1
else step := -1;
N := aLen div DeltaAbs;
I := 0;
while (I < aLen) and (DeltaAbs > 0) do
begin
Inc(a^[I], step);
Inc(I, N);
Dec(DeltaAbs);
end;
if DeltaAbs > 0 then
Inc(a^[aLen div 2], step);
end;
end;
end;
function RoundEx(AValue: Extended; ANumDigits: Integer): Extended;
var
AKoef, ADelta: Extended;
begin
if ANumDigits = 0 then
Result := Round(AValue)
else
begin
if Abs(ANumDigits) > 5 then
AKoef := Power(10, Abs(ANumDigits))
else
AKoef := RoundArray[Abs(ANumDigits)];
if AValue < 0 then
ADelta := -0.5
else
ADelta := 0.5;
if ANumDigits > 0 then
Result := Int(AValue * AKoef + ADelta) / AKoef
else
Result := Int(AValue / AKoef + ADelta) * AKoef;
end;
end;
function HexToIntDef(const S: string; ADefault: Integer = 0): Integer;
begin
if not HexToInt(S, Result) then
Result := ADefault;
end;
function HexToInt(const S: string; var AResult: Integer): Boolean;
var
I, AShift: Integer;
begin
Result := Length(S) <= 8;
if Result then
begin
AShift := 0;
AResult := 0;
for I := Length(S) downto 1 do
begin
case S[I] of
'0'..'9': AResult := AResult + ((Byte(S[i]) - Byte('0')) shl AShift);
'a'..'f': AResult := Aresult + ((Byte(S[i]) - Byte('a') + 10) shl AShift);
'A'..'F': AResult := Aresult + ((Byte(S[i]) - Byte('A') + 10) shl AShift);
else
begin
Result := False;
exit;
end;
end;
AShift := AShift + 4;
end;
end;
end;
function ExtractLine(const S: string; var P: Integer): string;
var
I, J, ALen: Integer;
begin
ALen := Length(S);
I := P;
while (P <= ALen) and not (S[P] in [#10, #13]) do Inc(P);
J := P;
if P <= ALen then
begin
if (P < ALen) and (((S[P] = #10) and (S[P + 1] = #13)) or
((S[P] = #13) and (S[P + 1] = #10))) then
Inc(P);
Inc(P);
end;
Result := Copy(S, I, J - I);
end;
function ExtractSubStr(const S: string; var Pos: Integer;
const Delims: TSysCharSet): string;
var
I: Integer;
begin
I := Pos;
while (I <= Length(S)) and not (S[I] in Delims) do Inc(I);
Result := Copy(S, Pos, I - Pos);
if (I <= Length(S)) and (S[I] in Delims) then Inc(I);
Pos := I;
end;
function vgrCharsetToIdent(ACharset: TFontCharset): string;
var
S: string;
begin
CharsetToIdent(ACharset, S);
if S = '' then
Result := IntToStr(ACharset)
else
Result := S;
end;
function vgrIdentToCharset(const AIdent: string): TFontCharset;
var
ACharset: Integer;
begin
if not IdentToCharset(AIdent, ACharset) then
Result := StrToIntDef(AIdent, DEFAULT_CHARSET)
else
Result := ACharset;
end;
procedure WriteString(AStream: TStream; const S: string);
var
N: Integer;
begin
N := Length(S);
AStream.Write(N, 4);
AStream.WriteBuffer(S[1], N);
end;
procedure WriteLnString(AStream: TStream; const S: string);
var
ABuf: string;
begin
ABuf := S + #13#10;
AStream.Write(ABuf[1], Length(ABuf));
end;
procedure WriteBoolean(AStream: TStream; Value: Boolean);
begin
AStream.Write(Value, 1);
end;
function ReadString(AStream: TStream): string;
var
N: Integer;
begin
AStream.Read(N, 4);
SetLength(Result, N);
AStream.Read(Result[1], N);
end;
function ReadBoolean(AStream: TStream): Boolean;
begin
AStream.Read(Result, 1);
end;
function GetFindFileName(const AFileName: string): string;
var
Buf: array [0..255] of char;
begin
Result := AddFlash(ExtractFilePath(ParamStr(0))) + AFileName;
if not FileExists(Result) then
begin
{find in System dir}
GetSystemDirectory(Buf, 255);
Result := AddFlash(StrPas(Buf)) + AFileName;
if not FileExists(Result) then
begin
{find in Windows dir}
GetWindowsDirectory(Buf, 255);
Result := AddFlash(StrPas(Buf)) + AFileName;
if not FileExists(Result) then
Result := AddFlash(ExtractFilePath(ParamStr(0))) + AFileName;
end;
end;
end;
function GetRelativePathToFile(const AFileName: string; const ADirectory: string): string;
var
ADir, AFilePath: string;
I, J, AFileNameLen, ADirLen: Integer;
begin
ADir := AddFlash(ADirectory);
AFileNameLen := Length(AFileName);
AFilePath := ExtractFilePath(AFileName);
ADirLen := Length(ADir);
I := 0;
while (I < AFileNameLen) and (I < ADirLen) and
(AnsiCompareText(Copy(AFileName, 1, I + 1), Copy(ADir, 1, I + 1)) = 0) do Inc(I);
if I = 0 then
Result := AFileName
else
begin
Result := '';
J := ADirLen;
while J > I do
begin
if ADir[J] = '\' then
Result := Result + '..\';
Dec(J);
end;
Result := Result + Copy(AFileName, I + 1, AFileNameLen);
end;
end;
function AddFlash(const APathName: string): string;
begin
Result := APathName;
if Result[Length(Result)] <> '\' then
Result := Result + '\';
end;
function GetCurrencyFormat: string;
var
CurrStr: string;
I: Integer;
C: Char;
begin
if CurrencyDecimals > 0 then
begin
SetLength(Result, CurrencyDecimals);
FillChar(Result[1], Length(Result), '0');
end
else
Result := '';
Result := ',0.' + Result;
CurrStr := '';
for I := 1 to Length(CurrencyString) do
begin
C := CurrencyString[I];
if C in [',', '.'] then
CurrStr := CurrStr + '''' + C + ''''
else
CurrStr := CurrStr + C;
end;
if Length(CurrStr) > 0 then
case Sysutils.CurrencyFormat of
0: Result := CurrStr + Result; { '$1' }
1: Result := Result + CurrStr; { '1$' }
2: Result := CurrStr + ' ' + Result; { '$ 1' }
3: Result := Result + ' ' + CurrStr; { '1 $' }
end;
Result := Format('%s;-%s', [Result, Result]);
end;
{$IFNDEF VTK_D7}
function TryEncodeDate(Year, Month, Day: Word; out Date: TDateTime): Boolean;
var
I: Integer;
DayTable: PDayTable;
begin
Result := False;
DayTable := @MonthDays[IsLeapYear(Year)];
if (Year >= 1) and (Year <= 9999) and (Month >= 1) and (Month <= 12) and
(Day >= 1) and (Day <= DayTable^[Month]) then
begin
for I := 1 to Month - 1 do Inc(Day, DayTable^[I]);
I := Year - 1;
Date := I * 365 + I div 4 - I div 100 + I div 400 + Day - DateDelta;
Result := True;
end;
end;
type
TDateOrder = (doMDY, doDMY, doYMD);
function GetDateOrder(const DateFormat: string): TDateOrder;
var
I: Integer;
begin
Result := doMDY;
I := 1;
while I <= Length(DateFormat) do
begin
case Chr(Ord(DateFormat[I]) and $DF) of
'E': Result := doYMD;
'Y': Result := doYMD;
'M': Result := doMDY;
'D': Result := doDMY;
else
Inc(I);
Continue;
end;
Exit;
end;
Result := doMDY;
end;
function StrCharLength(const Str: PChar): Integer;
begin
if SysLocale.FarEast then
Result := Integer(CharNext(Str)) - Integer(Str)
else
Result := 1;
end;
function NextCharIndex(const S: string; Index: Integer): Integer;
begin
Result := Index + 1;
assert((Index > 0) and (Index <= Length(S)));
if SysLocale.FarEast and (S[Index] in LeadBytes) then
Result := Index + StrCharLength(PChar(S) + Index - 1);
end;
procedure ScanBlanks(const S: string; var Pos: Integer);
var
I: Integer;
begin
I := Pos;
while (I <= Length(S)) and (S[I] = ' ') do Inc(I);
Pos := I;
end;
function ScanChar(const S: string; var Pos: Integer; Ch: Char): Boolean;
begin
Result := False;
ScanBlanks(S, Pos);
if (Pos <= Length(S)) and (S[Pos] = Ch) then
begin
Inc(Pos);
Result := True;
end;
end;
function ScanNumber(const S: string; var Pos: Integer;
var Number: Word; var CharCount: Byte): Boolean;
var
I: Integer;
N: Word;
begin
Result := False;
CharCount := 0;
ScanBlanks(S, Pos);
I := Pos;
N := 0;
while (I <= Length(S)) and (S[I] in ['0'..'9']) and (N < 1000) do
begin
N := N * 10 + (Ord(S[I]) - Ord('0'));
Inc(I);
end;
if I > Pos then
begin
CharCount := I - Pos;
Pos := I;
Number := N;
Result := True;
end;
end;
procedure ScanToNumber(const S: string; var Pos: Integer);
begin
while (Pos <= Length(S)) and not (S[Pos] in ['0'..'9']) do
begin
if S[Pos] in LeadBytes then
Pos := NextCharIndex(S, Pos)
else
Inc(Pos);
end;
end;
function GetEraYearOffset(const Name: string): Integer;
var
I: Integer;
begin
Result := 0;
for I := Low(EraNames) to High(EraNames) do
begin
if EraNames[I] = '' then Break;
if AnsiStrPos(PChar(EraNames[I]), PChar(Name)) <> nil then
begin
Result := EraYearOffsets[I];
Exit;
end;
end;
end;
function CurrentYear: Word;
var
SystemTime: TSystemTime;
begin
GetLocalTime(SystemTime);
Result := SystemTime.wYear;
end;
function ScanDate(const S: string; var Pos: Integer;
var Date: TDateTime): Boolean; overload;
var
DateOrder: TDateOrder;
N1, N2, N3, Y, M, D: Word;
L1, L2, L3, YearLen: Byte;
CenturyBase: Integer;
EraName : string;
EraYearOffset: Integer;
function EraToYear(Year: Integer): Integer;
begin
if SysLocale.PriLangID = LANG_KOREAN then
begin
if Year <= 99 then
Inc(Year, (CurrentYear + Abs(EraYearOffset)) div 100 * 100);
if EraYearOffset > 0 then
EraYearOffset := -EraYearOffset;
end
else
Dec(EraYearOffset);
Result := Year + EraYearOffset;
end;
begin
Y := 0;
M := 0;
D := 0;
YearLen := 0;
Result := False;
DateOrder := GetDateOrder(ShortDateFormat);
EraYearOffset := 0;
if (ShortDateFormat <> '') and (ShortDateFormat[1] = 'g') then // skip over prefix text
begin
ScanToNumber(S, Pos);
EraName := Trim(Copy(S, 1, Pos-1));
EraYearOffset := GetEraYearOffset(EraName);
end
else
if AnsiPos('e', ShortDateFormat) > 0 then
EraYearOffset := EraYearOffsets[1];
if not (ScanNumber(S, Pos, N1, L1) and ScanChar(S, Pos, DateSeparator) and
ScanNumber(S, Pos, N2, L2)) then Exit;
if ScanChar(S, Pos, DateSeparator) then
begin
if not ScanNumber(S, Pos, N3, L3) then Exit;
case DateOrder of
doMDY: begin Y := N3; YearLen := L3; M := N1; D := N2; end;
doDMY: begin Y := N3; YearLen := L3; M := N2; D := N1; end;
doYMD: begin Y := N1; YearLen := L1; M := N2; D := N3; end;
end;
if EraYearOffset > 0 then
Y := EraToYear(Y)
else
if (YearLen <= 2) then
begin
CenturyBase := CurrentYear - TwoDigitYearCenturyWindow;
Inc(Y, CenturyBase div 100 * 100);
if (TwoDigitYearCenturyWindow > 0) and (Y < CenturyBase) then
Inc(Y, 100);
end;
end else
begin
Y := CurrentYear;
if DateOrder = doDMY then
begin
D := N1; M := N2;
end else
begin
M := N1; D := N2;
end;
end;
ScanChar(S, Pos, DateSeparator);
ScanBlanks(S, Pos);
if SysLocale.FarEast and (System.Pos('ddd', ShortDateFormat) <> 0) then
begin // ignore trailing text
if ShortTimeFormat[1] in ['0'..'9'] then // stop at time digit
ScanToNumber(S, Pos)
else // stop at time prefix
repeat
while (Pos <= Length(S)) and (S[Pos] <> ' ') do Inc(Pos);
ScanBlanks(S, Pos);
until (Pos > Length(S)) or
(AnsiCompareText(TimeAMString, Copy(S, Pos, Length(TimeAMString))) = 0) or
(AnsiCompareText(TimePMString, Copy(S, Pos, Length(TimePMString))) = 0);
end;
Result := TryEncodeDate(Y, M, D, Date);
end;
function ScanString(const S: string; var Pos: Integer;
const Symbol: string): Boolean;
begin
Result := False;
if Symbol <> '' then
begin
ScanBlanks(S, Pos);
if AnsiCompareText(Symbol, Copy(S, Pos, Length(Symbol))) = 0 then
begin
Inc(Pos, Length(Symbol));
Result := True;
end;
end;
end;
function TryEncodeTime(Hour, Min, Sec, MSec: Word; out Time: TDateTime): Boolean;
begin
Result := False;
if (Hour < HoursPerDay) and (Min < MinsPerHour) and (Sec < SecsPerMin) and (MSec < MSecsPerSec) then
begin
Time := (Hour * (MinsPerHour * SecsPerMin * MSecsPerSec) +
Min * (SecsPerMin * MSecsPerSec) +
Sec * MSecsPerSec +
MSec) / MSecsPerDay;
Result := True;
end;
end;
function ScanTime(const S: string; var Pos: Integer;
var Time: TDateTime): Boolean; overload;
var
BaseHour: Integer;
Hour, Min, Sec, MSec: Word;
Junk: Byte;
begin
Result := False;
BaseHour := -1;
if ScanString(S, Pos, TimeAMString) or ScanString(S, Pos, 'AM') then
BaseHour := 0
else if ScanString(S, Pos, TimePMString) or ScanString(S, Pos, 'PM') then
BaseHour := 12;
if BaseHour >= 0 then ScanBlanks(S, Pos);
if not ScanNumber(S, Pos, Hour, Junk) then Exit;
Min := 0;
Sec := 0;
MSec := 0;
if ScanChar(S, Pos, TimeSeparator) then
begin
if not ScanNumber(S, Pos, Min, Junk) then Exit;
if ScanChar(S, Pos, TimeSeparator) then
begin
if not ScanNumber(S, Pos, Sec, Junk) then Exit;
if ScanChar(S, Pos, DecimalSeparator) then
if not ScanNumber(S, Pos, MSec, Junk) then Exit;
end;
end;
if BaseHour < 0 then
if ScanString(S, Pos, TimeAMString) or ScanString(S, Pos, 'AM') then
BaseHour := 0
else
if ScanString(S, Pos, TimePMString) or ScanString(S, Pos, 'PM') then
BaseHour := 12;
if BaseHour >= 0 then
begin
if (Hour = 0) or (Hour > 12) then Exit;
if Hour = 12 then Hour := 0;
Inc(Hour, BaseHour);
end;
ScanBlanks(S, Pos);
Result := TryEncodeTime(Hour, Min, Sec, MSec, Time);
end;
function TryStrToTime(const S: string; out Value: TDateTime): Boolean;
var
Pos: Integer;
begin
Pos := 1;
Result := ScanTime(S, Pos, Value) and (Pos > Length(S));
end;
function TryStrToDateTime(const S: string; out Value: TDateTime): Boolean;
var
Pos: Integer;
Date, Time: TDateTime;
begin
Result := True;
Pos := 1;
Time := 0;
if not ScanDate(S, Pos, Date) or
not ((Pos > Length(S)) or ScanTime(S, Pos, Time)) then
// Try time only
Result := TryStrToTime(S, Value)
else
if Date >= 0 then
Value := Date + Time
else
Value := Date - Time;
end;
function StrToDateTimeDef(const S: string; ADefDateTime: TDateTime): TDateTime;
begin
if not TryStrToDateTime(S, Result) then
Result := ADefDateTime;
end;
{$ENDIF}
{$IFNDEF VTK_D6_OR_D7}
function Supports(const Instance: IInterface; const IID: TGUID; out Intf): Boolean;
begin
Result := (Instance <> nil) and (Instance.QueryInterface(IID, Intf) = 0);
end;
function SupportsObject(const Instance: TObject; const IID: TGUID; out Intf): Boolean;
var
LUnknown: IInterface;
begin
Result := (Instance <> nil) and
((Instance.GetInterface(IUnknown, LUnknown) and Supports(LUnknown, IID, Intf)) or
Instance.GetInterface(IID, Intf));
end;
function Supports(const Instance: IInterface; const IID: TGUID): Boolean;
var
Temp: IInterface;
begin
Result := Supports(Instance, IID, Temp);
end;
function Supports(const Instance: TObject; const IID: TGUID): Boolean;
var
Temp: IInterface;
begin
Result := SupportsObject(Instance, IID, Temp);
end;
function Supports(const AClass: TClass; const IID: TGUID): Boolean;
begin
Result := AClass.GetInterfaceEntry(IID) <> nil;
end;
function DirectoryExists(const Directory: string): Boolean;
var
Code: Integer;
begin
Code := GetFileAttributes(PChar(Directory));
Result := (Code <> -1) and (FILE_ATTRIBUTE_DIRECTORY and Code <> 0);
end;
function IsZero(const A: Extended; Epsilon: Extended): Boolean;
begin
if Epsilon = 0 then
Epsilon := ExtendedResolution;
Result := Abs(A) <= Epsilon;
end;
function IsZero(const A: Double; Epsilon: Double): Boolean;
begin
if Epsilon = 0 then
Epsilon := DoubleResolution;
Result := Abs(A) <= Epsilon;
end;
function IsZero(const A: Single; Epsilon: Single): Boolean;
begin
if Epsilon = 0 then
Epsilon := SingleResolution;
Result := Abs(A) <= Epsilon;
end;
{$ENDIF}
function GetWorksheetColCaption(ColNumber : integer) : string;
begin
Result := '';
repeat
Result := char(ColNumber mod 26+byte('A'))+Result;
ColNumber := ColNumber div 26;
if ColNumber=1 then
Result := 'A'+Result;
until ColNumber<=1;
end;
function GetWorksheetRowCaption(RowNumber : integer) : string;
begin
Result := IntToStr(RowNumber+1);
end;
function RectOverRect(const r1: TRect; const r2: TRect): boolean;
begin
Result :=
(((r1.Left >= r2.Left) and (r1.Left <= r2.Right)) or ((r1.Right >= r2.Left) and (r1.Right <= r2.Right)) or ((r1.Left <= r2.Left) and (r1.Right >= r2.Left)))
and
(((r1.Top >= r2.Top) and (r1.Top <= r2.Bottom)) or ((r1.Bottom >= r2.Top) and (r1.Bottom <= r2.Bottom)) or ((r1.Top <= r2.Top) and (r1.Bottom >= r2.Top)));
end;
function NormalizeRect(const r: TRect): TRect;
begin
Result := NormalizeRect(r.Left,r.Top,r.Right,r.Bottom);
end;
function NormalizeRect(x1,y1,x2,y2: Integer): TRect;
begin
if x1 > x2 then
begin
Result.Left := x2;
Result.Right := x1;
end
else
begin
Result.Left := x1;
Result.Right := x2;
end;
if y1 > y2 then
begin
Result.Top := y2;
Result.Bottom := y1;
end
else
begin
Result.Top := y1;
Result.Bottom := y2;
end;
end;
function Size(cx, cy: Integer): TSize;
begin
Result.cx := cx;
Result.cy := cy;
end;
function RectInRect(const ASmallRect, ALargeRect: TRect): Boolean;
begin
Result := PtInRect(ALargeRect, ASmallRect.TopLeft) and
PtInRect(ALargeRect, ASmallRect.BottomRight);
end;
function RectInSelRect(const ASmallRect, ALargeRect: TRect): Boolean;
begin
Result := (ALargeRect.Left <= ASmallRect.Left) and
(ALargeRect.Right >= ASmallRect.Right) and
(ALargeRect.Top <= ASmallRect.Top) and
(ALargeRect.Bottom >= ASmallRect.Bottom);
end;
function PointInSelRect(const APoint: TPoint; ARect: TRect): Boolean;
begin
with APoint, ARect do
Result := (X >= Left) and (X <= Right) and (Y >= Top) and (Y <= Bottom);
end;
function HorzCenterOfRect(const ARect: TRect): Integer;
begin
Result := ARect.Left + (ARect.Right - ARect.Left) div 2;
end;
procedure GetEnumNamesToStrings(ATypeInfo: PTypeInfo; AStrings: TStrings; ADeleteFirstCharCount: Integer = 0);
var
I: Integer;
s: string;
begin
for I := GetTypeData(ATypeInfo).MinValue to GetTypeData(ATypeInfo).MaxValue do
begin
s := GetEnumName(ATypeInfo, I);
Delete(s, 1, ADeleteFirstCharCount);
AStrings.Add(s);
end;
end;
function GetUniqueComponentName(AComponent: TComponent): string;
var
I: Integer;
AParent: TComponent;
APrefix: string;
begin
AParent := AComponent.GetParentComponent;
Result := '';
while AParent <> nil do
begin
Result := AParent.Name + Result;
AParent := AParent.GetParentComponent;
end;
APrefix := AComponent.ClassName;
Delete(APrefix, 1, 1);
if AComponent.Owner = nil then
Result := Result + APrefix
else
begin
I := 1;
while (I < MaxInt) and (AComponent.Owner.FindComponent(Result + APrefix + IntToStr(I)) <> nil) do Inc(I);
Result := Result + APrefix + IntToStr(I);
end;
end;
function CheckComponentName(AComponent: TComponent; const ANewName: string): Boolean;
begin
Result := (ANewName <> '') and ((AComponent.Owner = nil) or (AComponent.Owner.FindComponent(ANewName) = nil) or (AComponent.Owner.FindComponent(ANewName) = AComponent));
end;
function FormatVariant(const AFormat: string; const AValue: Variant): string;
begin
case VarType(AValue) of
varSmallint, varInteger, varSingle,
{$IFDEF VRK_D6_OR_D7}varShortInt,
varWord, varLongWord, varInt64,{$ENDIF}
varByte, varDouble, varCurrency:
Result := FormatFloat(AFormat, AValue);
varDate:
Result := FormatDateTime(AFormat, AValue);
varOleStr, {$IFDEF VRK_D6_OR_D7}varStrArg, {$ENDIF}varString:
Result := VarToStr(AValue);
else
Result := '';
end;
end;
function IndexInStrings(const S: string; AList: TStrings): Integer;
begin
Result := 0;
while (Result < AList.Count) and (AnsiCompareText(AList[Result], S) <> 0) do Inc(Result);
if Result >= AList.Count then
Result := -1;
end;
function PosToRowAndCol(AStrings: TStrings; APos: Integer; var ARow, ACol: Integer; AStringDelimiters: TSysCharSet): Boolean;
var
S: string;
C: char;
I: Integer;
AMaxPos: Integer;
begin
ARow := 1;
ACol := 1;
S := AStrings.Text;
AMaxPos := Min(APos, Length(S));
I := 1;
while I < AMaxPos do
begin
ACol := 1;
while (I < AMaxPos) and not(S[I] in AStringDelimiters) do
begin
Inc(ACol);
Inc(I);
end;
if (I < AMaxPos) and (S[I] in AStringDelimiters) then
begin
C := S[I];
Inc(I);
if (I < AMaxPos) and (S[I] in AStringDelimiters) and (S[I] <> c) then
Inc(I);
end;
// while (I < AMaxPos) and (S[I] in AStringDelimiters) do Inc(I);
if I > AMaxPos then
break;
Inc(ARow);
end;
Result := I >= APos;
end;
function PosToRowAndCol(AStrings: TStrings; APos: Integer; var ARow, ACol: Integer): Boolean;
begin
Result := PosToRowAndCol(AStrings, APos, ARow, ACol, [#13, #10]);
end;
procedure BeginEnumLines(const S: string; var ALineInfo: TvgrTextLineInfo);
begin
with ALineInfo do
begin
Start := 1;
Length := 0;
FullLength := 0;
TextLength := System.Length(S);
CrLf := False;
end;
end;
procedure FindEndOfLineBreak(const S: string; ALen: Integer; var I: Integer);
begin
if (I <= ALen) and ((S[I] = #13) or (S[I] = #10)) then
begin
Inc(I);
if (I <= ALen) and ((S[I] = #13) or (S[I] = #10)) and (S[I] <> S[I - 1]) then
Inc(I);
end;
end;
function EnumLines(const S: string; var ALineInfo: TvgrTextLineInfo): Boolean;
var
I: Integer;
begin
with ALineInfo do
begin
Start := Start + FullLength;
Result := Start <= TextLength;
if Result then
begin
I := Start;
while (I <= TextLength) and (S[I] <> #13) and (S[I] <> #10) do Inc(I);
Length := I - Start;
if I <= TextLength then
begin
FindEndOfLineBreak(S, TextLength, I);
FullLength := I - Start;
if I > TextLength then
begin
if CrLf then
begin
// CrLf := false;
Result := True;
end
else
begin
CrLf := True;
FullLength := Length;
end;
end;
end
else
FullLength := Length;
end;
// Assert(not (Result and (FullLength = 0)));
end;
end;
procedure FreeListItems(AList: TList);
var
I: Integer;
begin
for I := 0 to AList.Count - 1 do
TObject(AList[I]).Free;
end;
{$IFDEF VTK_D4}
procedure FreeAndNil(var AObject);
var
P: TObject;
begin
P := TObject(AObject);
TObject(AObject) := nil; // clear the reference before destroying the object
P.Free;
end;
{$ENDIF}
procedure FreeList(var AList: TList);
begin
FreeListItems(AList);
FreeAndNil(AList);
end;
procedure StreamToClipboard(AClipboardFormat: Word; AStream: TMemoryStream);
var
hMem: THandle;
pMem: Pointer;
begin
ClipBoard.Open;
try
hMem := GlobalAlloc(GMEM_MOVEABLE + GMEM_SHARE + GMEM_ZEROINIT, AStream.Size);
if hMem <> 0 then
begin
pMem := GlobalLock(hMem);
if pMem <> nil then
begin
CopyMemory(pMem, AStream.Memory, AStream.Size);
GlobalUnLock(hMem);
ClipBoard.SetAsHandle(AClipboardFormat, hMem);
end;
end;
finally
ClipBoard.Close;
end;
end;
procedure StreamFromClipboard(AClipboardFormat: Word; AStream: TMemoryStream);
var
hMem: THandle;
pMem: Pointer;
ASize: Integer;
begin
ClipBoard.Open;
try
hMem := Clipboard.GetAsHandle(AClipboardFormat);
pMem := GlobalLock(hMem);
if pMem <> nil then
begin
ASize := GlobalSize(hMem);
AStream.Clear;
AStream.SetSize(ASize);
MoveMemory(AStream.Memory, pMem, ASize);
GlobalUnlock(hMem);
end;
finally
ClipBoard.Close;
end;
end;
function GetBorderPartSize(ASize: Integer; ASide: TvgrBorderSide): Integer;
begin
if ASize = 0 then
Result := 0
else
case ASide of
vgrbsLeft: Result := (ASize - 1) div 2{ASize div 2};
vgrbsTop: Result := (ASize - 1) div 2{ASize div 2};
vgrbsRight: Result := 1 + ASize div 2{(ASize + 1) div 2};
else {vgrbsBottom}
Result := 1 + ASize div 2{(ASize + 1) div 2};
end;
end;
function ConvertTwipsToPixelsX(Twips : integer) : integer;
begin
Result := Round(ScreenPixelsPerInchX/TwipsPerInch*Twips);
end;
function ConvertTwipsToPixelsY(Twips : integer) : integer;
begin
Result := Round(ScreenPixelsPerInchY/TwipsPerInch*Twips);
end;
function ConvertTwipsToPixelsX(Twips: integer; PixelsPerX: Integer): integer;
begin
Result := Round(PixelsPerX/TwipsPerInch*Twips);
end;
function ConvertTwipsToPixelsY(Twips: integer; PixelsPerY: Integer): integer;
begin
Result := Round(PixelsPerY/TwipsPerInch*Twips);
end;
function ConvertPixelsToTwipsX(Pixels: integer) : integer;
begin
Result := Round(TwipsPerInch/ScreenPixelsPerInchX*Pixels);
end;
function ConvertPixelsToTwipsY(Pixels: integer) : integer;
begin
Result := Round(TwipsPerInch/ScreenPixelsPerInchY*Pixels);
end;
function ConvertPixelsToTwipsX(Pixels: integer; PixelsPerX: Integer): integer;
begin
Result := Round(TwipsPerInch/PixelsPerX*Pixels);
end;
function ConvertPixelsToTwipsY(Pixels: integer; PixelsPerY: Integer): integer;
begin
Result := Round(TwipsPerInch/PixelsPerY*Pixels);
end;
function ConvertUnitsToTwips(AValue: Extended; AUnits: TvgrUnits): Integer;
begin
case AUnits of
vgruMms: Result := Round(TwipsPerMMs * AValue);
vgruCentimeters: Result := Round(TwipsPerMMs * 10 * AValue);
vgruInches: Result := Round(TwipsPerInch * AValue);
vgruTenthsMMs: Result := Round(TwipsPerMMs * AValue / 10);
else
Result := ConvertPixelsToTwipsX(Round(AValue));
end;
end;
function ConvertTwipsToUnits(ATwips: Integer; AUnits: TvgrUnits): Extended;
begin
case AUnits of
vgruMms: Result := ATwips / TwipsPerMMs;
vgruCentimeters: Result := ATwips / TwipsPerMMs / 10;
vgruInches: Result := ATwips / TwipsPerInch;
vgruTenthsMMs: Result := ATwips / TwipsPerMMs * 10;
else
Result := ConvertTwipsToPixelsX(ATwips);
end;
end;
function ConvertTwipsToUnitsStr(ATwips: Integer; AUnits: TvgrUnits): string;
const
AFormats: Array[TvgrUnits] of string = ('0.0', '0.00', '0.00', '0', '0');
begin
Result := FormatFloat(AFormats[AUnits], ConvertTwipsToUnits(ATwips, AUnits))
end;
function sp(Item1, Item2: Pointer): Integer;
begin
Result := Integer(Item1) - Integer(Item2);
end;
function CheckPageList(const S: string): Boolean;
var
L: TList;
begin
L := TList.Create;
try
Result := TextToPageList(S, L);
finally
L.Free;
end;
end;
function TextToPageList(const S: string; APagesList: TList): Boolean;
var
I, J, L, N1, N2: Integer;
begin
APagesList.Clear;
Result := Trim(s) = '';
if not Result then
begin
Result := false;
N2 := -1;
N1 := -1;
L := Length(S);
I := 1;
while I <= L do
begin
case S[i] of
'-':
begin
if (N2 = -1) or (N1 <> -1) then exit;
N1 := N2;
end;
',':
begin
if (N1 <> -1) and (N2 <> -1) then
for J := N1 to N2 do
APagesList.Add(pointer(J))
else
if n2 <> -1 then
APagesList.Add(pointer(N2))
else
exit;
N1 := -1;
N2 := -1;
end;
'0'..'9':
begin
J := I;
while (I <= L) and (S[i] in ['0'..'9']) do Inc(I);
N2 := StrToInt(Copy(S, J, I - J));
Dec(I);
end;
else
exit;
end;
Inc(I);
end;
if (N1 <> -1) and (N2 <> -1) then
for J := N1 to N2 do
APagesList.Add(pointer(J))
else
if n2 <> -1 then
APagesList.Add(pointer(N2))
else
exit;
APagesList.Sort(sp);
Result := True;
end;
end;
procedure DbgFileWriteString(const AFileName: string; const S: string);
var
AHandle: THandle;
ABytes: Cardinal;
begin
AHandle := CreateFile(PChar(AFileName),
GENERIC_WRITE,
FILE_SHARE_WRITE or FILE_SHARE_READ,
nil,
OPEN_ALWAYS,
0, 0);
if AHandle <> INVALID_HANDLE_VALUE then
begin
SetFilePointer(AHandle, 0, nil, FILE_END);
WriteFile(AHandle, S[1], Length(S), ABytes, nil);
CloseHandle(AHandle);
end;
end;
procedure DbgFileWriteString(const S: string);
begin
DbgFileWriteString(DbgFileFileName, S);
end;
procedure DbgFileRect(const ADescRect: string; const ARect: TRect);
begin
with ARect do
DbgFileWriteString(Format('%s= (%d, %d, %d, %d)', [ADescRect, Left, Top, Right, Bottom]));
end;
procedure DbgFileStr(const s: string);
begin
DbgFileWriteString(S);
end;
procedure DbgFileStrFmt(const AMask: string; AParams: array of const);
begin
DbgFileWriteString(Format(AMask, AParams));
end;
procedure DbgRect(const ADescRect: string; const ARect: TRect);
begin
with ARect do
OutputDebugString(PChar(Format('%s= (%d, %d, %d, %d)', [ADescRect, Left, Top, Right, Bottom])));
end;
procedure DbgStr(const s: string);
begin
OutputDebugString(PChar(s));
end;
procedure DbgStrFmt(const AMask: string; AParams: array of const);
begin
OutputDebugString(PChar(Format(AMask, AParams)));
end;
var
ADC: HDC;
initialization
ADC := GetDC(0);
ScreenPixelsPerInchX := GetDeviceCaps(ADC, LOGPIXELSX);
ScreenPixelsPerInchY := GetDeviceCaps(ADC, LOGPIXELSY);
ReleaseDC(0, ADC);
end.
|
unit Demo.Hrtf;
interface
uses
ECMA.TypedArray, SimpleSofaFile;
type
THrtfMeasurement = class
private
FPosition: TVector3;
FLeft: JFloat32Array;
FRight: JFloat32Array;
public
constructor Create(Position: TVector3; Left, Right: JFloat32Array);
function GetMaxLevel: Float;
property Position: TVector3 read FPosition;
property Left: JFloat32Array read FLeft;
property Right: JFloat32Array read FRight;
end;
THrtfs = class
private
FSampleFrames: Integer;
FSampleRate: Float;
FScaleFactor: Float;
FMeasurements: array of THrtfMeasurement;
function GetMeasurement(Index: Integer): THrtfMeasurement;
public
constructor Create(SofaFile: TSofaFile);
property SampleFrames: Integer read FSampleFrames;
property SampleRate: Float read FSampleRate;
property MeasurementCount: Integer read (Length(FMeasurements));
property Measurement[Index: Integer]: THrtfMeasurement read GetMeasurement;
property ScaleFactor: Float read FScaleFactor;
end;
implementation
uses
WHATWG.Console, ECMA.Base64;
{ THrtfMeasurement }
constructor THrtfMeasurement.Create(Position: TVector3; Left, Right: JFloat32Array);
begin
FPosition := Position;
FLeft := Left;
FRight := Right;
end;
function THrtfMeasurement.GetMaxLevel: Float;
begin
Result := 0;
for var Index := 0 to Left.length - 1 do
if Abs(Left[Index]) > Result then
Result := Abs(Left[Index]);
for var Index := 0 to Right.length - 1 do
if Abs(Right[Index]) > Result then
Result := Abs(Right[Index]);
end;
{ THrtfs }
constructor THrtfs.Create(SofaFile: TSofaFile);
begin
FSampleFrames := SofaFile.NumberOfDataSamples;
FSampleRate := SofaFile.SampleRate[0];
Assert(SofaFile.NumberOfMeasurements = SofaFile.NumberOfSources);
// find minimum z position
var MinZ := Abs(SofaFile.SourcePositions.GetPosition(0, False)[2]);
for var MeasurementIndex := 1 to SofaFile.NumberOfMeasurements - 1 do
begin
var Position := SofaFile.SourcePositions.GetPosition(MeasurementIndex, False);
if Abs(Position[2]) < MinZ then
MinZ := Abs(Position[2]);
end;
for var MeasurementIndex := 0 to SofaFile.NumberOfMeasurements - 1 do
begin
var Position := SofaFile.SourcePositions.GetPosition(MeasurementIndex, False);
// only consider the horizontal plane (more or less)
if Abs(Position[2]) > MinZ then
continue;
Assert(SofaFile.NumberOfReceivers >= 2);
FMeasurements.Add(THrtfMeasurement.Create(Position,
JFloat32Array.Create(JFloat32Array(SofaFile.ImpulseResponse[MeasurementIndex, 0])),
JFloat32Array.Create(JFloat32Array(SofaFile.ImpulseResponse[MeasurementIndex, 1]))));
end;
// normalize level
var GlobalMaxLevel := 0.0;
for var Measurement in FMeasurements do
begin
var MaxLevel := Measurement.GetMaxLevel;
if MaxLevel > GlobalMaxLevel then
GlobalMaxLevel := MaxLevel;
end;
FScaleFactor := if GlobalMaxLevel <> 0 then 1 / GlobalMaxLevel else 1;
end;
function THrtfs.GetMeasurement(Index: Integer): THrtfMeasurement;
begin
if (Index < 0) and (Index >= Length(FMeasurements)) then
raise Exception.Create('Index out of bounds');
Result := FMeasurements[Index];
end;
end. |
unit NotebookImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB, ExtCtrls;
type
TNotebookX = class(TActiveXControl, INotebookX)
private
{ Private declarations }
FDelphiControl: TNotebook;
FEvents: INotebookXEvents;
procedure ClickEvent(Sender: TObject);
procedure DblClickEvent(Sender: TObject);
procedure PageChangedEvent(Sender: TObject);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_ActivePage: WideString; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_Color: OLE_COLOR; safecall;
function Get_Ctl3D: WordBool; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Font: IFontDisp; safecall;
function Get_PageIndex: Integer; safecall;
function Get_Pages: IStrings; safecall;
function Get_ParentColor: WordBool; safecall;
function Get_ParentCtl3D: WordBool; safecall;
function Get_ParentFont: WordBool; safecall;
function Get_Visible: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure _Set_Font(const Value: IFontDisp); safecall;
procedure AboutBox; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure Set_ActivePage(const Value: WideString); safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_Color(Value: OLE_COLOR); safecall;
procedure Set_Ctl3D(Value: WordBool); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Font(const Value: IFontDisp); safecall;
procedure Set_PageIndex(Value: Integer); safecall;
procedure Set_Pages(const Value: IStrings); safecall;
procedure Set_ParentColor(Value: WordBool); safecall;
procedure Set_ParentCtl3D(Value: WordBool); safecall;
procedure Set_ParentFont(Value: WordBool); safecall;
procedure Set_Visible(Value: WordBool); safecall;
end;
implementation
uses ComObj, About19;
{ TNotebookX }
procedure TNotebookX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_NotebookXPage); }
end;
procedure TNotebookX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as INotebookXEvents;
end;
procedure TNotebookX.InitializeControl;
begin
FDelphiControl := Control as TNotebook;
FDelphiControl.OnClick := ClickEvent;
FDelphiControl.OnDblClick := DblClickEvent;
FDelphiControl.OnPageChanged := PageChangedEvent;
end;
function TNotebookX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TNotebookX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TNotebookX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TNotebookX.Get_ActivePage: WideString;
begin
Result := WideString(FDelphiControl.ActivePage);
end;
function TNotebookX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TNotebookX.Get_Color: OLE_COLOR;
begin
Result := OLE_COLOR(FDelphiControl.Color);
end;
function TNotebookX.Get_Ctl3D: WordBool;
begin
Result := FDelphiControl.Ctl3D;
end;
function TNotebookX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TNotebookX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TNotebookX.Get_DragCursor: Smallint;
begin
Result := Smallint(FDelphiControl.DragCursor);
end;
function TNotebookX.Get_DragMode: TxDragMode;
begin
Result := Ord(FDelphiControl.DragMode);
end;
function TNotebookX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TNotebookX.Get_Font: IFontDisp;
begin
GetOleFont(FDelphiControl.Font, Result);
end;
function TNotebookX.Get_PageIndex: Integer;
begin
Result := FDelphiControl.PageIndex;
end;
function TNotebookX.Get_Pages: IStrings;
begin
GetOleStrings(FDelphiControl.Pages, Result);
end;
function TNotebookX.Get_ParentColor: WordBool;
begin
Result := FDelphiControl.ParentColor;
end;
function TNotebookX.Get_ParentCtl3D: WordBool;
begin
Result := FDelphiControl.ParentCtl3D;
end;
function TNotebookX.Get_ParentFont: WordBool;
begin
Result := FDelphiControl.ParentFont;
end;
function TNotebookX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TNotebookX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TNotebookX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TNotebookX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TNotebookX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TNotebookX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TNotebookX._Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TNotebookX.AboutBox;
begin
ShowNotebookXAbout;
end;
procedure TNotebookX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TNotebookX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TNotebookX.Set_ActivePage(const Value: WideString);
begin
FDelphiControl.ActivePage := String(Value);
end;
procedure TNotebookX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TNotebookX.Set_Color(Value: OLE_COLOR);
begin
FDelphiControl.Color := TColor(Value);
end;
procedure TNotebookX.Set_Ctl3D(Value: WordBool);
begin
FDelphiControl.Ctl3D := Value;
end;
procedure TNotebookX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TNotebookX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TNotebookX.Set_DragCursor(Value: Smallint);
begin
FDelphiControl.DragCursor := TCursor(Value);
end;
procedure TNotebookX.Set_DragMode(Value: TxDragMode);
begin
FDelphiControl.DragMode := TDragMode(Value);
end;
procedure TNotebookX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TNotebookX.Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TNotebookX.Set_PageIndex(Value: Integer);
begin
FDelphiControl.PageIndex := Value;
end;
procedure TNotebookX.Set_Pages(const Value: IStrings);
begin
SetOleStrings(FDelphiControl.Pages, Value);
end;
procedure TNotebookX.Set_ParentColor(Value: WordBool);
begin
FDelphiControl.ParentColor := Value;
end;
procedure TNotebookX.Set_ParentCtl3D(Value: WordBool);
begin
FDelphiControl.ParentCtl3D := Value;
end;
procedure TNotebookX.Set_ParentFont(Value: WordBool);
begin
FDelphiControl.ParentFont := Value;
end;
procedure TNotebookX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TNotebookX.ClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnClick;
end;
procedure TNotebookX.DblClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnDblClick;
end;
procedure TNotebookX.PageChangedEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnPageChanged;
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TNotebookX,
TNotebook,
Class_NotebookX,
19,
'{695CDB68-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Mac.Devices;
interface
const
sMacDesktopDevice = 'Macintosh'; // do not localize
sMacRetinaDevice = 'Retina'; // do not localize
procedure AddDevices;
implementation
{$IFDEF MACOS}
uses Macapi.CocoaTypes, Macapi.Appkit, System.Types, System.SysUtils, System.Devices;
procedure AddDevices;
var
Screen: NSScreen;
Rect: NSRect;
LogicalSize, PhysicalSize: TSize;
Scale: CGFloat;
DeviceID: string;
begin
Screen := TNSScreen.Wrap(TNSScreen.OCClass.mainScreen);
Rect := Screen.frame;
Scale := Screen.backingScaleFactor;
LogicalSize := TSize.Create(Trunc(Rect.size.width), Trunc(Rect.size.height));
PhysicalSize := TSize.Create(Trunc(Rect.size.width * Scale), Trunc(Rect.size.height * Scale));
{ if Scale > 1.0 then
DeviceID := sMacRetinaDevice
else}
DeviceID := sMacDesktopDevice;
TDeviceInfo.AddDevice(TDeviceInfo.TDeviceClass.Desktop, DeviceID, PhysicalSize, LogicalSize,
TOSVersion.TPlatform.pfMacOS, Trunc(110 * Scale));
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
uses Winapi.Windows, System.Types, System.SysUtils, System.Devices;
// Since the above code cannot work under Windows, we still need to simulate a "mac device" on Windows at design-time.
// We'll just synthesize a "mac" desktop device using the Windows metrics.
procedure AddDevices;
var
LogicalSize, PhysicalSize: TSize;
begin
LogicalSize := TSize.Create(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
PhysicalSize := TSize.Create(Trunc(LogicalSize.cx * 2.0), Trunc(LogicalSize.cy * 2.0));
// For now use USER_DEFAULT_SCREEN_DPI - eventually this should be obtained from the OS, or if possible, calculated.
TDeviceInfo.AddDevice(TDeviceInfo.TDeviceClass.Desktop, sMacDesktopDevice, LogicalSize, LogicalSize,
TOSVersion.TPlatform.pfMacOS, USER_DEFAULT_SCREEN_DPI);
// Simulate a retina display "device" by merely using a 2x scaling factor
// TDeviceInfo.AddDevice(TDeviceInfo.TDeviceClass.Desktop, sMacRetinaDevice, PhysicalSize, LogicalSize,
// TOSVersion.TPlatform.pfMacOS, USER_DEFAULT_SCREEN_DPI * 2);
end;
{$ENDIF}
end.
|
{ Pascal procedure that writes string to file }
{ If you ever need to write a string variable quickly to a file, here is a function that works similarly to PHP’s file_put_contents() and to C#’s System.IO.File.WriteAllText(). }
procedure file_put_contents(filepath, content:string);
var f:text;
begin
assign(f, filepath);
rewrite(f);
write(f, content);
close(f);
end;
begin
file_put_contents('test.txt', 'You can write any string here of up to 255 characters');
end.
|
unit rCore;
interface
uses SysUtils, Classes, Forms, ORNet, ORFn, ORClasses, system.JSON;
{ record types used to return data from the RPC's. Generally, the delimited strings returned
by the RPC are mapped into the records defined below. }
const
UC_UNKNOWN = 0; // user class unknown
UC_CLERK = 1; // user class clerk
UC_NURSE = 2; // user class nurse
UC_PHYSICIAN = 3; // user class physician
type
TUserInfo = record // record for ORWU USERINFO
DUZ: Int64;
Name: string;
UserClass: Integer;
CanSignOrders: Boolean;
IsProvider: Boolean;
OrderRole: Integer;
NoOrdering: Boolean;
DTIME: Integer;
CountDown: Integer;
EnableVerify: Boolean;
NotifyAppsWM: Boolean;
PtMsgHang: Integer;
Domain: string;
Service: Integer;
AutoSave: Integer;
InitialTab: Integer;
UseLastTab: Boolean;
EnableActOneStep: Boolean;
WebAccess: Boolean;
IsRPL: string;
RPLList: string;
HasCorTabs: Boolean;
HasRptTab: Boolean;
IsReportsOnly: Boolean;
ToolsRptEdit: Boolean;
DisableHold: Boolean;
GECStatusCheck: Boolean;
StationNumber: string;
IsProductionAccount: boolean;
JobNumber: string;
EvaluateRemCoverSheetOnDialogFinish: BOOLEAN;
end;
TPtIDInfo = record // record for ORWPT IDINFO
Name: string;
SSN: string;
DOB: string;
Age: string;
Sex: string;
SCSts: string;
Vet: string;
Location: string;
RoomBed: string;
end;
TPtSelect = record // record for ORWPT SELECT
Name: string;
ICN: string;
SSN: string;
DOB: TFMDateTime;
Age: Integer;
Sex: Char;
LocationIEN: Integer;
Location: string;
WardService: string;
RoomBed: string;
SpecialtyIEN: Integer;
SpecialtySvc: string;
CWAD: string;
Restricted: Boolean;
AdmitTime: TFMDateTime;
ServiceConnected: Boolean;
SCPercent: Integer;
PrimaryTeam: string;
PrimaryProvider: string;
MHTC: string;
Attending: string;
Associate: string;
InProvider: string;
end;
TEncounterText = record // record for ORWPT ENCTITL
LocationName: string;
LocationAbbr: string;
RoomBed: string;
ProviderName: string;
end;
{ Date/Time functions - right now these make server calls to use server time}
function FMToday: TFMDateTime;
function FMNow: TFMDateTime;
function MakeRelativeDateTime(FMDateTime: TFMDateTime): string;
function StrToFMDateTime(const AString: string): TFMDateTime;
function ValidDateTimeStr(const AString, Flags: string): TFMDateTime;
procedure ListDateRangeClinic(Dest: TStrings);
function IsDateMoreRecent(Date1: TDateTime; Date2: TDateTime): Boolean;
{ General calls }
function ExternalName(IEN: Int64; FileNumber: Double): string;
function PersonHasKey(APerson: Int64; const AKey: string): Boolean;
function GlobalRefForFile(const FileID: string): string;
function SubsetOfGeneric(const StartFrom: string; Direction: Integer; const GlobalRef: string): TStrings;
function SubsetOfDevices(const StartFrom: string; Direction: Integer): TStrings;
function SubSetOfPersons(const StartFrom: string; Direction: Integer): TStrings;
function SubSetOfActiveAndInactivePersons(const StartFrom: string; Direction: Integer): TStrings;
function GetDefaultPrinter(DUZ: Int64; Location: integer): string;
procedure getSysUserParameters(DUZ: Int64);
{ User specific calls }
function GetUserInfo: TUserInfo;
function GetUserParam(const AParamName: string): string;
procedure GetUserListParam(Dest: TStrings; const AParamName: string);
function HasSecurityKey(const KeyName: string): Boolean;
function HasMenuOptionAccess(const OptionName: string): Boolean;
function ValidESCode(const ACode: string): Boolean;
//function otherInformationPanelControls: string;
{ Notifications calls }
procedure LoadNotifications(Dest: TStrings);
function LoadNotificationLongText(AlertID: string): string;
function IsSmartAlert(notIEN: integer): boolean;
procedure DeleteAlert(XQAID: string);
procedure DeleteAlertForUser(XQAID: string);
function GetXQAData(XQAID: string; pFlag: string = ''): string;
function GetTIUAlertInfo(XQAID: string): string;
procedure UpdateUnsignedOrderAlerts(PatientDFN: string);
function UnsignedOrderAlertFollowup(XQAID: string): string;
procedure UpdateExpiringMedAlerts(PatientDFN: string);
procedure UpdateExpiringFlaggedOIAlerts(PatientDFN: string; FollowUp: integer);
procedure AutoUnflagAlertedOrders(PatientDFN, XQAID: string);
procedure UpdateUnverifiedMedAlerts(PatientDFN: string);
procedure UpdateUnverifiedOrderAlerts(PatientDFN: string);
function GetNotificationFollowUpText(PatientDFN: string; Notification: integer; XQADATA: string): TStrings;
procedure ForwardAlert(XQAID: string; Recip: string; FWDtype: string; Comment: string);
procedure RenewAlert(XQAID: string);
function GetSortMethod: string;
procedure SetSortMethod(Sort: string; Direction: string);
procedure UpdateIndOrderAlerts();
{ Patient List calls }
function DfltPtList: string;
function DfltPtListSrc: Char;
function DefltPtListSrc: string;
procedure SavePtListDflt(const x: string);
procedure ListSpecialtyAll(Dest: TStrings);
procedure ListTeamAll(Dest: TStrings);
procedure ListPcmmAll(Dest: TStrings);
procedure ListWardAll(Dest: TStrings);
procedure ListProviderTop(Dest: TStrings);
function SubSetOfProviders(const StartFrom: string; Direction: Integer): TStrings;
function SubSetOfCosigners(const StartFrom: string; Direction: Integer; Date: TFMDateTime;
ATitle: integer; ADocType: integer): TStrings;
procedure ListClinicTop(Dest: TStrings);
function SubSetOfClinics(const StartFrom: string; Direction: Integer): TStrings;
function GetDfltSort: string;
procedure ResetDfltSort;
procedure ListPtByDflt(Dest: TStrings);
procedure ListPtByProvider(Dest: TStrings; ProviderIEN: Int64);
procedure ListPtByTeam(Dest: TStrings; TeamIEN: Integer);
procedure ListPtByPcmmTeam(Dest: TStrings; TeamIEN: Integer);
procedure ListPtBySpecialty(Dest: TStrings; SpecialtyIEN: Integer);
procedure ListPtByClinic(Dest: TStrings; ClinicIEN: Integer; FirstDt, LastDt: string);
procedure ListPtByWard(Dest: TStrings; WardIEN: Integer);
procedure ListPtByLast5(Dest: TStrings; const Last5: string);
procedure ListPtByRPLLast5(Dest: TStrings; const Last5: string);
procedure ListPtByFullSSN(Dest: TStrings; const FullSSN: string);
procedure ListPtByRPLFullSSN(Dest: TStrings; const FullSSN: string);
procedure ListPtTop(Dest: TStrings);
function SubSetOfPatients(const StartFrom: string; Direction: Integer): TStrings;
function DfltDateRangeClinic: string;
function MakeRPLPtList(RPLList: string): string;
function ReadRPLPtList(RPLJobNumber: string; const StartFrom: string; Direction: Integer) : TStrings;
procedure KillRPLPtList(RPLJobNumber: string);
{ Patient specific calls }
function CalcAge(BirthDate, DeathDate: TFMDateTime): Integer;
procedure CheckSensitiveRecordAccess(const DFN: string; var AccessStatus: Integer;
var MessageText: string);
procedure CheckRemotePatient(var Dest: string; Patient, ASite: string; var AccessStatus: Integer);
procedure CurrentLocationForPatient(const DFN: string; var ALocation: Integer; var AName: string; var ASvc: string);
function DateOfDeath(const DFN: string): TFMDateTime;
function GetPtIDInfo(const DFN: string): TPtIDInfo;
function HasLegacyData(const DFN: string; var AMsg: string): Boolean;
function LogSensitiveRecordAccess(const DFN: string): Boolean;
function MeansTestRequired(const DFN: string; var AMsg: string): Boolean;
function RestrictedPtRec(const DFN: string): Boolean;
procedure SelectPatient(const DFN: string; var PtSelect: TPtSelect);
function SimilarRecordsFound(const DFN: string; var AMsg: string): Boolean;
function GetDFNFromICN(AnICN: string): string;
function GetVAAData(const DFN: string; aList: TStrings): Boolean;
function GetMHVData(const DFN: string; aList: TStrings): Boolean;
function otherInformationPanel(const DFN: string): string;
procedure otherInformationPanelDetails(const DFN: string; valueType: string; var details: TStrings);
{ Encounter specific calls }
function GetEncounterText(const DFN: string; Location: integer; Provider: Int64): TEncounterText; //*DFN*
function GetActiveICDVersion(ADate: TFMDateTime = 0): String;
function GetICD10ImplementationDate: TFMDateTime;
procedure ListApptAll(Dest: TStrings; const DFN: string; From: TFMDateTime = 0;
Thru: TFMDateTime = 0);
procedure ListAdmitAll(Dest: TStrings; const DFN: string);
function SubSetOfLocations(const StartFrom: string; Direction: Integer): TStrings;
function SubSetOfNewLocs(const StartFrom: string; Direction: Integer): TStrings;
function SubSetOfInpatientLocations(const StartFrom: string; Direction: Integer): TStrings;
function SubSetOfProvWithClass(const StartFrom: string; Direction: Integer; DateTime: string): TStrings;
function SubSetOfUsersWithClass(const StartFrom: string; Direction: Integer; DateTime: string): TStrings;
{ Remote Data Access calls }
function HasRemoteData(const DFN: string; var ALocations: TStringList): Boolean;
function CheckHL7TCPLink: Boolean;
function GetVistaWebAddress(value: string): string;
function GetVistaWeb_JLV_LabelName: string;
implementation
uses XWBHash, uCore, ShlObj, Windows;
var
uPtListDfltSort: string = ''; // Current user's patient selection list default sort order.
{ private calls }
function FormatSSN(const x: string): string;
{ places the dashes in a social security number }
begin
if Length(x) > 8
then Result := Copy(x,1,3) + '-' + Copy(x,4,2) + '-' + Copy(x,6,Length(x))
else Result := x;
end;
function IsSSN(const x: string): Boolean;
var
i: Integer;
begin
Result := False;
if (Length(x) < 9) or (Length(x) > 10) then Exit;
for i := 1 to 9 do if not CharInSet(x[i], ['0'..'9']) then Exit;
Result := True;
end;
function IsFMDate(const x: string): Boolean;
var
i: Integer;
begin
Result := False;
if Length(x) <> 7 then Exit;
for i := 1 to 7 do if not CharInSet(x[i], ['0'..'9']) then Exit;
Result := True;
end;
{ Date/Time functions - not in ORFn because they make server calls to use server time}
function FMToday: TFMDateTime;
{ return the current date in Fileman format }
begin
Result := Int(FMNow);
end;
function FMNow: TFMDateTime;
{ return the current date/time in Fileman format }
var
x: string;
begin
x := sCallV('ORWU DT', ['NOW']);
Result := StrToFloatDef(x, 0.0);
end;
function MakeRelativeDateTime(FMDateTime: TFMDateTime): string;
var
Offset: Integer;
h,n,s,l: Word;
ADateTime: TDateTime;
ATime: string;
begin
Result := '';
if FMDateTime <= 0 then Exit;
ADateTime := FMDateTimeToDateTime(FMDateTime);
Offset := Trunc(Int(ADateTime) - Int(FMDateTimeToDateTime(FMToday)));
if Offset < 0 then Result := 'T' + IntToStr(Offset)
else if Offset = 0 then Result := 'T'
else Result := 'T+' + IntToStr(Offset);
DecodeTime(ADateTime, h, n, s, l);
ATime := Format('@%.2d:%.2d', [h, n]);
if ATime <> '@00:00' then Result := Result + ATime;
end;
function StrToFMDateTime(const AString: string): TFMDateTime;
{ use %DT the validate and convert a string to Fileman format (accepts T, T-1, NOW, etc.) }
var
x: string;
begin
x := sCallV('ORWU DT', [AString]);
Result := StrToFloat(x);
end;
function ValidDateTimeStr(const AString, Flags: string): TFMDateTime;
{ use %DT to validate & convert a string to Fileman format, accepts %DT flags }
begin
Result := StrToFloat(sCallV('ORWU VALDT', [AString, Flags]));
end;
procedure ListDateRangeClinic(Dest: TStrings);
{ returns date ranges for displaying clinic appointments in patient lookup }
begin
CallV('ORWPT CLINRNG', [nil]);
FastAssign(RPCBrokerV.Results, Dest);
end;
function IsDateMoreRecent(Date1: TDateTime; Date2: TDateTime): Boolean;
{ is Date1 more recent than Date2}
begin
if Date1 > Date2 then Result := True
else Result := False;
end;
function DfltDateRangeClinic;
{ returns current default date range settings for displaying clinic appointments in patient lookup }
begin
Result := sCallV('ORQPT DEFAULT CLINIC DATE RANG', [nil]);
end;
{ General calls }
function ExternalName(IEN: Int64; FileNumber: Double): string;
{ returns the external name of the IEN within a file }
begin
Result := sCallV('ORWU EXTNAME', [IEN, FileNumber]);
end;
function PersonHasKey(APerson: Int64; const AKey: string): Boolean;
begin
Result := sCallV('ORWU NPHASKEY', [APerson, AKey]) = '1';
end;
function GlobalRefForFile(const FileID: string): string;
begin
Result := sCallV('ORWU GBLREF', [FileID]);
end;
function SubsetOfGeneric(const StartFrom: string; Direction: Integer; const GlobalRef: string): TStrings;
begin
CallV('ORWU GENERIC', [StartFrom, Direction, GlobalRef]);
Result := RPCBrokerV.Results;
end;
function SubsetOfDevices(const StartFrom: string; Direction: Integer): TStrings;
{ returns a pointer to a list of devices (for use in a long list box) - The return value is
a pointer to RPCBrokerV.Results, so the data must be used BEFORE the next broker call! }
begin
CallV('ORWU DEVICE', [StartFrom, Direction]);
Result := RPCBrokerV.Results;
end;
function SubSetOfPersons(const StartFrom: string; Direction: Integer): TStrings;
{ returns a pointer to a list of persons (for use in a long list box) - The return value is
a pointer to RPCBrokerV.Results, so the data must be used BEFORE the next broker call! }
begin
CallV('ORWU NEWPERS', [StartFrom, Direction]);
// MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results;
end;
{ User specific calls }
function GetUserInfo: TUserInfo;
{ returns a record of user information,
Pieces: DUZ^NAME^USRCLS^CANSIGN^ISPROVIDER^ORDERROLE^NOORDER^DTIME^CNTDN^VERORD^NOTIFYAPPS^
MSGHANG^DOMAIN^SERVICE^AUTOSAVE^INITTAB^LASTTAB^WEBACCESS^ALLOWHOLD^ISRPL^RPLLIST^
CORTABS^RPTTAB^STATION#^GECStatus^Production account?}
var
x: string;
begin
x := sCallV('ORWU USERINFO', [nil]);
with Result do
begin
DUZ := StrToInt64Def(Piece(x, U, 1), 0);
Name := Piece(x, U, 2);
UserClass := StrToIntDef(Piece(x, U, 3), 0);
CanSignOrders := Piece(x, U, 4) = '1';
IsProvider := Piece(x, U, 5) = '1';
OrderRole := StrToIntDef(Piece(x, U, 6), 0);
NoOrdering := Piece(x, U, 7) = '1';
DTIME := StrToIntDef(Piece(x, U, 8), 300);
CountDown := StrToIntDef(Piece(x, U, 9), 10);
EnableVerify := Piece(x, U, 10) = '1';
EnableActOneStep := Piece(x, U, 27) = '0';
NotifyAppsWM := Piece(x, U, 11) = '1';
PtMsgHang := StrToIntDef(Piece(x, U, 12), 5);
Domain := Piece(x, U, 13);
Service := StrToIntDef(Piece(x, U, 14), 0);
AutoSave := StrToIntDef(Piece(x, U, 15), 180);
InitialTab := StrToIntDef(Piece(x, U, 16), 1);
UseLastTab := Piece(x, U, 17) = '1';
WebAccess := Piece(x, U, 18) <> '1';
DisableHold := Piece(x, U, 19) = '1';
IsRPL := Piece(x, U, 20);
RPLList := Piece(x, U, 21);
HasCorTabs := Piece(x, U, 22) = '1';
HasRptTab := Piece(x, U, 23) = '1';
StationNumber := Piece(x, U, 24);
GECStatusCheck := Piece(x, U, 25) = '1';
IsProductionAccount := Piece(x, U, 26) = '1';
IsReportsOnly := false;
if ((HasRptTab) and (not HasCorTabs)) then
IsReportsOnly := true;
// Remove next if and nested if should an "override" later be provided for RPL users,etc.:
if HasCorTabs then
if (IsRPL = '1') then
begin
IsRPL := '0'; // Hard set for now.
IsReportsOnly := false;
end;
// Following hard set to TRUE per VHA mgt decision:
ToolsRptEdit := true;
// x := GetUserParam('ORWT TOOLS RPT SETTINGS OFF');
// if x = '1' then
// ToolsRptEdit := false;
JobNumber := Piece(x, U, 28);
end;
end;
function GetUserParam(const AParamName: string): string;
begin
Result := sCallV('ORWU PARAM', [AParamName]);
end;
procedure GetUserListParam(Dest: TStrings; const AParamName: string);
var
tmplst: TStringList;
begin
tmplst := TStringList.Create;
try
tCallV(tmplst, 'ORWU PARAMS', [AParamName]);
FastAssign(tmplst, Dest);
finally
tmplst.Free;
end;
end;
function HasSecurityKey(const KeyName: string): Boolean;
{ returns true if the currently logged in user has a given security key }
var
x: string;
begin
Result := False;
x := sCallV('ORWU HASKEY', [KeyName]);
if x = '1' then Result := True;
end;
function HasMenuOptionAccess(const OptionName: string): Boolean;
begin
Result := (sCallV('ORWU HAS OPTION ACCESS', [OptionName]) = '1');
end;
function ValidESCode(const ACode: string): Boolean;
{ returns true if the electronic signature code in ACode is valid }
begin
Result := sCallV('ORWU VALIDSIG', [Encrypt(ACode)]) = '1';
end;
//function otherInformationPanelControls: string;
//begin
// Result := sCallV('ORWOTHER SHWOTHER', [USER.DUZ]);
//end;
{ Notifications Calls }
procedure LoadNotifications(Dest: TStrings);
var
tmplst: TStringList;
begin
tmplst := TStringList.Create;
try
//UpdateUnsignedOrderAlerts(Patient.DFN); //moved to AFTER signature and DC actions
tCallV(tmplst, 'ORWORB FASTUSER', [nil]);
FastAssign(tmplst, Dest);
finally
tmplst.Free;
end;
end;
function LoadNotificationLongText(AlertID: string): string;
var
temp: TStringList;
i: Integer;
begin
temp := TStringList.Create();
CallVistA('ORWORB GETLTXT', [AlertID], temp);
Result := ''; //CRLF
for i := 0 to temp.Count - 1 do
begin
Result := Result + temp[i] + CRLF
end;
end;
function IsSmartAlert(notIEN: integer):boolean;
var
temp: string;
begin
temp := sCallV('ORBSMART ISSMNOT',[notIEN]);
Result := temp = '1';
end;
procedure UpdateUnsignedOrderAlerts(PatientDFN: string);
begin
CallV('ORWORB KILL UNSIG ORDERS ALERT',[PatientDFN]);
end;
function UnsignedOrderAlertFollowup(XQAID: string): string;
begin
Result := sCallV('ORWORB UNSIG ORDERS FOLLOWUP',[XQAID]);
end;
procedure UpdateIndOrderAlerts();
begin
if Notifications.IndOrderDisplay then
begin
Notifications.IndOrderDisplay := False;
Notifications.Delete;
end;
end;
procedure UpdateExpiringMedAlerts(PatientDFN: string);
begin
CallV('ORWORB KILL EXPIR MED ALERT',[PatientDFN]);
end;
procedure UpdateExpiringFlaggedOIAlerts(PatientDFN: string; FollowUp: integer);
begin
CallV('ORWORB KILL EXPIR OI ALERT',[PatientDFN, FollowUp]);
end;
procedure UpdateUnverifiedMedAlerts(PatientDFN: string);
begin
CallV('ORWORB KILL UNVER MEDS ALERT',[PatientDFN]);
end;
procedure UpdateUnverifiedOrderAlerts(PatientDFN: string);
begin
CallV('ORWORB KILL UNVER ORDERS ALERT',[PatientDFN]);
end;
procedure AutoUnflagAlertedOrders(PatientDFN, XQAID: string);
begin
CallV('ORWORB AUTOUNFLAG ORDERS',[PatientDFN, XQAID]);
end;
procedure DeleteAlert(XQAID: string);
//deletes an alert
begin
CallV('ORB DELETE ALERT',[XQAID]);
end;
procedure DeleteAlertForUser(XQAID: string);
//deletes an alert
begin
CallV('ORB DELETE ALERT',[XQAID, True]);
end;
procedure ForwardAlert(XQAID: string; Recip: string; FWDtype: string; Comment: string);
// Forwards an alert with comment to Recip[ient]
begin
CallV('ORB FORWARD ALERT', [XQAID, Recip, FWDtype, Comment]);
end;
procedure RenewAlert(XQAID: string);
// Restores/renews an alert
begin
CallV('ORB RENEW ALERT', [XQAID]);
end;
function GetSortMethod: string;
// Returns alert sort method
begin
Result := sCallV('ORWORB GETSORT',[nil]);
end;
procedure SetSortMethod(Sort: string; Direction: string);
// Sets alert sort method for user
begin
CallV('ORWORB SETSORT', [Sort, Direction]);
end;
function GetXQAData(XQAID: string; pFlag: string = ''): string;
// Returns data associated with an alert
begin
Result := sCallV('ORWORB GETDATA',[XQAID, pFlag]);
end;
function GetTIUAlertInfo(XQAID: string): string;
// Returns DFN and document type associated with a TIU alert
begin
Result := sCallV('TIU GET ALERT INFO',[XQAID]);
end;
function GetNotificationFollowUpText(PatientDFN: string; Notification: integer; XQADATA: string): TStrings;
// Returns follow-up text for an alert
begin
CallV('ORWORB TEXT FOLLOWUP', [PatientDFN, Notification, XQADATA]);
Result := RPCBrokerV.Results;
end;
{ Patient List Calls }
function DfltPtList: string;
{ returns the name of the current user's default patient list, null if none is defined
Pieces: Ptr to Source File^Source Name^Source Type }
begin
Result := sCallV('ORQPT DEFAULT LIST SOURCE', [nil]);
if Length(Result) > 0 then Result := Pieces(Result, U, 2, 3);
end;
function DfltPtListSrc: Char;
begin
Result := CharAt(sCallV('ORWPT DFLTSRC', [nil]), 1);
end;
function DefltPtListSrc: string;
{ returns the default pastient list source as string}
// TDP - ADDED 5/28/2014 to handle new possible "E" default list source
begin
Result := sCallV('ORWPT DFLTSRC', [nil]);
end;
procedure SavePtListDflt(const x: string);
begin
CallV('ORWPT SAVDFLT', [x]);
end;
procedure ListSpecialtyAll(Dest: TStrings);
{ lists all treating specialties: IEN^Treating Specialty Name }
begin
CallV('ORQPT SPECIALTIES', [nil]);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListTeamAll(Dest: TStrings);
{ lists all patient care teams: IEN^Team Name }
begin
CallV('ORQPT TEAMS', [nil]);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListPcmmAll(Dest: TStrings);
{ lists all patient care teams: IEN^Team Name }
// TDP - Added 5/27/2014 as part of PCMMR mods
begin
CallV('ORQPT PTEAMPR', [nil]);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListWardAll(Dest: TStrings);
{ lists all active inpatient wards: IEN^Ward Name }
begin
CallV('ORQPT WARDS', [nil]);
//MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListProviderTop(Dest: TStrings);
{ checks parameters for list of commonly selected providers }
begin
end;
function SubSetOfProviders(const StartFrom: string; Direction: Integer): TStrings;
{ returns a pointer to a list of providers (for use in a long list box) - The return value is
a pointer to RPCBrokerV.Results, so the data must be used BEFORE the next broker call! }
begin
CallV('ORWU NEWPERS', [StartFrom, Direction, 'PROVIDER']);
// MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results;
end;
function SubSetOfCosigners(const StartFrom: string; Direction: Integer; Date: TFMDateTime;
ATitle: integer; ADocType: integer): TStrings;
{ returns a pointer to a list of cosigners (for use in a long list box) - The return value is
a pointer to RPCBrokerV.Results, so the data must be used BEFORE the next broker call! }
begin
if ATitle > 0 then ADocType := 0;
// CQ #17218 - Correcting order of parameters for this call - jcs
//CallV('ORWU2 COSIGNER', [StartFrom, Direction, Date, ATitle, ADocType]);
CallV('ORWU2 COSIGNER', [StartFrom, Direction, Date, ADocType, ATitle]);
// MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results;
end;
function SubSetOfProvWithClass(const StartFrom: string; Direction: Integer; DateTime: string): TStrings;
{ returns a pointer to a list of providers (for use in a long list box) - The return value is
a pointer to RPCBrokerV.Results, so the data must be used BEFORE the next broker call! }
begin
CallV('ORWU NEWPERS', [StartFrom, Direction, 'PROVIDER', DateTime]);
MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results;
end;
function SubSetOfUsersWithClass(const StartFrom: string; Direction: Integer; DateTime: string): TStrings;
{ returns a pointer to a list of users (for use in a long list box) - The return value is
a pointer to RPCBrokerV.Results, so the data must be used BEFORE the next broker call! }
begin
CallV('ORWU NEWPERS', [StartFrom, Direction, '', DateTime]);
MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results;
end;
function SubSetOfActiveAndInactivePersons(const StartFrom: string; Direction: Integer): TStrings;
{ returns a pointer to a list of users (for use in a long list box) - The return value is
a pointer to RPCBrokerV.Results, so the data must be used BEFORE the next broker call!}
begin
CallV('ORWU NEWPERS', [StartFrom, Direction, '', '', '', True]); //TRUE = return all active and inactive users
MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results;
end;
procedure ListClinicTop(Dest: TStrings);
{ checks parameters for list of commonly selected clinics }
begin
end;
function SubSetOfClinics(const StartFrom: string; Direction: Integer): TStrings;
{ returns a pointer to a list of clinics (for use in a long list box) - The return value is
a pointer to RPCBrokerV.Results, so the data must be used BEFORE the next broker call! }
begin
CallV('ORWU CLINLOC', [StartFrom, Direction]);
MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results;
end;
function GetDfltSort: string;
{ Assigns uPtLstDfltSort to user's default patient list sort order (string character).}
begin
uPtListDfltSort := sCallV('ORQPT DEFAULT LIST SORT', [nil]);
if uPtListDfltSort = '' then uPtListDfltSort := 'A'; // Default is always "A" for alpha.
result := uPtListDfltSort;
end;
procedure ResetDfltSort;
begin
uPtListDfltSort := '';
end;
procedure ListPtByDflt(Dest: TStrings);
{ loads the default patient list into Dest, Pieces: DFN^PATIENT NAME, ETC. }
var
i, SourceType: Integer;
ATime, APlace, Sort, Source, x: string;
tmplst: TORStringList;
begin
Sort := GetDfltSort();
tmplst := TORStringList.Create;
try
tCallV(tmplst, 'ORQPT DEFAULT PATIENT LIST', [nil]);
Source := sCallV('ORWPT DFLTSRC', [nil]);
if Source = 'C' then // Clinics.
begin
if Sort = 'P' then // "Appointments" sort.
SortByPiece(tmplst, U, 4)
else
SortByPiece(tmplst, U, 2);
for i := 0 to tmplst.Count - 1 do
begin
x := tmplst[i];
ATime := Piece(x, U, 4);
APlace := Piece(x, U, 3);
ATime := FormatFMDateTime('hh:nn mmm dd, yyyy', MakeFMDateTime(ATime));
SetPiece(x, U, 3, ATime);
x := x + U + APlace;
tmplst[i] := x;
end;
end
else
begin
SourceType := 0; // Default.
if Source = 'M' then SourceType := 1; // Combinations.
if Source = 'W' then SourceType := 2; // Wards.
case SourceType of
1 : if Sort = 'S' then tmplst.SortByPieces([3, 8, 2]) // "Source" sort.
else if Sort = 'P' then tmplst.SortByPieces([8, 2]) // "Appointment" sort.
else if Sort = 'T' then SortByPiece(tmplst, U, 5) // "Terminal Digit" sort.
else SortByPiece(tmplst, U, 2); // "Alphabetical" (also the default) sort.
2 : if Sort = 'R' then tmplst.SortByPieces([3, 2])
else SortByPiece(tmplst, U, 2);
else SortByPiece(tmplst, U, 2);
end;
end;
MixedCaseList(tmplst);
FastAssign(tmplst, Dest);
finally
tmplst.Free;
end;
end;
procedure ListPtByProvider(Dest: TStrings; ProviderIEN: Int64);
{ lists all patients associated with a given provider: DFN^Patient Name }
begin
CallV('ORQPT PROVIDER PATIENTS', [ProviderIEN]);
SortByPiece(TStringList(RPCBrokerV.Results), U, 2);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListPtByTeam(Dest: TStrings; TeamIEN: Integer);
{ lists all patients associated with a given team: DFN^Patient Name }
begin
CallV('ORQPT TEAM PATIENTS', [TeamIEN]);
SortByPiece(TStringList(RPCBrokerV.Results), U, 2);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListPtByPcmmTeam(Dest: TStrings; TeamIEN: Integer);
{ lists all patients associated with a given PCMM team: DFN^Patient Name }
// TDP - Added 5/23/2014
begin
CallV('ORQPT PTEAM PATIENTS', [TeamIEN]);
SortByPiece(TStringList(RPCBrokerV.Results), U, 2);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListPtBySpecialty(Dest: TStrings; SpecialtyIEN: Integer);
{ lists all patients associated with a given specialty: DFN^Patient Name }
begin
CallV('ORQPT SPECIALTY PATIENTS', [SpecialtyIEN]);
SortByPiece(TStringList(RPCBrokerV.Results), U, 2);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListPtByClinic(Dest: TStrings; ClinicIEN: Integer; FirstDt, LastDt: string); //TFMDateTime);
{ lists all patients associated with a given clinic: DFN^Patient Name^App't }
var
i: Integer;
x, ATime, APlace, Sort: string;
begin
Sort := GetDfltSort();
CallV('ORQPT CLINIC PATIENTS', [ClinicIEN, FirstDt, LastDt]);
with RPCBrokerV do
begin
if Sort = 'P' then
SortByPiece(TStringList(Results), U, 4)
else
SortByPiece(TStringList(Results), U, 2);
for i := 0 to Results.Count - 1 do
begin
x := Results[i];
ATime := Piece(x, U, 4);
APlace := Piece(x, U, 3);
ATime := FormatFMDateTime('hh:nn mmm dd, yyyy', MakeFMDateTime(ATime));
SetPiece(x, U, 3, ATime);
x := x + U + APlace;
Results[i] := x;
end;
MixedCaseList(Results);
FastAssign(Results, Dest);
end;
end;
procedure ListPtByWard(Dest: TStrings; WardIEN: Integer);
{ lists all patients associated with a given ward: DFN^Patient Name^Room/Bed }
var
Sort: string;
begin
Sort := GetDfltSort();
CallV('ORWPT BYWARD', [WardIEN]);
if Sort = 'R' then
SortByPiece(TStringList(RPCBrokerV.Results), U, 3)
else
SortByPiece(TStringList(RPCBrokerV.Results), U, 2);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListPtByLast5(Dest: TStrings; const Last5: string);
var
i: Integer;
x, ADate, AnSSN: string;
begin
{ Lists all patients found in the BS and BS5 xrefs that match Last5: DFN^Patient Name }
CallV('ORWPT LAST5', [UpperCase(Last5)]);
SortByPiece(TStringList(RPCBrokerV.Results), U, 2);
with RPCBrokerV do for i := 0 to Results.Count - 1 do
begin
x := Results[i];
ADate := Piece(x, U, 3);
AnSSN := Piece(x, U, 4);
if IsFMDate(ADate) then ADate := FormatFMDateTimeStr('mmm d, yyyy', ADate);
if IsSSN(AnSSN) then AnSSN := FormatSSN(AnSSN);
SetPiece(x, U, 3, AnSSN + ' ' + ADate);
Results[i] := x;
end;
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListPtByRPLLast5(Dest: TStrings; const Last5: string);
var
i: Integer;
x, ADate, AnSSN: string;
begin
{ Lists patients from RPL list that match Last5: DFN^Patient Name }
CallV('ORWPT LAST5 RPL', [UpperCase(Last5)]);
SortByPiece(TStringList(RPCBrokerV.Results), U, 2);
with RPCBrokerV do for i := 0 to Results.Count - 1 do
begin
x := Results[i];
ADate := Piece(x, U, 3);
AnSSN := Piece(x, U, 4);
if IsFMDate(ADate) then ADate := FormatFMDateTimeStr('mmm d, yyyy', ADate);
if IsSSN(AnSSN) then AnSSN := FormatSSN(AnSSN);
SetPiece(x, U, 3, AnSSN + ' ' + ADate);
Results[i] := x;
end;
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListPtByFullSSN(Dest: TStrings; const FullSSN: string);
{ lists all patients found in the SSN xref that match FullSSN: DFN^Patient Name }
var
i: integer;
x, ADate, AnSSN: string;
begin
x := FullSSN;
i := Pos('-', x);
while i > 0 do
begin
x := Copy(x, 1, i-1) + Copy(x, i+1, 12);
i := Pos('-', x);
end;
CallV('ORWPT FULLSSN', [UpperCase(x)]);
SortByPiece(TStringList(RPCBrokerV.Results), U, 2);
with RPCBrokerV do for i := 0 to Results.Count - 1 do
begin
x := Results[i];
ADate := Piece(x, U, 3);
AnSSN := Piece(x, U, 4);
if IsFMDate(ADate) then ADate := FormatFMDateTimeStr('mmm d, yyyy', ADate);
if IsSSN(AnSSN) then AnSSN := FormatSSN(AnSSN);
SetPiece(x, U, 3, AnSSN + ' ' + ADate);
Results[i] := x;
end;
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListPtByRPLFullSSN(Dest: TStrings; const FullSSN: string);
{ lists all patients found in the SSN xref that match FullSSN: DFN^Patient Name }
var
i: integer;
x, ADate, AnSSN: string;
begin
x := FullSSN;
i := Pos('-', x);
while i > 0 do
begin
x := Copy(x, 1, i-1) + Copy(x, i+1, 12);
i := Pos('-', x);
end;
CallV('ORWPT FULLSSN RPL', [UpperCase(x)]);
SortByPiece(TStringList(RPCBrokerV.Results), U, 2);
with RPCBrokerV do for i := 0 to Results.Count - 1 do
begin
x := Results[i];
ADate := Piece(x, U, 3);
AnSSN := Piece(x, U, 4);
if IsFMDate(ADate) then ADate := FormatFMDateTimeStr('mmm d, yyyy', ADate);
if IsSSN(AnSSN) then AnSSN := FormatSSN(AnSSN);
SetPiece(x, U, 3, AnSSN + ' ' + ADate);
Results[i] := x;
end;
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure ListPtTop(Dest: TStrings);
{ currently returns the last patient selected }
begin
CallV('ORWPT TOP', [nil]);
MixedCaseList(RPCBrokerV.Results);
FastAssign(RPCBrokerV.Results, Dest);
end;
function SubSetOfPatients(const StartFrom: string; Direction: Integer): TStrings;
{ returns a pointer to a list of patients (for use in a long list box) - The return value is
a pointer to RPCBrokerV.Results, so the data must be used BEFORE the next broker call! }
begin
CallV('ORWPT LIST ALL', [StartFrom, Direction]);
MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results;
end;
function MakeRPLPtList(RPLList: string): string;
{ Creates "RPL" Restricted Patient List based on Team List info in user's record. }
begin
result := sCallV('ORQPT MAKE RPL', [RPLList]);
end;
function ReadRPLPtList(RPLJobNumber: string; const StartFrom: string; Direction: Integer) : TStrings;
{ returns a pointer to a list of patients (for use in a long list box) - The return value is
a pointer to RPCBrokerV.Results, so the data must be used BEFORE the next broker call! }
begin
CallV('ORQPT READ RPL', [RPLJobNumber, StartFrom, Direction]);
MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results;
end;
procedure KillRPLPtList(RPLJobNumber: string);
begin
CallV('ORQPT KILL RPL', [RPLJobNumber]);
end;
{ Patient Specific Calls }
function CalcAge(BirthDate, DeathDate: TFMDateTime): Integer;
{ calculates age based on today's date and a birthdate (in Fileman format) }
begin
if (DeathDate > BirthDate) then
Result := Trunc(DeathDate - BirthDate) div 10000
else
Result := Trunc(FMToday - BirthDate) div 10000
end;
procedure CheckSensitiveRecordAccess(const DFN: string; var AccessStatus: Integer;
var MessageText: string);
begin
CallV('DG SENSITIVE RECORD ACCESS', [DFN]);
AccessStatus := -1;
MessageText := '';
with RPCBrokerV do
begin
if Results.Count > 0 then
begin
AccessStatus := StrToIntDef(Results[0], -1);
Results.Delete(0);
if Results.Count > 0 then MessageText := Results.Text;
end;
end;
end;
procedure CheckRemotePatient(var Dest: string; Patient, ASite: string; var AccessStatus: Integer);
begin
CallV('XWB DIRECT RPC', [ASite, 'ORWCIRN RESTRICT', 0, Patient]);
AccessStatus := -1;
Dest := '';
with RPCBrokerV do
begin
if Results.Count > 0 then
begin
if Results[0] = '' then Results.Delete(0);
end;
if Results.Count > 0 then
begin
if (length(piece(Results[0],'^',2)) > 0) and ((StrToIntDef(piece(Results[0],'^',1),0) = -1)) then
begin
AccessStatus := -1;
Dest := piece(Results[0],'^',2);
end
else
begin
AccessStatus := StrToIntDef(Results[0], -1);
Results.Delete(0);
if Results.Count > 0 then Dest := Results.Text;
end;
end;
end;
end;
procedure CurrentLocationForPatient(const DFN: string; var ALocation: Integer; var AName: string; var ASvc: string);
var
x: string;
begin
x := sCallV('ORWPT INPLOC', [DFN]);
ALocation := StrToIntDef(Piece(x, U, 1), 0);
AName := Piece(x, U, 2);
ASvc := Piece(x, U, 3);
end;
function DateOfDeath(const DFN: string): TFMDateTime;
{ returns 0 or the date a patient died }
begin
Result := MakeFMDateTime(sCallV('ORWPT DIEDON', [DFN]));
end;
function GetPtIDInfo(const DFN: string): TPtIDInfo; //*DFN*
{ returns the identifiers displayed upon patient selection
Pieces: SSN[1]^DOB[2]^SEX[3]^VET[4]^SC%[5]^WARD[6]^RM-BED[7]^NAME[8] }
var
x: string;
begin
x := sCallV('ORWPT ID INFO', [DFN]);
with Result do // map string into TPtIDInfo record
begin
Name := MixedCase(Piece(x, U, 8)); // Name
SSN := Piece(x, U, 1);
DOB := Piece(x, U, 2);
Age := '';
if IsSSN(SSN) then SSN := FormatSSN(Piece(x, U, 1)); // SSN (PID)
if IsFMDate(DOB) then DOB := FormatFMDateTimeStr('mmm dd,yyyy', DOB); // Date of Birth
//Age := IntToStr(CalcAge(MakeFMDateTime(Piece(x, U, 2)))); // Age
Sex := Piece(x, U, 3); // Sex
if Length(Sex) = 0 then Sex := 'U';
case Sex[1] of
'F','f': Sex := 'Female';
'M','m': Sex := 'Male';
else Sex := 'Unknown';
end;
if Piece(x, U, 4) = 'Y' then Vet := 'Veteran' else Vet := ''; // Veteran?
if Length(Piece(x, U, 5)) > 0 // % Service Connected
then SCSts := Piece(x, U, 5) + '% Service Connected'
else SCSts := '';
Location := Piece(x, U, 6); // Inpatient Location
RoomBed := Piece(x, U, 7); // Inpatient Room-Bed
end;
end;
function HasLegacyData(const DFN: string; var AMsg: string): Boolean;
var
i: Integer;
begin
Result := False;
AMsg := '';
CallV('ORWPT LEGACY', [DFN]);
with RPCBrokerV do if Results.Count > 0 then
begin
Result := Results[0] = '1';
for i := 1 to Results.Count - 1 do AMsg := AMsg + Results[i] + CRLF;
end;
end;
function LogSensitiveRecordAccess(const DFN: string): Boolean;
begin
Result := sCallV('DG SENSITIVE RECORD BULLETIN', [DFN]) = '1';
end;
function MeansTestRequired(const DFN: string; var AMsg: string): Boolean;
var
i: Integer;
begin
Result := False;
AMsg := '';
CallV('DG CHK PAT/DIV MEANS TEST', [DFN]);
with RPCBrokerV do if Results.Count > 0 then
begin
Result := Results[0] = '1';
for i := 1 to Results.Count - 1 do AMsg := AMsg + Results[i] + CRLF;
end;
end;
function RestrictedPtRec(const DFN: string): Boolean; //*DFN*
{ returns true if the record for a patient identified by DFN is restricted }
begin
Result := Piece(sCallV('ORWPT SELCHK', [DFN]), U, 1) = '1';
end;
procedure SelectPatient(const DFN: string; var PtSelect: TPtSelect); //*DFN*
{ selects the patient (updates DISV, calls Pt Select actions) & returns key fields
Pieces: NAME[1]^SEX[2]^DOB[3]^SSN[4]^LOCIEN[5]^LOCNAME[6]^ROOMBED[7]^CWAD[8]^SENSITIVE[9]^
ADMITTIME[10]^CONVERTED[11]^SVCONN[12]^SC%[13]^ICN[14]^Age[15]^TreatSpec[16] }
var
x: string;
begin
CallVista('ORWPT SELECT', [DFN], x);
with PtSelect do
begin
Name := Piece(x, U, 1);
ICN := Piece(x, U, 14);
SSN := FormatSSN(Piece(x, U, 4));
DOB := MakeFMDateTime(Piece(x, U, 3));
Age := StrToIntDef(Piece(x, U, 15), 0);
//Age := CalcAge(DOB, DateOfDeath(DFN));
if Length(Piece(x, U, 2)) > 0 then Sex := Piece(x, U, 2)[1] else Sex := 'U';
LocationIEN := StrToIntDef(Piece(x, U, 5), 0);
Location := Piece(x, U, 6);
RoomBed := Piece(x, U, 7);
SpecialtyIEN := StrToIntDef(Piece(x, U, 16), 0);
SpecialtySvc := Piece(x, U, 17);
CWAD := Piece(x, U, 8);
Restricted := Piece(x, U, 9) = '1';
AdmitTime := MakeFMDateTime(Piece(x, U, 10));
ServiceConnected := Piece(x, U, 12) = '1';
SCPercent := StrToIntDef(Piece(x, U, 13), 0);
end;
CallVistA('ORWPT1 PRCARE', [DFN], x);
with PtSelect do
begin
PrimaryTeam := Piece(x, U, 1);
PrimaryProvider := Piece(x, U, 2);
Associate := Piece(x, U, 4);
MHTC := Piece(x, U, 5);
if Length(Location) > 0 then
begin
Attending := Piece(x, U, 3);
InProvider := Piece(x, U, 6);
CallVistA('ORWPT INPLOC', [DFN], x);
WardService := Piece(x, U, 3);
end;
end;
end;
function GetVAAData(const DFN: string; aList: TStrings): Boolean;
begin
aList.Clear;
Result := CallVistA('ORVAA VAA', [DFN], aList);
end;
function GetMHVData(const DFN: string; aList: TStrings): Boolean;
begin
aList.Clear;
Result := CallVistA('ORWMHV MHV', [DFN], aList);
end;
function SimilarRecordsFound(const DFN: string; var AMsg: string): Boolean;
begin
Result := False;
AMsg := '';
CallV('DG CHK BS5 XREF Y/N', [DFN]);
with RPCBrokerV do if Results.Count > 0 then
begin
Result := Results[0] = '1';
Results.Delete(0);
AMsg := Results.Text;
end;
(*
CallV('DG CHK BS5 XREF ARRAY', [DFN]);
with RPCBrokerV do if Results.Count > 0 then
begin
Result := Results[0] = '1';
for i := 1 to Results.Count - 1 do
begin
if Piece(Results[i], U, 1) = '0' then AMsg := AMsg + Copy(Results[i], 3, Length(Results[i])) + CRLF;
if Piece(Results[i], U, 1) = '1' then AMsg := AMsg + Piece(Results[i], U, 3) + #9 +
FormatFMDateTimeStr('mmm dd,yyyy', Piece(Results[i], U, 4)) + #9 + Piece(Results[i], U, 5) + CRLF;
end;
end;
*)
end;
function GetDFNFromICN(AnICN: string): string;
begin
Result := Piece(sCallV('VAFCTFU CONVERT ICN TO DFN', [AnICN]), U, 1);
end;
function otherInformationPanel(const DFN: string): string;
begin
// result := sCallV('ORWPT2 COVID', [DFN]);
CallVistA('ORWPT2 COVID', [DFN], result);
end;
procedure otherInformationPanelDetails(const DFN: string; valueType: string; var details: TStrings);
begin
CallVistA('ORWOTHER DETAIL', [dfn, valueType], details);
// FastAssign(RPCBrokerV.Results, details);
end;
{ Encounter specific calls }
function GetEncounterText(const DFN: string; Location: integer; Provider: Int64): TEncounterText; //*DFN*
{ returns resolved external values Pieces: LOCNAME[1]^PROVNAME[2]^ROOMBED[3] }
var
x: string;
begin
x := sCallV('ORWPT ENCTITL', [DFN, Location, Provider]);
with Result do
begin
LocationName := Piece(x, U, 1);
LocationAbbr := Piece(x, U, 2);
RoomBed := Piece(x, U, 3);
ProviderName := Piece(x, U, 4);
// ProviderName := sCallV('ORWU1 NAMECVT', [Provider]);
end;
end;
function GetActiveICDVersion(ADate: TFMDateTime = 0): String;
begin
Result := sCallV('ORWPCE ICDVER', [ADate]);
end;
function GetICD10ImplementationDate: TFMDateTime;
var
impDt: String;
begin
impDt := sCallV('ORWPCE I10IMPDT', [nil]);
if impDt <> '' then
Result := StrToFMDateTime(impDt)
else
Result := 3141001; //Default to 10/01/2014
end;
procedure ListApptAll(Dest: TStrings; const DFN: string; From: TFMDateTime = 0;
Thru: TFMDateTime = 0);
{ lists appts/visits for a patient (uses same call as cover sheet)
V|A;DateTime;LocIEN^DateTime^LocName^Status }
const
SKIP_ADMITS = 1;
begin
CallV('ORWCV VST', [Patient.DFN, From, Thru, SKIP_ADMITS]);
with RPCBrokerV do
begin
InvertStringList(TStringList(Results));
MixedCaseList(Results);
SetListFMDateTime('mmm dd,yyyy hh:nn', TStringList(Results), U, 2);
FastAssign(Results, Dest);
end;
(*
CallV('ORWPT APPTLST', [DFN]);
with RPCBrokerV do
begin
SortByPiece(TStringList(Results), U, 1);
InvertStringList(TStringList(Results));
for i := 0 to Results.Count - 1 do
begin
x := Results[i];
ATime := Piece(x, U, 1);
ATime := FormatFMDateTime('mmm dd, yyyy hh:nn', MakeFMDateTime(ATime));
SetPiece(x, U, 5, ATime);
Results[i] := x;
end;
FastAssign(Results, Dest);
end;
*)
end;
procedure ListAdmitAll(Dest: TStrings; const DFN: string); //*DFN*
{ lists all admissions for a patient: MovementTime^LocIEN^LocName^Type }
var
i: Integer;
ATime, x: string;
begin
CallV('ORWPT ADMITLST', [DFN]);
with RPCBrokerV do
begin
for i := 0 to Results.Count - 1 do
begin
x := Results[i];
ATime := Piece(x, U, 1);
ATime := FormatFMDateTime('mmm dd, yyyy hh:nn', MakeFMDateTime(ATime));
SetPiece(x, U, 5, ATime);
Results[i] := x;
end;
FastAssign(Results, Dest);
end;
end;
function SubSetOfLocations(const StartFrom: string; Direction: Integer): TStrings;
{ returns a pointer to a list of locations (for use in a long list box) - The return value is
a pointer to RPCBrokerV.Results, so the data must be used BEFORE the next broker call! }
begin
CallV('ORWU HOSPLOC', [StartFrom, Direction]);
Result := RPCBrokerV.Results;
end;
function SubSetOfNewLocs(const StartFrom: string; Direction: Integer): TStrings;
{ Returns a pointer to a list of locations (for use in a long list box) - the return value is
a pointer to RPCBrokerV.Results, so the data must be used BEFORE the next broker call!
Filtered by C, W, and Z types - i.e., Clinics, Wards, and "Other" type locations.}
begin
CallV('ORWU1 NEWLOC', [StartFrom, Direction]);
Result := RPCBrokerV.Results;
end;
function SubSetOfInpatientLocations(const StartFrom: string; Direction: Integer): TStrings;
{ returns a pointer to a list of locations (for use in a long list box) - The return value is
a pointer to RPCBrokerV.Results, so the data must be used BEFORE the next broker call! }
begin
CallV('ORWU INPLOC', [StartFrom, Direction]);
Result := RPCBrokerV.Results;
end;
{ Remote Data Access calls }
function HasRemoteData(const DFN: string; var ALocations: TStringList): Boolean;
begin
CallV('ORWCIRN FACLIST', [DFN]);
FastAssign(RPCBrokerV.Results, ALocations);
Result := not (Piece(RPCBrokerV.Results[0], U, 1) = '-1');
// '-1^NO DFN'
// '-1^PATIENT NOT IN DATABASE'
// '-1^NO MPI Node'
// '-1^NO ICN'
// '-1^Parameter missing.'
// '-1^No patient DFN.'
// '-1^Could not find Treating Facilities'
// '-1^Remote access not allowed' <===parameter ORWCIRN REMOTE DATA ALLOW
end;
function CheckHL7TCPLink: Boolean;
begin
CallV('ORWCIRN CHECKLINK',[nil]);
Result := RPCBrokerV.Results[0] = '1';
end;
function GetVistaWebAddress(value: string): string;
begin
CallV('ORWCIRN WEBADDR', [value]);
result := RPCBrokerV.Results[0];
end;
function GetVistaWeb_JLV_LabelName: string;
begin
result := sCallV('ORWCIRN JLV LABEL', [nil]);
end;
function GetDefaultPrinter(DUZ: Int64; Location: integer): string;
begin
Result := sCallV('ORWRP GET DEFAULT PRINTER', [DUZ, Location]) ;
end;
procedure getSysUserParameters(DUZ: Int64);
var
aReturn: string;
begin
systemParameters := TsystemParameters.Create;
try
CallVistA('ORWU SYSPARAM', [DUZ], aReturn);
systemParameters.dataValues := TJSONObject.ParseJSONValue(aReturn);
finally
end;
end;
end.
|
program Sample;
var
f, t :BOOLEAN;
begin
WriteLn('FALSE: ', FALSE);
WriteLn('TRUE: ', TRUE);
f := FALSE;
WriteLn('f: ', f);
t := TRUE;
WriteLn('t: ', t);
end.
|
unit myclock;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls;
type
{ Uhr }
Uhr = class
private
sekunde, minute, stunde : integer;
public
procedure incSek();
procedure incMin();
procedure incStd();
constructor create();
property sek : integer read sekunde;
property min : integer read minute;
property std : integer read stunde;
end;
{ TClockForm }
TClockForm = class(TForm)
lblStd: TLabel;
lblMin: TLabel;
lblSek: TLabel;
lblDoppelpunkt1: TLabel;
lblDoppelpunkt2: TLabel;
clockPanel: TPanel;
Timer1: TTimer;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure zeigeUhrzeit();
private
{ private declarations }
public
{ public declarations }
end;
var
ClockForm: TClockForm;
u : Uhr;
function czero(val: integer) : string;
implementation
function czero(val: integer) : string;
begin
result := IntToStr(val);
if val < 10 then
result := '0'+IntToStr(val);
end;
{$R *.lfm}
{ TClockForm }
procedure TClockForm.zeigeUhrzeit;
begin
lblMin.caption := czero(u.min);
lblSek.caption := czero(u.sek);
lblStd.caption := czero(u.std);
u.incSek;
end;
procedure TClockForm.FormCreate(Sender: TObject);
begin
u := Uhr.create();
end;
procedure TClockForm.Button1Click(Sender: TObject);
begin
timer1.Enabled:= true;
end;
procedure TClockForm.FormDestroy(Sender: TObject);
begin
u.Free;
end;
procedure TClockForm.Timer1Timer(Sender: TObject);
begin
ClockForm.zeigeUhrzeit();
end;
{ Uhr }
procedure Uhr.incSek;
begin
if (sekunde >= 0) and (sekunde < 59) then
begin
inc(sekunde);
end
else
begin
sekunde := 0;
incMin();
end;
end;
procedure Uhr.incMin;
begin
if (minute >= 0) and (minute < 59) then
begin
inc(minute);
end
else
begin
minute := 0;
incStd();
end;
end;
procedure Uhr.incStd;
begin
if (stunde >= 0) and (stunde < 99) then
begin
inc(stunde);
end
else
begin
stunde := 0;
end;
end;
constructor Uhr.create;
begin
sekunde := 0;
minute := 0;
stunde := 0;
end;
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is ArraySet.pas. }
{ }
{ The Initial Developer of the Original Code is Jean-Philippe BEMPEL aka RDM. Portions created by }
{ Jean-Philippe BEMPEL are Copyright (C) Jean-Philippe BEMPEL (rdm_30 att yahoo dott com) }
{ All rights reserved. }
{ }
{ Contributors: }
{ Florent Ouchet (outchy) }
{ }
{**************************************************************************************************}
{ }
{ The Delphi Container Library }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $ }
{ Revision: $Rev:: 2376 $ }
{ Author: $Author:: obones $ }
{ }
{**************************************************************************************************}
unit JclArraySets;
{$I jcl.inc}
interface
uses
Classes,
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
{$IFDEF SUPPORTS_GENERICS}
{$IFDEF CLR}
System.Collections.Generic,
{$ENDIF CLR}
JclAlgorithms,
{$ENDIF SUPPORTS_GENERICS}
JclBase, JclAbstractContainers, JclContainerIntf, JclArrayLists, JclSynch;
{$I containers\JclContainerCommon.imp}
{$I containers\JclArraySets.int}
{$I containers\JclArraySets.imp}
type
(*$JPPEXPANDMACRO JCLARRAYSETINT(TJclIntfArraySet,TJclIntfArrayList,IJclIntfCollection,IJclIntfList,IJclIntfArray,IJclIntfSet, IJclIntfEqualityComparer\, IJclIntfComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,const ,AInterface,IInterface)*)
(*$JPPEXPANDMACRO JCLARRAYSETINT(TJclAnsiStrArraySet,TJclAnsiStrArrayList,IJclAnsiStrCollection,IJclAnsiStrList,IJclAnsiStrArray,IJclAnsiStrSet, IJclStrContainer\, IJclAnsiStrContainer\, IJclAnsiStrFlatContainer\, IJclAnsiStrEqualityComparer\, IJclAnsiStrComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,, override;,const ,AString,AnsiString)*)
(*$JPPEXPANDMACRO JCLARRAYSETINT(TJclWideStrArraySet,TJclWideStrArrayList,IJclWideStrCollection,IJclWideStrList,IJclWideStrArray,IJclWideStrSet, IJclStrContainer\, IJclWideStrContainer\, IJclWideStrFlatContainer\, IJclWideStrEqualityComparer\, IJclWideStrComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,, override;,const ,AString,WideString)*)
{$IFDEF CONTAINER_ANSISTR}
TJclStrArraySet = TJclAnsiStrArraySet;
{$ENDIF CONTAINER_ANSISTR}
{$IFDEF CONTAINER_WIDESTR}
TJclStrArraySet = TJclWideStrArraySet;
{$ENDIF CONTAINER_WIDESTR}
(*$JPPEXPANDMACRO JCLARRAYSETINT(TJclSingleArraySet,TJclSingleArrayList,IJclSingleCollection,IJclSingleList,IJclSingleArray,IJclSingleSet, IJclSingleContainer\, IJclSingleEqualityComparer\, IJclSingleComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,const ,AValue,Single)*)
(*$JPPEXPANDMACRO JCLARRAYSETINT(TJclDoubleArraySet,TJclDoubleArrayList,IJclDoubleCollection,IJclDoubleList,IJclDoubleArray,IJclDoubleSet, IJclDoubleContainer\, IJclDoubleEqualityComparer\, IJclDoubleComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,const ,AValue,Double)*)
(*$JPPEXPANDMACRO JCLARRAYSETINT(TJclExtendedArraySet,TJclExtendedArrayList,IJclExtendedCollection,IJclExtendedList,IJclExtendedArray,IJclExtendedSet, IJclExtendedContainer\, IJclExtendedEqualityComparer\, IJclExtendedComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,const ,AValue,Extended)*)
{$IFDEF MATH_EXTENDED_PRECISION}
TJclFloatArraySet = TJclExtendedArraySet;
{$ENDIF MATH_EXTENDED_PRECISION}
{$IFDEF MATH_DOUBLE_PRECISION}
TJclFloatArraySet = TJclDoubleArraySet;
{$ENDIF MATH_DOUBLE_PRECISION}
{$IFDEF MATH_SINGLE_PRECISION}
TJclFloatArraySet = TJclSingleArraySet;
{$ENDIF MATH_SINGLE_PRECISION}
(*$JPPEXPANDMACRO JCLARRAYSETINT(TJclIntegerArraySet,TJclIntegerArrayList,IJclIntegerCollection,IJclIntegerList,IJclIntegerArray,IJclIntegerSet, IJclIntegerEqualityComparer\, IJclIntegerComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,AValue,Integer)*)
(*$JPPEXPANDMACRO JCLARRAYSETINT(TJclCardinalArraySet,TJclCardinalArrayList,IJclCardinalCollection,IJclCardinalList,IJclCardinalArray,IJclCardinalSet, IJclCardinalEqualityComparer\, IJclCardinalComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,AValue,Cardinal)*)
(*$JPPEXPANDMACRO JCLARRAYSETINT(TJclInt64ArraySet,TJclInt64ArrayList,IJclInt64Collection,IJclInt64List,IJclInt64Array,IJclInt64Set, IJclInt64EqualityComparer\, IJclInt64Comparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,const ,AValue,Int64)*)
{$IFNDEF CLR}
(*$JPPEXPANDMACRO JCLARRAYSETINT(TJclPtrArraySet,TJclPtrArrayList,IJclPtrCollection,IJclPtrList,IJclPtrArray,IJclPtrSet, IJclPtrEqualityComparer\, IJclPtrComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,APtr,Pointer)*)
{$ENDIF ~CLR}
(*$JPPEXPANDMACRO JCLARRAYSETINT(TJclArraySet,TJclArrayList,IJclCollection,IJclList,IJclArray,IJclSet, IJclObjectOwner\, IJclEqualityComparer\, IJclComparer\,,,
function CreateEmptyContainer: TJclAbstractContainerBase; override;,,,,AObject,TObject)*)
{$IFDEF SUPPORTS_GENERICS}
(*$JPPEXPANDMACRO JCLARRAYSETINT(TJclArraySet<T>,TJclArrayList<T>,IJclCollection<T>,IJclList<T>,IJclArray<T>,IJclSet<T>, IJclItemOwner<T>\, IJclEqualityComparer<T>\, IJclComparer<T>\,,,,,,const ,AItem,T)*)
// E = External helper to compare items
TJclArraySetE<T> = class(TJclArraySet<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclPackable, IJclGrowable, IJclContainer, IJclItemOwner<T>, IJclEqualityComparer<T>, IJclComparer<T>,
IJclCollection<T>, IJclList<T>, IJclArray<T>, IJclSet<T>)
private
FComparer: IComparer<T>;
protected
procedure AssignPropertiesTo(Dest: TJclAbstractContainerBase); override;
function ItemsCompare(const A, B: T): Integer; override;
function ItemsEqual(const A, B: T): Boolean; override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(const AComparer: IComparer<T>; ACapacity: Integer; AOwnsItems: Boolean); overload;
constructor Create(const AComparer: IComparer<T>; const ACollection: IJclCollection<T>; AOwnsItems: Boolean); overload;
property Comparer: IComparer<T> read FComparer write FComparer;
end;
// F = Function to compare items
TJclArraySetF<T> = class(TJclArraySet<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclPackable, IJclGrowable, IJclContainer, IJclItemOwner<T>, IJclEqualityComparer<T>, IJclComparer<T>,
IJclCollection<T>, IJclList<T>, IJclArray<T>, IJclSet<T>)
protected
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
public
constructor Create(const ACompare: TCompare<T>; ACapacity: Integer; AOwnsItems: Boolean); overload;
constructor Create(const ACompare: TCompare<T>; const ACollection: IJclCollection<T>; AOwnsItems: Boolean); overload;
end;
// I = Items can compare themselves to others
TJclArraySetI<T: IComparable<T>> = class(TJclArraySet<T>, {$IFDEF THREADSAFE} IJclLockable, {$ENDIF THREADSAFE}
IJclIntfCloneable, IJclCloneable, IJclPackable, IJclGrowable, IJclContainer, IJclItemOwner<T>, IJclEqualityComparer<T>, IJclComparer<T>,
IJclCollection<T>, IJclList<T>, IJclArray<T>, IJclSet<T>)
protected
function ItemsCompare(const A, B: T): Integer; override;
function ItemsEqual(const A, B: T): Boolean; override;
function CreateEmptyContainer: TJclAbstractContainerBase; override;
{ IJclCloneable }
function IJclCloneable.Clone = ObjectClone;
{ IJclIntfCloneable }
function IJclIntfCloneable.Clone = IntfClone;
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL: https://jcl.svn.sourceforge.net:443/svnroot/jcl/tags/JCL-1.102-Build3072/jcl/source/prototypes/JclArraySets.pas $';
Revision: '$Revision: 2376 $';
Date: '$Date: 2008-06-05 15:35:37 +0200 (jeu., 05 juin 2008) $';
LogPath: 'JCL\source\common'
);
{$ENDIF UNITVERSIONING}
implementation
uses
SysUtils;
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntfArraySet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntfArraySet.Create(Size);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLARRAYSETIMP(TJclIntfArraySet,IJclIntfCollection,IJclIntfIterator,const ,AInterface,IInterface,nil,GetObject)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclAnsiStrArraySet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclAnsiStrArraySet.Create(Size);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLARRAYSETIMP(TJclAnsiStrArraySet,IJclAnsiStrCollection,IJclAnsiStrIterator,const ,AString,AnsiString,'',GetString)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclWideStrArraySet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclWideStrArraySet.Create(Size);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLARRAYSETIMP(TJclWideStrArraySet,IJclWideStrCollection,IJclWideStrIterator,const ,AString,WideString,'',GetString)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclSingleArraySet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclSingleArraySet.Create(Size);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLARRAYSETIMP(TJclSingleArraySet,IJclSingleCollection,IJclSingleIterator,const ,AValue,Single,0.0,GetValue)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclDoubleArraySet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclDoubleArraySet.Create(Size);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLARRAYSETIMP(TJclDoubleArraySet,IJclDoubleCollection,IJclDoubleIterator,const ,AValue,Double,0.0,GetValue)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclExtendedArraySet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclExtendedArraySet.Create(Size);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLARRAYSETIMP(TJclExtendedArraySet,IJclExtendedCollection,IJclExtendedIterator,const ,AValue,Extended,0.0,GetValue)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclIntegerArraySet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclIntegerArraySet.Create(Size);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLARRAYSETIMP(TJclIntegerArraySet,IJclIntegerCollection,IJclIntegerIterator,,AValue,Integer,0,GetValue)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclCardinalArraySet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclCardinalArraySet.Create(Size);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLARRAYSETIMP(TJclCardinalArraySet,IJclCardinalCollection,IJclCardinalIterator,,AValue,Cardinal,0,GetValue)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclInt64ArraySet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclInt64ArraySet.Create(Size);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLARRAYSETIMP(TJclInt64ArraySet,IJclInt64Collection,IJclInt64Iterator,const ,AValue,Int64,0,GetValue)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$IFNDEF CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclPtrArraySet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclPtrArraySet.Create(Size);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLARRAYSETIMP(TJclPtrArraySet,IJclPtrCollection,IJclPtrIterator,,APtr,Pointer,nil,GetPointer)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$ENDIF ~CLR}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER
function TJclArraySet.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclArraySet.Create(Size, False);
AssignPropertiesTo(Result);
end;
}
(*$JPPEXPANDMACRO JCLARRAYSETIMP(TJclArraySet,IJclCollection,IJclIterator,,AObject,TObject,nil,GetObject)*)
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
{$IFDEF SUPPORTS_GENERICS}
{$JPPDEFINEMACRO CREATEEMPTYCONTAINER}
{$JPPEXPANDMACRO JCLARRAYSETIMP(TJclArraySet<T>,IJclCollection<T>,IJclIterator<T>,const ,AItem,T,Default(T),GetItem)}
{$JPPUNDEFMACRO CREATEEMPTYCONTAINER}
//=== { TJclArraySetE<T> } ===================================================
constructor TJclArraySetE<T>.Create(const AComparer: IComparer<T>; ACapacity: Integer; AOwnsItems: Boolean);
begin
inherited Create(ACapacity, AOwnsItems);
FComparer := AComparer;
end;
constructor TJclArraySetE<T>.Create(const AComparer: IComparer<T>; const ACollection: IJclCollection<T>;
AOwnsItems: Boolean);
begin
inherited Create(ACollection, AOwnsItems);
FComparer := AComparer;
end;
procedure TJclArraySetE<T>.AssignPropertiesTo(Dest: TJclAbstractContainerBase);
begin
inherited AssignPropertiesTo(Dest);
if Dest is TJclArraySetE<T> then
TJclArraySetE<T>(Dest).FComparer := Comparer;
end;
function TJclArraySetE<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclArraySetE<T>.Create(Comparer, Size, False);
AssignPropertiesTo(Result);
end;
function TJclArraySetE<T>.ItemsCompare(const A, B: T): Integer;
begin
if Comparer <> nil then
Result := Comparer.Compare(A, B)
else
Result := inherited ItemsCompare(A, B);
end;
function TJclArraySetE<T>.ItemsEqual(const A, B: T): Boolean;
begin
if Comparer <> nil then
Result := Comparer.Compare(A, B) = 0
else
Result := inherited ItemsEqual(A, B);
end;
//=== { TJclArraySetF<T> } ===================================================
constructor TJclArraySetF<T>.Create(const ACompare: TCompare<T>; ACapacity: Integer; AOwnsItems: Boolean);
begin
inherited Create(ACapacity, AOwnsItems);
SetCompare(ACompare);
end;
constructor TJclArraySetF<T>.Create(const ACompare: TCompare<T>; const ACollection: IJclCollection<T>;
AOwnsItems: Boolean);
begin
inherited Create(ACollection, AOwnsItems);
SetCompare(ACompare);
end;
function TJclArraySetF<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclArraySetF<T>.Create(Compare, Size, False);
AssignPropertiesTo(Result);
end;
//=== { TJclArraySetI<T> } ===================================================
function TJclArraySetI<T>.CreateEmptyContainer: TJclAbstractContainerBase;
begin
Result := TJclArraySetI<T>.Create(Size, False);
AssignPropertiesTo(Result);
end;
function TJclArraySetI<T>.ItemsCompare(const A, B: T): Integer;
begin
if Assigned(FCompare) then
Result := FCompare(A, B)
else
Result := A.CompareTo(B);
end;
function TJclArraySetI<T>.ItemsEqual(const A, B: T): Boolean;
begin
if Assigned(FEqualityCompare) then
Result := FEqualityCompare(A, B)
else
if Assigned(FCompare) then
Result := FCompare(A, B) = 0
else
Result := A.CompareTo(B) = 0;
end;
{$ENDIF SUPPORTS_GENERICS}
{$IFDEF UNITVERSIONING}
initialization
RegisterUnitVersion(HInstance, UnitVersioning);
finalization
UnregisterUnitVersion(HInstance);
{$ENDIF UNITVERSIONING}
end.
|
unit f06_KembalikanBuku;
interface
uses
csv_parser,
user_handler,
peminjaman_handler,
pengembalian_handler,
utilitas,
tipe_data,
b02_denda,
buku_handler;
{ DEKLARASI FUNGSI DAN PROSEDUR }
procedure kembalikan_buku(who_login : user; var data_peminjaman : tabel_peminjaman; var data_buku : tabel_buku; var data_pengembalian : tabel_pengembalian);
{ IMPLEMENTASI FUNGSI DAN PROSEDUR }
implementation
procedure kembalikan_buku(who_login : user; var data_peminjaman : tabel_peminjaman; var data_buku : tabel_buku; var data_pengembalian : tabel_pengembalian);
{ DESKRIPSI : prosedur untuk mengembalikan buku }
{ PARAMETER : data pengguna, data peminjaman, data buku, dan data pengembalian }
{ KAMUS LOKAL }
var
ID_Buku,todayTanggal : String;
buku_pinjam : peminjaman;
judul_buku_pinjam : string;
i,amount_buku : integer;
found: boolean;
{ ALGORITMA }
begin
write('Masukkan id buku yang dikembalikan: '); Readln(ID_Buku);
i := 1; found := false;
while ((i < data_peminjaman.sz) and (found <> true)) do
begin
if ((ID_Buku = data_peminjaman.t[i].ID_Buku) and (who_login.Username = data_peminjaman.t[i].Username)) then
{ Jika buku yang dipinjam ada di riwayat peminjaman dengan username yang sama dengan pengguna }
begin
buku_pinjam := data_peminjaman.t[i];
found := true;
end else i := i+1;
end;
if(not found) then writeln('Anda tidak sedang meminjam buku ini.') else // Jika pengguna meminjam buku tersebut
begin
for i := 1 to (data_buku.sz - 1) do
begin
if ID_Buku = data_buku.t[i].ID_Buku then judul_buku_pinjam := data_buku.t[i].Judul_Buku;
end;
if (buku_pinjam.Status_Pengembalian = 'True') then writeln('Anda tidak sedang meminjam buku ini.') else
begin
writeln('Data peminjaman: ');
writeln('Username: ', buku_pinjam.Username);
writeln('Judul Buku: ', judul_buku_pinjam);
writeln('Tanggal peminjaman: ', buku_pinjam.Tanggal_Peminjaman);
writeln('Tanggal batas pengembalian: ',buku_pinjam.Tanggal_Batas_Pengembalian);
write('Masukkan Tanggal Hari ini: '); Readln(todayTanggal);
if(BedaHari(buku_pinjam.Tanggal_Peminjaman, todayTanggal) < 0) then writeln('Tanggal yang dimasukkan sebelum tanggal peminjaman.') // Jika pengguna memasukkan tanggal sebelum tanggal peminjaman
else
begin
denda(buku_pinjam.Tanggal_Batas_Pengembalian, todayTanggal);
for i := 1 to (data_peminjaman.sz - 1) do
begin
if ID_Buku = data_peminjaman.t[i].ID_Buku then
data_peminjaman.t[i].Status_Pengembalian := 'True';
end;
for i := 1 to (data_buku.sz - 1) do
begin
if ID_Buku = data_buku.t[i].ID_Buku then
begin
amount_buku := (StringToInt(data_buku.t[i].Jumlah_Buku) + 1) ;
data_buku.t[i].Jumlah_Buku := IntToString(amount_buku);
end;
end;
data_pengembalian.sz := data_pengembalian.sz + 1;
data_pengembalian.t[data_pengembalian.sz-1].Username := buku_pinjam.Username;
data_pengembalian.t[data_pengembalian.sz-1].ID_buku := buku_pinjam.ID_Buku;
data_pengembalian.t[data_pengembalian.sz-1].Tanggal_Pengembalian := todayTanggal;
end;
end;
end;
end;
end.
|
{
***************************************************************************
* *
* This source is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This code is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License for more details. *
* *
* A copy of the GNU General Public License is available on the World *
* Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also *
* obtain it by writing to the Free Software Foundation, *
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
***************************************************************************
Author: Kudriavtsev Pavel
This unit registers the TPdx component of the VCL.
}
unit RegisterPDX;
{$H+}
interface
uses
Classes, SysUtils, pdx, DesignIntf, DesignEditors, Dialogs, Forms;
{.$R PDX}
resourcestring
pdxAllDbasefiles = 'Paradox Files';
procedure Register;
implementation
type
{ TPdxFileNamePropertyEditor }
TPdxFilenamePropertyEditor = class(TStringProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
end;
{ TPdxLangEditor }
TPdxLangPropertyEditor = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
{ TPdxLangEditor }
function TPdxLangPropertyEditor.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paSortList];
end;
procedure TPdxLangPropertyEditor.GetValues(Proc: TGetStrProc);
var
i: integer;
begin
for i := 1 to 118 do
Proc(PdxLangTable[i].Name);
end;
function TPdxLangPropertyEditor.GetValue: string;
begin
Result := GetStrValue;
end;
procedure TPdxLangPropertyEditor.SetValue(const Value: string);
begin
SetStrValue(Value);
end;
procedure Register;
begin
RegisterComponents('Data Access',[TPdx]);
RegisterPropertyEditor(TypeInfo(string),
TPdx, 'TableName', TPdxFileNamePropertyEditor);
RegisterPropertyEditor(TypeInfo(string),
TPdx, 'Language', TPdxLangPropertyEditor);
end;
{ TPdxFilenamePropertyEditor }
procedure TPdxFilenamePropertyEditor.Edit;
begin
with TOpenDialog.Create(Application) do
try
//Title := RsJvCsvDataSetSelectCSVFileToOpen;
FileName := GetValue;
Filter := pdxAllDbaseFiles + ' (*.db)|*.db;*.DB|All Files (*.*)|*.*';
Options := Options + [ofPathMustExist];
if Execute then
SetValue(FileName);
finally
Free;
end;
end;
function TPdxFilenamePropertyEditor.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paRevertable];
end;
initialization
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC Nexus Database metadata }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.NexusMeta;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.Meta, FireDAC.Phys.SQLGenerator;
type
TFDPhysNexusMetadata = class (TFDPhysConnectionMetadata)
protected
function GetKind: TFDRDBMSKind; override;
function GetTxNested: Boolean; override;
function GetTruncateSupported: Boolean; override;
function GetParamNameMaxLength: Integer; override;
function GetNameParts: TFDPhysNameParts; override;
function GetNameCaseSensParts: TFDPhysNameParts; override;
function GetNameDefLowCaseParts: TFDPhysNameParts; override;
function GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel; ASide: TFDPhysNameQuoteSide): Char; override;
function GetNamedParamMark: TFDPhysParamMark; override;
function GetIdentityInsertSupported: Boolean; override;
function GetInlineRefresh: Boolean; override;
function GetPositionedParamMark: TFDPhysParamMark; override;
function GetSelectOptions: TFDPhysSelectOptions; override;
function GetAsyncAbortSupported: Boolean; override;
function GetDefValuesSupported: TFDPhysDefaultValues; override;
function GetNameQuotedCaseSensParts: TFDPhysNameParts; override;
function GetLimitOptions: TFDPhysLimitOptions; override;
function GetNullLocations: TFDPhysNullLocations; override;
function InternalEscapeDate(const AStr: String): String; override;
function InternalEscapeDateTime(const AStr: String): String; override;
function InternalEscapeFloat(const AStr: String): String; override;
function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override;
function InternalEscapeTime(const AStr: String): String; override;
function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override;
public
constructor Create(const AConnectionObj: TFDPhysConnection;
AServerVersion, AClientVerison: TFDVersion);
end;
TFDPhysNexusCommandGenerator = class(TFDPhysCommandGenerator)
protected
function GetInlineRefresh(const AStmt: String; ARequest: TFDUpdateRequest): String; override;
function GetIdentity(ASessionScope: Boolean): String; override;
function GetSingleRowTable: String; override;
function GetCall(const AName: String): String; override;
function GetStoredProcCall(const ACatalog, ASchema, APackage, AProc: String;
AOverload: Word; ASPUsage: TFDPhysCommandKind): String; override;
function GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind; const ACatalog,
ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String; override;
function GetLimitSelect(const ASQL: String; ASkip, ARows: Integer;
var AOptions: TFDPhysLimitOptions): String; override;
end;
implementation
uses
System.SysUtils, Data.DB,
FireDAC.Stan.Consts, FireDAC.Stan.Util, FireDAC.DatS, FireDAC.Stan.Param;
{-------------------------------------------------------------------------------}
{ TFDPhysNexusMetadata }
{-------------------------------------------------------------------------------}
constructor TFDPhysNexusMetadata.Create(const AConnectionObj: TFDPhysConnection;
AServerVersion, AClientVerison: TFDVersion);
begin
inherited Create(AConnectionObj, AServerVersion, AClientVerison, False);
FKeywords.CommaText := 'ABS,ACHAR,ADD,ALL,ALTER,AND,ANY,AS,ASC,ASSERT,' +
'ASTRING,AUTOINC,AVG,BETWEEN,BLOB,BLOCK,BLOCKSIZE,BOOL,' +
'BOOLEAN,BOTH,BY,BYTE,BYTEARRAY,CASCADE,CASE,CAST,' +
'CEILING,CHAR,CHARACTER,CHARACTER_LENGTH,CHAR_LENGTH,CHR,' +
'COALESCE,COLUMN,COUNT,CREATE,CROSS,CURRENT_DATE,' +
'CURRENT_TIME,CURRENT_TIMESTAMP,CURRENT_USER,DATE,DATETIME,' +
'DAY,DEFAULT,DELETE,DESC,DISTINCT,DROP,DWORD,ELSE,' +
'EMPTY,END,ESCAPE,EXISTS,EXP,EXTRACT,FALSE,FLOOR,FOR,' +
'FROM,FULL,GROUP,GROW,GROWSIZE,HAVING,HOUR,IDENTITY,' +
'IGNORE,IMAGE,IN,INDEX,INITIAL,INITIALSIZE,INNER,INSERT,' +
'INT,INTEGER,INTERVAL,INTO,IS,JOIN,KANA,KEY,LARGEINT,' +
'LEADING,LEFT,LIKE,LOCALE,LOG,LOWER,MATCH,MAX,MIN,' +
'MINUTE,MONEY,MONTH,NATURAL,NCHAR,NOT,NULL,NULLIF,' +
'NULLSTRING,NVARCHAR,ON,OR,ORDER,OUTER,PARTIAL,PERCENT,' +
'POSITION,POWER,PRIMARY,RAND,REAL,RIGHT,ROUND,SECOND,' +
'SELECT,SESSION_USER,SET,SHORTINT,SIZE,SMALLINT,SOME,' +
'SORT,STRING,SUBSTRING,SUM,SYMBOLS,TABLE,TEXT,THEN,' +
'TIME,TIMESTAMP,TINYINT,TO,TOP,TRAILING,TRIM,TRUE,' +
'TYPE,UNION,UNIQUE,UNKNOWN,UPDATE,UPPER,USE,USER,' +
'USING,VALUES,VARCHAR,WHEN,WHERE,WIDTH,WORD,YEAR';
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.NexusDB;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetNameQuotedCaseSensParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetNameCaseSensParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetNameDefLowCaseParts: TFDPhysNameParts;
begin
Result := [];
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetParamNameMaxLength: Integer;
begin
Result := 128;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetNameParts: TFDPhysNameParts;
begin
Result := [npSchema, npObject];
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel;
ASide: TFDPhysNameQuoteSide): Char;
begin
if AQuote = ncDefault then
Result := '"'
else
Result := #0;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetIdentityInsertSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetNamedParamMark: TFDPhysParamMark;
begin
Result := prName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetPositionedParamMark: TFDPhysParamMark;
begin
Result := prQMark;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetSelectOptions: TFDPhysSelectOptions;
begin
Result := [soWithoutFrom, soInlineView];
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetTxNested: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetInlineRefresh: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetTruncateSupported: Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetDefValuesSupported: TFDPhysDefaultValues;
begin
Result := dvDef;
end;
{ ----------------------------------------------------------------------------- }
function TFDPhysNexusMetadata.GetAsyncAbortSupported: Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetLimitOptions: TFDPhysLimitOptions;
begin
Result := [loSkip, loRows];
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.GetNullLocations: TFDPhysNullLocations;
begin
Result := [nlAscLast, nlDescLast];
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.InternalEscapeDate(const AStr: String): String;
begin
Result := 'DATE ' + AnsiQuotedStr(AStr, '''');
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.InternalEscapeDateTime(const AStr: String): String;
begin
Result := 'TIMESTAMP ' + AnsiQuotedStr(AStr, '''');
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.InternalEscapeTime(const AStr: String): String;
begin
Result := 'TIME ' + AnsiQuotedStr(AStr, '''');
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.InternalEscapeFloat(const AStr: String): String;
begin
Result := 'CAST(' + AnsiQuotedStr(AStr, '''') + ' AS DOUBLE)';
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String;
var
sName: String;
A1, A2, A3, A4: String;
i: Integer;
function AddArgs: string;
begin
Result := '(' + AddEscapeSequenceArgs(ASeq) + ')';
end;
begin
sName := ASeq.FName;
if Length(ASeq.FArgs) >= 1 then begin
A1 := ASeq.FArgs[0];
if Length(ASeq.FArgs) >= 2 then begin
A2 := ASeq.FArgs[1];
if Length(ASeq.FArgs) >= 3 then begin
A3 := ASeq.FArgs[2];
if Length(ASeq.FArgs) >= 4 then
A4 := ASeq.FArgs[3];
end;
end;
end;
case ASeq.FFunc of
// the same
// char
efCHAR_LENGTH,
efOCTET_LENGTH,
// numeric
efABS,
efATAN,
efATAN2,
efCEILING,
efCOS,
efEXP,
efFLOOR,
efMOD,
efPOWER,
efPI,
efROUND,
efSIN,
efSQRT:
Result := sName + AddArgs;
// char:
efASCII: Result := 'ORD' + AddArgs;
efBIT_LENGTH: Result := '(OCTET_LENGTH(' + A1 + ') * 8)';
efCHAR: Result := 'CHR' + AddArgs;
efCONCAT: Result := '(' + A1 + ' || ' + A2 + ')';
efINSERT: Result := '(SUBSTR(' + A1 + ' FROM 1 (' + A2 + ') - 1) || ' + A4 +
' || SUBSTR(' + A1 + ' FROM (' + A2 + ' + ' + A3 + ')))';
efLCASE: Result := 'LOWER' + AddArgs;
efLEFT: Result := 'SUBSTR(' + A1 + ' FROM 1 FOR ' + A2 + ')';
efLENGTH: Result := 'CHAR_LENGTH' + AddArgs;
efLTRIM: Result := 'TRIM(LEADING FROM ' + A1 + ')';
efLOCATE,
efPOSITION: Result := 'POSITION(' + A1 + ' IN ' + A2 + ')';
efRIGHT: Result := 'SUBSTR(' + A1 + ' FROM CHAR_LENGTH(' + A1 + ') + 1 - (' + A2 + '))';
efRTRIM: Result := 'TRIM(TRAILING FROM ' + A1 + ')';
efSUBSTRING:
begin
Result := 'SUBSTRING(' + A1 + ' FROM ' + A2;
if Length(ASeq.FArgs) = 3 then
Result := Result + ' FOR ' + A3;
Result := Result + ')'
end;
efUCASE: Result := 'UPPER' + AddArgs;
// numeric
efCOT: Result := '(COS(' + A1 + ') / SIN(' + A1 + '))';
efDEGREES: Result := '(180 * (' + A1 + ') / ' + S_FD_Pi + ')';
efLOG: Result := 'LN' + AddArgs;
efLOG10: Result := 'LOG(10, ' + A1 + ')';
efRADIANS: Result := '((' + A1 + ') / 180 * ' + S_FD_Pi + ')';
efRANDOM: Result := 'RAND' + AddArgs;
efSIGN: Result := 'CASE WHEN ' + A1 + ' > 0 THEN 1 WHEN ' + A1 + ' < 0 THEN -1 ELSE 0 END';
efTAN: Result := '(SIN(' + A1 + ') / COS(' + A1 + '))';
efTRUNCATE: Result := 'CAST(' + A1 + ' AS INTEGER)';
// date and time
efCURDATE: Result := 'CURRENT_DATE';
efCURTIME: Result := 'CURRENT_TIME';
efDAYOFMONTH: Result := 'EXTRACT(DAY FROM ' + A1 + ')';
efEXTRACT:
begin
A1 := UpperCase(FDUnquote(Trim(A1), ''''));
Result := sName + '(' + A1 + ' FROM ' + A2 + ')';
end;
efHOUR: Result := 'EXTRACT(HOUR FROM ' + A1 + ')';
efMINUTE: Result := 'EXTRACT(MINUTE FROM ' + A1 + ')';
efMONTH: Result := 'EXTRACT(MONTH FROM ' + A1 + ')';
efNOW: Result := 'CURRENT_TIMESTAMP';
efQUARTER: Result := '(FLOOR(EXTRACT(MONTH FROM ' + A1 + ') / 4) + 1)';
efSECOND: Result := 'EXTRACT(SECOND FROM ' + A1 + ')';
efYEAR: Result := 'EXTRACT(YEAR FROM ' + A1 + ')';
// system
efCATALOG: Result := '''''';
efIF: Result := 'CASE WHEN ' + A1 + ' THEN ' + A2 + ' ELSE ' + A3 + ' END';
efIFNULL: Result := 'CASE WHEN ' + A1 + ' IS NULL THEN ' + A2 + ' ELSE ' + A1 + ' END';
efDECODE:
begin
Result := 'CASE ' + ASeq.FArgs[0];
i := 1;
while i < Length(ASeq.FArgs) - 1 do begin
Result := Result + ' WHEN ' + ASeq.FArgs[i] + ' THEN ' + ASeq.FArgs[i + 1];
Inc(i, 2);
end;
if i = Length(ASeq.FArgs) - 1 then
Result := Result + ' ELSE ' + ASeq.FArgs[i];
Result := Result + ' END';
end;
efCONVERT:
begin
A2 := UpperCase(FDUnquote(Trim(A2), ''''));
Result := 'CAST(' + A1 + ' AS ' + A2 + ')';
end;
else
// efREPEAT, efREPLACE, efSPACE
// efACOS, efASIN
// efDAYNAME, efDAYOFWEEK, efDAYOFYEAR, efMONTHNAME, efWEEK,
// efTIMESTAMPADD, efTIMESTAMPDIFF
// efSCHEMA
UnsupportedEscape(ASeq);
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusMetadata.InternalGetSQLCommandKind(
const ATokens: TStrings): TFDPhysCommandKind;
var
sToken: String;
begin
sToken := ATokens[0];
if (sToken = 'DECLARE') or (sToken = 'CALL') then
Result := skExecute
else if sToken = 'ASSERT' then
Result := skAlter
else if sToken = 'START' then
if ATokens.Count = 1 then
Result := skNotResolved
else if ATokens[1] = 'TRANSACTION' then
Result := skStartTransaction
else
Result := inherited InternalGetSQLCommandKind(ATokens)
else
Result := inherited InternalGetSQLCommandKind(ATokens);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysNexusCommandGenerator }
{-------------------------------------------------------------------------------}
function TFDPhysNexusCommandGenerator.GetInlineRefresh(const AStmt: String;
ARequest: TFDUpdateRequest): String;
begin
Result := GenerateSelect(False);
if Result <> '' then
Result := AStmt + ';' + BRK + Result
else
Result := AStmt;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusCommandGenerator.GetIdentity(ASessionScope: Boolean): String;
begin
Result := 'LASTAUTOINC';
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusCommandGenerator.GetSingleRowTable: String;
begin
Result := '#DUMMY';
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusCommandGenerator.GetCall(const AName: String): String;
begin
Result := 'CALL ' + AName;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusCommandGenerator.GetStoredProcCall(const ACatalog, ASchema,
APackage, AProc: String; AOverload: Word; ASPUsage: TFDPhysCommandKind): String;
begin
//1) SP with input params -> CALL SP(:p1, ..., :pN)
//2) SP with output params -> as above
//3) SF with last SELECT -> CALL SF(:p1, ..., :pN) returns a cursor
//4) SF -> SELECT SF(:p1, ..., :pN)
//5) SF returning a table -> SELECT * FROM SF(:p1, ..., :pN)
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusCommandGenerator.GetSelectMetaInfo(AKind: TFDPhysMetaInfoKind;
const ACatalog, ASchema, ABaseObject, AObject, AWildcard: String;
AObjectScopes: TFDPhysObjectScopes; ATableKinds: TFDPhysTableKinds;
AOverload: Word): String;
var
lWasWhere: Boolean;
sKinds: String;
function AddParam(const AValue, AParam: String): String;
var
oPar: TFDParam;
begin
if AValue <> '' then begin
Result := ':' + AParam;
oPar := GetParams.Add;
oPar.Name := AParam;
oPar.DataType := ftString;
oPar.Size := 128;
end
else
Result := 'NULL';
end;
procedure AddWhere(const ACond: String; const AParam: String = '');
var
oPar: TFDParam;
begin
if lWasWhere then
Result := Result + ' AND ' + ACond
else begin
Result := Result + ' WHERE ' + ACond;
lWasWhere := True;
end;
if AParam <> '' then begin
oPar := GetParams.Add;
oPar.Name := AParam;
oPar.DataType := ftString;
oPar.Size := 128;
end;
end;
function EncodeDataType(const ATypeField, ALengthField, AScaleField: String): String;
function DT2Str(AType: TFDDataType): String;
begin
Result := IntToStr(Integer(AType));
end;
begin
Result :=
'CASE ' +
' WHEN ' + ATypeField + ' = ''SHORT'' OR ' + ATypeField + ' = ''SHORTINT'' THEN ' + DT2Str(dtInt16) +
' WHEN ' + ATypeField + ' = ''INTEGER'' OR ' + ATypeField + ' = ''Integer'' THEN ' + DT2Str(dtInt32) +
' WHEN ' + ATypeField + ' = ''LONG'' THEN ' + DT2Str(dtInt64) +
' WHEN ' + ATypeField + ' = ''AUTOINC'' THEN ' + DT2Str(dtInt32) +
' WHEN ' + ATypeField + ' = ''ROWVERSION'' THEN ' + DT2Str(dtInt64) +
' WHEN ' + ATypeField + ' = ''DOUBLE'' THEN ' + DT2Str(dtDouble) +
' WHEN ' + ATypeField + ' = ''CURDOUBLE'' THEN ' + DT2Str(dtCurrency) +
' WHEN ' + ATypeField + ' = ''MONEY'' OR ' + ATypeField + ' = ''Money'' THEN ' + DT2Str(dtCurrency) +
' WHEN ' + ATypeField + ' = ''NUMERIC'' OR ' + ATypeField + ' = ''Numeric'' THEN ' +
'CASE' +
' WHEN (' + ALengthField + ' - 2 > 18) OR (' + AScaleField + ' > 4) THEN ' + DT2Str(dtBCD) +
' ELSE ' + DT2Str(dtFmtBCD) +
' END' +
' WHEN ' + ATypeField + ' = ''CHAR'' OR ' + ATypeField + ' = ''CHARACTER'' THEN ' + DT2Str(dtAnsiString) +
' WHEN ' + ATypeField + ' = ''CICHAR'' OR ' + ATypeField + ' = ''CICHARACTER'' THEN ' + DT2Str(dtAnsiString) +
' WHEN ' + ATypeField + ' = ''VARCHAR'' OR ' + ATypeField + ' = ''VARCHARFOX'' THEN ' + DT2Str(dtAnsiString) +
' WHEN ' + ATypeField + ' = ''NCHAR'' THEN ' + DT2Str(dtWideString) +
' WHEN ' + ATypeField + ' = ''NVARCHAR'' THEN ' + DT2Str(dtWideString) +
' WHEN ' + ATypeField + ' = ''MEMO'' OR ' + ATypeField + ' = ''Memo'' THEN ' + DT2Str(dtMemo) +
' WHEN ' + ATypeField + ' = ''NMEMO'' THEN ' + DT2Str(dtWideMemo) +
' WHEN ' + ATypeField + ' = ''RAW'' THEN ' + DT2Str(dtByteString) +
' WHEN ' + ATypeField + ' = ''VARBINARY'' OR ' + ATypeField + ' = ''VARBINARYFOX'' THEN ' + DT2Str(dtByteString) +
' WHEN ' + ATypeField + ' = ''BINARY'' OR ' + ATypeField + ' = ''BLOB'' THEN ' + DT2Str(dtBlob) +
' WHEN ' + ATypeField + ' = ''IMAGE'' THEN ' + DT2Str(dtBlob) +
' WHEN ' + ATypeField + ' = ''DATE'' THEN ' + DT2Str(dtDate) +
' WHEN ' + ATypeField + ' = ''SHORTDATE'' THEN ' + DT2Str(dtDate) +
' WHEN ' + ATypeField + ' = ''TIME'' THEN ' + DT2Str(dtTime) +
' WHEN ' + ATypeField + ' = ''TIMESTAMP'' THEN ' + DT2Str(dtDateTimeStamp) +
' WHEN ' + ATypeField + ' = ''MODTIME'' THEN ' + DT2Str(dtDateTimeStamp) +
' WHEN ' + ATypeField + ' = ''LOGICAL'' THEN ' + DT2Str(dtBoolean) +
' ELSE ' + DT2Str(dtUnknown) +
' END';
end;
function EncodeAttrs(const ATypeField, ANullFieldName, ADefFieldName: String): String;
function Attrs2Str(AAttrs: TFDDataAttributes): String;
begin
Result := IntToStr(PWord(@AAttrs)^);
end;
begin
Result :=
'(CASE ' +
' WHEN ' + ATypeField + ' = ''AUTOINC'' THEN ' + Attrs2Str([caBase, caSearchable, caAutoInc]) +
' WHEN ' + ATypeField + ' = ''ROWVERSION'' THEN ' + Attrs2Str([caBase, caSearchable, caRowVersion, caReadOnly]) +
' WHEN ' + ATypeField + ' = ''CHAR'' OR ' + ATypeField + ' = ''CHARACTER'' THEN ' + Attrs2Str([caBase, caSearchable, caFixedLen]) +
' WHEN ' + ATypeField + ' = ''CICHAR'' OR ' + ATypeField + ' = ''CICHARACTER'' THEN ' + Attrs2Str([caBase, caSearchable, caFixedLen]) +
' WHEN ' + ATypeField + ' = ''NCHAR'' THEN ' + Attrs2Str([caBase, caSearchable, caFixedLen]) +
' WHEN ' + ATypeField + ' = ''MEMO'' OR ' + ATypeField + ' = ''Memo'' THEN ' + Attrs2Str([caBase, caBlobData]) +
' WHEN ' + ATypeField + ' = ''NMEMO'' THEN ' + Attrs2Str([caBase, caBlobData]) +
' WHEN ' + ATypeField + ' = ''RAW'' THEN ' + Attrs2Str([caBase, caSearchable, caFixedLen]) +
' WHEN ' + ATypeField + ' = ''BINARY'' OR ' + ATypeField + ' = ''BLOB'' THEN ' + Attrs2Str([caBase, caBlobData]) +
' WHEN ' + ATypeField + ' = ''IMAGE'' THEN ' + Attrs2Str([caBase, caBlobData]) +
' ELSE ' + Attrs2Str([caBase, caSearchable]) +
' END';
if ADefFieldName <> '' then
Result := Result +
' + CASE ' +
' WHEN (' + ADefFieldName + ' IS NOT NULL) AND (TRIM(' + ADefFieldName + ') <> '''') AND ' +
'(TRIM(' + ADefFieldName + ') <> ''NULL'') THEN ' + Attrs2Str([caDefault]) +
' ELSE 0' +
' END';
if ANullFieldName <> '' then
Result := Result +
' + CASE ' +
' WHEN (' + ANullFieldName + ' IS NOT NULL) AND (' + ANullFieldName + ' = 1) THEN ' + Attrs2Str([caAllowNull]) +
' ELSE 0' +
' END'
else
Result := Result +
' + ' + Attrs2Str([caAllowNull]);
Result := Result + ')';
end;
function EncodePrec(const ATypeField, APrecField: String): String;
begin
Result :=
'CASE ' +
' WHEN ' + ATypeField + ' = ''CURDOUBLE'' THEN 15' +
' WHEN ' + ATypeField + ' = ''MONEY'' OR ' + ATypeField + ' = ''Money'' THEN 19' +
' WHEN ' + ATypeField + ' = ''NUMERIC'' OR ' + ATypeField + ' = ''Numeric'' THEN ' + APrecField + ' - 2' +
' ELSE 0' +
' END';
end;
function EncodeScale(const ATypeField, AScaleField: String): String;
begin
Result :=
'CASE ' +
' WHEN ' + ATypeField + ' = ''CURDOUBLE'' THEN 4' +
' WHEN ' + ATypeField + ' = ''MONEY'' OR ' + ATypeField + ' = ''Money'' THEN 4' +
' WHEN ' + ATypeField + ' = ''NUMERIC'' OR ' + ATypeField + ' = ''Numeric'' THEN ' + AScaleField +
' ELSE 0' +
' END';
end;
function EncodeLength(const ATypeField, ALengthField: String): String;
begin
Result :=
'CASE ' +
' WHEN ' + ATypeField + ' = ''CHAR'' OR ' + ATypeField + ' = ''CHARACTER'' THEN ' + ALengthField +
' WHEN ' + ATypeField + ' = ''CICHAR'' OR ' + ATypeField + ' = ''CICHARACTER'' THEN ' + ALengthField +
' WHEN ' + ATypeField + ' = ''VARCHAR'' OR ' + ATypeField + ' = ''VARCHARFOX'' THEN ' + ALengthField +
' WHEN ' + ATypeField + ' = ''NCHAR'' THEN ' + ALengthField +
' WHEN ' + ATypeField + ' = ''NVARCHAR'' THEN ' + ALengthField +
' WHEN ' + ATypeField + ' = ''RAW'' THEN ' + ALengthField +
' WHEN ' + ATypeField + ' = ''VARBINARY'' OR ' + ATypeField + ' = ''VARBINARYFOX'' THEN ' + ALengthField +
' ELSE 0' +
' END';
end;
begin
lWasWhere := False;
Result := '';
case AKind of
mkCatalogs:
;
mkSchemas:
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, SCHEMA_NAME ' +
'FROM #SCHEMAS';
mkTables:
begin
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'CASE ' +
' WHEN A.TABLE_TYPE = ''TABLE'' THEN ' + IntToStr(Integer(tkTable)) +
' WHEN A.TABLE_TYPE = ''VIEW'' THEN ' + IntToStr(Integer(tkView)) +
' WHEN A.TABLE_TYPE = ''SYSTEM TABLE'' THEN ' + IntToStr(Integer(tkTable)) +
' WHEN A.TABLE_TYPE = ''LOCAL TEMPORARY'' THEN ' + IntToStr(Integer(tkLocalTable)) +
' END AS TABLE_TYPE, ' +
'CASE ' +
' WHEN A.TABLE_TYPE = ''SYSTEM TABLE'' THEN ' + IntToStr(Integer(osSystem)) +
' ELSE ' + IntToStr(Integer(osMy)) +
' END AS TABLE_SCOPE ' +
'FROM (EXECUTE PROCEDURE sp_GetTables(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AWildcard, 'WIL');
sKinds := '';
if osMy in AObjectScopes then begin
if tkTable in ATableKinds then
sKinds := sKinds + 'TABLE;';
if tkView in ATableKinds then
sKinds := sKinds + 'VIEW;';
if tkLocalTable in ATableKinds then
sKinds := sKinds + 'LOCAL TEMPORARY;';
end;
if osSystem in AObjectScopes then
if tkTable in ATableKinds then
sKinds := sKinds + 'SYSTEM TABLE;';
if sKinds = '' then
sKinds := 'NONE;';
Result := Result + ', ''' + Copy(sKinds, 1, Length(sKinds) - 1) + ''')) A' +
' ORDER BY 4';
end;
mkTableFields:
begin
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'A.COLUMN_NAME, ' +
'A.ORDINAL_POSITION AS COLUMN_POSITION, ' +
EncodeDataType('A.TYPE_NAME', 'A.COLUMN_SIZE', 'A.DECIMAL_DIGITS') + ' AS COLUMN_DATATYPE, ' +
'A.TYPE_NAME AS COLUMN_TYPENAME, ' +
EncodeAttrs('A.TYPE_NAME', 'A.NULLABLE', 'A.COLUMN_DEF') + ' AS COLUMN_ATTRIBUTES, ' +
EncodePrec('A.TYPE_NAME', 'A.COLUMN_SIZE') + ' AS COLUMN_PRECISION, ' +
EncodeScale('A.TYPE_NAME', 'A.DECIMAL_DIGITS') + ' AS COLUMN_SCALE, ' +
EncodeLength('A.TYPE_NAME', 'A.COLUMN_SIZE') + ' AS COLUMN_LENGTH ' +
'FROM (EXECUTE PROCEDURE sp_GetColumns(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AObject, 'OBJ') + ', ' + AddParam(AWildcard, 'WIL') +
')) A ORDER BY 6';
end;
mkIndexes:
begin
Result := 'SELECT DISTINCT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'A.INDEX_NAME, ' +
'B.PK_NAME AS CONSTRAINT_NAME, ' +
'CASE' +
' WHEN B.PK_NAME IS NOT NULL THEN 2' +
' WHEN NON_UNIQUE THEN 0' +
' ELSE 1 ' +
'END AS INDEX_TYPE ' +
'FROM (EXECUTE PROCEDURE sp_GetIndexInfo(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AObject, 'OBJ') + ', False, True)) A ' +
' LEFT OUTER JOIN' +
' (EXECUTE PROCEDURE sp_GetPrimaryKeys(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AObject, 'OBJ') + ')) B' +
' ON A.INDEX_NAME = B.PK_NAME ' +
'WHERE A.TYPE <> 0';
if AWildcard <> '' then
Result := Result + ' AND A.INDEX_NAME LIKE ' + AddParam(AWildcard, 'WIL');
Result := Result + ' ORDER BY 7 DESC, 5';
end;
mkIndexFields:
begin
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'A.INDEX_NAME, ' +
'A.COLUMN_NAME, ' +
'A.ORDINAL_POSITION AS COLUMN_POSITION, ' +
'A.ASC_OR_DESC AS SORT_ORDER, ' +
'A.FILTER_CONDITION AS FILTER ' +
'FROM (EXECUTE PROCEDURE sp_GetIndexInfo(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(ABaseObject, 'BAS') + ', False, True)) A';
AddWhere('A.INDEX_NAME = :OBJ', 'OBJ');
if AWildcard <> '' then
AddWhere('A.COLUMN_NAME LIKE :WIL', 'WIL');
Result := Result + ' ORDER BY 7';
end;
mkPrimaryKey:
begin
Result := 'SELECT DISTINCT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'A.PK_NAME AS INDEX_NAME, ' +
'A.PK_NAME AS CONSTRAINT_NAME, ' +
IntToStr(Integer(ikPrimaryKey)) + ' AS INDEX_TYPE ' +
'FROM (EXECUTE PROCEDURE sp_GetPrimaryKeys(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AObject, 'OBJ') + ')) A';
if AWildcard <> '' then
AddWhere('A.PK_NAME LIKE :WIL', 'WIL');
Result := Result + ' ORDER BY 5';
end;
mkPrimaryKeyFields:
begin
Result := 'SELECT DISTINCT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'A.PK_NAME AS INDEX_NAME, ' +
'A.COLUMN_NAME AS COLUMN_NAME, ' +
'A.KEY_SEQ + 1 AS COLUMN_POSITION, ' +
'''A'' AS SORT_ORDER, ' +
'CAST(NULL AS SQL_VARCHAR(50)) AS FILTER ' +
'FROM (EXECUTE PROCEDURE sp_GetPrimaryKeys(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(ABaseObject, 'BAS') + ')) A';
if AWildcard <> '' then
AddWhere('A.COLUMN_NAME LIKE :WIL', 'WIL');
Result := Result + ' ORDER BY 7';
end;
mkForeignKeys:
begin
Result := 'SELECT DISTINCT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'A.FK_NAME AS FKEY_NAME, ' +
'A.PKTABLE_CAT AS PKEY_CATALOG_NAME, ' +
'A.PKTABLE_SCHEM AS PKEY_SCHEMA_NAME, ' +
'A.PKTABLE_NAME AS PKEY_TABLE_NAME, ' +
'A.DELETE_RULE AS DELETE_RULE, ' +
'A.UPDATE_RULE AS UPDATE_RULE ' +
'FROM (EXECUTE PROCEDURE sp_GetImportedKeys(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AObject, 'OBJ') + ')) A';
if AWildcard <> '' then
AddWhere('A.FK_NAME LIKE :WIL', 'WIL');
Result := Result + ' ORDER BY 5';
end;
mkForeignKeyFields:
begin
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.TABLE_CAT AS CATALOG_NAME, ' +
'A.TABLE_SCHEM AS SCHEMA_NAME, ' +
'A.TABLE_NAME, ' +
'A.FK_NAME AS FKEY_NAME, ' +
'A.FKCOLUMN_NAME AS COLUMN_NAME, ' +
'A.PKCOLUMN_NAME AS PKEY_COLUMN_NAME, ' +
'A.KEY_SEQ AS COLUMN_POSITION ' +
'FROM (EXECUTE PROCEDURE sp_GetImportedKeys(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(ABaseObject, 'BAS') + ')) A';
AddWhere('A.FK_NAME = :OBJ', 'OBJ');
if AWildcard <> '' then
AddWhere('A.FKCOLUMN_NAME LIKE :WIL', 'WIL');
Result := Result + ' ORDER BY 8';
end;
mkPackages:
begin
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'CAST(NULL AS SQL_VARCHAR(200)) AS CATALOG_NAME, ' +
'CAST(NULL AS SQL_VARCHAR(200)) AS SCHEMA_NAME, ' +
'A.NAME AS PACKAGE_NAME, ' +
IntToStr(Integer(osMy)) + ' AS PACKAGE_SCOPE ' +
'FROM system.packages A ';
if not (osMy in AObjectScopes) then
AddWhere('0 = 1');
if AWildcard <> '' then
AddWhere('A.NAME LIKE :WIL', 'WIL');
Result := Result + ' ORDER BY 4';
end;
mkProcs:
begin
if ABaseObject = '' then begin
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.PROCEDURE_CAT AS CATALOG_NAME, ' +
'A.PROCEDURE_SCHEM AS SCHEMA_NAME, ' +
'CAST(NULL AS SQL_VARCHAR(200)) AS PACK_NAME, ' +
'A.PROCEDURE_NAME AS PROC_NAME, ' +
'CAST(NULL AS SQL_INTEGER) AS OVERLOAD, ' +
IntToStr(Integer(pkProcedure)) + ' AS PROC_TYPE, ' +
IntToStr(Integer(osMy)) + ' AS PROC_SCOPE, ' +
'SUM(CASE WHEN B.COLUMN_TYPE IS NOT NULL AND B.COLUMN_TYPE = 1 THEN 1 ELSE 0 END) AS IN_PARAMS, ' +
'SUM(CASE WHEN B.COLUMN_TYPE IS NOT NULL AND B.COLUMN_TYPE = 3 THEN 1 ELSE 0 END) AS OUT_PARAMS ' +
'FROM (EXECUTE PROCEDURE sp_GetProcedures(' + AddParam(ACatalog, 'CAT') +
', NULL, NULL)) A ' +
'LEFT OUTER JOIN ' +
'(EXECUTE PROCEDURE sp_GetProcedureColumns(' + AddParam(ACatalog, 'CAT') +
', NULL, NULL, NULL)) B ' +
'ON TRIM(A.PROCEDURE_CAT) = TRIM(B.PROCEDURE_CAT) AND ' +
' TRIM(A.PROCEDURE_SCHEM) = TRIM(B.PROCEDURE_SCHEM) AND ' +
' TRIM(A.PROCEDURE_NAME) = TRIM(B.PROCEDURE_NAME) ';
if not (osMy in AObjectScopes) then
AddWhere('0 = 1');
if AWildcard <> '' then
AddWhere('A.PROCEDURE_NAME LIKE :WIL', 'WIL');
Result := Result +
' GROUP BY A.PROCEDURE_CAT, A.PROCEDURE_SCHEM, A.PROCEDURE_NAME ' +
'UNION ALL ';
end;
Result := Result +
'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'CAST(DATABASE() AS SQL_VARCHAR(200)) AS CATALOG_NAME, ' +
'CAST(NULL AS SQL_VARCHAR(200)) AS SCHEMA_NAME, ' +
'C.Package AS PACK_NAME, ' +
'C.Name AS PROC_NAME, ' +
'CAST(NULL AS SQL_INTEGER) AS OVERLOAD, ' +
IntToStr(Integer(pkFunction)) + ' AS PROC_TYPE, ' +
IntToStr(Integer(osMy)) + ' AS PROC_SCOPE, ' +
'-1 AS IN_PARAMS, ' +
'0 AS OUT_PARAMS ' +
'FROM system.functions C';
if ABaseObject = '' then
AddWhere('C.Package IS NULL')
else
AddWhere('C.Package = :BAS', 'BAS');
if not (osMy in AObjectScopes) then
AddWhere('0 = 1');
if AWildcard <> '' then
AddWhere('C.Name LIKE :WIL', 'WIL');
Result := Result +
' ORDER BY 4, 5';
end;
mkProcArgs:
if ABaseObject <> '' then
Result := ''
else begin
Result := 'SELECT CAST(NULL AS SQL_INTEGER) AS RECNO, ' +
'A.PROCEDURE_CAT AS CATALOG_NAME, ' +
'A.PROCEDURE_SCHEM AS SCHEMA_NAME, ' +
'CAST(NULL AS SQL_VARCHAR(200)) AS PACK_NAME, ' +
'A.PROCEDURE_NAME AS PROC_NAME, ' +
'CAST(NULL AS SQL_INTEGER) AS OVERLOAD, ' +
'A.COLUMN_NAME AS PARAM_NAME, ' +
'ROWNUM() AS PARAM_POSITION, ' +
'CASE WHEN A.COLUMN_TYPE = 1 THEN ' + IntToStr(Integer(ptInput)) +
'WHEN A.COLUMN_TYPE = 3 THEN ' + IntToStr(Integer(ptOutput)) + ' ELSE 0 END AS PARAM_TYPE, ' +
EncodeDataType('A.TYPE_NAME', 'A.LENGTH', 'A.SCALE') + ' AS PARAM_DATATYPE, ' +
'A.TYPE_NAME AS PARAM_TYPENAME, ' +
EncodeAttrs('A.TYPE_NAME', '', '') + ' AS PARAM_ATTRIBUTES, ' +
EncodePrec('A.TYPE_NAME', 'A.PRECISION') + ' AS PARAM_PRECISION, ' +
EncodeScale('A.TYPE_NAME', 'A.SCALE') + ' AS PARAM_SCALE, ' +
EncodeLength('A.TYPE_NAME', 'A.LENGTH') + ' AS PARAM_LENGTH ' +
'FROM (EXECUTE PROCEDURE sp_GetProcedureColumns(' + AddParam(ACatalog, 'CAT') +
', NULL, ' + AddParam(AObject, 'OBJ') + ', NULL)) A';
if AWildcard <> '' then
AddWhere('A.COLUMN_NAME LIKE :WIL', 'WIL');
end;
mkGenerators,
mkResultSetFields,
mkTableTypeFields:
;
else
Result := '';
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysNexusCommandGenerator.GetLimitSelect(const ASQL: String;
ASkip, ARows: Integer; var AOptions: TFDPhysLimitOptions): String;
begin
if ASkip > 0 then
Result := 'SELECT TOP ' + IntToStr(ARows) + ', ' + IntToStr(ASkip + 1) +
' A.* FROM (' + BRK + ASQL + BRK + ') A'
else if ARows >= 0 then
Result := 'SELECT TOP ' + IntToStr(ARows) +
' A.* FROM (' + BRK + ASQL + BRK + ') A'
else begin
Result := ASQL;
AOptions := [];
end;
end;
{-------------------------------------------------------------------------------}
initialization
FDPhysManager().RegisterRDBMSKind(TFDRDBMSKinds.NexusDB, S_FD_Nexus_RDBMS);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Runtime Library }
{ System Utilities Unit }
{ }
{ Copyright (C) 1995,99 Inprise Corporation }
{ }
{*******************************************************}
unit SysUtils;
{$H+}
interface
uses Windows, SysConst;
const
{ File open modes }
fmOpenRead = $0000;
fmOpenWrite = $0001;
fmOpenReadWrite = $0002;
fmShareCompat = $0000;
fmShareExclusive = $0010;
fmShareDenyWrite = $0020;
fmShareDenyRead = $0030;
fmShareDenyNone = $0040;
{ File attribute constants }
faReadOnly = $00000001;
faHidden = $00000002;
faSysFile = $00000004;
faVolumeID = $00000008;
faDirectory = $00000010;
faArchive = $00000020;
faAnyFile = $0000003F;
{ File mode magic numbers }
fmClosed = $D7B0;
fmInput = $D7B1;
fmOutput = $D7B2;
fmInOut = $D7B3;
{ Seconds and milliseconds per day }
SecsPerDay = 24 * 60 * 60;
MSecsPerDay = SecsPerDay * 1000;
{ Days between 1/1/0001 and 12/31/1899 }
DateDelta = 693594;
type
{ Standard Character set type }
TSysCharSet = set of Char;
{ Set access to an integer }
TIntegerSet = set of 0..SizeOf(Integer) * 8 - 1;
{ Type conversion records }
WordRec = packed record
Lo, Hi: Byte;
end;
LongRec = packed record
Lo, Hi: Word;
end;
Int64Rec = packed record
Lo, Hi: DWORD;
end;
TMethod = record
Code, Data: Pointer;
end;
{ General arrays }
PByteArray = ^TByteArray;
TByteArray = array[0..32767] of Byte;
PWordArray = ^TWordArray;
TWordArray = array[0..16383] of Word;
{ Generic procedure pointer }
TProcedure = procedure;
{ Generic filename type }
TFileName = type string;
{ Search record used by FindFirst, FindNext, and FindClose }
TSearchRec = record
Time: Integer;
Size: Integer;
Attr: Integer;
Name: TFileName;
ExcludeAttr: Integer;
FindHandle: THandle;
FindData: TWin32FindData;
end;
{ Typed-file and untyped-file record }
TFileRec = packed record (* must match the size the compiler generates: 332 bytes *)
Handle: Integer;
Mode: Integer;
RecSize: Cardinal;
Private: array[1..28] of Byte;
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;
Mode: Integer;
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;
{ FloatToText, FloatToTextFmt, TextToFloat, and FloatToDecimal type codes }
TFloatValue = (fvExtended, fvCurrency);
{ FloatToText format codes }
TFloatFormat = (ffGeneral, ffExponent, ffFixed, ffNumber, ffCurrency);
{ FloatToDecimal result record }
TFloatRec = packed record
Exponent: Smallint;
Negative: Boolean;
Digits: array[0..20] of Char;
end;
{ Date and time record }
TTimeStamp = record
Time: Integer; { Number of milliseconds since midnight }
Date: Integer; { One plus number of days since 1/1/0001 }
end;
{ MultiByte Character Set (MBCS) byte type }
TMbcsByteType = (mbSingleByte, mbLeadByte, mbTrailByte);
{ System Locale information record }
TSysLocale = packed record
DefaultLCID: LCID;
PriLangID: LANGID;
SubLangID: LANGID;
FarEast: Boolean;
MiddleEast: Boolean;
end;
{ This is used by TLanguages }
TLangRec = packed record
FName: string;
FLCID: LCID;
FExt: string;
end;
{ This stores the langauges that the system supports }
TLanguages = class
private
FSysLangs: array of TLangRec;
function LocalesCallback(LocaleID: PChar): Integer; stdcall;
function GetExt(Index: Integer): string;
function GetID(Index: Integer): string;
function GetLCID(Index: Integer): LCID;
function GetName(Index: Integer): string;
function GetNameFromLocaleID(ID: LCID): string;
function GetNameFromLCID(const ID: string): string;
function GetCount: integer;
public
constructor Create;
function IndexOf(ID: LCID): Integer;
property Count: Integer read GetCount;
property Name[Index: Integer]: string read GetName;
property NameFromLocaleID[ID: LCID]: string read GetNameFromLocaleID;
property NameFromLCID[const ID: string]: string read GetNameFromLCID;
property ID[Index: Integer]: string read GetID;
property LocaleID[Index: Integer]: LCID read GetLCID;
property Ext[Index: Integer]: string read GetExt;
end;
{ Exceptions }
Exception = class(TObject)
private
FMessage: string;
FHelpContext: Integer;
public
constructor Create(const Msg: string);
constructor CreateFmt(const Msg: string; const Args: array of const);
constructor CreateRes(Ident: Integer); overload;
constructor CreateRes(ResStringRec: PResStringRec); overload;
constructor CreateResFmt(Ident: Integer; const Args: array of const); overload;
constructor CreateResFmt(ResStringRec: PResStringRec; const Args: array of const); overload;
constructor CreateHelp(const Msg: string; AHelpContext: Integer);
constructor CreateFmtHelp(const Msg: string; const Args: array of const;
AHelpContext: Integer);
constructor CreateResHelp(Ident: Integer; AHelpContext: Integer); overload;
constructor CreateResHelp(ResStringRec: PResStringRec; AHelpContext: Integer); overload;
constructor CreateResFmtHelp(ResStringRec: PResStringRec; const Args: array of const;
AHelpContext: Integer); overload;
constructor CreateResFmtHelp(Ident: Integer; const Args: array of const;
AHelpContext: Integer); overload;
property HelpContext: Integer read FHelpContext write FHelpContext;
property Message: string read FMessage write FMessage;
end;
ExceptClass = class of Exception;
EAbort = class(Exception);
EHeapException = class(Exception)
private
AllowFree: Boolean;
public
procedure FreeInstance; override;
end;
EOutOfMemory = class(EHeapException);
EInOutError = class(Exception)
public
ErrorCode: Integer;
end;
EExternal = class(Exception)
public
ExceptionRecord: PExceptionRecord;
end;
EExternalException = class(EExternal);
EIntError = class(EExternal);
EDivByZero = class(EIntError);
ERangeError = class(EIntError);
EIntOverflow = class(EIntError);
EMathError = class(EExternal);
EInvalidOp = class(EMathError);
EZeroDivide = class(EMathError);
EOverflow = class(EMathError);
EUnderflow = class(EMathError);
EInvalidPointer = class(EHeapException);
EInvalidCast = class(Exception);
EConvertError = class(Exception);
EAccessViolation = class(EExternal);
EPrivilege = class(EExternal);
EStackOverflow = class(EExternal);
EControlC = class(EExternal);
EVariantError = class(Exception);
EPropReadOnly = class(Exception);
EPropWriteOnly = class(Exception);
EAssertionFailed = class(Exception);
EAbstractError = class(Exception);
EIntfCastError = class(Exception);
EInvalidContainer = class(Exception);
EInvalidInsert = class(Exception);
EPackageError = class(Exception);
EWin32Error = class(Exception)
public
ErrorCode: DWORD;
end;
ESafecallException = class(Exception);
var
{ Empty string and null string pointer. These constants are provided for
backwards compatibility only. }
EmptyStr: string = '';
NullStr: PString = @EmptyStr;
{ Win32 platform identifier. This will be one of the following values:
VER_PLATFORM_WIN32s
VER_PLATFORM_WIN32_WINDOWS
VER_PLATFORM_WIN32_NT
See WINDOWS.PAS for the numerical values. }
Win32Platform: Integer = 0;
{ Win32 OS version information -
see TOSVersionInfo.dwMajorVersion/dwMinorVersion/dwBuildNumber }
Win32MajorVersion: Integer = 0;
Win32MinorVersion: Integer = 0;
Win32BuildNumber: Integer = 0;
{ Win32 OS extra version info string -
see TOSVersionInfo.szCSDVersion }
Win32CSDVersion: string = '';
{ Currency and date/time formatting options
The initial values of these variables are fetched from the system registry
using the GetLocaleInfo function in the Win32 API. The description of each
variable specifies the LOCALE_XXXX constant used to fetch the initial
value.
CurrencyString - Defines the currency symbol used in floating-point to
decimal conversions. The initial value is fetched from LOCALE_SCURRENCY.
CurrencyFormat - Defines the currency symbol placement and separation
used in floating-point to decimal conversions. Possible values are:
0 = '$1'
1 = '1$'
2 = '$ 1'
3 = '1 $'
The initial value is fetched from LOCALE_ICURRENCY.
NegCurrFormat - Defines the currency format for used in floating-point to
decimal conversions of negative numbers. Possible values are:
0 = '($1)' 4 = '(1$)' 8 = '-1 $' 12 = '$ -1'
1 = '-$1' 5 = '-1$' 9 = '-$ 1' 13 = '1- $'
2 = '$-1' 6 = '1-$' 10 = '1 $-' 14 = '($ 1)'
3 = '$1-' 7 = '1$-' 11 = '$ 1-' 15 = '(1 $)'
The initial value is fetched from LOCALE_INEGCURR.
ThousandSeparator - The character used to separate thousands in numbers
with more than three digits to the left of the decimal separator. The
initial value is fetched from LOCALE_STHOUSAND.
DecimalSeparator - The character used to separate the integer part from
the fractional part of a number. The initial value is fetched from
LOCALE_SDECIMAL.
CurrencyDecimals - The number of digits to the right of the decimal point
in a currency amount. The initial value is fetched from LOCALE_ICURRDIGITS.
DateSeparator - The character used to separate the year, month, and day
parts of a date value. The initial value is fetched from LOCATE_SDATE.
ShortDateFormat - The format string used to convert a date value to a
short string suitable for editing. For a complete description of date and
time format strings, refer to the documentation for the FormatDate
function. The short date format should only use the date separator
character and the m, mm, d, dd, yy, and yyyy format specifiers. The
initial value is fetched from LOCALE_SSHORTDATE.
LongDateFormat - The format string used to convert a date value to a long
string suitable for display but not for editing. For a complete description
of date and time format strings, refer to the documentation for the
FormatDate function. The initial value is fetched from LOCALE_SLONGDATE.
TimeSeparator - The character used to separate the hour, minute, and
second parts of a time value. The initial value is fetched from
LOCALE_STIME.
TimeAMString - The suffix string used for time values between 00:00 and
11:59 in 12-hour clock format. The initial value is fetched from
LOCALE_S1159.
TimePMString - The suffix string used for time values between 12:00 and
23:59 in 12-hour clock format. The initial value is fetched from
LOCALE_S2359.
ShortTimeFormat - The format string used to convert a time value to a
short string with only hours and minutes. The default value is computed
from LOCALE_ITIME and LOCALE_ITLZERO.
LongTimeFormat - The format string used to convert a time value to a long
string with hours, minutes, and seconds. The default value is computed
from LOCALE_ITIME and LOCALE_ITLZERO.
ShortMonthNames - Array of strings containing short month names. The mmm
format specifier in a format string passed to FormatDate causes a short
month name to be substituted. The default values are fecthed from the
LOCALE_SABBREVMONTHNAME system locale entries.
LongMonthNames - Array of strings containing long month names. The mmmm
format specifier in a format string passed to FormatDate causes a long
month name to be substituted. The default values are fecthed from the
LOCALE_SMONTHNAME system locale entries.
ShortDayNames - Array of strings containing short day names. The ddd
format specifier in a format string passed to FormatDate causes a short
day name to be substituted. The default values are fecthed from the
LOCALE_SABBREVDAYNAME system locale entries.
LongDayNames - Array of strings containing long day names. The dddd
format specifier in a format string passed to FormatDate causes a long
day name to be substituted. The default values are fecthed from the
LOCALE_SDAYNAME system locale entries.
ListSeparator - The character used to separate items in a list. The
initial value is fetched from LOCALE_SLIST.
TwoDigitYearCenturyWindow - Determines what century is added to two
digit years when converting string dates to numeric dates. This value
is subtracted from the current year before extracting the century.
This can be used to extend the lifetime of existing applications that
are inextricably tied to 2 digit year data entry. The best solution
to Year 2000 (Y2k) issues is not to accept 2 digit years at all - require
4 digit years in data entry to eliminate century ambiguities.
Examples:
Current TwoDigitCenturyWindow Century StrToDate() of:
Year Value Pivot '01/01/03' '01/01/68' '01/01/50'
-------------------------------------------------------------------------
1998 0 1900 1903 1968 1950
2002 0 2000 2003 2068 2050
1998 50 (default) 1948 2003 1968 1950
2002 50 (default) 1952 2003 1968 2050
2020 50 (default) 1970 2003 2068 2050
}
var
CurrencyString: string;
CurrencyFormat: Byte;
NegCurrFormat: Byte;
ThousandSeparator: Char;
DecimalSeparator: Char;
CurrencyDecimals: Byte;
DateSeparator: Char;
ShortDateFormat: string;
LongDateFormat: string;
TimeSeparator: Char;
TimeAMString: string;
TimePMString: string;
ShortTimeFormat: string;
LongTimeFormat: string;
ShortMonthNames: array[1..12] of string;
LongMonthNames: array[1..12] of string;
ShortDayNames: array[1..7] of string;
LongDayNames: array[1..7] of string;
SysLocale: TSysLocale;
EraNames: array[1..7] of string;
EraYearOffsets: array[1..7] of Integer;
TwoDigitYearCenturyWindow: Word = 50;
ListSeparator: Char;
function Languages: TLanguages;
{ Memory management routines }
{ AllocMem allocates a block of the given size on the heap. Each byte in
the allocated buffer is set to zero. To dispose the buffer, use the
FreeMem standard procedure. }
function AllocMem(Size: Cardinal): Pointer;
{ Exit procedure handling }
{ AddExitProc adds the given procedure to the run-time library's exit
procedure list. When an application terminates, its exit procedures are
executed in reverse order of definition, i.e. the last procedure passed
to AddExitProc is the first one to get executed upon termination. }
procedure AddExitProc(Proc: TProcedure);
{ String handling routines }
{ NewStr allocates a string on the heap. NewStr is provided for backwards
compatibility only. }
function NewStr(const S: string): PString;
{ DisposeStr disposes a string pointer that was previously allocated using
NewStr. DisposeStr is provided for backwards compatibility only. }
procedure DisposeStr(P: PString);
{ AssignStr assigns a new dynamically allocated string to the given string
pointer. AssignStr is provided for backwards compatibility only. }
procedure AssignStr(var P: PString; const S: string);
{ AppendStr appends S to the end of Dest. AppendStr is provided for
backwards compatibility only. Use "Dest := Dest + S" instead. }
procedure AppendStr(var Dest: string; const S: string);
{ UpperCase converts all ASCII characters in the given string to upper case.
The conversion affects only 7-bit ASCII characters between 'a' and 'z'. To
convert 8-bit international characters, use AnsiUpperCase. }
function UpperCase(const S: string): string;
{ LowerCase converts all ASCII characters in the given string to lower case.
The conversion affects only 7-bit ASCII characters between 'A' and 'Z'. To
convert 8-bit international characters, use AnsiLowerCase. }
function LowerCase(const S: string): string;
{ CompareStr compares S1 to S2, with case-sensitivity. The return value is
less than 0 if S1 < S2, 0 if S1 = S2, or greater than 0 if S1 > S2. The
compare operation is based on the 8-bit ordinal value of each character
and is not affected by the current Windows locale. }
function CompareStr(const S1, S2: string): Integer;
{ CompareMem performs a binary compare of Length bytes of memory referenced
by P1 to that of P2. CompareMem returns True if the memory referenced by
P1 is identical to that of P2. }
function CompareMem(P1, P2: Pointer; Length: Integer): Boolean; assembler;
{ CompareText compares S1 to S2, without case-sensitivity. The return value
is the same as for CompareStr. The compare operation is based on the 8-bit
ordinal value of each character, after converting 'a'..'z' to 'A'..'Z',
and is not affected by the current Windows locale. }
function CompareText(const S1, S2: string): Integer;
{ SameText compares S1 to S2, without case-sensitivity. Returns true if
S1 and S2 are the equal, that is, if CompareText would return 0. SameText
has the same 8-bit limitations as CompareText }
function SameText(const S1, S2: string): Boolean;
{ AnsiUpperCase converts all characters in the given string to upper case.
The conversion uses the current Windows locale. }
function AnsiUpperCase(const S: string): string;
{ AnsiLowerCase converts all characters in the given string to lower case.
The conversion uses the current Windows locale. }
function AnsiLowerCase(const S: string): string;
{ AnsiCompareStr compares S1 to S2, with case-sensitivity. The compare
operation is controlled by the current Windows locale. The return value
is the same as for CompareStr. }
function AnsiCompareStr(const S1, S2: string): Integer;
{ AnsiSameStr compares S1 to S2, with case-sensitivity. The compare
operation is controlled by the current Windows locale. The return value
is True if AnsiCompareStr would have returned 0. }
function AnsiSameStr(const S1, S2: string): Boolean;
{ AnsiCompareText compares S1 to S2, without case-sensitivity. The compare
operation is controlled by the current Windows locale. The return value
is the same as for CompareStr. }
function AnsiCompareText(const S1, S2: string): Integer;
{ AnsiSameText compares S1 to S2, without case-sensitivity. The compare
operation is controlled by the current Windows locale. The return value
is True if AnsiCompareText would have returned 0. }
function AnsiSameText(const S1, S2: string): Boolean;
{ AnsiStrComp compares S1 to S2, with case-sensitivity. The compare
operation is controlled by the current Windows locale. The return value
is the same as for CompareStr. }
function AnsiStrComp(S1, S2: PChar): Integer;
{ AnsiStrIComp compares S1 to S2, without case-sensitivity. The compare
operation is controlled by the current Windows locale. The return value
is the same as for CompareStr. }
function AnsiStrIComp(S1, S2: PChar): Integer;
{ AnsiStrLComp compares S1 to S2, with case-sensitivity, up to a maximum
length of MaxLen bytes. The compare operation is controlled by the
current Windows locale. The return value is the same as for CompareStr. }
function AnsiStrLComp(S1, S2: PChar; MaxLen: Cardinal): Integer;
{ AnsiStrLIComp compares S1 to S2, without case-sensitivity, up to a maximum
length of MaxLen bytes. The compare operation is controlled by the
current Windows locale. The return value is the same as for CompareStr. }
function AnsiStrLIComp(S1, S2: PChar; MaxLen: Cardinal): Integer;
{ AnsiStrLower converts all characters in the given string to lower case.
The conversion uses the current Windows locale. }
function AnsiStrLower(Str: PChar): PChar;
{ AnsiStrUpper converts all characters in the given string to upper case.
The conversion uses the current Windows locale. }
function AnsiStrUpper(Str: PChar): PChar;
{ AnsiLastChar returns a pointer to the last full character in the string.
This function supports multibyte characters }
function AnsiLastChar(const S: string): PChar;
{ AnsiStrLastChar returns a pointer to the last full character in the string.
This function supports multibyte characters. }
function AnsiStrLastChar(P: PChar): PChar;
{ Trim trims leading and trailing spaces and control characters from the
given string. }
function Trim(const S: string): string;
{ TrimLeft trims leading spaces and control characters from the given
string. }
function TrimLeft(const S: string): string;
{ TrimRight trims trailing spaces and control characters from the given
string. }
function TrimRight(const S: string): string;
{ QuotedStr returns the given string as a quoted string. A single quote
character is inserted at the beginning and the end of the string, and
for each single quote character in the string, another one is added. }
function QuotedStr(const S: string): string;
{ AnsiQuotedStr returns the given string as a quoted string, using the
provided Quote character. A Quote character is inserted at the beginning
and end of thestring, and each Quote character in the string is doubled.
This function supports multibyte character strings (MBCS). }
function AnsiQuotedStr(const S: string; Quote: Char): string;
{ AnsiExtractQuotedStr removes the Quote characters from the beginning and end
of a quoted string, and reduces pairs of Quote characters within the quoted
string to a single character. If the first character in Src is not the Quote
character, the function returns an empty string. The function copies
characters from the Src to the result string until the second solitary
Quote character or the first null character in Src. The Src parameter is
updated to point to the first character following the quoted string. If
the Src string does not contain a matching end Quote character, the Src
parameter is updated to point to the terminating null character in Src.
This function supports multibyte character strings (MBCS). }
function AnsiExtractQuotedStr(var Src: PChar; Quote: Char): string;
{ AdjustLineBreaks adjusts all line breaks in the given string to be true
CR/LF sequences. The function changes any CR characters not followed by
a LF and any LF characters not preceded by a CR into CR/LF pairs. }
function AdjustLineBreaks(const S: string): string;
{ IsValidIdent returns true if the given string is a valid identifier. An
identifier is defined as a character from the set ['A'..'Z', 'a'..'z', '_']
followed by zero or more characters from the set ['A'..'Z', 'a'..'z',
'0..'9', '_']. }
function IsValidIdent(const Ident: string): Boolean;
{ IntToStr converts the given value to its decimal string representation. }
function IntToStr(Value: Integer): string; overload;
function IntToStr(Value: Int64): string; overload;
{ IntToHex converts the given value to a hexadecimal string representation
with the minimum number of digits specified. }
function IntToHex(Value: Integer; Digits: Integer): string; overload;
function IntToHex(Value: Int64; Digits: Integer): string; overload;
{ StrToInt converts the given string to an integer value. If the string
doesn't contain a valid value, an EConvertError exception is raised. }
function StrToInt(const S: string): Integer;
function StrToInt64(const S: string): Int64;
{ StrToIntDef converts the given string to an integer value. If the string
doesn't contain a valid value, the value given by Default is returned. }
function StrToIntDef(const S: string; Default: Integer): Integer;
function StrToInt64Def(const S: string; Default: Int64): Int64;
{ LoadStr loads the string resource given by Ident from the application's
executable file. If the string resource does not exist, an empty string
is returned. }
function LoadStr(Ident: Integer): string;
{ LoadStr loads the string resource given by Ident from the application's
executable file, and uses it as the format string in a call to the
Format function with the given arguments. }
function FmtLoadStr(Ident: Integer; const Args: array of const): string;
{ File management routines }
{ FileOpen opens the specified file using the specified access mode. The
access mode value is constructed by OR-ing one of the fmOpenXXXX constants
with one of the fmShareXXXX constants. If the return value is positive,
the function was successful and the value is the file handle of the opened
file. A return value of -1 indicates that an error occurred. }
function FileOpen(const FileName: string; Mode: LongWord): Integer;
{ FileCreate creates a new file by the specified name. If the return value
is positive, the function was successful and the value is the file handle
of the new file. A return value of -1 indicates that an error occurred. }
function FileCreate(const FileName: string): Integer;
{ FileRead reads Count bytes from the file given by Handle into the buffer
specified by Buffer. The return value is the number of bytes actually
read; it is less than Count if the end of the file was reached. The return
value is -1 if an error occurred. }
function FileRead(Handle: Integer; var Buffer; Count: LongWord): Integer;
{ FileWrite writes Count bytes to the file given by Handle from the buffer
specified by Buffer. The return value is the number of bytes actually
written, or -1 if an error occurred. }
function FileWrite(Handle: Integer; const Buffer; Count: LongWord): Integer;
{ FileSeek changes the current position of the file given by Handle to be
Offset bytes relative to the point given by Origin. Origin = 0 means that
Offset is relative to the beginning of the file, Origin = 1 means that
Offset is relative to the current position, and Origin = 2 means that
Offset is relative to the end of the file. The return value is the new
current position, relative to the beginning of the file, or -1 if an error
occurred. }
function FileSeek(Handle, Offset, Origin: Integer): Integer; overload;
function FileSeek(Handle: Integer; const Offset: Int64; Origin: Integer): Int64; overload;
{ FileClose closes the specified file. }
procedure FileClose(Handle: Integer);
{ FileAge returns the date-and-time stamp of the specified file. The return
value can be converted to a TDateTime value using the FileDateToDateTime
function. The return value is -1 if the file does not exist. }
function FileAge(const FileName: string): Integer;
{ FileExists returns a boolean value that indicates whether the specified
file exists. }
function FileExists(const FileName: string): Boolean;
{ FindFirst searches the directory given by Path for the first entry that
matches the filename given by Path and the attributes given by Attr. The
result is returned in the search record given by SearchRec. The return
value is zero if the function was successful. Otherwise the return value
is a Windows error code. FindFirst is typically used in conjunction with
FindNext and FindClose as follows:
Result := FindFirst(Path, Attr, SearchRec);
while Result = 0 do
begin
ProcessSearchRec(SearchRec);
Result := FindNext(SearchRec);
end;
FindClose(SearchRec);
where ProcessSearchRec represents user-defined code that processes the
information in a search record. }
function FindFirst(const Path: string; Attr: Integer;
var F: TSearchRec): Integer;
{ FindNext returs the next entry that matches the name and attributes
specified in a previous call to FindFirst. The search record must be one
that was passed to FindFirst. The return value is zero if the function was
successful. Otherwise the return value is a Windows error code. }
function FindNext(var F: TSearchRec): Integer;
{ FindClose terminates a FindFirst/FindNext sequence. FindClose does nothing
in the 16-bit version of Windows, but is required in the 32-bit version,
so for maximum portability every FindFirst/FindNext sequence should end
with a call to FindClose. }
procedure FindClose(var F: TSearchRec);
{ FileGetDate returns the DOS date-and-time stamp of the file given by
Handle. The return value is -1 if the handle is invalid. The
FileDateToDateTime function can be used to convert the returned value to
a TDateTime value. }
function FileGetDate(Handle: Integer): Integer;
{ FileSetDate sets the DOS date-and-time stamp of the file given by Handle
to the value given by Age. The DateTimeToFileDate function can be used to
convert a TDateTime value to a DOS date-and-time stamp. The return value
is zero if the function was successful. Otherwise the return value is a
Windows error code. }
function FileSetDate(Handle: Integer; Age: Integer): Integer;
{ FileGetAttr returns the file attributes of the file given by FileName. The
attributes can be examined by AND-ing with the faXXXX constants defined
above. A return value of -1 indicates that an error occurred. }
function FileGetAttr(const FileName: string): Integer;
{ FileSetAttr sets the file attributes of the file given by FileName to the
value given by Attr. The attribute value is formed by OR-ing the
appropriate faXXXX constants. The return value is zero if the function was
successful. Otherwise the return value is a Windows error code. }
function FileSetAttr(const FileName: string; Attr: Integer): Integer;
{ DeleteFile deletes the file given by FileName. The return value is True if
the file was successfully deleted, or False if an error occurred. }
function DeleteFile(const FileName: string): Boolean;
{ RenameFile renames the file given by OldName to the name given by NewName.
The return value is True if the file was successfully renamed, or False if
an error occurred. }
function RenameFile(const OldName, NewName: string): Boolean;
{ ChangeFileExt changes the extension of a filename. FileName specifies a
filename with or without an extension, and Extension specifies the new
extension for the filename. The new extension can be a an empty string or
a period followed by up to three characters. }
function ChangeFileExt(const FileName, Extension: string): string;
{ ExtractFilePath extracts the drive and directory parts of the given
filename. The resulting string is the leftmost characters of FileName,
up to and including the colon or backslash that separates the path
information from the name and extension. The resulting string is empty
if FileName contains no drive and directory parts. }
function ExtractFilePath(const FileName: string): string;
{ ExtractFileDir extracts the drive and directory parts of the given
filename. The resulting string is a directory name suitable for passing
to SetCurrentDir, CreateDir, etc. The resulting string is empty if
FileName contains no drive and directory parts. }
function ExtractFileDir(const FileName: string): string;
{ ExtractFileDrive extracts the drive part of the given filename. For
filenames with drive letters, the resulting string is '<drive>:'.
For filenames with a UNC path, the resulting string is in the form
'\\<servername>\<sharename>'. If the given path contains neither
style of filename, the result is an empty string. }
function ExtractFileDrive(const FileName: string): string;
{ ExtractFileName extracts the name and extension parts of the given
filename. The resulting string is the leftmost characters of FileName,
starting with the first character after the colon or backslash that
separates the path information from the name and extension. The resulting
string is equal to FileName if FileName contains no drive and directory
parts. }
function ExtractFileName(const FileName: string): string;
{ ExtractFileExt extracts the extension part of the given filename. The
resulting string includes the period character that separates the name
and extension parts. The resulting string is empty if the given filename
has no extension. }
function ExtractFileExt(const FileName: string): string;
{ ExpandFileName expands the given filename to a fully qualified filename.
The resulting string consists of a drive letter, a colon, a root relative
directory path, and a filename. Embedded '.' and '..' directory references
are removed. }
function ExpandFileName(const FileName: string): string;
{ ExpandUNCFileName expands the given filename to a fully qualified filename.
This function is the same as ExpandFileName except that it will return the
drive portion of the filename in the format '\\<servername>\<sharename> if
that drive is actually a network resource instead of a local resource.
Like ExpandFileName, embedded '.' and '..' directory references are
removed. }
function ExpandUNCFileName(const FileName: string): string;
{ ExtractRelativePath will return a file path name relative to the given
BaseName. It strips the common path dirs and adds '..\' for each level
up from the BaseName path. }
function ExtractRelativePath(const BaseName, DestName: string): string;
{ ExtractShortPathName will convert the given filename to the short form
by calling the GetShortPathName API. Will return an empty string if
the file or directory specified does not exist }
function ExtractShortPathName(const FileName: string): string;
{ FileSearch searches for the file given by Name in the list of directories
given by DirList. The directory paths in DirList must be separated by
semicolons. The search always starts with the current directory of the
current drive. The returned value is a concatenation of one of the
directory paths and the filename, or an empty string if the file could not
be located. }
function FileSearch(const Name, DirList: string): string;
{ DiskFree returns the number of free bytes on the specified drive number,
where 0 = Current, 1 = A, 2 = B, etc. DiskFree returns -1 if the drive
number is invalid. }
function DiskFree(Drive: Byte): Int64;
{ DiskSize returns the size in bytes of the specified drive number, where
0 = Current, 1 = A, 2 = B, etc. DiskSize returns -1 if the drive number
is invalid. }
function DiskSize(Drive: Byte): Int64;
{ FileDateToDateTime converts a DOS date-and-time value to a TDateTime
value. The FileAge, FileGetDate, and FileSetDate routines operate on DOS
date-and-time values, and the Time field of a TSearchRec used by the
FindFirst and FindNext functions contains a DOS date-and-time value. }
function FileDateToDateTime(FileDate: Integer): TDateTime;
{ DateTimeToFileDate converts a TDateTime value to a DOS date-and-time
value. The FileAge, FileGetDate, and FileSetDate routines operate on DOS
date-and-time values, and the Time field of a TSearchRec used by the
FindFirst and FindNext functions contains a DOS date-and-time value. }
function DateTimeToFileDate(DateTime: TDateTime): Integer;
{ GetCurrentDir returns the current directory. }
function GetCurrentDir: string;
{ SetCurrentDir sets the current directory. The return value is True if
the current directory was successfully changed, or False if an error
occurred. }
function SetCurrentDir(const Dir: string): Boolean;
{ CreateDir creates a new directory. The return value is True if a new
directory was successfully created, or False if an error occurred. }
function CreateDir(const Dir: string): Boolean;
{ RemoveDir deletes an existing empty directory. The return value is
True if the directory was successfully deleted, or False if an error
occurred. }
function RemoveDir(const Dir: string): Boolean;
{ PChar routines }
{ const params help simplify C++ code. No effect on pascal code }
{ StrLen returns the number of characters in Str, not counting the null
terminator. }
function StrLen(const Str: PChar): Cardinal;
{ StrEnd returns a pointer to the null character that terminates Str. }
function StrEnd(const Str: PChar): PChar;
{ StrMove copies exactly Count characters from Source to Dest and returns
Dest. Source and Dest may overlap. }
function StrMove(Dest: PChar; const Source: PChar; Count: Cardinal): PChar;
{ StrCopy copies Source to Dest and returns Dest. }
function StrCopy(Dest: PChar; const Source: PChar): PChar;
{ StrECopy copies Source to Dest and returns StrEnd(Dest). }
function StrECopy(Dest:PChar; const Source: PChar): PChar;
{ StrLCopy copies at most MaxLen characters from Source to Dest and
returns Dest. }
function StrLCopy(Dest: PChar; const Source: PChar; MaxLen: Cardinal): PChar;
{ StrPCopy copies the Pascal style string Source into Dest and
returns Dest. }
function StrPCopy(Dest: PChar; const Source: string): PChar;
{ StrPLCopy copies at most MaxLen characters from the Pascal style string
Source into Dest and returns Dest. }
function StrPLCopy(Dest: PChar; const Source: string;
MaxLen: Cardinal): PChar;
{ StrCat appends a copy of Source to the end of Dest and returns Dest. }
function StrCat(Dest: PChar; const Source: PChar): PChar;
{ StrLCat appends at most MaxLen - StrLen(Dest) characters from Source to
the end of Dest, and returns Dest. }
function StrLCat(Dest: PChar; const Source: PChar; MaxLen: Cardinal): PChar;
{ StrComp compares Str1 to Str2. The return value is less than 0 if
Str1 < Str2, 0 if Str1 = Str2, or greater than 0 if Str1 > Str2. }
function StrComp(const Str1, Str2: PChar): Integer;
{ StrIComp compares Str1 to Str2, without case sensitivity. The return
value is the same as StrComp. }
function StrIComp(const Str1, Str2: PChar): Integer;
{ StrLComp compares Str1 to Str2, for a maximum length of MaxLen
characters. The return value is the same as StrComp. }
function StrLComp(const Str1, Str2: PChar; MaxLen: Cardinal): Integer;
{ StrLIComp compares Str1 to Str2, for a maximum length of MaxLen
characters, without case sensitivity. The return value is the same
as StrComp. }
function StrLIComp(const Str1, Str2: PChar; MaxLen: Cardinal): Integer;
{ StrScan returns a pointer to the first occurrence of Chr in Str. If Chr
does not occur in Str, StrScan returns NIL. The null terminator is
considered to be part of the string. }
function StrScan(const Str: PChar; Chr: Char): PChar;
{ StrRScan returns a pointer to the last occurrence of Chr in Str. If Chr
does not occur in Str, StrRScan returns NIL. The null terminator is
considered to be part of the string. }
function StrRScan(const Str: PChar; Chr: Char): PChar;
{ StrPos returns a pointer to the first occurrence of Str2 in Str1. If
Str2 does not occur in Str1, StrPos returns NIL. }
function StrPos(const Str1, Str2: PChar): PChar;
{ StrUpper converts Str to upper case and returns Str. }
function StrUpper(Str: PChar): PChar;
{ StrLower converts Str to lower case and returns Str. }
function StrLower(Str: PChar): PChar;
{ StrPas converts Str to a Pascal style string. This function is provided
for backwards compatibility only. To convert a null terminated string to
a Pascal style string, use a string type cast or an assignment. }
function StrPas(const Str: PChar): string;
{ StrAlloc allocates a buffer of the given size on the heap. The size of
the allocated buffer is encoded in a four byte header that immediately
preceeds the buffer. To dispose the buffer, use StrDispose. }
function StrAlloc(Size: Cardinal): PChar;
{ StrBufSize returns the allocated size of the given buffer, not including
the two byte header. }
function StrBufSize(const Str: PChar): Cardinal;
{ StrNew allocates a copy of Str on the heap. If Str is NIL, StrNew returns
NIL and doesn't allocate any heap space. Otherwise, StrNew makes a
duplicate of Str, obtaining space with a call to the StrAlloc function,
and returns a pointer to the duplicated string. To dispose the string,
use StrDispose. }
function StrNew(const Str: PChar): PChar;
{ StrDispose disposes a string that was previously allocated with StrAlloc
or StrNew. If Str is NIL, StrDispose does nothing. }
procedure StrDispose(Str: PChar);
{ String formatting routines }
{ The Format routine formats the argument list given by the Args parameter
using the format string given by the Format parameter.
Format strings contain two types of objects--plain characters and format
specifiers. Plain characters are copied verbatim to the resulting string.
Format specifiers fetch arguments from the argument list and apply
formatting to them.
Format specifiers have the following form:
"%" [index ":"] ["-"] [width] ["." prec] type
A format specifier begins with a % character. After the % come the
following, in this order:
- an optional argument index specifier, [index ":"]
- an optional left-justification indicator, ["-"]
- an optional width specifier, [width]
- an optional precision specifier, ["." prec]
- the conversion type character, type
The following conversion characters are supported:
d Decimal. The argument must be an integer value. The value is converted
to a string of decimal digits. If the format string contains a precision
specifier, it indicates that the resulting string must contain at least
the specified number of digits; if the value has less digits, the
resulting string is left-padded with zeros.
u Unsigned decimal. Similar to 'd' but no sign is output.
e Scientific. The argument must be a floating-point value. The value is
converted to a string of the form "-d.ddd...E+ddd". The resulting
string starts with a minus sign if the number is negative, and one digit
always precedes the decimal point. The total number of digits in the
resulting string (including the one before the decimal point) is given
by the precision specifer in the format string--a default precision of
15 is assumed if no precision specifer is present. The "E" exponent
character in the resulting string is always followed by a plus or minus
sign and at least three digits.
f Fixed. The argument must be a floating-point value. The value is
converted to a string of the form "-ddd.ddd...". The resulting string
starts with a minus sign if the number is negative. The number of digits
after the decimal point is given by the precision specifier in the
format string--a default of 2 decimal digits is assumed if no precision
specifier is present.
g General. The argument must be a floating-point value. The value is
converted to the shortest possible decimal string using fixed or
scientific format. The number of significant digits in the resulting
string is given by the precision specifier in the format string--a
default precision of 15 is assumed if no precision specifier is present.
Trailing zeros are removed from the resulting string, and a decimal
point appears only if necessary. The resulting string uses fixed point
format if the number of digits to the left of the decimal point in the
value is less than or equal to the specified precision, and if the
value is greater than or equal to 0.00001. Otherwise the resulting
string uses scientific format.
n Number. The argument must be a floating-point value. The value is
converted to a string of the form "-d,ddd,ddd.ddd...". The "n" format
corresponds to the "f" format, except that the resulting string
contains thousand separators.
m Money. The argument must be a floating-point value. The value is
converted to a string that represents a currency amount. The conversion
is controlled by the CurrencyString, CurrencyFormat, NegCurrFormat,
ThousandSeparator, DecimalSeparator, and CurrencyDecimals global
variables, all of which are initialized from the Currency Format in
the International section of the Windows Control Panel. If the format
string contains a precision specifier, it overrides the value given
by the CurrencyDecimals global variable.
p Pointer. The argument must be a pointer value. The value is converted
to a string of the form "XXXX:YYYY" where XXXX and YYYY are the
segment and offset parts of the pointer expressed as four hexadecimal
digits.
s String. The argument must be a character, a string, or a PChar value.
The string or character is inserted in place of the format specifier.
The precision specifier, if present in the format string, specifies the
maximum length of the resulting string. If the argument is a string
that is longer than this maximum, the string is truncated.
x Hexadecimal. The argument must be an integer value. The value is
converted to a string of hexadecimal digits. If the format string
contains a precision specifier, it indicates that the resulting string
must contain at least the specified number of digits; if the value has
less digits, the resulting string is left-padded with zeros.
Conversion characters may be specified in upper case as well as in lower
case--both produce the same results.
For all floating-point formats, the actual characters used as decimal and
thousand separators are obtained from the DecimalSeparator and
ThousandSeparator global variables.
Index, width, and precision specifiers can be specified directly using
decimal digit string (for example "%10d"), or indirectly using an asterisk
charcater (for example "%*.*f"). When using an asterisk, the next argument
in the argument list (which must be an integer value) becomes the value
that is actually used. For example "Format('%*.*f', [8, 2, 123.456])" is
the same as "Format('%8.2f', [123.456])".
A width specifier sets the minimum field width for a conversion. If the
resulting string is shorter than the minimum field width, it is padded
with blanks to increase the field width. The default is to right-justify
the result by adding blanks in front of the value, but if the format
specifier contains a left-justification indicator (a "-" character
preceding the width specifier), the result is left-justified by adding
blanks after the value.
An index specifier sets the current argument list index to the specified
value. The index of the first argument in the argument list is 0. Using
index specifiers, it is possible to format the same argument multiple
times. For example "Format('%d %d %0:d %d', [10, 20])" produces the string
'10 20 10 20'.
The Format function can be combined with other formatting functions. For
example
S := Format('Your total was %s on %s', [
FormatFloat('$#,##0.00;;zero', Total),
FormatDateTime('mm/dd/yy', Date)]);
which uses the FormatFloat and FormatDateTime functions to customize the
format beyond what is possible with Format. }
function Format(const Format: string; const Args: array of const): string;
{ FmtStr formats the argument list given by Args using the format string
given by Format into the string variable given by Result. For further
details, see the description of the Format function. }
procedure FmtStr(var Result: string; const Format: string;
const Args: array of const);
{ StrFmt formats the argument list given by Args using the format string
given by Format into the buffer given by Buffer. It is up to the caller to
ensure that Buffer is large enough for the resulting string. The returned
value is Buffer. For further details, see the description of the Format
function. }
function StrFmt(Buffer, Format: PChar; const Args: array of const): PChar;
{ StrFmt formats the argument list given by Args using the format string
given by Format into the buffer given by Buffer. The resulting string will
contain no more than MaxLen characters, not including the null terminator.
The returned value is Buffer. For further details, see the description of
the Format function. }
function StrLFmt(Buffer: PChar; MaxLen: Cardinal; Format: PChar;
const Args: array of const): PChar;
{ FormatBuf formats the argument list given by Args using the format string
given by Format and FmtLen into the buffer given by Buffer and BufLen.
The Format parameter is a reference to a buffer containing FmtLen
characters, and the Buffer parameter is a reference to a buffer of BufLen
characters. The returned value is the number of characters actually stored
in Buffer. The returned value is always less than or equal to BufLen. For
further details, see the description of the Format function. }
function FormatBuf(var Buffer; BufLen: Cardinal; const Format;
FmtLen: Cardinal; const Args: array of const): Cardinal;
{ Floating point conversion routines }
{ FloatToStr converts the floating-point value given by Value to its string
representation. The conversion uses general number format with 15
significant digits. For further details, see the description of the
FloatToStrF function. }
function FloatToStr(Value: Extended): string;
{ CurrToStr converts the currency value given by Value to its string
representation. The conversion uses general number format. For further
details, see the description of the CurrToStrF function. }
function CurrToStr(Value: Currency): string;
{ FloatToStrF converts the floating-point value given by Value to its string
representation. The Format parameter controls the format of the resulting
string. The Precision parameter specifies the precision of the given value.
It should be 7 or less for values of type Single, 15 or less for values of
type Double, and 18 or less for values of type Extended. The meaning of the
Digits parameter depends on the particular format selected.
The possible values of the Format parameter, and the meaning of each, are
described below.
ffGeneral - General number format. The value is converted to the shortest
possible decimal string using fixed or scientific format. Trailing zeros
are removed from the resulting string, and a decimal point appears only
if necessary. The resulting string uses fixed point format if the number
of digits to the left of the decimal point in the value is less than or
equal to the specified precision, and if the value is greater than or
equal to 0.00001. Otherwise the resulting string uses scientific format,
and the Digits parameter specifies the minimum number of digits in the
exponent (between 0 and 4).
ffExponent - Scientific format. The value is converted to a string of the
form "-d.ddd...E+dddd". The resulting string starts with a minus sign if
the number is negative, and one digit always precedes the decimal point.
The total number of digits in the resulting string (including the one
before the decimal point) is given by the Precision parameter. The "E"
exponent character in the resulting string is always followed by a plus
or minus sign and up to four digits. The Digits parameter specifies the
minimum number of digits in the exponent (between 0 and 4).
ffFixed - Fixed point format. The value is converted to a string of the
form "-ddd.ddd...". The resulting string starts with a minus sign if the
number is negative, and at least one digit always precedes the decimal
point. The number of digits after the decimal point is given by the Digits
parameter--it must be between 0 and 18. If the number of digits to the
left of the decimal point is greater than the specified precision, the
resulting value will use scientific format.
ffNumber - Number format. The value is converted to a string of the form
"-d,ddd,ddd.ddd...". The ffNumber format corresponds to the ffFixed format,
except that the resulting string contains thousand separators.
ffCurrency - Currency format. The value is converted to a string that
represents a currency amount. The conversion is controlled by the
CurrencyString, CurrencyFormat, NegCurrFormat, ThousandSeparator, and
DecimalSeparator global variables, all of which are initialized from the
Currency Format in the International section of the Windows Control Panel.
The number of digits after the decimal point is given by the Digits
parameter--it must be between 0 and 18.
For all formats, the actual characters used as decimal and thousand
separators are obtained from the DecimalSeparator and ThousandSeparator
global variables.
If the given value is a NAN (not-a-number), the resulting string is 'NAN'.
If the given value is positive infinity, the resulting string is 'INF'. If
the given value is negative infinity, the resulting string is '-INF'. }
function FloatToStrF(Value: Extended; Format: TFloatFormat;
Precision, Digits: Integer): string;
{ CurrToStrF converts the currency value given by Value to its string
representation. A call to CurrToStrF corresponds to a call to
FloatToStrF with an implied precision of 19 digits. }
function CurrToStrF(Value: Currency; Format: TFloatFormat;
Digits: Integer): string;
{ FloatToText converts the given floating-point value to its decimal
representation using the specified format, precision, and digits. The
Value parameter must be a variable of type Extended or Currency, as
indicated by the ValueType parameter. The resulting string of characters
is stored in the given buffer, and the returned value is the number of
characters stored. The resulting string is not null-terminated. For
further details, see the description of the FloatToStrF function. }
function FloatToText(Buffer: PChar; const Value; ValueType: TFloatValue;
Format: TFloatFormat; Precision, Digits: Integer): Integer;
{ FormatFloat formats the floating-point value given by Value using the
format string given by Format. The following format specifiers are
supported in the format string:
0 Digit placeholder. If the value being formatted has a digit in the
position where the '0' appears in the format string, then that digit
is copied to the output string. Otherwise, a '0' is stored in that
position in the output string.
# Digit placeholder. If the value being formatted has a digit in the
position where the '#' appears in the format string, then that digit
is copied to the output string. Otherwise, nothing is stored in that
position in the output string.
. Decimal point. The first '.' character in the format string
determines the location of the decimal separator in the formatted
value; any additional '.' characters are ignored. The actual
character used as a the decimal separator in the output string is
determined by the DecimalSeparator global variable. The default value
of DecimalSeparator is specified in the Number Format of the
International section in the Windows Control Panel.
, Thousand separator. If the format string contains one or more ','
characters, the output will have thousand separators inserted between
each group of three digits to the left of the decimal point. The
placement and number of ',' characters in the format string does not
affect the output, except to indicate that thousand separators are
wanted. The actual character used as a the thousand separator in the
output is determined by the ThousandSeparator global variable. The
default value of ThousandSeparator is specified in the Number Format
of the International section in the Windows Control Panel.
E+ Scientific notation. If any of the strings 'E+', 'E-', 'e+', or 'e-'
E- are contained in the format string, the number is formatted using
e+ scientific notation. A group of up to four '0' characters can
e- immediately follow the 'E+', 'E-', 'e+', or 'e-' to determine the
minimum number of digits in the exponent. The 'E+' and 'e+' formats
cause a plus sign to be output for positive exponents and a minus
sign to be output for negative exponents. The 'E-' and 'e-' formats
output a sign character only for negative exponents.
'xx' Characters enclosed in single or double quotes are output as-is, and
"xx" do not affect formatting.
; Separates sections for positive, negative, and zero numbers in the
format string.
The locations of the leftmost '0' before the decimal point in the format
string and the rightmost '0' after the decimal point in the format string
determine the range of digits that are always present in the output string.
The number being formatted is always rounded to as many decimal places as
there are digit placeholders ('0' or '#') to the right of the decimal
point. If the format string contains no decimal point, the value being
formatted is rounded to the nearest whole number.
If the number being formatted has more digits to the left of the decimal
separator than there are digit placeholders to the left of the '.'
character in the format string, the extra digits are output before the
first digit placeholder.
To allow different formats for positive, negative, and zero values, the
format string can contain between one and three sections separated by
semicolons.
One section - The format string applies to all values.
Two sections - The first section applies to positive values and zeros, and
the second section applies to negative values.
Three sections - The first section applies to positive values, the second
applies to negative values, and the third applies to zeros.
If the section for negative values or the section for zero values is empty,
that is if there is nothing between the semicolons that delimit the
section, the section for positive values is used instead.
If the section for positive values is empty, or if the entire format string
is empty, the value is formatted using general floating-point formatting
with 15 significant digits, corresponding to a call to FloatToStrF with
the ffGeneral format. General floating-point formatting is also used if
the value has more than 18 digits to the left of the decimal point and
the format string does not specify scientific notation.
The table below shows some sample formats and the results produced when
the formats are applied to different values:
Format string 1234 -1234 0.5 0
-----------------------------------------------------------------------
1234 -1234 0.5 0
0 1234 -1234 1 0
0.00 1234.00 -1234.00 0.50 0.00
#.## 1234 -1234 .5
#,##0.00 1,234.00 -1,234.00 0.50 0.00
#,##0.00;(#,##0.00) 1,234.00 (1,234.00) 0.50 0.00
#,##0.00;;Zero 1,234.00 -1,234.00 0.50 Zero
0.000E+00 1.234E+03 -1.234E+03 5.000E-01 0.000E+00
#.###E-0 1.234E3 -1.234E3 5E-1 0E0
----------------------------------------------------------------------- }
function FormatFloat(const Format: string; Value: Extended): string;
{ FormatCurr formats the currency value given by Value using the format
string given by Format. For further details, see the description of the
FormatFloat function. }
function FormatCurr(const Format: string; Value: Currency): string;
{ FloatToTextFmt converts the given floating-point value to its decimal
representation using the specified format. The Value parameter must be a
variable of type Extended or Currency, as indicated by the ValueType
parameter. The resulting string of characters is stored in the given
buffer, and the returned value is the number of characters stored. The
resulting string is not null-terminated. For further details, see the
description of the FormatFloat function. }
function FloatToTextFmt(Buffer: PChar; const Value; ValueType: TFloatValue;
Format: PChar): Integer;
{ StrToFloat converts the given string to a floating-point value. The string
must consist of an optional sign (+ or -), a string of digits with an
optional decimal point, and an optional 'E' or 'e' followed by a signed
integer. Leading and trailing blanks in the string are ignored. The
DecimalSeparator global variable defines the character that must be used
as a decimal point. Thousand separators and currency symbols are not
allowed in the string. If the string doesn't contain a valid value, an
EConvertError exception is raised. }
function StrToFloat(const S: string): Extended;
{ StrToCurr converts the given string to a currency value. For further
details, see the description of the StrToFloat function. }
function StrToCurr(const S: string): Currency;
{ TextToFloat converts the null-terminated string given by Buffer to a
floating-point value which is returned in the variable given by Value.
The Value parameter must be a variable of type Extended or Currency, as
indicated by the ValueType parameter. The return value is True if the
conversion was successful, or False if the string is not a valid
floating-point value. For further details, see the description of the
StrToFloat function. }
function TextToFloat(Buffer: PChar; var Value;
ValueType: TFloatValue): Boolean;
{ FloatToDecimal converts a floating-point value to a decimal representation
that is suited for further formatting. The Value parameter must be a
variable of type Extended or Currency, as indicated by the ValueType
parameter. For values of type Extended, the Precision parameter specifies
the requested number of significant digits in the result--the allowed range
is 1..18. For values of type Currency, the Precision parameter is ignored,
and the implied precision of the conversion is 19 digits. The Decimals
parameter specifies the requested maximum number of digits to the left of
the decimal point in the result. Precision and Decimals together control
how the result is rounded. To produce a result that always has a given
number of significant digits regardless of the magnitude of the number,
specify 9999 for the Decimals parameter. The result of the conversion is
stored in the specified TFloatRec record as follows:
Exponent - Contains the magnitude of the number, i.e. the number of
significant digits to the right of the decimal point. The Exponent field
is negative if the absolute value of the number is less than one. If the
number is a NAN (not-a-number), Exponent is set to -32768. If the number
is INF or -INF (positive or negative infinity), Exponent is set to 32767.
Negative - True if the number is negative, False if the number is zero
or positive.
Digits - Contains up to 18 (for type Extended) or 19 (for type Currency)
significant digits followed by a null terminator. The implied decimal
point (if any) is not stored in Digits. Trailing zeros are removed, and
if the resulting number is zero, NAN, or INF, Digits contains nothing but
the null terminator. }
procedure FloatToDecimal(var Result: TFloatRec; const Value;
ValueType: TFloatValue; Precision, Decimals: Integer);
{ Date/time support routines }
function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp;
function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
function MSecsToTimeStamp(MSecs: Comp): TTimeStamp;
function TimeStampToMSecs(const TimeStamp: TTimeStamp): Comp;
{ EncodeDate encodes the given year, month, and day into a TDateTime value.
The year must be between 1 and 9999, the month must be between 1 and 12,
and the day must be between 1 and N, where N is the number of days in the
specified month. If the specified values are not within range, an
EConvertError exception is raised. The resulting value is the number of
days between 12/30/1899 and the given date. }
function EncodeDate(Year, Month, Day: Word): TDateTime;
{ EncodeTime encodes the given hour, minute, second, and millisecond into a
TDateTime value. The hour must be between 0 and 23, the minute must be
between 0 and 59, the second must be between 0 and 59, and the millisecond
must be between 0 and 999. If the specified values are not within range, an
EConvertError exception is raised. The resulting value is a number between
0 (inclusive) and 1 (not inclusive) that indicates the fractional part of
a day given by the specified time. The value 0 corresponds to midnight,
0.5 corresponds to noon, 0.75 corresponds to 6:00 pm, etc. }
function EncodeTime(Hour, Min, Sec, MSec: Word): TDateTime;
{ DecodeDate decodes the integral (date) part of the given TDateTime value
into its corresponding year, month, and day. If the given TDateTime value
is less than or equal to zero, the year, month, and day return parameters
are all set to zero. }
procedure DecodeDate(Date: TDateTime; var Year, Month, Day: Word);
{ DecodeTime decodes the fractional (time) part of the given TDateTime value
into its corresponding hour, minute, second, and millisecond. }
procedure DecodeTime(Time: TDateTime; var Hour, Min, Sec, MSec: Word);
{ DateTimeToSystemTime converts a date and time from Delphi's TDateTime
format into the Win32 API's TSystemTime format. }
procedure DateTimeToSystemTime(DateTime: TDateTime; var SystemTime: TSystemTime);
{ SystemTimeToDateTime converts a date and time from the Win32 API's
TSystemTime format into Delphi's TDateTime format. }
function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
{ DayOfWeek returns the day of the week of the given date. The result is an
integer between 1 and 7, corresponding to Sunday through Saturday. }
function DayOfWeek(Date: TDateTime): Integer;
{ Date returns the current date. }
function Date: TDateTime;
{ Time returns the current time. }
function Time: TDateTime;
{ Now returns the current date and time, corresponding to Date + Time. }
function Now: TDateTime;
{ IncMonth returns Date shifted by the specified number of months.
NumberOfMonths parameter can be negative, to return a date N months ago.
If the input day of month is greater than the last day of the resulting
month, the day is set to the last day of the resulting month.
Input time of day is copied to the DateTime result. }
function IncMonth(const Date: TDateTime; NumberOfMonths: Integer): TDateTime;
{ ReplaceTime replaces the time portion of the DateTime parameter with the given
time value, adjusting the signs as needed if the date is prior to 1900
(Date value less than zero) }
procedure ReplaceTime(var DateTime: TDateTime; const NewTime: TDateTime);
{ ReplaceDate replaces the date portion of the DateTime parameter with the given
date value, adjusting as needed for negative dates }
procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime);
{ IsLeapYear determines whether the given year is a leap year. }
function IsLeapYear(Year: Word): Boolean;
type
PDayTable = ^TDayTable;
TDayTable = array[1..12] of Word;
{ The MonthDays array can be used to quickly find the number of
days in a month: MonthDays[IsLeapYear(Y), M] }
const
MonthDays: array [Boolean] of TDayTable =
((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31));
{ DateToStr converts the date part of the given TDateTime value to a string.
The conversion uses the format specified by the ShortDateFormat global
variable. }
function DateToStr(Date: TDateTime): string;
{ TimeToStr converts the time part of the given TDateTime value to a string.
The conversion uses the format specified by the LongTimeFormat global
variable. }
function TimeToStr(Time: TDateTime): string;
{ DateTimeToStr converts the given date and time to a string. The resulting
string consists of a date and time formatted using the ShortDateFormat and
LongTimeFormat global variables. Time information is included in the
resulting string only if the fractional part of the given date and time
value is non-zero. }
function DateTimeToStr(DateTime: TDateTime): string;
{ StrToDate converts the given string to a date value. The string must
consist of two or three numbers, separated by the character defined by
the DateSeparator global variable. The order for month, day, and year is
determined by the ShortDateFormat global variable--possible combinations
are m/d/y, d/m/y, and y/m/d. If the string contains only two numbers, it
is interpreted as a date (m/d or d/m) in the current year. Year values
between 0 and 99 are assumed to be in the current century. If the given
string does not contain a valid date, an EConvertError exception is
raised. }
function StrToDate(const S: string): TDateTime;
{ StrToTime converts the given string to a time value. The string must
consist of two or three numbers, separated by the character defined by
the TimeSeparator global variable, optionally followed by an AM or PM
indicator. The numbers represent hour, minute, and (optionally) second,
in that order. If the time is followed by AM or PM, it is assumed to be
in 12-hour clock format. If no AM or PM indicator is included, the time
is assumed to be in 24-hour clock format. If the given string does not
contain a valid time, an EConvertError exception is raised. }
function StrToTime(const S: string): TDateTime;
{ StrToDateTime converts the given string to a date and time value. The
string must contain a date optionally followed by a time. The date and
time parts of the string must follow the formats described for the
StrToDate and StrToTime functions. }
function StrToDateTime(const S: string): TDateTime;
{ FormatDateTime formats the date-and-time value given by DateTime using the
format given by Format. The following format specifiers are supported:
c Displays the date using the format given by the ShortDateFormat
global variable, followed by the time using the format given by
the LongTimeFormat global variable. The time is not displayed if
the fractional part of the DateTime value is zero.
d Displays the day as a number without a leading zero (1-31).
dd Displays the day as a number with a leading zero (01-31).
ddd Displays the day as an abbreviation (Sun-Sat) using the strings
given by the ShortDayNames global variable.
dddd Displays the day as a full name (Sunday-Saturday) using the strings
given by the LongDayNames global variable.
ddddd Displays the date using the format given by the ShortDateFormat
global variable.
dddddd Displays the date using the format given by the LongDateFormat
global variable.
g Displays the period/era as an abbreviation (Japanese and
Taiwanese locales only).
gg Displays the period/era as a full name.
e Displays the year in the current period/era as a number without
a leading zero (Japanese, Korean and Taiwanese locales only).
ee Displays the year in the current period/era as a number with
a leading zero (Japanese, Korean and Taiwanese locales only).
m Displays the month as a number without a leading zero (1-12). If
the m specifier immediately follows an h or hh specifier, the
minute rather than the month is displayed.
mm Displays the month as a number with a leading zero (01-12). If
the mm specifier immediately follows an h or hh specifier, the
minute rather than the month is displayed.
mmm Displays the month as an abbreviation (Jan-Dec) using the strings
given by the ShortMonthNames global variable.
mmmm Displays the month as a full name (January-December) using the
strings given by the LongMonthNames global variable.
yy Displays the year as a two-digit number (00-99).
yyyy Displays the year as a four-digit number (0000-9999).
h Displays the hour without a leading zero (0-23).
hh Displays the hour with a leading zero (00-23).
n Displays the minute without a leading zero (0-59).
nn Displays the minute with a leading zero (00-59).
s Displays the second without a leading zero (0-59).
ss Displays the second with a leading zero (00-59).
z Displays the millisecond without a leading zero (0-999).
zzz Displays the millisecond with a leading zero (000-999).
t Displays the time using the format given by the ShortTimeFormat
global variable.
tt Displays the time using the format given by the LongTimeFormat
global variable.
am/pm Uses the 12-hour clock for the preceding h or hh specifier, and
displays 'am' for any hour before noon, and 'pm' for any hour
after noon. The am/pm specifier can use lower, upper, or mixed
case, and the result is displayed accordingly.
a/p Uses the 12-hour clock for the preceding h or hh specifier, and
displays 'a' for any hour before noon, and 'p' for any hour after
noon. The a/p specifier can use lower, upper, or mixed case, and
the result is displayed accordingly.
ampm Uses the 12-hour clock for the preceding h or hh specifier, and
displays the contents of the TimeAMString global variable for any
hour before noon, and the contents of the TimePMString global
variable for any hour after noon.
/ Displays the date separator character given by the DateSeparator
global variable.
: Displays the time separator character given by the TimeSeparator
global variable.
'xx' Characters enclosed in single or double quotes are displayed as-is,
"xx" and do not affect formatting.
Format specifiers may be written in upper case as well as in lower case
letters--both produce the same result.
If the string given by the Format parameter is empty, the date and time
value is formatted as if a 'c' format specifier had been given.
The following example:
S := FormatDateTime('"The meeting is on" dddd, mmmm d, yyyy, ' +
'"at" hh:mm AM/PM', StrToDateTime('2/15/95 10:30am'));
assigns 'The meeting is on Wednesday, February 15, 1995 at 10:30 AM' to
the string variable S. }
function FormatDateTime(const Format: string; DateTime: TDateTime): string;
{ DateTimeToString converts the date and time value given by DateTime using
the format string given by Format into the string variable given by Result.
For further details, see the description of the FormatDateTime function. }
procedure DateTimeToString(var Result: string; const Format: string;
DateTime: TDateTime);
{ System error messages }
function SysErrorMessage(ErrorCode: Integer): string;
{ Initialization file support }
function GetLocaleStr(Locale, LocaleType: Integer; const Default: string): string;
function GetLocaleChar(Locale, LocaleType: Integer; Default: Char): Char;
{ GetFormatSettings resets all date and number format variables to their
default values. }
procedure GetFormatSettings;
{ Exception handling routines }
function ExceptObject: TObject;
function ExceptAddr: Pointer;
function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
Buffer: PChar; Size: Integer): Integer;
procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
procedure Abort;
procedure OutOfMemoryError;
procedure Beep;
{ MBCS functions }
{ LeadBytes is a char set that indicates which char values are lead bytes
in multibyte character sets (Japanese, Chinese, etc).
This set is always empty for western locales. }
var
LeadBytes: set of Char = [];
(*$EXTERNALSYM LeadBytes*)
(*$HPPEMIT 'namespace Sysutils {'*)
(*$HPPEMIT 'extern PACKAGE System::Set<Byte, 0, 255> LeadBytes;'*)
(*$HPPEMIT '} // namespace Sysutils'*)
{ ByteType indicates what kind of byte exists at the Index'th byte in S.
Western locales always return mbSingleByte. Far East multibyte locales
may also return mbLeadByte, indicating the byte is the first in a multibyte
character sequence, and mbTrailByte, indicating that the byte is the second
in a multibyte character sequence. Parameters are assumed to be valid. }
function ByteType(const S: string; Index: Integer): TMbcsByteType;
{ StrByteType works the same as ByteType, but on null-terminated PChar strings }
function StrByteType(Str: PChar; Index: Cardinal): TMbcsByteType;
{ ByteToCharLen returns the character length of a MBCS string, scanning the
string for up to MaxLen bytes. In multibyte character sets, the number of
characters in a string may be less than the number of bytes. }
function ByteToCharLen(const S: string; MaxLen: Integer): Integer;
{ CharToByteLen returns the byte length of a MBCS string, scanning the string
for up to MaxLen characters. }
function CharToByteLen(const S: string; MaxLen: Integer): Integer;
{ ByteToCharIndex returns the 1-based character index of the Index'th byte in
a MBCS string. Returns zero if Index is out of range:
(Index <= 0) or (Index > Length(S)) }
function ByteToCharIndex(const S: string; Index: Integer): Integer;
{ CharToByteIndex returns the 1-based byte index of the Index'th character
in a MBCS string. Returns zero if Index or Result are out of range:
(Index <= 0) or (Index > Length(S)) or (Result would be > Length(S)) }
function CharToByteIndex(const S: string; Index: Integer): Integer;
{ IsPathDelimiter returns True if the character at byte S[Index]
is '\', and it is not a MBCS lead or trail byte. }
function IsPathDelimiter(const S: string; Index: Integer): Boolean;
{ IsDelimiter returns True if the character at byte S[Index] matches any
character in the Delimiters string, and the character is not a MBCS lead or
trail byte. S may contain multibyte characters; Delimiters must contain
only single byte characters. }
function IsDelimiter(const Delimiters, S: string; Index: Integer): Boolean;
{ IncludeTrailingBackslash returns the path with a '\' at the end.
This function is MBCS enabled. }
function IncludeTrailingBackslash(const S: string): string;
{ ExcludeTrailingBackslash returns the path without a '\' at the end.
This function is MBCS enabled. }
function ExcludeTrailingBackslash(const S: string): string;
{ LastDelimiter returns the byte index in S of the rightmost whole
character that matches any character in Delimiters (except null (#0)).
S may contain multibyte characters; Delimiters must contain only single
byte non-null characters.
Example: LastDelimiter('\.:', 'c:\filename.ext') returns 12. }
function LastDelimiter(const Delimiters, S: string): Integer;
{ AnsiCompareFileName supports DOS file name comparison idiosyncracies
in Far East locales (Zenkaku). In non-MBCS locales, AnsiCompareFileName
is identical to AnsiCompareText. For general purpose file name comparisions,
you should use this function instead of AnsiCompareText. }
function AnsiCompareFileName(const S1, S2: string): Integer;
{ AnsiLowerCaseFileName supports lowercase conversion idiosyncracies of
DOS file names in Far East locales (Zenkaku). In non-MBCS locales,
AnsiLowerCaseFileName is identical to AnsiLowerCase. }
function AnsiLowerCaseFileName(const S: string): string;
{ AnsiUpperCaseFileName supports uppercase conversion idiosyncracies of
DOS file names in Far East locales (Zenkaku). In non-MBCS locales,
AnsiUpperCaseFileName is identical to AnsiUpperCase. }
function AnsiUpperCaseFileName(const S: string): string;
{ AnsiPos: Same as Pos but supports MBCS strings }
function AnsiPos(const Substr, S: string): Integer;
{ AnsiStrPos: Same as StrPos but supports MBCS strings }
function AnsiStrPos(Str, SubStr: PChar): PChar;
{ AnsiStrRScan: Same as StrRScan but supports MBCS strings }
function AnsiStrRScan(Str: PChar; Chr: Char): PChar;
{ AnsiStrScan: Same as StrScan but supports MBCS strings }
function AnsiStrScan(Str: PChar; Chr: Char): PChar;
{ StringReplace replaces occurances of <oldpattern> with <newpattern> in a
given string. Assumes the string may contain Multibyte characters }
type
TReplaceFlags = set of (rfReplaceAll, rfIgnoreCase);
function StringReplace(const S, OldPattern, NewPattern: string;
Flags: TReplaceFlags): string;
{ WrapText will scan a string for BreakChars and insert the BreakStr at the
last BreakChar position before MaxCol. Will not insert a break into an
embedded quoted string (both ''' and '"' supported) }
function WrapText(const Line, BreakStr: string; BreakChars: TSysCharSet;
MaxCol: Integer): string; overload;
function WrapText(const Line: string; MaxCol: Integer = 45): string; overload;
{ FindCmdLineSwitch determines whether the string in the Switch parameter
was passed as a command line argument to the application. SwitchChars
identifies valid argument-delimiter characters (i.e., "-" and "/" are
common delimiters). The IgnoreCase paramter controls whether a
case-sensistive or case-insensitive search is performed. }
function FindCmdLineSwitch(const Switch: string; SwitchChars: TSysCharSet;
IgnoreCase: Boolean): Boolean;
{ FreeAndNil frees the given TObject instance and sets the variable reference
to nil. Be careful to only pass TObjects to this routine. }
procedure FreeAndNil(var Obj);
{ Interface support routines }
function Supports(const Instance: IUnknown; const Intf: TGUID; out Inst): Boolean; overload;
function Supports(Instance: TObject; const Intf: TGUID; out Inst): Boolean; overload;
{ Package support routines }
{ Package Info flags }
const
pfNeverBuild = $00000001;
pfDesignOnly = $00000002;
pfRunOnly = $00000004;
pfIgnoreDupUnits = $00000008;
pfModuleTypeMask = $C0000000;
pfExeModule = $00000000;
pfPackageModule = $40000000;
pfProducerMask = $0C000000;
pfV3Produced = $00000000;
pfProducerUndefined = $04000000;
pfBCB4Produced = $08000000;
pfDelphi4Produced = $0C000000;
pfLibraryModule = $80000000;
{ Unit info flags }
const
ufMainUnit = $01;
ufPackageUnit = $02;
ufWeakUnit = $04;
ufOrgWeakUnit = $08;
ufImplicitUnit = $10;
ufWeakPackageUnit = ufPackageUnit or ufWeakUnit;
{ Procedure type of the callback given to GetPackageInfo. Name is the actual
name of the package element. If IsUnit is True then Name is the name of
a contained unit; a required package if False. Param is the value passed
to GetPackageInfo }
type
TNameType = (ntContainsUnit, ntRequiresPackage);
TPackageInfoProc = procedure (const Name: string; NameType: TNameType; Flags: Byte; Param: Pointer);
{ LoadPackage loads a given package DLL, checks for duplicate units and
calls the initialization blocks of all the contained units }
function LoadPackage(const Name: string): HMODULE;
{ UnloadPackage does the opposite of LoadPackage by calling the finalization
blocks of all contained units, then unloading the package DLL }
procedure UnloadPackage(Module: HMODULE);
{ GetPackageInfo accesses the given package's info table and enumerates
all the contained units and required packages }
procedure GetPackageInfo(Module: HMODULE; Param: Pointer; var Flags: Integer;
InfoProc: TPackageInfoProc);
{ GetPackageDescription loads the description resource from the package
library. If the description resource does not exist,
an empty string is returned. }
function GetPackageDescription(ModuleName: PChar): string;
{ InitializePackage Validates and initializes the given package DLL }
procedure InitializePackage(Module: HMODULE);
{ FinalizePackage finalizes the given package DLL }
procedure FinalizePackage(Module: HMODULE);
{ RaiseLastWin32Error calls the GetLastError API to retrieve the code for }
{ the last occuring Win32 error. If GetLastError returns an error code, }
{ RaiseLastWin32Error then raises an exception with the error code and }
{ message associated with with error. }
procedure RaiseLastWin32Error;
{ Win32Check is used to check the return value of a Win32 API function }
{ which returns a BOOL to indicate success. If the Win32 API function }
{ returns False (indicating failure), Win32Check calls RaiseLastWin32Error }
{ to raise an exception. If the Win32 API function returns True, }
{ Win32Check returns True. }
function Win32Check(RetVal: BOOL): BOOL;
{ Termination procedure support }
type
TTerminateProc = function: Boolean;
{ Call AddTerminateProc to add a terminate procedure to the system list of }
{ termination procedures. Delphi will call all of the function in the }
{ termination procedure list before an application terminates. The user- }
{ defined TermProc function should return True if the application can }
{ safely terminate or False if the application cannot safely terminate. }
{ If one of the functions in the termination procedure list returns False, }
{ the application will not terminate. }
procedure AddTerminateProc(TermProc: TTerminateProc);
{ CallTerminateProcs is called by VCL when an application is about to }
{ terminate. It returns True only if all of the functions in the }
{ system's terminate procedure list return True. This function is }
{ intended only to be called by Delphi, and it should not be called }
{ directly. }
function CallTerminateProcs: Boolean;
function GDAL: LongWord;
procedure RCS;
procedure RPR;
{ HexDisplayPrefix contains the prefix to display on hexadecimal
values - '$' for Pascal syntax, '0x' for C++ syntax. This is
for display only - this does not affect the string-to-integer
conversion routines. }
var
HexDisplayPrefix: string = '$';
{ The GetDiskFreeSpace Win32 API does not support partitions larger than 2GB
under Win95. A new Win32 function, GetDiskFreeSpaceEx, supports partitions
larger than 2GB but only exists on Win NT 4.0 and Win95 OSR2.
The GetDiskFreeSpaceEx function pointer variable below will be initialized
at startup to point to either the actual OS API function if it exists on
the system, or to an internal Delphi function if it does not. When running
on Win95 pre-OSR2, the output of this function will still be limited to
the 2GB range reported by Win95, but at least you don't have to worry
about which API function to call in code you write. }
var
GetDiskFreeSpaceEx: function (Directory: PChar; var FreeAvailable,
TotalSpace: TLargeInteger; TotalFree: PLargeInteger): Bool stdcall = nil;
{ SafeLoadLibrary calls LoadLibrary, disabling normal Win32 error message
popup dialogs if the requested file can't be loaded. SafeLoadLibrary also
preserves the current FPU control word (precision, exception masks) across
the LoadLibrary call (in case the DLL you're loading hammers the FPU control
word in its initialization, as many MS DLLs do)}
function SafeLoadLibrary(const Filename: string;
ErrorMode: UINT = SEM_NOOPENFILEERRORBOX): HMODULE;
{ Thread synchronization }
{ TMultiReadExclusiveWriteSynchronizer minimizes thread serialization to gain
read access to a resource shared among threads while still providing complete
exclusivity to callers needing write access to the shared resource.
(multithread shared reads, single thread exclusive write)
Reading is allowed while owning a write lock.
Read locks can be promoted to write locks.}
type
TActiveThreadRecord = record
ThreadID: Integer;
RecursionCount: Integer;
end;
TActiveThreadArray = array of TActiveThreadRecord;
TMultiReadExclusiveWriteSynchronizer = class
private
FLock: TRTLCriticalSection;
FReadExit: THandle;
FCount: Integer;
FSaveReadCount: Integer;
FActiveThreads: TActiveThreadArray;
FWriteRequestorID: Integer;
FReallocFlag: Integer;
FWriting: Boolean;
function WriterIsOnlyReader: Boolean;
public
constructor Create;
destructor Destroy; override;
procedure BeginRead;
procedure EndRead;
procedure BeginWrite;
procedure EndWrite;
end;
implementation
{ Utility routines }
procedure DivMod(Dividend: Integer; Divisor: Word;
var Result, Remainder: Word);
asm
PUSH EBX
MOV EBX,EDX
MOV EDX,EAX
SHR EDX,16
DIV BX
MOV EBX,Remainder
MOV [ECX],AX
MOV [EBX],DX
POP EBX
end;
procedure ConvertError(const Ident: string);
begin
raise EConvertError.Create(Ident);
end;
procedure ConvertErrorFmt(ResString: PResStringRec; const Args: array of const);
begin
raise EConvertError.CreateFmt(LoadResString(ResString), Args);
end;
{ Memory management routines }
function AllocMem(Size: Cardinal): Pointer;
begin
GetMem(Result, Size);
FillChar(Result^, Size, 0);
end;
{ Exit procedure handling }
type
PExitProcInfo = ^TExitProcInfo;
TExitProcInfo = record
Next: PExitProcInfo;
SaveExit: Pointer;
Proc: TProcedure;
end;
const
ExitProcList: PExitProcInfo = nil;
procedure DoExitProc;
var
P: PExitProcInfo;
Proc: TProcedure;
begin
P := ExitProcList;
ExitProcList := P^.Next;
ExitProc := P^.SaveExit;
Proc := P^.Proc;
Dispose(P);
Proc;
end;
procedure AddExitProc(Proc: TProcedure);
var
P: PExitProcInfo;
begin
New(P);
P^.Next := ExitProcList;
P^.SaveExit := ExitProc;
P^.Proc := Proc;
ExitProcList := P;
ExitProc := @DoExitProc;
end;
{ String handling routines }
function NewStr(const S: string): PString;
begin
if S = '' then Result := NullStr else
begin
New(Result);
Result^ := S;
end;
end;
procedure DisposeStr(P: PString);
begin
if (P <> nil) and (P^ <> '') then Dispose(P);
end;
procedure AssignStr(var P: PString; const S: string);
var
Temp: PString;
begin
Temp := P;
P := NewStr(S);
DisposeStr(Temp);
end;
procedure AppendStr(var Dest: string; const S: string);
begin
Dest := Dest + S;
end;
function UpperCase(const S: string): string;
var
Ch: Char;
L: Integer;
Source, Dest: PChar;
begin
L := Length(S);
SetLength(Result, L);
Source := Pointer(S);
Dest := Pointer(Result);
while L <> 0 do
begin
Ch := Source^;
if (Ch >= 'a') and (Ch <= 'z') then Dec(Ch, 32);
Dest^ := Ch;
Inc(Source);
Inc(Dest);
Dec(L);
end;
end;
function LowerCase(const S: string): string;
var
Ch: Char;
L: Integer;
Source, Dest: PChar;
begin
L := Length(S);
SetLength(Result, L);
Source := Pointer(S);
Dest := Pointer(Result);
while L <> 0 do
begin
Ch := Source^;
if (Ch >= 'A') and (Ch <= 'Z') then Inc(Ch, 32);
Dest^ := Ch;
Inc(Source);
Inc(Dest);
Dec(L);
end;
end;
function CompareStr(const S1, S2: string): Integer; assembler;
asm
PUSH ESI
PUSH EDI
MOV ESI,EAX
MOV EDI,EDX
OR EAX,EAX
JE @@1
MOV EAX,[EAX-4]
@@1: OR EDX,EDX
JE @@2
MOV EDX,[EDX-4]
@@2: MOV ECX,EAX
CMP ECX,EDX
JBE @@3
MOV ECX,EDX
@@3: CMP ECX,ECX
REPE CMPSB
JE @@4
MOVZX EAX,BYTE PTR [ESI-1]
MOVZX EDX,BYTE PTR [EDI-1]
@@4: SUB EAX,EDX
POP EDI
POP ESI
end;
function CompareMem(P1, P2: Pointer; Length: Integer): Boolean; assembler;
asm
PUSH ESI
PUSH EDI
MOV ESI,P1
MOV EDI,P2
MOV EDX,ECX
XOR EAX,EAX
AND EDX,3
SHR ECX,1
SHR ECX,1
REPE CMPSD
JNE @@2
MOV ECX,EDX
REPE CMPSB
JNE @@2
@@1: INC EAX
@@2: POP EDI
POP ESI
end;
function CompareText(const S1, S2: string): Integer; assembler;
asm
PUSH ESI
PUSH EDI
PUSH EBX
MOV ESI,EAX
MOV EDI,EDX
OR EAX,EAX
JE @@0
MOV EAX,[EAX-4]
@@0: OR EDX,EDX
JE @@1
MOV EDX,[EDX-4]
@@1: MOV ECX,EAX
CMP ECX,EDX
JBE @@2
MOV ECX,EDX
@@2: CMP ECX,ECX
@@3: REPE CMPSB
JE @@6
MOV BL,BYTE PTR [ESI-1]
CMP BL,'a'
JB @@4
CMP BL,'z'
JA @@4
SUB BL,20H
@@4: MOV BH,BYTE PTR [EDI-1]
CMP BH,'a'
JB @@5
CMP BH,'z'
JA @@5
SUB BH,20H
@@5: CMP BL,BH
JE @@3
MOVZX EAX,BL
MOVZX EDX,BH
@@6: SUB EAX,EDX
POP EBX
POP EDI
POP ESI
end;
function SameText(const S1, S2: string): Boolean; assembler;
asm
CMP EAX,EDX
JZ @1
OR EAX,EAX
JZ @2
OR EDX,EDX
JZ @3
MOV ECX,[EAX-4]
CMP ECX,[EDX-4]
JNE @3
CALL CompareText
TEST EAX,EAX
JNZ @3
@1: MOV AL,1
@2: RET
@3: XOR EAX,EAX
end;
function AnsiUpperCase(const S: string): string;
var
Len: Integer;
begin
Len := Length(S);
SetString(Result, PChar(S), Len);
if Len > 0 then CharUpperBuff(Pointer(Result), Len);
end;
function AnsiLowerCase(const S: string): string;
var
Len: Integer;
begin
Len := Length(S);
SetString(Result, PChar(S), Len);
if Len > 0 then CharLowerBuff(Pointer(Result), Len);
end;
function AnsiCompareStr(const S1, S2: string): Integer;
begin
Result := CompareString(LOCALE_USER_DEFAULT, 0, PChar(S1), Length(S1),
PChar(S2), Length(S2)) - 2;
end;
function AnsiSameStr(const S1, S2: string): Boolean;
begin
Result := CompareString(LOCALE_USER_DEFAULT, 0, PChar(S1), Length(S1),
PChar(S2), Length(S2)) = 2;
end;
function AnsiCompareText(const S1, S2: string): Integer;
begin
Result := CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, PChar(S1),
Length(S1), PChar(S2), Length(S2)) - 2;
end;
function AnsiSameText(const S1, S2: string): Boolean;
begin
Result := CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, PChar(S1),
Length(S1), PChar(S2), Length(S2)) = 2;
end;
function AnsiStrComp(S1, S2: PChar): Integer;
begin
Result := CompareString(LOCALE_USER_DEFAULT, 0, S1, -1, S2, -1) - 2;
end;
function AnsiStrIComp(S1, S2: PChar): Integer;
begin
Result := CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE, S1, -1,
S2, -1) - 2;
end;
function AnsiStrLComp(S1, S2: PChar; MaxLen: Cardinal): Integer;
begin
Result := CompareString(LOCALE_USER_DEFAULT, 0,
S1, MaxLen, S2, MaxLen) - 2;
end;
function AnsiStrLIComp(S1, S2: PChar; MaxLen: Cardinal): Integer;
begin
Result := CompareString(LOCALE_USER_DEFAULT, NORM_IGNORECASE,
S1, MaxLen, S2, MaxLen) - 2;
end;
function AnsiStrLower(Str: PChar): PChar;
begin
CharLower(Str);
Result := Str;
end;
function AnsiStrUpper(Str: PChar): PChar;
begin
CharUpper(Str);
Result := Str;
end;
function Trim(const S: string): string;
var
I, L: Integer;
begin
L := Length(S);
I := 1;
while (I <= L) and (S[I] <= ' ') do Inc(I);
if I > L then Result := '' else
begin
while S[L] <= ' ' do Dec(L);
Result := Copy(S, I, L - I + 1);
end;
end;
function TrimLeft(const S: string): string;
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;
function TrimRight(const S: string): string;
var
I: Integer;
begin
I := Length(S);
while (I > 0) and (S[I] <= ' ') do Dec(I);
Result := Copy(S, 1, I);
end;
function QuotedStr(const S: string): string;
var
I: Integer;
begin
Result := S;
for I := Length(Result) downto 1 do
if Result[I] = '''' then Insert('''', Result, I);
Result := '''' + Result + '''';
end;
function AnsiQuotedStr(const S: string; Quote: Char): string;
var
P, Src, Dest: PChar;
AddCount: Integer;
begin
AddCount := 0;
P := AnsiStrScan(PChar(S), Quote);
while P <> nil do
begin
Inc(P);
Inc(AddCount);
P := AnsiStrScan(P, Quote);
end;
if AddCount = 0 then
begin
Result := Quote + S + Quote;
Exit;
end;
SetLength(Result, Length(S) + AddCount + 2);
Dest := Pointer(Result);
Dest^ := Quote;
Inc(Dest);
Src := Pointer(S);
P := AnsiStrScan(Src, Quote);
repeat
Inc(P);
Move(Src^, Dest^, P - Src);
Inc(Dest, P - Src);
Dest^ := Quote;
Inc(Dest);
Src := P;
P := AnsiStrScan(Src, Quote);
until P = nil;
P := StrEnd(Src);
Move(Src^, Dest^, P - Src);
Inc(Dest, P - Src);
Dest^ := Quote;
end;
function AnsiExtractQuotedStr(var Src: PChar; Quote: Char): string;
var
P, Dest: PChar;
DropCount: Integer;
begin
Result := '';
if (Src = nil) or (Src^ <> Quote) then Exit;
Inc(Src);
DropCount := 1;
P := Src;
Src := AnsiStrScan(Src, Quote);
while Src <> nil do // count adjacent pairs of quote chars
begin
Inc(Src);
if Src^ <> Quote then Break;
Inc(Src);
Inc(DropCount);
Src := AnsiStrScan(Src, Quote);
end;
if Src = nil then Src := StrEnd(P);
if ((Src - P) <= 1) then Exit;
if DropCount = 1 then
SetString(Result, P, Src - P - 1)
else
begin
SetLength(Result, Src - P - DropCount);
Dest := PChar(Result);
Src := AnsiStrScan(P, Quote);
while Src <> nil do
begin
Inc(Src);
if Src^ <> Quote then Break;
Move(P^, Dest^, Src - P);
Inc(Dest, Src - P);
Inc(Src);
P := Src;
Src := AnsiStrScan(Src, Quote);
end;
if Src = nil then Src := StrEnd(P);
Move(P^, Dest^, Src - P - 1);
end;
end;
function AdjustLineBreaks(const S: string): string;
var
Source, SourceEnd, Dest: PChar;
Extra: Integer;
begin
Source := Pointer(S);
SourceEnd := Source + Length(S);
Extra := 0;
while Source < SourceEnd do
begin
case Source^ of
#10:
Inc(Extra);
#13:
if Source[1] = #10 then Inc(Source) else Inc(Extra);
else
if Source^ in LeadBytes then
Inc(Source)
end;
Inc(Source);
end;
if Extra = 0 then Result := S else
begin
Source := Pointer(S);
SetString(Result, nil, SourceEnd - Source + Extra);
Dest := Pointer(Result);
while Source < SourceEnd do
case Source^ of
#10:
begin
Dest^ := #13;
Inc(Dest);
Dest^ := #10;
Inc(Dest);
Inc(Source);
end;
#13:
begin
Dest^ := #13;
Inc(Dest);
Dest^ := #10;
Inc(Dest);
Inc(Source);
if Source^ = #10 then Inc(Source);
end;
else
if Source^ in LeadBytes then
begin
Dest^ := Source^;
Inc(Dest);
Inc(Source);
end;
Dest^ := Source^;
Inc(Dest);
Inc(Source);
end;
end;
end;
function IsValidIdent(const Ident: string): Boolean;
const
Alpha = ['A'..'Z', 'a'..'z', '_'];
AlphaNumeric = Alpha + ['0'..'9'];
var
I: Integer;
begin
Result := False;
if (Length(Ident) = 0) or not (Ident[1] in Alpha) then Exit;
for I := 2 to Length(Ident) do if not (Ident[I] in AlphaNumeric) then Exit;
Result := True;
end;
function IntToStr(Value: Integer): string;
begin
FmtStr(Result, '%d', [Value]);
end;
function IntToStr(Value: Int64): string;
begin
FmtStr(Result, '%d', [Value]);
end;
function IntToHex(Value: Integer; Digits: Integer): string;
begin
FmtStr(Result, '%.*x', [Digits, Value]);
end;
function IntToHex(Value: Int64; Digits: Integer): string;
begin
FmtStr(Result, '%.*x', [Digits, Value]);
end;
function StrToInt(const S: string): Integer;
var
E: Integer;
begin
Val(S, Result, E);
if E <> 0 then ConvertErrorFmt(@SInvalidInteger, [S]);
end;
function StrToInt64(const S: string): Int64;
var
E: Integer;
begin
Val(S, Result, E);
if E <> 0 then ConvertErrorFmt(@SInvalidInteger, [S]);
end;
function StrToIntDef(const S: string; Default: Integer): Integer;
var
E: Integer;
begin
Val(S, Result, E);
if E <> 0 then Result := Default;
end;
function StrToInt64Def(const S: string; Default: Int64): Int64;
var
E: Integer;
begin
Val(S, Result, E);
if E <> 0 then Result := Default;
end;
type
PStrData = ^TStrData;
TStrData = record
Ident: Integer;
Buffer: PChar;
BufSize: Integer;
nChars: Integer;
end;
function EnumStringModules(Instance: Longint; Data: Pointer): Boolean;
begin
with PStrData(Data)^ do
begin
nChars := LoadString(Instance, Ident, Buffer, BufSize);
Result := nChars = 0;
end;
end;
function FindStringResource(Ident: Integer; Buffer: PChar; BufSize: Integer): Integer;
var
StrData: TStrData;
begin
StrData.Ident := Ident;
StrData.Buffer := Buffer;
StrData.BufSize := BufSize;
StrData.nChars := 0;
EnumResourceModules(EnumStringModules, @StrData);
Result := StrData.nChars;
end;
function LoadStr(Ident: Integer): string;
var
Buffer: array[0..1023] of Char;
begin
SetString(Result, Buffer, FindStringResource(Ident, Buffer, SizeOf(Buffer)));
end;
function FmtLoadStr(Ident: Integer; const Args: array of const): string;
begin
FmtStr(Result, LoadStr(Ident), Args);
end;
{ File management routines }
function FileOpen(const FileName: string; Mode: LongWord): Integer;
const
AccessMode: array[0..2] of LongWord = (
GENERIC_READ,
GENERIC_WRITE,
GENERIC_READ or GENERIC_WRITE);
ShareMode: array[0..4] of LongWord = (
0,
0,
FILE_SHARE_READ,
FILE_SHARE_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE);
begin
Result := Integer(CreateFile(PChar(FileName), AccessMode[Mode and 3],
ShareMode[(Mode and $F0) shr 4], nil, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, 0));
end;
function FileCreate(const FileName: string): Integer;
begin
Result := Integer(CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE,
0, nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0));
end;
function FileRead(Handle: Integer; var Buffer; Count: LongWord): Integer;
begin
if not ReadFile(THandle(Handle), Buffer, Count, LongWord(Result), nil) then
Result := -1;
end;
function FileWrite(Handle: Integer; const Buffer; Count: LongWord): Integer;
begin
if not WriteFile(THandle(Handle), Buffer, Count, LongWord(Result), nil) then
Result := -1;
end;
function FileSeek(Handle, Offset, Origin: Integer): Integer;
begin
Result := SetFilePointer(THandle(Handle), Offset, nil, Origin);
end;
function FileSeek(Handle: Integer; const Offset: Int64; Origin: Integer): Int64;
begin
Result := Offset;
Int64Rec(Result).Lo := SetFilePointer(THandle(Handle), Int64Rec(Result).Lo,
@Int64Rec(Result).Hi, Origin);
end;
procedure FileClose(Handle: Integer);
begin
CloseHandle(THandle(Handle));
end;
function FileAge(const FileName: string): Integer;
var
Handle: THandle;
FindData: TWin32FindData;
LocalFileTime: TFileTime;
begin
Handle := FindFirstFile(PChar(FileName), FindData);
if Handle <> INVALID_HANDLE_VALUE then
begin
Windows.FindClose(Handle);
if (FindData.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) = 0 then
begin
FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
if FileTimeToDosDateTime(LocalFileTime, LongRec(Result).Hi,
LongRec(Result).Lo) then Exit;
end;
end;
Result := -1;
end;
function FileExists(const FileName: string): Boolean;
begin
Result := FileAge(FileName) <> -1;
end;
function FileGetDate(Handle: Integer): Integer;
var
FileTime, LocalFileTime: TFileTime;
begin
if GetFileTime(THandle(Handle), nil, nil, @FileTime) and
FileTimeToLocalFileTime(FileTime, LocalFileTime) and
FileTimeToDosDateTime(LocalFileTime, LongRec(Result).Hi,
LongRec(Result).Lo) then Exit;
Result := -1;
end;
function FileSetDate(Handle: Integer; Age: Integer): Integer;
var
LocalFileTime, FileTime: TFileTime;
begin
Result := 0;
if DosDateTimeToFileTime(LongRec(Age).Hi, LongRec(Age).Lo, LocalFileTime) and
LocalFileTimeToFileTime(LocalFileTime, FileTime) and
SetFileTime(Handle, nil, nil, @FileTime) then Exit;
Result := GetLastError;
end;
function FileGetAttr(const FileName: string): Integer;
begin
Result := GetFileAttributes(PChar(FileName));
end;
function FileSetAttr(const FileName: string; Attr: Integer): Integer;
begin
Result := 0;
if not SetFileAttributes(PChar(FileName), Attr) then
Result := GetLastError;
end;
function FindMatchingFile(var F: TSearchRec): Integer;
var
LocalFileTime: TFileTime;
begin
with F do
begin
while FindData.dwFileAttributes and ExcludeAttr <> 0 do
if not FindNextFile(FindHandle, FindData) then
begin
Result := GetLastError;
Exit;
end;
FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
FileTimeToDosDateTime(LocalFileTime, LongRec(Time).Hi,
LongRec(Time).Lo);
Size := FindData.nFileSizeLow;
Attr := FindData.dwFileAttributes;
Name := FindData.cFileName;
end;
Result := 0;
end;
function FindFirst(const Path: string; Attr: Integer;
var F: TSearchRec): Integer;
const
faSpecial = faHidden or faSysFile or faVolumeID or faDirectory;
begin
F.ExcludeAttr := not Attr and faSpecial;
F.FindHandle := FindFirstFile(PChar(Path), F.FindData);
if F.FindHandle <> INVALID_HANDLE_VALUE then
begin
Result := FindMatchingFile(F);
if Result <> 0 then FindClose(F);
end else
Result := GetLastError;
end;
function FindNext(var F: TSearchRec): Integer;
begin
if FindNextFile(F.FindHandle, F.FindData) then
Result := FindMatchingFile(F) else
Result := GetLastError;
end;
procedure FindClose(var F: TSearchRec);
begin
if F.FindHandle <> INVALID_HANDLE_VALUE then
begin
Windows.FindClose(F.FindHandle);
F.FindHandle := INVALID_HANDLE_VALUE;
end;
end;
function DeleteFile(const FileName: string): Boolean;
begin
Result := Windows.DeleteFile(PChar(FileName));
end;
function RenameFile(const OldName, NewName: string): Boolean;
begin
Result := MoveFile(PChar(OldName), PChar(NewName));
end;
function AnsiStrLastChar(P: PChar): PChar;
var
LastByte: Integer;
begin
LastByte := StrLen(P) - 1;
Result := @P[LastByte];
if StrByteType(P, LastByte) = mbTrailByte then Dec(Result);
end;
function AnsiLastChar(const S: string): PChar;
var
LastByte: Integer;
begin
LastByte := Length(S);
if LastByte <> 0 then
begin
Result := @S[LastByte];
if ByteType(S, LastByte) = mbTrailByte then Dec(Result);
end
else
Result := nil;
end;
function LastDelimiter(const Delimiters, S: string): Integer;
var
P: PChar;
begin
Result := Length(S);
P := PChar(Delimiters);
while Result > 0 do
begin
if (S[Result] <> #0) and (StrScan(P, S[Result]) <> nil) then
if (ByteType(S, Result) = mbTrailByte) then
Dec(Result)
else
Exit;
Dec(Result);
end;
end;
function ChangeFileExt(const FileName, Extension: string): string;
var
I: Integer;
begin
I := LastDelimiter('.\:',Filename);
if (I = 0) or (FileName[I] <> '.') then I := MaxInt;
Result := Copy(FileName, 1, I - 1) + Extension;
end;
function ExtractFilePath(const FileName: string): string;
var
I: Integer;
begin
I := LastDelimiter('\:', FileName);
Result := Copy(FileName, 1, I);
end;
function ExtractFileDir(const FileName: string): string;
var
I: Integer;
begin
I := LastDelimiter('\:',Filename);
if (I > 1) and (FileName[I] = '\') and
(not (FileName[I - 1] in ['\', ':']) or
(ByteType(FileName, I-1) = mbTrailByte)) then Dec(I);
Result := Copy(FileName, 1, I);
end;
function ExtractFileDrive(const FileName: string): string;
var
I, J: Integer;
begin
if (Length(FileName) >= 2) and (FileName[2] = ':') then
Result := Copy(FileName, 1, 2)
else if (Length(FileName) >= 2) and (FileName[1] = '\') and
(FileName[2] = '\') then
begin
J := 0;
I := 3;
While (I < Length(FileName)) and (J < 2) do
begin
if FileName[I] = '\' then Inc(J);
if J < 2 then Inc(I);
end;
if FileName[I] = '\' then Dec(I);
Result := Copy(FileName, 1, I);
end else Result := '';
end;
function ExtractFileName(const FileName: string): string;
var
I: Integer;
begin
I := LastDelimiter('\:', FileName);
Result := Copy(FileName, I + 1, MaxInt);
end;
function ExtractFileExt(const FileName: string): string;
var
I: Integer;
begin
I := LastDelimiter('.\:', FileName);
if (I > 0) and (FileName[I] = '.') then
Result := Copy(FileName, I, MaxInt) else
Result := '';
end;
function ExpandFileName(const FileName: string): string;
var
FName: PChar;
Buffer: array[0..MAX_PATH - 1] of Char;
begin
SetString(Result, Buffer, GetFullPathName(PChar(FileName), SizeOf(Buffer),
Buffer, FName));
end;
function GetUniversalName(const FileName: string): string;
type
PNetResourceArray = ^TNetResourceArray;
TNetResourceArray = array[0..MaxInt div SizeOf(TNetResource) - 1] of TNetResource;
var
I, BufSize, NetResult: Integer;
Count, Size: LongWord;
Drive: Char;
NetHandle: THandle;
NetResources: PNetResourceArray;
RemoteNameInfo: array[0..1023] of Byte;
begin
Result := FileName;
if (Win32Platform <> VER_PLATFORM_WIN32_WINDOWS) or (Win32MajorVersion > 4) then
begin
Size := SizeOf(RemoteNameInfo);
if WNetGetUniversalName(PChar(FileName), UNIVERSAL_NAME_INFO_LEVEL,
@RemoteNameInfo, Size) <> NO_ERROR then Exit;
Result := PRemoteNameInfo(@RemoteNameInfo).lpUniversalName;
end else
begin
{ The following works around a bug in WNetGetUniversalName under Windows 95 }
Drive := UpCase(FileName[1]);
if (Drive < 'A') or (Drive > 'Z') or (Length(FileName) < 3) or
(FileName[2] <> ':') or (FileName[3] <> '\') then
Exit;
if WNetOpenEnum(RESOURCE_CONNECTED, RESOURCETYPE_DISK, 0, nil,
NetHandle) <> NO_ERROR then Exit;
try
BufSize := 50 * SizeOf(TNetResource);
GetMem(NetResources, BufSize);
try
while True do
begin
Count := $FFFFFFFF;
Size := BufSize;
NetResult := WNetEnumResource(NetHandle, Count, NetResources, Size);
if NetResult = ERROR_MORE_DATA then
begin
BufSize := Size;
ReallocMem(NetResources, BufSize);
Continue;
end;
if NetResult <> NO_ERROR then Exit;
for I := 0 to Count - 1 do
with NetResources^[I] do
if (lpLocalName <> nil) and (Drive = UpCase(lpLocalName[0])) then
begin
Result := lpRemoteName + Copy(FileName, 3, Length(FileName) - 2);
Exit;
end;
end;
finally
FreeMem(NetResources, BufSize);
end;
finally
WNetCloseEnum(NetHandle);
end;
end;
end;
function ExpandUNCFileName(const FileName: string): string;
begin
{ First get the local resource version of the file name }
Result := ExpandFileName(FileName);
if (Length(Result) >= 3) and (Result[2] = ':') and (Upcase(Result[1]) >= 'A')
and (Upcase(Result[1]) <= 'Z') then
Result := GetUniversalName(Result);
end;
function ExtractRelativePath(const BaseName, DestName: string): string;
var
BasePath, DestPath: string;
BaseDirs, DestDirs: array[0..129] of PChar;
BaseDirCount, DestDirCount: Integer;
I, J: Integer;
function ExtractFilePathNoDrive(const FileName: string): string;
begin
Result := ExtractFilePath(FileName);
Result := Copy(Result, Length(ExtractFileDrive(FileName)) + 1, 32767);
end;
procedure SplitDirs(var Path: string; var Dirs: array of PChar;
var DirCount: Integer);
var
I, J: Integer;
begin
I := 1;
J := 0;
while I <= Length(Path) do
begin
if Path[I] in LeadBytes then Inc(I)
else if Path[I] = '\' then { Do not localize }
begin
Path[I] := #0;
Dirs[J] := @Path[I + 1];
Inc(J);
end;
Inc(I);
end;
DirCount := J - 1;
end;
begin
if AnsiCompareText(ExtractFileDrive(BaseName), ExtractFileDrive(DestName)) = 0 then
begin
BasePath := ExtractFilePathNoDrive(BaseName);
DestPath := ExtractFilePathNoDrive(DestName);
SplitDirs(BasePath, BaseDirs, BaseDirCount);
SplitDirs(DestPath, DestDirs, DestDirCount);
I := 0;
while (I < BaseDirCount) and (I < DestDirCount) do
begin
if AnsiStrIComp(BaseDirs[I], DestDirs[I]) = 0 then
Inc(I)
else Break;
end;
Result := '';
for J := I to BaseDirCount - 1 do
Result := Result + '..\'; { Do not localize }
for J := I to DestDirCount - 1 do
Result := Result + DestDirs[J] + '\'; { Do not localize }
Result := Result + ExtractFileName(DestName);
end else Result := DestName;
end;
function ExtractShortPathName(const FileName: string): string;
var
Buffer: array[0..MAX_PATH - 1] of Char;
begin
SetString(Result, Buffer,
GetShortPathName(PChar(FileName), Buffer, SizeOf(Buffer)));
end;
function FileSearch(const Name, DirList: string): string;
var
I, P, L: Integer;
begin
Result := Name;
P := 1;
L := Length(DirList);
while True do
begin
if FileExists(Result) then Exit;
while (P <= L) and (DirList[P] = ';') do Inc(P);
if P > L then Break;
I := P;
while (P <= L) and (DirList[P] <> ';') do
begin
if DirList[P] in LeadBytes then Inc(P);
Inc(P);
end;
Result := Copy(DirList, I, P - I);
if not (AnsiLastChar(Result)^ in [':', '\']) then Result := Result + '\';
Result := Result + Name;
end;
Result := '';
end;
// This function is used if the OS doesn't support GetDiskFreeSpaceEx
function BackfillGetDiskFreeSpaceEx(Directory: PChar; var FreeAvailable,
TotalSpace: TLargeInteger; TotalFree: PLargeInteger): Bool; stdcall;
var
SectorsPerCluster, BytesPerSector, FreeClusters, TotalClusters: LongWord;
Temp: Int64;
Dir: PChar;
begin
if Directory <> nil then
Dir := Directory
else
Dir := nil;
Result := GetDiskFreeSpaceA(Dir, SectorsPerCluster, BytesPerSector,
FreeClusters, TotalClusters);
Temp := SectorsPerCluster * BytesPerSector;
FreeAvailable := Temp * FreeClusters;
TotalSpace := Temp * TotalClusters;
end;
function InternalGetDiskSpace(Drive: Byte;
var TotalSpace, FreeSpaceAvailable: Int64): Bool;
var
RootPath: array[0..4] of Char;
RootPtr: PChar;
begin
RootPtr := nil;
if Drive > 0 then
begin
RootPath[0] := Char(Drive + $40);
RootPath[1] := ':';
RootPath[2] := '\';
RootPath[3] := #0;
RootPtr := RootPath;
end;
Result := GetDiskFreeSpaceEx(RootPtr, FreeSpaceAvailable, TotalSpace, nil);
end;
function DiskFree(Drive: Byte): Int64;
var
TotalSpace: Int64;
begin
if not InternalGetDiskSpace(Drive, TotalSpace, Result) then
Result := -1;
end;
function DiskSize(Drive: Byte): Int64;
var
FreeSpace: Int64;
begin
if not InternalGetDiskSpace(Drive, Result, FreeSpace) then
Result := -1;
end;
function FileDateToDateTime(FileDate: Integer): TDateTime;
begin
Result :=
EncodeDate(
LongRec(FileDate).Hi shr 9 + 1980,
LongRec(FileDate).Hi shr 5 and 15,
LongRec(FileDate).Hi and 31) +
EncodeTime(
LongRec(FileDate).Lo shr 11,
LongRec(FileDate).Lo shr 5 and 63,
LongRec(FileDate).Lo and 31 shl 1, 0);
end;
function DateTimeToFileDate(DateTime: TDateTime): Integer;
var
Year, Month, Day, Hour, Min, Sec, MSec: Word;
begin
DecodeDate(DateTime, Year, Month, Day);
if (Year < 1980) or (Year > 2099) then Result := 0 else
begin
DecodeTime(DateTime, Hour, Min, Sec, MSec);
LongRec(Result).Lo := (Sec shr 1) or (Min shl 5) or (Hour shl 11);
LongRec(Result).Hi := Day or (Month shl 5) or ((Year - 1980) shl 9);
end;
end;
function GetCurrentDir: string;
var
Buffer: array[0..MAX_PATH - 1] of Char;
begin
SetString(Result, Buffer, GetCurrentDirectory(SizeOf(Buffer), Buffer));
end;
function SetCurrentDir(const Dir: string): Boolean;
begin
Result := SetCurrentDirectory(PChar(Dir));
end;
function CreateDir(const Dir: string): Boolean;
begin
Result := CreateDirectory(PChar(Dir), nil);
end;
function RemoveDir(const Dir: string): Boolean;
begin
Result := RemoveDirectory(PChar(Dir));
end;
{ PChar routines }
function StrLen(const Str: PChar): Cardinal; assembler;
asm
MOV EDX,EDI
MOV EDI,EAX
MOV ECX,0FFFFFFFFH
XOR AL,AL
REPNE SCASB
MOV EAX,0FFFFFFFEH
SUB EAX,ECX
MOV EDI,EDX
end;
function StrEnd(const Str: PChar): PChar; assembler;
asm
MOV EDX,EDI
MOV EDI,EAX
MOV ECX,0FFFFFFFFH
XOR AL,AL
REPNE SCASB
LEA EAX,[EDI-1]
MOV EDI,EDX
end;
function StrMove(Dest: PChar; const Source: PChar; Count: Cardinal): PChar; assembler;
asm
PUSH ESI
PUSH EDI
MOV ESI,EDX
MOV EDI,EAX
MOV EDX,ECX
CMP EDI,ESI
JA @@1
JE @@2
SHR ECX,2
REP MOVSD
MOV ECX,EDX
AND ECX,3
REP MOVSB
JMP @@2
@@1: LEA ESI,[ESI+ECX-1]
LEA EDI,[EDI+ECX-1]
AND ECX,3
STD
REP MOVSB
SUB ESI,3
SUB EDI,3
MOV ECX,EDX
SHR ECX,2
REP MOVSD
CLD
@@2: POP EDI
POP ESI
end;
function StrCopy(Dest: PChar; const Source: PChar): PChar; assembler;
asm
PUSH EDI
PUSH ESI
MOV ESI,EAX
MOV EDI,EDX
MOV ECX,0FFFFFFFFH
XOR AL,AL
REPNE SCASB
NOT ECX
MOV EDI,ESI
MOV ESI,EDX
MOV EDX,ECX
MOV EAX,EDI
SHR ECX,2
REP MOVSD
MOV ECX,EDX
AND ECX,3
REP MOVSB
POP ESI
POP EDI
end;
function StrECopy(Dest: PChar; const Source: PChar): PChar; assembler;
asm
PUSH EDI
PUSH ESI
MOV ESI,EAX
MOV EDI,EDX
MOV ECX,0FFFFFFFFH
XOR AL,AL
REPNE SCASB
NOT ECX
MOV EDI,ESI
MOV ESI,EDX
MOV EDX,ECX
SHR ECX,2
REP MOVSD
MOV ECX,EDX
AND ECX,3
REP MOVSB
LEA EAX,[EDI-1]
POP ESI
POP EDI
end;
function StrLCopy(Dest: PChar; const Source: PChar; MaxLen: Cardinal): PChar; assembler;
asm
PUSH EDI
PUSH ESI
PUSH EBX
MOV ESI,EAX
MOV EDI,EDX
MOV EBX,ECX
XOR AL,AL
TEST ECX,ECX
JZ @@1
REPNE SCASB
JNE @@1
INC ECX
@@1: SUB EBX,ECX
MOV EDI,ESI
MOV ESI,EDX
MOV EDX,EDI
MOV ECX,EBX
SHR ECX,2
REP MOVSD
MOV ECX,EBX
AND ECX,3
REP MOVSB
STOSB
MOV EAX,EDX
POP EBX
POP ESI
POP EDI
end;
function StrPCopy(Dest: PChar; const Source: string): PChar;
begin
Result := StrLCopy(Dest, PChar(Source), Length(Source));
end;
function StrPLCopy(Dest: PChar; const Source: string;
MaxLen: Cardinal): PChar;
begin
Result := StrLCopy(Dest, PChar(Source), MaxLen);
end;
function StrCat(Dest: PChar; const Source: PChar): PChar;
begin
StrCopy(StrEnd(Dest), Source);
Result := Dest;
end;
function StrLCat(Dest: PChar; const Source: PChar; MaxLen: Cardinal): PChar; assembler;
asm
PUSH EDI
PUSH ESI
PUSH EBX
MOV EDI,Dest
MOV ESI,Source
MOV EBX,MaxLen
CALL StrEnd
MOV ECX,EDI
ADD ECX,EBX
SUB ECX,EAX
JBE @@1
MOV EDX,ESI
CALL StrLCopy
@@1: MOV EAX,EDI
POP EBX
POP ESI
POP EDI
end;
function StrComp(const Str1, Str2: PChar): Integer; assembler;
asm
PUSH EDI
PUSH ESI
MOV EDI,EDX
MOV ESI,EAX
MOV ECX,0FFFFFFFFH
XOR EAX,EAX
REPNE SCASB
NOT ECX
MOV EDI,EDX
XOR EDX,EDX
REPE CMPSB
MOV AL,[ESI-1]
MOV DL,[EDI-1]
SUB EAX,EDX
POP ESI
POP EDI
end;
function StrIComp(const Str1, Str2: PChar): Integer; assembler;
asm
PUSH EDI
PUSH ESI
MOV EDI,EDX
MOV ESI,EAX
MOV ECX,0FFFFFFFFH
XOR EAX,EAX
REPNE SCASB
NOT ECX
MOV EDI,EDX
XOR EDX,EDX
@@1: REPE CMPSB
JE @@4
MOV AL,[ESI-1]
CMP AL,'a'
JB @@2
CMP AL,'z'
JA @@2
SUB AL,20H
@@2: MOV DL,[EDI-1]
CMP DL,'a'
JB @@3
CMP DL,'z'
JA @@3
SUB DL,20H
@@3: SUB EAX,EDX
JE @@1
@@4: POP ESI
POP EDI
end;
function StrLComp(const Str1, Str2: PChar; MaxLen: Cardinal): Integer; assembler;
asm
PUSH EDI
PUSH ESI
PUSH EBX
MOV EDI,EDX
MOV ESI,EAX
MOV EBX,ECX
XOR EAX,EAX
OR ECX,ECX
JE @@1
REPNE SCASB
SUB EBX,ECX
MOV ECX,EBX
MOV EDI,EDX
XOR EDX,EDX
REPE CMPSB
MOV AL,[ESI-1]
MOV DL,[EDI-1]
SUB EAX,EDX
@@1: POP EBX
POP ESI
POP EDI
end;
function StrLIComp(const Str1, Str2: PChar; MaxLen: Cardinal): Integer; assembler;
asm
PUSH EDI
PUSH ESI
PUSH EBX
MOV EDI,EDX
MOV ESI,EAX
MOV EBX,ECX
XOR EAX,EAX
OR ECX,ECX
JE @@4
REPNE SCASB
SUB EBX,ECX
MOV ECX,EBX
MOV EDI,EDX
XOR EDX,EDX
@@1: REPE CMPSB
JE @@4
MOV AL,[ESI-1]
CMP AL,'a'
JB @@2
CMP AL,'z'
JA @@2
SUB AL,20H
@@2: MOV DL,[EDI-1]
CMP DL,'a'
JB @@3
CMP DL,'z'
JA @@3
SUB DL,20H
@@3: SUB EAX,EDX
JE @@1
@@4: POP EBX
POP ESI
POP EDI
end;
function StrScan(const Str: PChar; Chr: Char): PChar; assembler;
asm
PUSH EDI
PUSH EAX
MOV EDI,Str
MOV ECX,0FFFFFFFFH
XOR AL,AL
REPNE SCASB
NOT ECX
POP EDI
MOV AL,Chr
REPNE SCASB
MOV EAX,0
JNE @@1
MOV EAX,EDI
DEC EAX
@@1: POP EDI
end;
function StrRScan(const Str: PChar; Chr: Char): PChar; assembler;
asm
PUSH EDI
MOV EDI,Str
MOV ECX,0FFFFFFFFH
XOR AL,AL
REPNE SCASB
NOT ECX
STD
DEC EDI
MOV AL,Chr
REPNE SCASB
MOV EAX,0
JNE @@1
MOV EAX,EDI
INC EAX
@@1: CLD
POP EDI
end;
function StrPos(const Str1, Str2: PChar): PChar; assembler;
asm
PUSH EDI
PUSH ESI
PUSH EBX
OR EAX,EAX
JE @@2
OR EDX,EDX
JE @@2
MOV EBX,EAX
MOV EDI,EDX
XOR AL,AL
MOV ECX,0FFFFFFFFH
REPNE SCASB
NOT ECX
DEC ECX
JE @@2
MOV ESI,ECX
MOV EDI,EBX
MOV ECX,0FFFFFFFFH
REPNE SCASB
NOT ECX
SUB ECX,ESI
JBE @@2
MOV EDI,EBX
LEA EBX,[ESI-1]
@@1: MOV ESI,EDX
LODSB
REPNE SCASB
JNE @@2
MOV EAX,ECX
PUSH EDI
MOV ECX,EBX
REPE CMPSB
POP EDI
MOV ECX,EAX
JNE @@1
LEA EAX,[EDI-1]
JMP @@3
@@2: XOR EAX,EAX
@@3: POP EBX
POP ESI
POP EDI
end;
function StrUpper(Str: PChar): PChar; assembler;
asm
PUSH ESI
MOV ESI,Str
MOV EDX,Str
@@1: LODSB
OR AL,AL
JE @@2
CMP AL,'a'
JB @@1
CMP AL,'z'
JA @@1
SUB AL,20H
MOV [ESI-1],AL
JMP @@1
@@2: XCHG EAX,EDX
POP ESI
end;
function StrLower(Str: PChar): PChar; assembler;
asm
PUSH ESI
MOV ESI,Str
MOV EDX,Str
@@1: LODSB
OR AL,AL
JE @@2
CMP AL,'A'
JB @@1
CMP AL,'Z'
JA @@1
ADD AL,20H
MOV [ESI-1],AL
JMP @@1
@@2: XCHG EAX,EDX
POP ESI
end;
function StrPas(const Str: PChar): string;
begin
Result := Str;
end;
function StrAlloc(Size: Cardinal): PChar;
begin
Inc(Size, SizeOf(Cardinal));
GetMem(Result, Size);
Cardinal(Pointer(Result)^) := Size;
Inc(Result, SizeOf(Cardinal));
end;
function StrBufSize(const Str: PChar): Cardinal;
var
P: PChar;
begin
P := Str;
Dec(P, SizeOf(Cardinal));
Result := Cardinal(Pointer(P)^) - SizeOf(Cardinal);
end;
function StrNew(const Str: PChar): PChar;
var
Size: Cardinal;
begin
if Str = nil then Result := nil else
begin
Size := StrLen(Str) + 1;
Result := StrMove(StrAlloc(Size), Str, Size);
end;
end;
procedure StrDispose(Str: PChar);
begin
if Str <> nil then
begin
Dec(Str, SizeOf(Cardinal));
FreeMem(Str, Cardinal(Pointer(Str)^));
end;
end;
{ String formatting routines }
procedure FormatError(ErrorCode: Integer; Format: PChar; FmtLen: Cardinal);
const
FormatErrorStrs: array[0..1] of PResStringRec = (
@SInvalidFormat, @SArgumentMissing);
var
Buffer: array[0..31] of Char;
begin
if FmtLen > 31 then FmtLen := 31;
if StrByteType(Format, FmtLen-1) = mbLeadByte then Dec(FmtLen);
StrMove(Buffer, Format, FmtLen);
Buffer[FmtLen] := #0;
ConvertErrorFmt(FormatErrorStrs[ErrorCode], [PChar(@Buffer)]);
end;
procedure FormatVarToStr(var S: string; const V: Variant);
begin
S := V;
end;
procedure FormatClearStr(var S: string);
begin
S := '';
end;
function FormatBuf(var Buffer; BufLen: Cardinal; const Format;
FmtLen: Cardinal; const Args: array of const): Cardinal;
const
C10000: Single = 10000;
var
ArgIndex, Width, Prec: Integer;
BufferOrg, FormatOrg, FormatPtr, TempStr: PChar;
JustFlag: Byte;
StrBuf: array[0..64] of Char;
TempAnsiStr: string;
TempInt64 : int64;
asm
{ in: eax <-> Buffer }
{ in: edx <-> BufLen }
{ in: ecx <-> Format }
PUSH EBX
PUSH ESI
PUSH EDI
MOV EDI,EAX
MOV ESI,ECX
ADD ECX,FmtLen
MOV BufferOrg,EDI
XOR EAX,EAX
MOV ArgIndex,EAX
MOV TempStr,EAX
MOV TempAnsiStr,EAX
@Loop:
OR EDX,EDX
JE @Done
@NextChar:
CMP ESI,ECX
JE @Done
LODSB
CMP AL,'%'
JE @Format
@StoreChar:
STOSB
DEC EDX
JNE @NextChar
@Done:
MOV EAX,EDI
SUB EAX,BufferOrg
JMP @Exit
@Format:
CMP ESI,ECX
JE @Done
LODSB
CMP AL,'%'
JE @StoreChar
LEA EBX,[ESI-2]
MOV FormatOrg,EBX
@A0: MOV JustFlag,AL
CMP AL,'-'
JNE @A1
CMP ESI,ECX
JE @Done
LODSB
@A1: CALL @Specifier
CMP AL,':'
JNE @A2
MOV ArgIndex,EBX
CMP ESI,ECX
JE @Done
LODSB
JMP @A0
@A2: MOV Width,EBX
MOV EBX,-1
CMP AL,'.'
JNE @A3
CMP ESI,ECX
JE @Done
LODSB
CALL @Specifier
@A3: MOV Prec,EBX
MOV FormatPtr,ESI
PUSH ECX
PUSH EDX
CALL @Convert
POP EDX
MOV EBX,Width
SUB EBX,ECX (* ECX <=> number of characters output *)
JAE @A4 (* jump -> output smaller than width *)
XOR EBX,EBX
@A4: CMP JustFlag,'-'
JNE @A6
SUB EDX,ECX
JAE @A5
ADD ECX,EDX
XOR EDX,EDX
@A5: REP MOVSB
@A6: XCHG EBX,ECX
SUB EDX,ECX
JAE @A7
ADD ECX,EDX
XOR EDX,EDX
@A7: MOV AL,' '
REP STOSB
XCHG EBX,ECX
SUB EDX,ECX
JAE @A8
ADD ECX,EDX
XOR EDX,EDX
@A8: REP MOVSB
CMP TempStr,0
JE @A9
PUSH EDX
LEA EAX,TempStr
CALL FormatClearStr
POP EDX
@A9: POP ECX
MOV ESI,FormatPtr
JMP @Loop
@Specifier:
XOR EBX,EBX
CMP AL,'*'
JE @B3
@B1: CMP AL,'0'
JB @B5
CMP AL,'9'
JA @B5
IMUL EBX,EBX,10
SUB AL,'0'
MOVZX EAX,AL
ADD EBX,EAX
CMP ESI,ECX
JE @B2
LODSB
JMP @B1
@B2: POP EAX
JMP @Done
@B3: MOV EAX,ArgIndex
CMP EAX,Args.Integer[-4]
JA @B4
INC ArgIndex
MOV EBX,Args
CMP [EBX+EAX*8].Byte[4],vtInteger
MOV EBX,[EBX+EAX*8]
JE @B4
XOR EBX,EBX
@B4: CMP ESI,ECX
JE @B2
LODSB
@B5: RET
@Convert:
AND AL,0DFH
MOV CL,AL
MOV EAX,1
MOV EBX,ArgIndex
CMP EBX,Args.Integer[-4]
JA @ErrorExit
INC ArgIndex
MOV ESI,Args
LEA ESI,[ESI+EBX*8]
MOV EAX,[ESI].Integer[0] // TVarRec.data
MOVZX EBX,[ESI].Byte[4] // TVarRec.VType
JMP @CvtVector.Pointer[EBX*4]
@CvtVector:
DD @CvtInteger // vtInteger
DD @CvtBoolean // vtBoolean
DD @CvtChar // vtChar
DD @CvtExtended // vtExtended
DD @CvtShortStr // vtString
DD @CvtPointer // vtPointer
DD @CvtPChar // vtPChar
DD @CvtObject // vtObject
DD @CvtClass // vtClass
DD @CvtWideChar // vtWideChar
DD @CvtPWideChar // vtPWideChar
DD @CvtAnsiStr // vtAnsiString
DD @CvtCurrency // vtCurrency
DD @CvtVariant // vtVariant
DD @CvtInterface // vtInterface
DD @CvtWideString // vtWideString
DD @CvtInt64 // vtInt64
@CvtBoolean:
@CvtObject:
@CvtClass:
@CvtWideChar:
@CvtInterface:
@CvtError:
XOR EAX,EAX
@ErrorExit:
CALL @ClearTmpAnsiStr
MOV EDX,FormatOrg
MOV ECX,FormatPtr
SUB ECX,EDX
CALL FormatError
// The above call raises an exception and does not return
@CvtInt64:
// CL <= format character
// EAX <= address of int64
// EBX <= TVarRec.VType
LEA EBX, TempInt64 // (input is array of const; save original)
MOV EDX, [EAX]
MOV [EBX], EDX
MOV EDX, [EAX + 4]
MOV [EBX + 4], EDX
// EBX <= address of TempInt64
CMP CL,'D'
JE @DecI64
CMP CL,'U'
JE @DecI64_2
CMP CL,'X'
JNE @CvtError
@HexI64:
MOV ECX,16 // hex divisor
JMP @CvtI64
@DecI64:
TEST DWORD PTR [EBX + 4], $80000000 // sign bit set?
JE @DecI64_2 // no -> bypass '-' output
NEG DWORD PTR [EBX] // negate lo-order, then hi-order
ADC DWORD PTR [EBX+4], 0
NEG DWORD PTR [EBX+4]
CALL @DecI64_2
MOV AL,'-'
INC ECX
DEC ESI
MOV [ESI],AL
RET
@DecI64_2: // unsigned int64 output
MOV ECX,10 // decimal divisor
@CvtI64:
LEA ESI,StrBuf[32]
@CvtI64_1:
PUSH ECX // save radix
PUSH 0
PUSH ECX // radix divisor (10 or 16 only)
MOV EAX, [EBX]
MOV EDX, [EBX + 4]
CALL System.@_llumod
POP ECX // saved radix
XCHG EAX, EDX // lo-value to EDX for character output
ADD DL,'0'
CMP DL,'0'+10
JB @CvtI64_2
ADD DL,'A'-'0'-10
@CvtI64_2:
DEC ESI
MOV [ESI],DL
PUSH ECX // save radix
PUSH 0
PUSH ECX // radix divisor (10 or 16 only)
MOV EAX, [EBX] // value := value DIV radix
MOV EDX, [EBX + 4]
CALL System.@_lludiv
POP ECX // saved radix
MOV [EBX], EAX
MOV [EBX + 4], EDX
OR EAX,EDX // anything left to output?
JNE @CvtI64_1 // no jump => EDX:EAX = 0
LEA ECX,StrBuf[32]
SUB ECX,ESI
MOV EDX,Prec
CMP EDX,16
JBE @CvtI64_3
RET
@CvtI64_3:
SUB EDX,ECX
JBE @CvtI64_5
ADD ECX,EDX
MOV AL,'0'
@CvtI64_4:
DEC ESI
MOV [ESI],AL
DEC EDX
JNE @CvtI64_4
@CvtI64_5:
RET
////////////////////////////////////////////////
@CvtInteger:
CMP CL,'D'
JE @C1
CMP CL,'U'
JE @C2
CMP CL,'X'
JNE @CvtError
MOV ECX,16
JMP @CvtLong
@C1: OR EAX,EAX
JNS @C2
NEG EAX
CALL @C2
MOV AL,'-'
INC ECX
DEC ESI
MOV [ESI],AL
RET
@C2: MOV ECX,10
@CvtLong:
LEA ESI,StrBuf[16]
@D1: XOR EDX,EDX
DIV ECX
ADD DL,'0'
CMP DL,'0'+10
JB @D2
ADD DL,'A'-'0'-10
@D2: DEC ESI
MOV [ESI],DL
OR EAX,EAX
JNE @D1
LEA ECX,StrBuf[16]
SUB ECX,ESI
MOV EDX,Prec
CMP EDX,16
JBE @D3
RET
@D3: SUB EDX,ECX
JBE @D5
ADD ECX,EDX
MOV AL,'0'
@D4: DEC ESI
MOV [ESI],AL
DEC EDX
JNE @D4
@D5: RET
@CvtChar:
CMP CL,'S'
JNE @CvtError
MOV ECX,1
RET
@CvtVariant:
CMP CL,'S'
JNE @CvtError
CMP [EAX].TVarData.VType,varNull
JBE @CvtEmptyStr
MOV EDX,EAX
LEA EAX,TempStr
CALL FormatVarToStr
MOV ESI,TempStr
JMP @CvtStrRef
@CvtEmptyStr:
XOR ECX,ECX
RET
@CvtShortStr:
CMP CL,'S'
JNE @CvtError
MOV ESI,EAX
LODSB
MOVZX ECX,AL
JMP @CvtStrLen
@CvtPWideChar:
MOV ESI,OFFSET System.@LStrFromPWChar
JMP @CvtWideThing
@CvtWideString:
MOV ESI,OFFSET System.@LStrFromWStr
@CvtWideThing:
CMP CL,'S'
JNE @CvtError
MOV EDX,EAX
LEA EAX,TempAnsiStr
CALL ESI
MOV ESI,TempAnsiStr
MOV EAX,ESI
JMP @CvtStrRef
@CvtAnsiStr:
CMP CL,'S'
JNE @CvtError
MOV ESI,EAX
@CvtStrRef:
OR ESI,ESI
JE @CvtEmptyStr
MOV ECX,[ESI-4]
@CvtStrLen:
CMP ECX,Prec
JA @E1
RET
@E1: MOV ECX,Prec
RET
@CvtPChar:
CMP CL,'S'
JNE @CvtError
MOV ESI,EAX
PUSH EDI
MOV EDI,EAX
XOR AL,AL
MOV ECX,Prec
JECXZ @F1
REPNE SCASB
JNE @F1
DEC EDI
@F1: MOV ECX,EDI
SUB ECX,ESI
POP EDI
RET
@CvtPointer:
CMP CL,'P'
JNE @CvtError
MOV Prec,8
MOV ECX,16
JMP @CvtLong
@CvtCurrency:
MOV BH,fvCurrency
JMP @CvtFloat
@CvtExtended:
MOV BH,fvExtended
@CvtFloat:
MOV ESI,EAX
MOV BL,ffGeneral
CMP CL,'G'
JE @G2
MOV BL,ffExponent
CMP CL,'E'
JE @G2
MOV BL,ffFixed
CMP CL,'F'
JE @G1
MOV BL,ffNumber
CMP CL,'N'
JE @G1
CMP CL,'M'
JNE @CvtError
MOV BL,ffCurrency
@G1: MOV EAX,18
MOV EDX,Prec
CMP EDX,EAX
JBE @G3
MOV EDX,2
CMP CL,'M'
JNE @G3
MOVZX EDX,CurrencyDecimals
JMP @G3
@G2: MOV EAX,Prec
MOV EDX,3
CMP EAX,18
JBE @G3
MOV EAX,15
@G3: PUSH EBX
PUSH EAX
PUSH EDX
LEA EAX,StrBuf
MOV EDX,ESI
MOVZX ECX,BH
CALL FloatToText
MOV ECX,EAX
LEA ESI,StrBuf
RET
@ClearTmpAnsiStr:
PUSH EAX
LEA EAX,TempAnsiStr
CALL System.@LStrClr
POP EAX
RET
@Exit:
CALL @ClearTmpAnsiStr
POP EDI
POP ESI
POP EBX
end;
function StrFmt(Buffer, Format: PChar; const Args: array of const): PChar;
begin
Buffer[FormatBuf(Buffer^, MaxInt, Format^, StrLen(Format), Args)] := #0;
Result := Buffer;
end;
function StrLFmt(Buffer: PChar; MaxLen: Cardinal; Format: PChar;
const Args: array of const): PChar;
begin
Buffer[FormatBuf(Buffer^, MaxLen, Format^, StrLen(Format), Args)] := #0;
Result := Buffer;
end;
function Format(const Format: string; const Args: array of const): string;
begin
FmtStr(Result, Format, Args);
end;
procedure FmtStr(var Result: string; const Format: string;
const Args: array of const);
var
Len, BufLen: Integer;
Buffer: array[0..4097] of Char;
begin
BufLen := SizeOf(Buffer);
if Length(Format) < (BufLen - (BufLen div 4)) then
Len := FormatBuf(Buffer, BufLen - 1, Pointer(Format)^, Length(Format), Args)
else
begin
BufLen := Length(Format);
Len := BufLen;
end;
if Len >= BufLen - 1 then
begin
while Len >= BufLen - 1 do
begin
Inc(BufLen, BufLen);
Result := ''; // prevent copying of existing data, for speed
SetLength(Result, BufLen);
Len := FormatBuf(Pointer(Result)^, BufLen - 1, Pointer(Format)^,
Length(Format), Args);
end;
SetLength(Result, Len);
end
else
SetString(Result, Buffer, Len);
end;
{ Floating point conversion routines }
{$L FFMT.OBJ}
procedure FloatToDecimal(var Result: TFloatRec; const Value;
ValueType: TFloatValue; Precision, Decimals: Integer); external;
function FloatToText(Buffer: PChar; const Value; ValueType: TFloatValue;
Format: TFloatFormat; Precision, Digits: Integer): Integer; external;
function FloatToTextFmt(Buffer: PChar; const Value; ValueType: TFloatValue;
Format: PChar): Integer; external;
function TextToFloat(Buffer: PChar; var Value;
ValueType: TFloatValue): Boolean; external;
function FloatToStr(Value: Extended): string;
var
Buffer: array[0..63] of Char;
begin
SetString(Result, Buffer, FloatToText(Buffer, Value, fvExtended,
ffGeneral, 15, 0));
end;
function CurrToStr(Value: Currency): string;
var
Buffer: array[0..63] of Char;
begin
SetString(Result, Buffer, FloatToText(Buffer, Value, fvCurrency,
ffGeneral, 0, 0));
end;
function FloatToStrF(Value: Extended; Format: TFloatFormat;
Precision, Digits: Integer): string;
var
Buffer: array[0..63] of Char;
begin
SetString(Result, Buffer, FloatToText(Buffer, Value, fvExtended,
Format, Precision, Digits));
end;
function CurrToStrF(Value: Currency; Format: TFloatFormat;
Digits: Integer): string;
var
Buffer: array[0..63] of Char;
begin
SetString(Result, Buffer, FloatToText(Buffer, Value, fvCurrency,
Format, 0, Digits));
end;
function FormatFloat(const Format: string; Value: Extended): string;
var
Buffer: array[0..255] of Char;
begin
if Length(Format) > SizeOf(Buffer) - 32 then ConvertError(SFormatTooLong);
SetString(Result, Buffer, FloatToTextFmt(Buffer, Value, fvExtended,
PChar(Format)));
end;
function FormatCurr(const Format: string; Value: Currency): string;
var
Buffer: array[0..255] of Char;
begin
if Length(Format) > SizeOf(Buffer) - 32 then ConvertError(SFormatTooLong);
SetString(Result, Buffer, FloatToTextFmt(Buffer, Value, fvCurrency,
PChar(Format)));
end;
function StrToFloat(const S: string): Extended;
begin
if not TextToFloat(PChar(S), Result, fvExtended) then
ConvertErrorFmt(@SInvalidFloat, [S]);
end;
function StrToCurr(const S: string): Currency;
begin
if not TextToFloat(PChar(S), Result, fvCurrency) then
ConvertErrorFmt(@SInvalidFloat, [S]);
end;
{ Date/time support routines }
const
FMSecsPerDay: Single = MSecsPerDay;
IMSecsPerDay: Integer = MSecsPerDay;
function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp;
asm
MOV ECX,EAX
FLD DateTime
FMUL FMSecsPerDay
SUB ESP,8
FISTP QWORD PTR [ESP]
FWAIT
POP EAX
POP EDX
OR EDX,EDX
JNS @@1
NEG EDX
NEG EAX
SBB EDX,0
DIV IMSecsPerDay
NEG EAX
JMP @@2
@@1: DIV IMSecsPerDay
@@2: ADD EAX,DateDelta
MOV [ECX].TTimeStamp.Time,EDX
MOV [ECX].TTimeStamp.Date,EAX
end;
function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
asm
MOV ECX,[EAX].TTimeStamp.Time
MOV EAX,[EAX].TTimeStamp.Date
SUB EAX,DateDelta
IMUL IMSecsPerDay
OR EDX,EDX
JNS @@1
SUB EAX,ECX
SBB EDX,0
JMP @@2
@@1: ADD EAX,ECX
ADC EDX,0
@@2: PUSH EDX
PUSH EAX
FILD QWORD PTR [ESP]
FDIV FMSecsPerDay
ADD ESP,8
end;
function MSecsToTimeStamp(MSecs: Comp): TTimeStamp;
asm
MOV ECX,EAX
MOV EAX,MSecs.Integer[0]
MOV EDX,MSecs.Integer[4]
DIV IMSecsPerDay
MOV [ECX].TTimeStamp.Time,EDX
MOV [ECX].TTimeStamp.Date,EAX
end;
function TimeStampToMSecs(const TimeStamp: TTimeStamp): Comp;
asm
FILD [EAX].TTimeStamp.Date
FMUL FMSecsPerDay
FIADD [EAX].TTimeStamp.Time
end;
{ Time encoding and decoding }
function DoEncodeTime(Hour, Min, Sec, MSec: Word; var Time: TDateTime): Boolean;
begin
Result := False;
if (Hour < 24) and (Min < 60) and (Sec < 60) and (MSec < 1000) then
begin
Time := (Hour * 3600000 + Min * 60000 + Sec * 1000 + MSec) / MSecsPerDay;
Result := True;
end;
end;
function EncodeTime(Hour, Min, Sec, MSec: Word): TDateTime;
begin
if not DoEncodeTime(Hour, Min, Sec, MSec, Result) then
ConvertError(STimeEncodeError);
end;
procedure DecodeTime(Time: TDateTime; var Hour, Min, Sec, MSec: Word);
var
MinCount, MSecCount: Word;
begin
DivMod(DateTimeToTimeStamp(Time).Time, 60000, MinCount, MSecCount);
DivMod(MinCount, 60, Hour, Min);
DivMod(MSecCount, 1000, Sec, MSec);
end;
{ Date encoding and decoding }
function IsLeapYear(Year: Word): Boolean;
begin
Result := (Year mod 4 = 0) and ((Year mod 100 <> 0) or (Year mod 400 = 0));
end;
function DoEncodeDate(Year, Month, Day: Word; var Date: TDateTime): Boolean;
var
I: Integer;
DayTable: PDayTable;
begin
Result := False;
DayTable := @MonthDays[IsLeapYear(Year)];
if (Year >= 1) and (Year <= 9999) and (Month >= 1) and (Month <= 12) and
(Day >= 1) and (Day <= DayTable^[Month]) then
begin
for I := 1 to Month - 1 do Inc(Day, DayTable^[I]);
I := Year - 1;
Date := I * 365 + I div 4 - I div 100 + I div 400 + Day - DateDelta;
Result := True;
end;
end;
function EncodeDate(Year, Month, Day: Word): TDateTime;
begin
if not DoEncodeDate(Year, Month, Day, Result) then
ConvertError(SDateEncodeError);
end;
procedure InternalDecodeDate(Date: TDateTime; var Year, Month, Day, DOW: Word);
const
D1 = 365;
D4 = D1 * 4 + 1;
D100 = D4 * 25 - 1;
D400 = D100 * 4 + 1;
var
Y, M, D, I: Word;
T: Integer;
DayTable: PDayTable;
begin
T := DateTimeToTimeStamp(Date).Date;
if T <= 0 then
begin
Year := 0;
Month := 0;
Day := 0;
DOW := 0;
end else
begin
DOW := T mod 7;
Dec(T);
Y := 1;
while T >= D400 do
begin
Dec(T, D400);
Inc(Y, 400);
end;
DivMod(T, D100, I, D);
if I = 4 then
begin
Dec(I);
Inc(D, D100);
end;
Inc(Y, I * 100);
DivMod(D, D4, I, D);
Inc(Y, I * 4);
DivMod(D, D1, I, D);
if I = 4 then
begin
Dec(I);
Inc(D, D1);
end;
Inc(Y, I);
DayTable := @MonthDays[IsLeapYear(Y)];
M := 1;
while True do
begin
I := DayTable^[M];
if D < I then Break;
Dec(D, I);
Inc(M);
end;
Year := Y;
Month := M;
Day := D + 1;
end;
end;
procedure DecodeDate(Date: TDateTime; var Year, Month, Day: Word);
var
Dummy: Word;
begin
InternalDecodeDate(Date, Year, Month, Day, Dummy);
end;
procedure DateTimeToSystemTime(DateTime: TDateTime; var SystemTime: TSystemTime);
begin
with SystemTime do
begin
InternalDecodeDate(DateTime, wYear, wMonth, wDay, wDayOfWeek);
DecodeTime(DateTime, wHour, wMinute, wSecond, wMilliseconds);
end;
end;
function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
begin
with SystemTime do
begin
Result := EncodeDate(wYear, wMonth, wDay);
if Result >= 0 then
Result := Result + EncodeTime(wHour, wMinute, wSecond, wMilliSeconds)
else
Result := Result - EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
end;
end;
function DayOfWeek(Date: TDateTime): Integer;
begin
Result := DateTimeToTimeStamp(Date).Date mod 7 + 1;
end;
function Date: TDateTime;
var
SystemTime: TSystemTime;
begin
GetLocalTime(SystemTime);
with SystemTime do Result := EncodeDate(wYear, wMonth, wDay);
end;
function Time: TDateTime;
var
SystemTime: TSystemTime;
begin
GetLocalTime(SystemTime);
with SystemTime do
Result := EncodeTime(wHour, wMinute, wSecond, wMilliSeconds);
end;
function Now: TDateTime;
var
SystemTime: TSystemTime;
begin
GetLocalTime(SystemTime);
with SystemTime do
Result := EncodeDate(wYear, wMonth, wDay) +
EncodeTime(wHour, wMinute, wSecond, wMilliseconds);
end;
function IncMonth(const Date: TDateTime; NumberOfMonths: Integer): TDateTime;
var
DayTable: PDayTable;
Year, Month, Day: Word;
Sign: Integer;
begin
if NumberOfMonths >= 0 then Sign := 1 else Sign := -1;
DecodeDate(Date, Year, Month, Day);
Year := Year + (NumberOfMonths div 12);
NumberOfMonths := NumberOfMonths mod 12;
Inc(Month, NumberOfMonths);
if Word(Month-1) > 11 then // if Month <= 0, word(Month-1) > 11)
begin
Inc(Year, Sign);
Inc(Month, -12 * Sign);
end;
DayTable := @MonthDays[IsLeapYear(Year)];
if Day > DayTable^[Month] then Day := DayTable^[Month];
Result := EncodeDate(Year, Month, Day);
ReplaceTime(Result, Date);
end;
procedure ReplaceTime(var DateTime: TDateTime; const NewTime: TDateTime);
begin
DateTime := Trunc(DateTime);
if DateTime >= 0 then
DateTime := DateTime + Abs(Frac(NewTime))
else
DateTime := DateTime - Abs(Frac(NewTime));
end;
procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime);
var
Temp: TDateTime;
begin
Temp := NewDate;
ReplaceTime(Temp, DateTime);
DateTime := Temp;
end;
function CurrentYear: Word;
var
SystemTime: TSystemTime;
begin
GetLocalTime(SystemTime);
Result := SystemTime.wYear;
end;
{ Date/time to string conversions }
procedure DateTimeToString(var Result: string; const Format: string;
DateTime: TDateTime);
var
BufPos, AppendLevel: Integer;
Buffer: array[0..255] of Char;
procedure AppendChars(P: PChar; Count: Integer);
var
N: Integer;
begin
N := SizeOf(Buffer) - BufPos;
if N > Count then N := Count;
if N <> 0 then Move(P[0], Buffer[BufPos], N);
Inc(BufPos, N);
end;
procedure AppendString(const S: string);
begin
AppendChars(Pointer(S), Length(S));
end;
procedure AppendNumber(Number, Digits: Integer);
const
Format: array[0..3] of Char = '%.*d';
var
NumBuf: array[0..15] of Char;
begin
AppendChars(NumBuf, FormatBuf(NumBuf, SizeOf(NumBuf), Format,
SizeOf(Format), [Digits, Number]));
end;
procedure AppendFormat(Format: PChar);
var
Starter, Token, LastToken: Char;
DateDecoded, TimeDecoded, Use12HourClock,
BetweenQuotes: Boolean;
P: PChar;
Count: Integer;
Year, Month, Day, Hour, Min, Sec, MSec, H: Word;
procedure GetCount;
var
P: PChar;
begin
P := Format;
while Format^ = Starter do Inc(Format);
Count := Format - P + 1;
end;
procedure GetDate;
begin
if not DateDecoded then
begin
DecodeDate(DateTime, Year, Month, Day);
DateDecoded := True;
end;
end;
procedure GetTime;
begin
if not TimeDecoded then
begin
DecodeTime(DateTime, Hour, Min, Sec, MSec);
TimeDecoded := True;
end;
end;
function ConvertEraString(const Count: Integer) : string;
var
FormatStr: string;
SystemTime: TSystemTime;
Buffer: array[Byte] of Char;
P: PChar;
begin
Result := '';
with SystemTime do
begin
wYear := Year;
wMonth := Month;
wDay := Day;
end;
FormatStr := 'gg';
if GetDateFormat(GetThreadLocale, DATE_USE_ALT_CALENDAR, @SystemTime,
PChar(FormatStr), Buffer, SizeOf(Buffer)) <> 0 then
begin
Result := Buffer;
if Count = 1 then
begin
case SysLocale.PriLangID of
LANG_JAPANESE:
Result := Copy(Result, 1, CharToBytelen(Result, 1));
LANG_CHINESE:
if (SysLocale.SubLangID = SUBLANG_CHINESE_TRADITIONAL)
and (ByteToCharLen(Result, Length(Result)) = 4) then
begin
P := Buffer + CharToByteIndex(Result, 3) - 1;
SetString(Result, P, CharToByteLen(P, 2));
end;
end;
end;
end;
end;
function ConvertYearString(const Count: Integer): string;
var
FormatStr: string;
SystemTime: TSystemTime;
Buffer: array[Byte] of Char;
begin
Result := '';
with SystemTime do
begin
wYear := Year;
wMonth := Month;
wDay := Day;
end;
if Count <= 2 then
FormatStr := 'yy' // avoid Win95 bug.
else
FormatStr := 'yyyy';
if GetDateFormat(GetThreadLocale, DATE_USE_ALT_CALENDAR, @SystemTime,
PChar(FormatStr), Buffer, SizeOf(Buffer)) <> 0 then
begin
Result := Buffer;
if (Count = 1) and (Result[1] = '0') then
Result := Copy(Result, 2, Length(Result)-1);
end;
end;
begin
if (Format <> nil) and (AppendLevel < 2) then
begin
Inc(AppendLevel);
LastToken := ' ';
DateDecoded := False;
TimeDecoded := False;
Use12HourClock := False;
while Format^ <> #0 do
begin
Starter := Format^;
Inc(Format);
if Starter in LeadBytes then
begin
if Format^ = #0 then Break;
Inc(Format);
LastToken := ' ';
Continue;
end;
Token := Starter;
if Token in ['a'..'z'] then Dec(Token, 32);
if Token in ['A'..'Z'] then
begin
if (Token = 'M') and (LastToken = 'H') then Token := 'N';
LastToken := Token;
end;
case Token of
'Y':
begin
GetCount;
GetDate;
if Count <= 2 then
AppendNumber(Year mod 100, 2) else
AppendNumber(Year, 4);
end;
'G':
begin
GetCount;
GetDate;
AppendString(ConvertEraString(Count));
end;
'E':
begin
GetCount;
GetDate;
AppendString(ConvertYearString(Count));
end;
'M':
begin
GetCount;
GetDate;
case Count of
1, 2: AppendNumber(Month, Count);
3: AppendString(ShortMonthNames[Month]);
else
AppendString(LongMonthNames[Month]);
end;
end;
'D':
begin
GetCount;
case Count of
1, 2:
begin
GetDate;
AppendNumber(Day, Count);
end;
3: AppendString(ShortDayNames[DayOfWeek(DateTime)]);
4: AppendString(LongDayNames[DayOfWeek(DateTime)]);
5: AppendFormat(Pointer(ShortDateFormat));
else
AppendFormat(Pointer(LongDateFormat));
end;
end;
'H':
begin
GetCount;
GetTime;
BetweenQuotes := False;
P := Format;
while P^ <> #0 do
begin
if P^ in LeadBytes then
begin
Inc(P);
if P^ = #0 then Break;
Inc(P);
Continue;
end;
case P^ of
'A', 'a':
if not BetweenQuotes then
begin
if ( (StrLIComp(P, 'AM/PM', 5) = 0)
or (StrLIComp(P, 'A/P', 3) = 0)
or (StrLIComp(P, 'AMPM', 4) = 0) ) then
Use12HourClock := True;
Break;
end;
'H', 'h':
Break;
'''', '"': BetweenQuotes := not BetweenQuotes;
end;
Inc(P);
end;
H := Hour;
if Use12HourClock then
if H = 0 then H := 12 else if H > 12 then Dec(H, 12);
if Count > 2 then Count := 2;
AppendNumber(H, Count);
end;
'N':
begin
GetCount;
GetTime;
if Count > 2 then Count := 2;
AppendNumber(Min, Count);
end;
'S':
begin
GetCount;
GetTime;
if Count > 2 then Count := 2;
AppendNumber(Sec, Count);
end;
'T':
begin
GetCount;
if Count = 1 then
AppendFormat(Pointer(ShortTimeFormat)) else
AppendFormat(Pointer(LongTimeFormat));
end;
'Z':
begin
GetCount;
GetTime;
if Count > 3 then Count := 3;
AppendNumber(MSec, Count);
end;
'A':
begin
GetTime;
P := Format - 1;
if StrLIComp(P, 'AM/PM', 5) = 0 then
begin
if Hour >= 12 then Inc(P, 3);
AppendChars(P, 2);
Inc(Format, 4);
Use12HourClock := TRUE;
end else
if StrLIComp(P, 'A/P', 3) = 0 then
begin
if Hour >= 12 then Inc(P, 2);
AppendChars(P, 1);
Inc(Format, 2);
Use12HourClock := TRUE;
end else
if StrLIComp(P, 'AMPM', 4) = 0 then
begin
if Hour < 12 then
AppendString(TimeAMString) else
AppendString(TimePMString);
Inc(Format, 3);
Use12HourClock := TRUE;
end else
if StrLIComp(P, 'AAAA', 4) = 0 then
begin
GetDate;
AppendString(LongDayNames[DayOfWeek(DateTime)]);
Inc(Format, 3);
end else
if StrLIComp(P, 'AAA', 3) = 0 then
begin
GetDate;
AppendString(ShortDayNames[DayOfWeek(DateTime)]);
Inc(Format, 2);
end else
AppendChars(@Starter, 1);
end;
'C':
begin
GetCount;
AppendFormat(Pointer(ShortDateFormat));
GetTime;
if (Hour <> 0) or (Min <> 0) or (Sec <> 0) then
begin
AppendChars(' ', 1);
AppendFormat(Pointer(LongTimeFormat));
end;
end;
'/':
AppendChars(@DateSeparator, 1);
':':
AppendChars(@TimeSeparator, 1);
'''', '"':
begin
P := Format;
while (Format^ <> #0) and (Format^ <> Starter) do
begin
if Format^ in LeadBytes then
begin
Inc(Format);
if Format^ = #0 then Break;
end;
Inc(Format);
end;
AppendChars(P, Format - P);
if Format^ <> #0 then Inc(Format);
end;
else
AppendChars(@Starter, 1);
end;
end;
Dec(AppendLevel);
end;
end;
begin
BufPos := 0;
AppendLevel := 0;
if Format <> '' then AppendFormat(Pointer(Format)) else AppendFormat('C');
SetString(Result, Buffer, BufPos);
end;
function DateToStr(Date: TDateTime): string;
begin
DateTimeToString(Result, ShortDateFormat, Date);
end;
function TimeToStr(Time: TDateTime): string;
begin
DateTimeToString(Result, LongTimeFormat, Time);
end;
function DateTimeToStr(DateTime: TDateTime): string;
begin
DateTimeToString(Result, '', DateTime);
end;
function FormatDateTime(const Format: string; DateTime: TDateTime): string;
begin
DateTimeToString(Result, Format, DateTime);
end;
{ String to date/time conversions }
type
TDateOrder = (doMDY, doDMY, doYMD);
procedure ScanBlanks(const S: string; var Pos: Integer);
var
I: Integer;
begin
I := Pos;
while (I <= Length(S)) and (S[I] = ' ') do Inc(I);
Pos := I;
end;
function ScanNumber(const S: string; var Pos: Integer;
var Number: Word; var CharCount: Byte): Boolean;
var
I: Integer;
N: Word;
begin
Result := False;
CharCount := 0;
ScanBlanks(S, Pos);
I := Pos;
N := 0;
while (I <= Length(S)) and (S[I] in ['0'..'9']) and (N < 1000) do
begin
N := N * 10 + (Ord(S[I]) - Ord('0'));
Inc(I);
end;
if I > Pos then
begin
CharCount := I - Pos;
Pos := I;
Number := N;
Result := True;
end;
end;
function ScanString(const S: string; var Pos: Integer;
const Symbol: string): Boolean;
begin
Result := False;
if Symbol <> '' then
begin
ScanBlanks(S, Pos);
if AnsiCompareText(Symbol, Copy(S, Pos, Length(Symbol))) = 0 then
begin
Inc(Pos, Length(Symbol));
Result := True;
end;
end;
end;
function ScanChar(const S: string; var Pos: Integer; Ch: Char): Boolean;
begin
Result := False;
ScanBlanks(S, Pos);
if (Pos <= Length(S)) and (S[Pos] = Ch) then
begin
Inc(Pos);
Result := True;
end;
end;
function GetDateOrder(const DateFormat: string): TDateOrder;
var
I: Integer;
begin
Result := doMDY;
I := 1;
while I <= Length(DateFormat) do
begin
case Chr(Ord(DateFormat[I]) and $DF) of
'E': Result := doYMD;
'Y': Result := doYMD;
'M': Result := doMDY;
'D': Result := doDMY;
else
Inc(I);
Continue;
end;
Exit;
end;
Result := doMDY;
end;
procedure ScanToNumber(const S: string; var Pos: Integer);
begin
while (Pos <= Length(S)) and not (S[Pos] in ['0'..'9']) do
begin
if S[Pos] in LeadBytes then Inc(Pos);
Inc(Pos);
end;
end;
function GetEraYearOffset(const Name: string): Integer;
var
I: Integer;
begin
Result := 0;
for I := Low(EraNames) to High(EraNames) do
begin
if EraNames[I] = '' then Break;
if AnsiStrPos(PChar(EraNames[I]), PChar(Name)) <> nil then
begin
Result := EraYearOffsets[I];
Exit;
end;
end;
end;
function ScanDate(const S: string; var Pos: Integer;
var Date: TDateTime): Boolean;
var
DateOrder: TDateOrder;
N1, N2, N3, Y, M, D: Word;
L1, L2, L3, YearLen: Byte;
EraName : string;
EraYearOffset: Integer;
CenturyBase: Integer;
function EraToYear(Year: Integer): Integer;
begin
if SysLocale.PriLangID = LANG_KOREAN then
begin
if Year <= 99 then
Inc(Year, (CurrentYear + Abs(EraYearOffset)) div 100 * 100);
if EraYearOffset > 0 then
EraYearOffset := -EraYearOffset;
end
else
Dec(EraYearOffset);
Result := Year + EraYearOffset;
end;
begin
Y := 0;
M := 0;
D := 0;
YearLen := 0;
Result := False;
DateOrder := GetDateOrder(ShortDateFormat);
EraYearOffset := 0;
if ShortDateFormat[1] = 'g' then // skip over prefix text
begin
ScanToNumber(S, Pos);
EraName := Trim(Copy(S, 1, Pos-1));
EraYearOffset := GetEraYearOffset(EraName);
end
else
if AnsiPos('e', ShortDateFormat) > 0 then
EraYearOffset := EraYearOffsets[1];
if not (ScanNumber(S, Pos, N1, L1) and ScanChar(S, Pos, DateSeparator) and
ScanNumber(S, Pos, N2, L2)) then Exit;
if ScanChar(S, Pos, DateSeparator) then
begin
if not ScanNumber(S, Pos, N3, L3) then Exit;
case DateOrder of
doMDY: begin Y := N3; YearLen := L3; M := N1; D := N2; end;
doDMY: begin Y := N3; YearLen := L3; M := N2; D := N1; end;
doYMD: begin Y := N1; YearLen := L1; M := N2; D := N3; end;
end;
if EraYearOffset > 0 then
Y := EraToYear(Y)
else if (YearLen <= 2) then
begin
CenturyBase := CurrentYear - TwoDigitYearCenturyWindow;
Inc(Y, CenturyBase div 100 * 100);
if (TwoDigitYearCenturyWindow > 0) and (Y < CenturyBase) then
Inc(Y, 100);
end;
end else
begin
Y := CurrentYear;
if DateOrder = doDMY then
begin
D := N1; M := N2;
end else
begin
M := N1; D := N2;
end;
end;
ScanChar(S, Pos, DateSeparator);
ScanBlanks(S, Pos);
if SysLocale.FarEast and (System.Pos('ddd', ShortDateFormat) <> 0) then
begin // ignore trailing text
if ShortTimeFormat[1] in ['0'..'9'] then // stop at time digit
ScanToNumber(S, Pos)
else // stop at time prefix
repeat
while (Pos <= Length(S)) and (S[Pos] <> ' ') do Inc(Pos);
ScanBlanks(S, Pos);
until (Pos > Length(S)) or
(AnsiCompareText(TimeAMString, Copy(S, Pos, Length(TimeAMString))) = 0) or
(AnsiCompareText(TimePMString, Copy(S, Pos, Length(TimePMString))) = 0);
end;
Result := DoEncodeDate(Y, M, D, Date);
end;
function ScanTime(const S: string; var Pos: Integer;
var Time: TDateTime): Boolean;
var
BaseHour: Integer;
Hour, Min, Sec, MSec: Word;
Junk: Byte;
begin
Result := False;
BaseHour := -1;
if ScanString(S, Pos, TimeAMString) or ScanString(S, Pos, 'AM') then
BaseHour := 0
else if ScanString(S, Pos, TimePMString) or ScanString(S, Pos, 'PM') then
BaseHour := 12;
if BaseHour >= 0 then ScanBlanks(S, Pos);
if not ScanNumber(S, Pos, Hour, Junk) then Exit;
Min := 0;
if ScanChar(S, Pos, TimeSeparator) then
if not ScanNumber(S, Pos, Min, Junk) then Exit;
Sec := 0;
if ScanChar(S, Pos, TimeSeparator) then
if not ScanNumber(S, Pos, Sec, Junk) then Exit;
MSec := 0;
if ScanChar(S, Pos, DecimalSeparator) then
if not ScanNumber(S, Pos, MSec, Junk) then Exit;
if BaseHour < 0 then
if ScanString(S, Pos, TimeAMString) or ScanString(S, Pos, 'AM') then
BaseHour := 0
else
if ScanString(S, Pos, TimePMString) or ScanString(S, Pos, 'PM') then
BaseHour := 12;
if BaseHour >= 0 then
begin
if (Hour = 0) or (Hour > 12) then Exit;
if Hour = 12 then Hour := 0;
Inc(Hour, BaseHour);
end;
ScanBlanks(S, Pos);
Result := DoEncodeTime(Hour, Min, Sec, MSec, Time);
end;
function StrToDate(const S: string): TDateTime;
var
Pos: Integer;
begin
Pos := 1;
if not ScanDate(S, Pos, Result) or (Pos <= Length(S)) then
ConvertErrorFmt(@SInvalidDate, [S]);
end;
function StrToTime(const S: string): TDateTime;
var
Pos: Integer;
begin
Pos := 1;
if not ScanTime(S, Pos, Result) or (Pos <= Length(S)) then
ConvertErrorFmt(@SInvalidTime, [S]);
end;
function StrToDateTime(const S: string): TDateTime;
var
Pos: Integer;
Date, Time: TDateTime;
begin
Pos := 1;
Time := 0;
if not ScanDate(S, Pos, Date) or not ((Pos > Length(S)) or
ScanTime(S, Pos, Time)) then
begin // Try time only
Pos := 1;
if not ScanTime(S, Pos, Result) or (Pos <= Length(S)) then
ConvertErrorFmt(@SInvalidDateTime, [S]);
end else
if Date >= 0 then
Result := Date + Time else
Result := Date - Time;
end;
{ System error messages }
function SysErrorMessage(ErrorCode: Integer): string;
var
Len: Integer;
Buffer: array[0..255] of Char;
begin
Len := FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM or
FORMAT_MESSAGE_ARGUMENT_ARRAY, nil, ErrorCode, 0, Buffer,
SizeOf(Buffer), nil);
while (Len > 0) and (Buffer[Len - 1] in [#0..#32, '.']) do Dec(Len);
SetString(Result, Buffer, Len);
end;
{ Initialization file support }
function GetLocaleStr(Locale, LocaleType: Integer; const Default: string): string;
var
L: Integer;
Buffer: array[0..255] of Char;
begin
L := GetLocaleInfo(Locale, LocaleType, Buffer, SizeOf(Buffer));
if L > 0 then SetString(Result, Buffer, L - 1) else Result := Default;
end;
function GetLocaleChar(Locale, LocaleType: Integer; Default: Char): Char;
var
Buffer: array[0..1] of Char;
begin
if GetLocaleInfo(Locale, LocaleType, Buffer, 2) > 0 then
Result := Buffer[0] else
Result := Default;
end;
var
DefShortMonthNames: array[1..12] of Pointer = (@SShortMonthNameJan,
@SShortMonthNameFeb, @SShortMonthNameMar, @SShortMonthNameApr,
@SShortMonthNameMay, @SShortMonthNameJun, @SShortMonthNameJul,
@SShortMonthNameAug, @SShortMonthNameSep, @SShortMonthNameOct,
@SShortMonthNameNov, @SShortMonthNameDec);
DefLongMonthNames: array[1..12] of Pointer = (@SLongMonthNameJan,
@SLongMonthNameFeb, @SLongMonthNameMar, @SLongMonthNameApr,
@SLongMonthNameMay, @SLongMonthNameJun, @SLongMonthNameJul,
@SLongMonthNameAug, @SLongMonthNameSep, @SLongMonthNameOct,
@SLongMonthNameNov, @SLongMonthNameDec);
DefShortDayNames: array[1..7] of Pointer = (@SShortDayNameSun,
@SShortDayNameMon, @SShortDayNameTue, @SShortDayNameWed,
@SShortDayNameThu, @SShortDayNameFri, @SShortDayNameSat);
DefLongDayNames: array[1..7] of Pointer = (@SLongDayNameSun,
@SLongDayNameMon, @SLongDayNameTue, @SLongDayNameWed,
@SLongDayNameThu, @SLongDayNameFri, @SLongDayNameSat);
procedure GetMonthDayNames;
var
I, Day: Integer;
DefaultLCID: LCID;
function LocalGetLocaleStr(LocaleType, Index: Integer;
const DefValues: array of Pointer): string;
begin
Result := GetLocaleStr(DefaultLCID, LocaleType, '');
if Result = '' then Result := LoadResString(DefValues[Index]);
end;
begin
DefaultLCID := GetThreadLocale;
for I := 1 to 12 do
begin
ShortMonthNames[I] := LocalGetLocaleStr(LOCALE_SABBREVMONTHNAME1 + I - 1,
I - Low(DefShortMonthNames), DefShortMonthNames);
LongMonthNames[I] := LocalGetLocaleStr(LOCALE_SMONTHNAME1 + I - 1,
I - Low(DefLongMonthNames), DefLongMonthNames);
end;
for I := 1 to 7 do
begin
Day := (I + 5) mod 7;
ShortDayNames[I] := LocalGetLocaleStr(LOCALE_SABBREVDAYNAME1 + Day,
I - Low(DefShortDayNames), DefShortDayNames);
LongDayNames[I] := LocalGetLocaleStr(LOCALE_SDAYNAME1 + Day,
I - Low(DefLongDayNames), DefLongDayNames);
end;
end;
function EnumEraNames(Names: PChar): Integer; stdcall;
var
I: Integer;
begin
Result := 0;
I := Low(EraNames);
while EraNames[I] <> '' do
if (I = High(EraNames)) then
Exit
else Inc(I);
EraNames[I] := Names;
Result := 1;
end;
function EnumEraYearOffsets(YearOffsets: PChar): Integer; stdcall;
var
I: Integer;
begin
Result := 0;
I := Low(EraYearOffsets);
while EraYearOffsets[I] <> -1 do
if (I = High(EraYearOffsets)) then
Exit
else Inc(I);
EraYearOffsets[I] := StrToIntDef(YearOffsets, 0);
Result := 1;
end;
procedure GetEraNamesAndYearOffsets;
var
J: Integer;
CalendarType: CALTYPE;
begin
CalendarType := StrToIntDef(GetLocaleStr(GetThreadLocale,
LOCALE_IOPTIONALCALENDAR, '1'), 1);
if CalendarType in [CAL_JAPAN, CAL_TAIWAN, CAL_KOREA] then
begin
EnumCalendarInfoA(@EnumEraNames, GetThreadLocale, CalendarType,
CAL_SERASTRING);
for J := Low(EraYearOffsets) to High(EraYearOffsets) do
EraYearOffsets[J] := -1;
EnumCalendarInfoA(@EnumEraYearOffsets, GetThreadLocale, CalendarType,
CAL_IYEAROFFSETRANGE);
end;
end;
function TranslateDateFormat(const FormatStr: string): string;
var
I: Integer;
CalendarType: CALTYPE;
RemoveEra: Boolean;
begin
I := 1;
Result := '';
CalendarType := StrToIntDef(GetLocaleStr(GetThreadLocale,
LOCALE_ICALENDARTYPE, '1'), 1);
if not (CalendarType in [CAL_JAPAN, CAL_TAIWAN, CAL_KOREA]) then
begin
RemoveEra := SysLocale.PriLangID in [LANG_JAPANESE, LANG_CHINESE, LANG_KOREAN];
if RemoveEra then
begin
While I <= Length(FormatStr) do
begin
if not (FormatStr[I] in ['g', 'G']) then
Result := Result + FormatStr[I];
Inc(I);
end;
end
else
Result := FormatStr;
Exit;
end;
while I <= Length(FormatStr) do
begin
if FormatStr[I] in LeadBytes then
begin
Result := Result + Copy(FormatStr, I, 2);
Inc(I, 2);
end else
begin
if StrLIComp(@FormatStr[I], 'gg', 2) = 0 then
begin
Result := Result + 'ggg';
Inc(I, 1);
end
else if StrLIComp(@FormatStr[I], 'yyyy', 4) = 0 then
begin
Result := Result + 'eeee';
Inc(I, 4-1);
end
else if StrLIComp(@FormatStr[I], 'yy', 2) = 0 then
begin
Result := Result + 'ee';
Inc(I, 2-1);
end
else if FormatStr[I] in ['y', 'Y'] then
Result := Result + 'e'
else
Result := Result + FormatStr[I];
Inc(I);
end;
end;
end;
{ Exception handling routines }
var
OutOfMemory: EOutOfMemory;
InvalidPointer: EInvalidPointer;
type
PRaiseFrame = ^TRaiseFrame;
TRaiseFrame = record
NextRaise: PRaiseFrame;
ExceptAddr: Pointer;
ExceptObject: TObject;
ExceptionRecord: PExceptionRecord;
end;
{ Return current exception object }
function ExceptObject: TObject;
begin
if RaiseList <> nil then
Result := PRaiseFrame(RaiseList)^.ExceptObject else
Result := nil;
end;
{ Return current exception address }
function ExceptAddr: Pointer;
begin
if RaiseList <> nil then
Result := PRaiseFrame(RaiseList)^.ExceptAddr else
Result := nil;
end;
{ Convert physical address to logical address }
function ConvertAddr(Address: Pointer): Pointer; assembler;
asm
TEST EAX,EAX { Always convert nil to nil }
JE @@1
SUB EAX, $1000 { offset from code start; code start set by linker to $1000 }
@@1:
end;
{ Format and return an exception error message }
function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
Buffer: PChar; Size: Integer): Integer;
var
MsgPtr: PChar;
MsgEnd: PChar;
MsgLen: Integer;
ModuleName: array[0..MAX_PATH] of Char;
Temp: array[0..MAX_PATH] of Char;
Format: array[0..255] of Char;
Info: TMemoryBasicInformation;
ConvertedAddress: Pointer;
begin
VirtualQuery(ExceptAddr, Info, sizeof(Info));
if (Info.State <> MEM_COMMIT) or
(GetModuleFilename(THandle(Info.AllocationBase), Temp, SizeOf(Temp)) = 0) then
begin
GetModuleFileName(HInstance, Temp, SizeOf(Temp));
ConvertedAddress := ConvertAddr(ExceptAddr);
end
else
Integer(ConvertedAddress) := Integer(ExceptAddr) - Integer(Info.AllocationBase);
StrLCopy(ModuleName, AnsiStrRScan(Temp, '\') + 1, SizeOf(ModuleName) - 1);
MsgPtr := '';
MsgEnd := '';
if ExceptObject is Exception then
begin
MsgPtr := PChar(Exception(ExceptObject).Message);
MsgLen := StrLen(MsgPtr);
if (MsgLen <> 0) and (MsgPtr[MsgLen - 1] <> '.') then MsgEnd := '.';
end;
LoadString(FindResourceHInstance(HInstance),
PResStringRec(@SException).Identifier, Format, SizeOf(Format));
StrLFmt(Buffer, Size, Format, [ExceptObject.ClassName, ModuleName,
ConvertedAddress, MsgPtr, MsgEnd]);
Result := StrLen(Buffer);
end;
{ Display exception message box }
procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
var
Title: array[0..63] of Char;
Buffer: array[0..1023] of Char;
begin
ExceptionErrorMessage(ExceptObject, ExceptAddr, Buffer, SizeOf(Buffer));
if IsConsole then
WriteLn(Buffer)
else
begin
LoadString(FindResourceHInstance(HInstance), PResStringRec(@SExceptTitle).Identifier,
Title, SizeOf(Title));
MessageBox(0, Buffer, Title, MB_OK or MB_ICONSTOP or MB_TASKMODAL);
end;
end;
{ Raise abort exception }
procedure Abort;
function ReturnAddr: Pointer;
asm
// MOV EAX,[ESP + 4] !!! codegen dependant
MOV EAX,[EBP - 4]
end;
begin
raise EAbort.Create(SOperationAborted) at ReturnAddr;
end;
{ Raise out of memory exception }
procedure OutOfMemoryError;
begin
raise OutOfMemory;
end;
{ Exception class }
constructor Exception.Create(const Msg: string);
begin
FMessage := Msg;
end;
constructor Exception.CreateFmt(const Msg: string;
const Args: array of const);
begin
FMessage := Format(Msg, Args);
end;
constructor Exception.CreateRes(Ident: Integer);
begin
FMessage := LoadStr(Ident);
end;
constructor Exception.CreateRes(ResStringRec: PResStringRec);
begin
FMessage := LoadResString(ResStringRec);
end;
constructor Exception.CreateResFmt(Ident: Integer;
const Args: array of const);
begin
FMessage := Format(LoadStr(Ident), Args);
end;
constructor Exception.CreateResFmt(ResStringRec: PResStringRec;
const Args: array of const);
begin
FMessage := Format(LoadResString(ResStringRec), Args);
end;
constructor Exception.CreateHelp(const Msg: string; AHelpContext: Integer);
begin
FMessage := Msg;
FHelpContext := AHelpContext;
end;
constructor Exception.CreateFmtHelp(const Msg: string; const Args: array of const;
AHelpContext: Integer);
begin
FMessage := Format(Msg, Args);
FHelpContext := AHelpContext;
end;
constructor Exception.CreateResHelp(Ident: Integer; AHelpContext: Integer);
begin
FMessage := LoadStr(Ident);
FHelpContext := AHelpContext;
end;
constructor Exception.CreateResHelp(ResStringRec: PResStringRec;
AHelpContext: Integer);
begin
FMessage := LoadResString(ResStringRec);
FHelpContext := AHelpContext;
end;
constructor Exception.CreateResFmtHelp(Ident: Integer;
const Args: array of const;
AHelpContext: Integer);
begin
FMessage := Format(LoadStr(Ident), Args);
FHelpContext := AHelpContext;
end;
constructor Exception.CreateResFmtHelp(ResStringRec: PResStringRec;
const Args: array of const;
AHelpContext: Integer);
begin
FMessage := Format(LoadResString(ResStringRec), Args);
FHelpContext := AHelpContext;
end;
{ EHeapException class }
procedure EHeapException.FreeInstance;
begin
if AllowFree then
inherited FreeInstance;
end;
{ Create I/O exception }
function CreateInOutError: EInOutError;
type
TErrorRec = record
Code: Integer;
Ident: string;
end;
const
ErrorMap: array[0..6] of TErrorRec = (
(Code: 2; Ident: SFileNotFound),
(Code: 3; Ident: SInvalidFilename),
(Code: 4; Ident: STooManyOpenFiles),
(Code: 5; Ident: SAccessDenied),
(Code: 100; Ident: SEndOfFile),
(Code: 101; Ident: SDiskFull),
(Code: 106; Ident: SInvalidInput));
var
I: Integer;
InOutRes: Integer;
begin
I := Low(ErrorMap);
InOutRes := IOResult; // resets IOResult to zero
while (I <= High(ErrorMap)) and (ErrorMap[I].Code <> InOutRes) do Inc(I);
if I <= High(ErrorMap) then
Result := EInOutError.Create(ErrorMap[I].Ident) else
Result := EInOutError.CreateResFmt(@SInOutError, [InOutRes]);
Result.ErrorCode := InOutRes;
end;
{ RTL error handler }
type
TExceptRec = record
EClass: ExceptClass;
EIdent: string;
end;
const
ExceptMap: array[3..24] of TExceptRec = (
(EClass: EDivByZero; EIdent: SDivByZero),
(EClass: ERangeError; EIdent: SRangeError),
(EClass: EIntOverflow; EIdent: SIntOverflow),
(EClass: EInvalidOp; EIdent: SInvalidOp),
(EClass: EZeroDivide; EIdent: SZeroDivide),
(EClass: EOverflow; EIdent: SOverflow),
(EClass: EUnderflow; EIdent: SUnderflow),
(EClass: EInvalidCast; EIdent: SInvalidCast),
(EClass: EAccessViolation; EIdent: SAccessViolation),
(EClass: EPrivilege; EIdent: SPrivilege),
(EClass: EControlC; EIdent: SControlC),
(EClass: EStackOverflow; EIdent: SStackOverflow),
(EClass: EVariantError; EIdent: SInvalidVarCast),
(EClass: EVariantError; EIdent: SInvalidVarOp),
(EClass: EVariantError; EIdent: SDispatchError),
(EClass: EVariantError; EIdent: SVarArrayCreate),
(EClass: EVariantError; EIdent: SVarNotArray),
(EClass: EVariantError; EIdent: SVarArrayBounds),
(EClass: EAssertionFailed; EIdent: SAssertionFailed),
(EClass: EExternalException; EIdent: SExternalException),
(EClass: EIntfCastError; EIdent: SIntfCastError),
(EClass: ESafecallException; EIdent: SSafecallException));
procedure ErrorHandler(ErrorCode: Integer; ErrorAddr: Pointer);
var
E: Exception;
begin
case ErrorCode of
1: E := OutOfMemory;
2: E := InvalidPointer;
3..24: with ExceptMap[ErrorCode] do E := EClass.Create(EIdent);
else
E := CreateInOutError;
end;
raise E at ErrorAddr;
end;
{ Assertion error handler }
{ This is complicated by the desire to make it look like the exception }
{ happened in the user routine, so the debugger can give a decent stack }
{ trace. To make that feasible, AssertErrorHandler calls a helper function }
{ to create the exception object, so that AssertErrorHandler itself does }
{ not need any temps. After the exception object is created, the asm }
{ routine RaiseAssertException sets up the registers just as if the user }
{ code itself had raised the exception. }
function CreateAssertException(const Message, Filename: string;
LineNumber: Integer): Exception;
var
S: string;
begin
if Message <> '' then S := Message else S := SAssertionFailed;
Result := EAssertionFailed.CreateFmt(SAssertError,
[S, Filename, LineNumber]);
end;
{ This code is based on the following assumptions: }
{ - Our direct caller (AssertErrorHandler) has an EBP frame }
{ - ErrorStack points to where the return address would be if the }
{ user program had called System.@RaiseExcept directly }
procedure RaiseAssertException(const E: Exception; const ErrorAddr, ErrorStack: Pointer);
asm
MOV ESP,ECX
MOV [ESP],EDX
MOV EBP,[EBP]
JMP System.@RaiseExcept
end;
{ If you change this procedure, make sure it does not have any local variables }
{ or temps that need cleanup - they won't get cleaned up due to the way }
{ RaiseAssertException frame works. Also, it can not have an exception frame. }
procedure AssertErrorHandler(const Message, Filename: string;
LineNumber: Integer; ErrorAddr: Pointer);
var
E: Exception;
begin
E := CreateAssertException(Message, Filename, LineNumber);
RaiseAssertException(E, ErrorAddr, PChar(@ErrorAddr)+4);
end;
{ Abstract method invoke error handler }
procedure AbstractErrorHandler;
begin
raise EAbstractError.CreateResFmt(@SAbstractError, ['']);
end;
function MapException(P: PExceptionRecord): Byte;
begin
case P.ExceptionCode of
STATUS_INTEGER_DIVIDE_BY_ZERO:
Result := 3;
STATUS_ARRAY_BOUNDS_EXCEEDED:
Result := 4;
STATUS_INTEGER_OVERFLOW:
Result := 5;
STATUS_FLOAT_INEXACT_RESULT,
STATUS_FLOAT_INVALID_OPERATION,
STATUS_FLOAT_STACK_CHECK:
Result := 6;
STATUS_FLOAT_DIVIDE_BY_ZERO:
Result := 7;
STATUS_FLOAT_OVERFLOW:
Result := 8;
STATUS_FLOAT_UNDERFLOW,
STATUS_FLOAT_DENORMAL_OPERAND:
Result := 9;
STATUS_ACCESS_VIOLATION:
Result := 11;
STATUS_PRIVILEGED_INSTRUCTION:
Result := 12;
STATUS_CONTROL_C_EXIT:
Result := 13;
STATUS_STACK_OVERFLOW:
Result := 14;
else
Result := 22; { must match System.reExternalException }
end;
end;
function GetExceptionClass(P: PExceptionRecord): ExceptClass;
var
ErrorCode: Byte;
begin
ErrorCode := MapException(P);
Result := ExceptMap[ErrorCode].EClass;
end;
function GetExceptionObject(P: PExceptionRecord): Exception;
var
ErrorCode: Integer;
function CreateAVObject: Exception;
var
AccessOp: string; // string ID indicating the access type READ or WRITE
AccessAddress: Pointer;
MemInfo: TMemoryBasicInformation;
ModName: array[0..MAX_PATH] of Char;
begin
with P^ do
begin
if ExceptionInformation[0] = 0 then
AccessOp := SReadAccess else
AccessOp := SWriteAccess;
AccessAddress := Pointer(ExceptionInformation[1]);
VirtualQuery(ExceptionAddress, MemInfo, SizeOf(MemInfo));
if (MemInfo.State = MEM_COMMIT) and (GetModuleFileName(THandle(MemInfo.AllocationBase),
ModName, SizeOf(ModName)) <> 0) then
Result := EAccessViolation.CreateFmt(sModuleAccessViolation,
[ExceptionAddress, ExtractFileName(ModName), AccessOp,
AccessAddress])
else Result := EAccessViolation.CreateFmt(sAccessViolation,
[ExceptionAddress, AccessOp, AccessAddress]);
end;
end;
begin
ErrorCode := MapException(P);
case ErrorCode of
3..10, 12..21:
with ExceptMap[ErrorCode] do Result := EClass.Create(EIdent);
11: Result := CreateAVObject;
else
Result := EExternalException.CreateFmt(SExternalException, [P.ExceptionCode]);
end;
if Result is EExternal then
begin
EExternal(Result).ExceptionRecord := P;
if P.ExceptionCode = $0EEFFACE then
Result.FMessage := 'C++ Exception'; // do not localize
end;
end;
{ RTL exception handler }
procedure ExceptHandler(ExceptObject: TObject; ExceptAddr: Pointer); far;
begin
ShowException(ExceptObject, ExceptAddr);
Halt(1);
end;
procedure InitExceptions;
begin
OutOfMemory := EOutOfMemory.Create(SOutOfMemory);
InvalidPointer := EInvalidPointer.Create(SInvalidPointer);
ErrorProc := @ErrorHandler;
ExceptProc := @ExceptHandler;
ExceptionClass := Exception;
ExceptClsProc := @GetExceptionClass;
ExceptObjProc := @GetExceptionObject;
AssertErrorProc := @AssertErrorHandler;
AbstractErrorProc := @AbstractErrorHandler;
end;
procedure DoneExceptions;
begin
OutOfMemory.AllowFree := True;
OutOfMemory.FreeInstance;
OutOfMemory := nil;
InvalidPointer.AllowFree := True;
InvalidPointer.Free;
InvalidPointer := nil;
ErrorProc := nil;
ExceptProc := nil;
ExceptionClass := nil;
ExceptClsProc := nil;
ExceptObjProc := nil;
AssertErrorProc := nil;
end;
procedure InitPlatformId;
var
OSVersionInfo: TOSVersionInfo;
begin
OSVersionInfo.dwOSVersionInfoSize := SizeOf(OSVersionInfo);
if GetVersionEx(OSVersionInfo) then
with OSVersionInfo do
begin
Win32Platform := dwPlatformId;
Win32MajorVersion := dwMajorVersion;
Win32MinorVersion := dwMinorVersion;
Win32BuildNumber := dwBuildNumber;
Win32CSDVersion := szCSDVersion;
end;
end;
procedure Beep;
begin
MessageBeep(0);
end;
{ MBCS functions }
function ByteTypeTest(P: PChar; Index: Integer): TMbcsByteType;
var
I: Integer;
begin
Result := mbSingleByte;
if (P = nil) or (P[Index] = #$0) then Exit;
if (Index = 0) then
begin
if P[0] in LeadBytes then Result := mbLeadByte;
end
else
begin
I := Index - 1;
while (I >= 0) and (P[I] in LeadBytes) do Dec(I);
if ((Index - I) mod 2) = 0 then Result := mbTrailByte
else if P[Index] in LeadBytes then Result := mbLeadByte;
end;
end;
function ByteType(const S: string; Index: Integer): TMbcsByteType;
begin
Result := mbSingleByte;
if SysLocale.FarEast then
Result := ByteTypeTest(PChar(S), Index-1);
end;
function StrByteType(Str: PChar; Index: Cardinal): TMbcsByteType;
begin
Result := mbSingleByte;
if SysLocale.FarEast then
Result := ByteTypeTest(Str, Index);
end;
function ByteToCharLen(const S: string; MaxLen: Integer): Integer;
begin
if Length(S) < MaxLen then MaxLen := Length(S);
Result := ByteToCharIndex(S, MaxLen);
end;
function ByteToCharIndex(const S: string; Index: Integer): Integer;
var
I: Integer;
begin
Result := 0;
if (Index <= 0) or (Index > Length(S)) then Exit;
Result := Index;
if not SysLocale.FarEast then Exit;
I := 1;
Result := 0;
while I <= Index do
begin
if S[I] in LeadBytes then Inc(I);
Inc(I);
Inc(Result);
end;
end;
procedure CountChars(const S: string; MaxChars: Integer; var CharCount, ByteCount: Integer);
var
C, L, B: Integer;
begin
L := Length(S);
C := 1;
B := 1;
while (B < L) and (C < MaxChars) do
begin
Inc(C);
if S[B] in LeadBytes then Inc(B);
Inc(B);
end;
if (C = MaxChars) and (B < L) and (S[B] in LeadBytes) then Inc(B);
CharCount := C;
ByteCount := B;
end;
function CharToByteIndex(const S: string; Index: Integer): Integer;
var
Chars: Integer;
begin
Result := 0;
if (Index <= 0) or (Index > Length(S)) then Exit;
if (Index > 1) and SysLocale.FarEast then
begin
CountChars(S, Index-1, Chars, Result);
if (Chars < (Index-1)) or (Result >= Length(S)) then
Result := 0 // Char index out of range
else
Inc(Result);
end
else
Result := Index;
end;
function CharToByteLen(const S: string; MaxLen: Integer): Integer;
var
Chars: Integer;
begin
Result := 0;
if MaxLen <= 0 then Exit;
if MaxLen > Length(S) then MaxLen := Length(S);
if SysLocale.FarEast then
begin
CountChars(S, MaxLen, Chars, Result);
if Result > Length(S) then
Result := Length(S);
end
else
Result := MaxLen;
end;
function IsPathDelimiter(const S: string; Index: Integer): Boolean;
begin
Result := (Index > 0) and (Index <= Length(S)) and (S[Index] = '\')
and (ByteType(S, Index) = mbSingleByte);
end;
function IsDelimiter(const Delimiters, S: string; Index: Integer): Boolean;
begin
Result := False;
if (Index <= 0) or (Index > Length(S)) or (ByteType(S, Index) <> mbSingleByte) then exit;
Result := StrScan(PChar(Delimiters), S[Index]) <> nil;
end;
function IncludeTrailingBackslash(const S: string): string;
begin
Result := S;
if not IsPathDelimiter(Result, Length(Result)) then Result := Result + '\';
end;
function ExcludeTrailingBackslash(const S: string): string;
begin
Result := S;
if IsPathDelimiter(Result, Length(Result)) then
SetLength(Result, Length(Result)-1);
end;
function AnsiPos(const Substr, S: string): Integer;
var
P: PChar;
begin
Result := 0;
P := AnsiStrPos(PChar(S), PChar(SubStr));
if P <> nil then
Result := Integer(P) - Integer(PChar(S)) + 1;
end;
function AnsiCompareFileName(const S1, S2: string): Integer;
begin
Result := AnsiCompareStr(AnsiLowerCaseFileName(S1), AnsiLowerCaseFileName(S2));
end;
function AnsiLowerCaseFileName(const S: string): string;
var
I,L: Integer;
begin
if SysLocale.FarEast then
begin
L := Length(S);
SetLength(Result, L);
I := 1;
while I <= L do
begin
Result[I] := S[I];
if S[I] in LeadBytes then
begin
Inc(I);
Result[I] := S[I];
end
else
if Result[I] in ['A'..'Z'] then Inc(Byte(Result[I]), 32);
Inc(I);
end;
end
else
Result := AnsiLowerCase(S);
end;
function AnsiUpperCaseFileName(const S: string): string;
var
I,L: Integer;
begin
if SysLocale.FarEast then
begin
L := Length(S);
SetLength(Result, L);
I := 1;
while I <= L do
begin
Result[I] := S[I];
if S[I] in LeadBytes then
begin
Inc(I);
Result[I] := S[I];
end
else
if Result[I] in ['a'..'z'] then Dec(Byte(Result[I]), 32);
Inc(I);
end;
end
else
Result := AnsiUpperCase(S);
end;
function AnsiStrPos(Str, SubStr: PChar): PChar;
var
L1, L2: Cardinal;
ByteType : TMbcsByteType;
begin
Result := nil;
if (Str = nil) or (Str^ = #0) or (SubStr = nil) or (SubStr^ = #0) then Exit;
L1 := StrLen(Str);
L2 := StrLen(SubStr);
Result := StrPos(Str, SubStr);
while (Result <> nil) and ((L1 - Cardinal(Result - Str)) >= L2) do
begin
ByteType := StrByteType(Str, Integer(Result-Str));
if (ByteType <> mbTrailByte) and
(CompareString(LOCALE_USER_DEFAULT, 0, Result, L2, SubStr, L2) = 2) then Exit;
if (ByteType = mbLeadByte) then Inc(Result);
Inc(Result);
Result := StrPos(Result, SubStr);
end;
Result := nil;
end;
function AnsiStrRScan(Str: PChar; Chr: Char): PChar;
begin
Str := AnsiStrScan(Str, Chr);
Result := Str;
if Chr <> #$0 then
begin
while Str <> nil do
begin
Result := Str;
Inc(Str);
Str := AnsiStrScan(Str, Chr);
end;
end
end;
function AnsiStrScan(Str: PChar; Chr: Char): PChar;
begin
Result := StrScan(Str, Chr);
while Result <> nil do
begin
case StrByteType(Str, Integer(Result-Str)) of
mbSingleByte: Exit;
mbLeadByte: Inc(Result);
end;
Inc(Result);
Result := StrScan(Result, Chr);
end;
end;
procedure InitSysLocale;
var
DefaultLCID: LCID;
DefaultLangID: LANGID;
AnsiCPInfo: TCPInfo;
I: Integer;
J: Byte;
begin
{ Set default to English (US). }
SysLocale.DefaultLCID := $0409;
SysLocale.PriLangID := LANG_ENGLISH;
SysLocale.SubLangID := SUBLANG_ENGLISH_US;
DefaultLCID := GetThreadLocale;
if DefaultLCID <> 0 then SysLocale.DefaultLCID := DefaultLCID;
DefaultLangID := Word(DefaultLCID);
if DefaultLangID <> 0 then
begin
SysLocale.PriLangID := DefaultLangID and $3ff;
SysLocale.SubLangID := DefaultLangID shr 10;
end;
SysLocale.MiddleEast := GetSystemMetrics(SM_MIDEASTENABLED) <> 0;
SysLocale.FarEast := GetSystemMetrics(SM_DBCSENABLED) <> 0;
if not SysLocale.FarEast then Exit;
GetCPInfo(CP_ACP, AnsiCPInfo);
with AnsiCPInfo do
begin
I := 0;
while (I < MAX_LEADBYTES) and ((LeadByte[I] or LeadByte[I+1]) <> 0) do
begin
for J := LeadByte[I] to LeadByte[I+1] do
Include(LeadBytes, Char(J));
Inc(I,2);
end;
end;
end;
procedure GetFormatSettings;
var
HourFormat, TimePrefix, TimePostfix: string;
DefaultLCID: LCID;
begin
InitSysLocale;
GetMonthDayNames;
if SysLocale.FarEast then GetEraNamesAndYearOffsets;
DefaultLCID := GetThreadLocale;
CurrencyString := GetLocaleStr(DefaultLCID, LOCALE_SCURRENCY, '');
CurrencyFormat := StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ICURRENCY, '0'), 0);
NegCurrFormat := StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_INEGCURR, '0'), 0);
ThousandSeparator := GetLocaleChar(DefaultLCID, LOCALE_STHOUSAND, ',');
DecimalSeparator := GetLocaleChar(DefaultLCID, LOCALE_SDECIMAL, '.');
CurrencyDecimals := StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ICURRDIGITS, '0'), 0);
DateSeparator := GetLocaleChar(DefaultLCID, LOCALE_SDATE, '/');
ShortDateFormat := TranslateDateFormat(GetLocaleStr(DefaultLCID, LOCALE_SSHORTDATE, 'm/d/yy'));
LongDateFormat := TranslateDateFormat(GetLocaleStr(DefaultLCID, LOCALE_SLONGDATE, 'mmmm d, yyyy'));
TimeSeparator := GetLocaleChar(DefaultLCID, LOCALE_STIME, ':');
TimeAMString := GetLocaleStr(DefaultLCID, LOCALE_S1159, 'am');
TimePMString := GetLocaleStr(DefaultLCID, LOCALE_S2359, 'pm');
TimePrefix := '';
TimePostfix := '';
if StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ITLZERO, '0'), 0) = 0 then
HourFormat := 'h' else
HourFormat := 'hh';
if StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ITIME, '0'), 0) = 0 then
if StrToIntDef(GetLocaleStr(DefaultLCID, LOCALE_ITIMEMARKPOSN, '0'), 0) = 0 then
TimePostfix := ' AMPM'
else
TimePrefix := 'AMPM ';
ShortTimeFormat := TimePrefix + HourFormat + ':mm' + TimePostfix;
LongTimeFormat := TimePrefix + HourFormat + ':mm:ss' + TimePostfix;
ListSeparator := GetLocaleChar(DefaultLCID, LOCALE_SLIST, ',');
end;
function StringReplace(const S, OldPattern, NewPattern: string;
Flags: TReplaceFlags): string;
var
SearchStr, Patt, NewStr: string;
Offset: Integer;
begin
if rfIgnoreCase in Flags then
begin
SearchStr := AnsiUpperCase(S);
Patt := AnsiUpperCase(OldPattern);
end else
begin
SearchStr := S;
Patt := OldPattern;
end;
NewStr := S;
Result := '';
while SearchStr <> '' do
begin
Offset := AnsiPos(Patt, SearchStr);
if Offset = 0 then
begin
Result := Result + NewStr;
Break;
end;
Result := Result + Copy(NewStr, 1, Offset - 1) + NewPattern;
NewStr := Copy(NewStr, Offset + Length(OldPattern), MaxInt);
if not (rfReplaceAll in Flags) then
begin
Result := Result + NewStr;
Break;
end;
SearchStr := Copy(SearchStr, Offset + Length(Patt), MaxInt);
end;
end;
function WrapText(const Line, BreakStr: string; BreakChars: TSysCharSet;
MaxCol: Integer): string;
const
QuoteChars = ['''', '"'];
var
Col, Pos: Integer;
LinePos, LineLen: Integer;
BreakLen, BreakPos: Integer;
QuoteChar, CurChar: Char;
ExistingBreak: Boolean;
begin
Col := 1;
Pos := 1;
LinePos := 1;
BreakPos := 0;
QuoteChar := ' ';
ExistingBreak := False;
LineLen := Length(Line);
BreakLen := Length(BreakStr);
Result := '';
while Pos <= LineLen do
begin
CurChar := Line[Pos];
if CurChar in LeadBytes then
begin
Inc(Pos);
Inc(Col);
end else
if CurChar = BreakStr[1] then
begin
if QuoteChar = ' ' then
begin
ExistingBreak := CompareText(BreakStr, Copy(Line, Pos, BreakLen)) = 0;
if ExistingBreak then
begin
Inc(Pos, BreakLen-1);
BreakPos := Pos;
end;
end
end
else if CurChar in BreakChars then
begin
if QuoteChar = ' ' then BreakPos := Pos
end
else if CurChar in QuoteChars then
if CurChar = QuoteChar then
QuoteChar := ' '
else if QuoteChar = ' ' then
QuoteChar := CurChar;
Inc(Pos);
Inc(Col);
if not (QuoteChar in QuoteChars) and (ExistingBreak or
((Col > MaxCol) and (BreakPos > LinePos))) then
begin
Col := Pos - BreakPos;
Result := Result + Copy(Line, LinePos, BreakPos - LinePos + 1);
if not (CurChar in QuoteChars) then
while (Pos <= LineLen) and (Line[Pos] in BreakChars + [#13, #10]) do Inc(Pos);
if not ExistingBreak and (Pos < LineLen) then
Result := Result + BreakStr;
Inc(BreakPos);
LinePos := BreakPos;
ExistingBreak := False;
end;
end;
Result := Result + Copy(Line, LinePos, MaxInt);
end;
function WrapText(const Line: string; MaxCol: Integer): string;
begin
Result := WrapText(Line, #13#10, [' ', '-', #9], MaxCol); { do not localize }
end;
function FindCmdLineSwitch(const Switch: string; SwitchChars: TSysCharSet;
IgnoreCase: Boolean): Boolean;
var
I: Integer;
S: string;
begin
for I := 1 to ParamCount do
begin
S := ParamStr(I);
if (SwitchChars = []) or (S[1] in SwitchChars) then
if IgnoreCase then
begin
if (AnsiCompareText(Copy(S, 2, Maxint), Switch) = 0) then
begin
Result := True;
Exit;
end;
end
else begin
if (AnsiCompareStr(Copy(S, 2, Maxint), Switch) = 0) then
begin
Result := True;
Exit;
end;
end;
end;
Result := False;
end;
{ Package info structures }
type
PPkgName = ^TPkgName;
TPkgName = packed record
HashCode: Byte;
Name: array[0..255] of Char;
end;
{ PackageUnitFlags:
bit meaning
-----------------------------------------------------------------------------------------
0 | main unit
1 | package unit (dpk source)
2 | $WEAKPACKAGEUNIT unit
3 | original containment of $WEAKPACKAGEUNIT (package into which it was compiled)
4 | implicitly imported
5..7 | reserved
}
PUnitName = ^TUnitName;
TUnitName = packed record
Flags : Byte;
HashCode: Byte;
Name: array[0..255] of Char;
end;
{ Package flags:
bit meaning
-----------------------------------------------------------------------------------------
0 | 1: never-build 0: always build
1 | 1: design-time only 0: not design-time only on => bit 2 = off
2 | 1: run-time only 0: not run-time only on => bit 1 = off
3 | 1: do not check for dup units 0: perform normal dup unit check
4..25 | reserved
26..27| (producer) 0: pre-V4, 1: undefined, 2: c++, 3: Pascal
28..29| reserved
30..31| 0: EXE, 1: Package DLL, 2: Library DLL, 3: undefined
}
PPackageInfoHeader = ^TPackageInfoHeader;
TPackageInfoHeader = packed record
Flags: DWORD;
RequiresCount: Integer;
{Requires: array[0..9999] of TPkgName;
ContainsCount: Integer;
Contains: array[0..9999] of TUnitName;}
end;
function PackageInfoTable(Module: HMODULE): PPackageInfoHeader;
var
ResInfo: HRSRC;
Data: THandle;
begin
Result := nil;
ResInfo := FindResource(Module, 'PACKAGEINFO', RT_RCDATA);
if ResInfo <> 0 then
begin
Data := LoadResource(Module, ResInfo);
if Data <> 0 then
try
Result := LockResource(Data);
UnlockResource(Data);
finally
FreeResource(Data);
end;
end;
end;
function GetModuleName(Module: HMODULE): string;
var
ModName: array[0..MAX_PATH] of Char;
begin
SetString(Result, ModName, Windows.GetModuleFileName(Module, ModName, SizeOf(ModName)));
end;
var
Reserved: Integer;
procedure CheckForDuplicateUnits(Module: HMODULE);
var
ModuleFlags: DWORD;
function IsUnitPresent(HC: Byte; UnitName: PChar; Module: HMODULE;
const ModuleName: string; var UnitPackage: string): Boolean;
var
I: Integer;
InfoTable: PPackageInfoHeader;
LibModule: PLibModule;
PkgName: PPkgName;
UName : PUnitName;
Count: Integer;
begin
Result := True;
if (StrIComp(UnitName, 'SysInit') <> 0) and
(StrIComp(UnitName, PChar(ModuleName)) <> 0) then
begin
LibModule := LibModuleList;
while LibModule <> nil do
begin
if LibModule.Instance <> Module then
begin
InfoTable := PackageInfoTable(HMODULE(LibModule.Instance));
if (InfoTable <> nil) and (InfoTable.Flags and pfModuleTypeMask = pfPackageModule) and
((InfoTable.Flags and pfIgnoreDupUnits) = (ModuleFlags and pfIgnoreDupUnits)) then
begin
PkgName := PPkgName(Integer(InfoTable) + SizeOf(InfoTable^));
Count := InfoTable.RequiresCount;
{ Skip the Requires list }
for I := 0 to Count - 1 do Inc(Integer(PkgName), StrLen(PkgName.Name) + 2);
Count := Integer(Pointer(PkgName)^);
UName := PUnitName(Integer(PkgName) + 4);
for I := 0 to Count - 1 do
begin
with UName^ do
// Test Flags to ignore weak package units
if ((HashCode = HC) or (HashCode = 0) or (HC = 0)) and
((Flags and $06) = 0) and (StrIComp(UnitName, Name) = 0) then
begin
UnitPackage := ChangeFileExt(ExtractFileName(
GetModuleName(HMODULE(LibModule.Instance))), '');
Exit;
end;
Inc(Integer(UName), StrLen(UName.Name) + 3);
end;
end;
end;
LibModule := LibModule.Next;
end;
end;
Result := False;
end;
function FindLibModule(Module: HModule): PLibModule;
begin
Result := LibModuleList;
while Result <> nil do
begin
if Result.Instance = Module then Exit;
Result := Result.Next;
end;
end;
procedure InternalUnitCheck(Module: HModule);
var
I: Integer;
InfoTable: PPackageInfoHeader;
UnitPackage: string;
ModuleName: string;
PkgName: PPkgName;
UName: PUnitName;
Count: Integer;
LibModule: PLibModule;
begin
InfoTable := PackageInfoTable(Module);
if (InfoTable <> nil) and (InfoTable.Flags and pfModuleTypeMask = pfPackageModule) then
begin
if ModuleFlags = 0 then ModuleFlags := InfoTable.Flags;
ModuleName := ChangeFileExt(ExtractFileName(GetModuleName(Module)), '');
PkgName := PPkgName(Integer(InfoTable) + SizeOf(InfoTable^));
Count := InfoTable.RequiresCount;
for I := 0 to Count - 1 do
begin
with PkgName^ do
InternalUnitCheck(GetModuleHandle(PChar(ChangeFileExt(Name, '.bpl'))));
Inc(Integer(PkgName), StrLen(PkgName.Name) + 2);
end;
LibModule := FindLibModule(Module);
if (LibModule = nil) or ((LibModule <> nil) and (LibModule.Reserved <> Reserved)) then
begin
if LibModule <> nil then LibModule.Reserved := Reserved;
Count := Integer(Pointer(PkgName)^);
UName := PUnitName(Integer(PkgName) + 4);
for I := 0 to Count - 1 do
begin
with UName^ do
// Test Flags to ignore weak package units
if ((Flags and ufWeakPackageUnit) = 0 ) and
IsUnitPresent(HashCode, Name, Module, ModuleName, UnitPackage) then
raise EPackageError.CreateResFmt(@SDuplicatePackageUnit,
[ModuleName, Name, UnitPackage]);
Inc(Integer(UName), StrLen(UName.Name) + 3);
end;
end;
end;
end;
begin
Inc(Reserved);
ModuleFlags := 0;
InternalUnitCheck(Module);
end;
{ InitializePackage }
procedure InitializePackage(Module: HMODULE);
type
TPackageLoad = procedure;
var
PackageLoad: TPackageLoad;
begin
CheckForDuplicateUnits(Module);
@PackageLoad := GetProcAddress(Module, 'Initialize'); //Do not localize
if Assigned(PackageLoad) then
PackageLoad else
raise Exception.CreateFmt(sInvalidPackageFile, [GetModuleName(Module)]);
end;
{ FinalizePackage }
procedure FinalizePackage(Module: HMODULE);
type
TPackageUnload = procedure;
var
PackageUnload: TPackageUnload;
begin
@PackageUnload := GetProcAddress(Module, 'Finalize'); //Do not localize
if Assigned(PackageUnload) then
PackageUnload else
raise EPackageError.CreateRes(@sInvalidPackageHandle);
end;
{ LoadPackage }
function LoadPackage(const Name: string): HMODULE;
begin
Result := SafeLoadLibrary(Name);
if Result = 0 then
raise EPackageError.CreateResFmt(@sErrorLoadingPackage,
[Name, SysErrorMessage(GetLastError)]);
try
InitializePackage(Result);
except
FreeLibrary(Result);
raise;
end;
end;
{ UnloadPackage }
procedure UnloadPackage(Module: HMODULE);
begin
FinalizePackage(Module);
FreeLibrary(Module);
end;
{ GetPackageInfo }
procedure GetPackageInfo(Module: HMODULE; Param: Pointer; var Flags: Integer;
InfoProc: TPackageInfoProc);
var
InfoTable: PPackageInfoHeader;
I: Integer;
PkgName: PPkgName;
UName: PUnitName;
Count: Integer;
begin
InfoTable := PackageInfoTable(Module);
if not Assigned(InfoTable) then
raise Exception.CreateFmt(SCannotReadPackageInfo,
[ExtractFileName(GetModuleName(Module))]);
Flags := InfoTable.Flags;
with InfoTable^ do
begin
PkgName := PPkgName(Integer(InfoTable) + SizeOf(InfoTable^));
Count := RequiresCount;
for I := 0 to Count - 1 do
begin
InfoProc(PkgName.Name, ntRequiresPackage, 0, Param);
Inc(Integer(PkgName), StrLen(PkgName.Name) + 2);
end;
Count := Integer(Pointer(PkgName)^);
UName := PUnitName(Integer(PkgName) + 4);
for I := 0 to Count - 1 do
begin
InfoProc(UName.Name, ntContainsUnit, UName.Flags, Param);
Inc(Integer(UName), StrLen(UName.Name) + 3);
end;
end;
end;
function GetPackageDescription(ModuleName: PChar): string;
var
ResModule: HModule;
ResInfo: HRSRC;
ResData: HGLOBAL;
begin
Result := '';
ResModule := LoadResourceModule(ModuleName);
if ResModule = 0 then
begin
ResModule := LoadLibraryEx(ModuleName, 0, LOAD_LIBRARY_AS_DATAFILE);
if ResModule = 0 then
raise EPackageError.CreateResFmt(@sErrorLoadingPackage,
[ModuleName, SysErrorMessage(GetLastError)]);
end;
try
ResInfo := FindResource(ResModule, 'DESCRIPTION', RT_RCDATA);
if ResInfo <> 0 then
begin
ResData := LoadResource(ResModule, ResInfo);
if ResData <> 0 then
try
Result := PWideChar(LockResource(ResData));
UnlockResource(ResData);
finally
FreeResource(ResData);
end;
end;
finally
FreeLibrary(ResModule);
end;
end;
{ RaiseLastWin32Error }
procedure RaiseLastWin32Error;
var
LastError: DWORD;
Error: EWin32Error;
begin
LastError := GetLastError;
if LastError <> ERROR_SUCCESS then
Error := EWin32Error.CreateResFmt(@SWin32Error, [LastError,
SysErrorMessage(LastError)])
else
Error := EWin32Error.CreateRes(@SUnkWin32Error);
Error.ErrorCode := LastError;
raise Error;
end;
{ Win32Check }
function Win32Check(RetVal: BOOL): BOOL;
begin
if not RetVal then RaiseLastWin32Error;
Result := RetVal;
end;
type
PTerminateProcInfo = ^TTerminateProcInfo;
TTerminateProcInfo = record
Next: PTerminateProcInfo;
Proc: TTerminateProc;
end;
var
TerminateProcList: PTerminateProcInfo = nil;
procedure AddTerminateProc(TermProc: TTerminateProc);
var
P: PTerminateProcInfo;
begin
New(P);
P^.Next := TerminateProcList;
P^.Proc := TermProc;
TerminateProcList := P;
end;
function CallTerminateProcs: Boolean;
var
PI: PTerminateProcInfo;
begin
Result := True;
PI := TerminateProcList;
while Result and (PI <> nil) do
begin
Result := PI^.Proc;
PI := PI^.Next;
end;
end;
procedure FreeTerminateProcs;
var
PI: PTerminateProcInfo;
begin
while TerminateProcList <> nil do
begin
PI := TerminateProcList;
TerminateProcList := PI^.Next;
Dispose(PI);
end;
end;
{ --- }
function AL1(const P): LongWord;
asm
MOV EDX,DWORD PTR [P]
XOR EDX,DWORD PTR [P+4]
XOR EDX,DWORD PTR [P+8]
XOR EDX,DWORD PTR [P+12]
MOV EAX,EDX
end;
function AL2(const P): LongWord;
asm
MOV EDX,DWORD PTR [P]
ROR EDX,5
XOR EDX,DWORD PTR [P+4]
ROR EDX,5
XOR EDX,DWORD PTR [P+8]
ROR EDX,5
XOR EDX,DWORD PTR [P+12]
MOV EAX,EDX
end;
const
AL1s: array[0..2] of LongWord = ($FFFFFFF0, $FFFFEBF0, 0);
AL2s: array[0..2] of LongWord = ($42C3ECEF, $20F7AEB6, $D1C2F74E);
procedure ALV;
begin
raise Exception.Create(SNL);
end;
function ALR: Pointer;
var
LibModule: PLibModule;
begin
if MainInstance <> 0 then
Result := Pointer(LoadResource(MainInstance, FindResource(MainInstance, 'DVCLAL',
RT_RCDATA)))
else
begin
Result := nil;
LibModule := LibModuleList;
while LibModule <> nil do
begin
with LibModule^ do
begin
Result := Pointer(LoadResource(Instance, FindResource(Instance, 'DVCLAL',
RT_RCDATA)));
if Result <> nil then Break;
end;
LibModule := LibModule.Next;
end;
end;
if Result = nil then ALV;
end;
function GDAL: LongWord;
type
TDVCLAL = array[0..3] of LongWord;
PDVCLAL = ^TDVCLAL;
var
P: Pointer;
A1, A2: LongWord;
PAL1s, PAL2s: PDVCLAL;
ALOK: Boolean;
begin
P := ALR;
A1 := AL1(P^);
A2 := AL2(P^);
Result := A1;
PAL1s := @AL1s;
PAL2s := @AL2s;
ALOK := ((A1 = PAL1s[0]) and (A2 = PAL2s[0])) or
((A1 = PAL1s[1]) and (A2 = PAL2s[1])) or
((A1 = PAL1s[2]) and (A2 = PAL2s[2]));
FreeResource(Integer(P));
if not ALOK then ALV;
end;
procedure RCS;
var
P: Pointer;
ALOK: Boolean;
begin
P := ALR;
ALOK := (AL1(P^) = AL1s[2]) and (AL2(P^) = AL2s[2]);
FreeResource(Integer(P));
if not ALOK then ALV;
end;
procedure RPR;
var
AL: LongWord;
begin
AL := GDAL;
if (AL <> AL1s[1]) and (AL <> AL1s[2]) then ALV;
end;
procedure InitDriveSpacePtr;
var
Kernel: THandle;
begin
Kernel := GetModuleHandle(Windows.Kernel32);
if Kernel <> 0 then
@GetDiskFreeSpaceEx := GetProcAddress(Kernel, 'GetDiskFreeSpaceExA');
if not Assigned(GetDiskFreeSpaceEx) then
GetDiskFreeSpaceEx := @BackfillGetDiskFreeSpaceEx;
end;
{ TMultiReadExclusiveWriteSynchronizer }
constructor TMultiReadExclusiveWriteSynchronizer.Create;
begin
inherited Create;
InitializeCriticalSection(FLock);
FReadExit := CreateEvent(nil, True, True, nil); // manual reset, start signaled
SetLength(FActiveThreads, 4);
end;
destructor TMultiReadExclusiveWriteSynchronizer.Destroy;
begin
BeginWrite;
inherited Destroy;
CloseHandle(FReadExit);
DeleteCriticalSection(FLock);
end;
function TMultiReadExclusiveWriteSynchronizer.WriterIsOnlyReader: Boolean;
var
I, Len: Integer;
begin
Result := False;
if FWriteRequestorID = 0 then Exit;
// We know a writer is waiting for entry with the FLock locked,
// so FActiveThreads is stable - no BeginRead could be resizing it now
I := 0;
Len := High(FActiveThreads);
while (I < Len) and
((FActiveThreads[I].ThreadID = 0) or (FActiveThreads[I].ThreadID = FWriteRequestorID)) do
Inc(I);
Result := I >= Len;
end;
procedure TMultiReadExclusiveWriteSynchronizer.BeginWrite;
begin
EnterCriticalSection(FLock); // Block new read or write ops from starting
if not FWriting then
begin
FWriteRequestorID := GetCurrentThreadID; // Indicate that writer is waiting for entry
if not WriterIsOnlyReader then // See if any other thread is reading
WaitForSingleObject(FReadExit, INFINITE); // Wait for current readers to finish
FSaveReadCount := FCount; // record prior read recursions for this thread
FCount := 0;
FWriteRequestorID := 0;
FWriting := True;
end;
Inc(FCount); // allow read recursions during write without signalling FReadExit event
end;
procedure TMultiReadExclusiveWriteSynchronizer.EndWrite;
begin
Dec(FCount);
if FCount = 0 then
begin
FCount := FSaveReadCount; // restore read recursion count
FSaveReadCount := 0;
FWriting := False;
end;
LeaveCriticalSection(FLock);
end;
procedure TMultiReadExclusiveWriteSynchronizer.BeginRead;
var
I: Integer;
ThreadID: Integer;
ZeroSlot: Integer;
AlreadyInRead: Boolean;
begin
ThreadID := GetCurrentThreadID;
// First, do a lightweight check to see if this thread already has a read lock
while InterlockedExchange(FReallocFlag, ThreadID) <> 0 do Sleep(0);
try // FActiveThreads array is now stable
I := 0;
while (I < High(FActiveThreads)) and (FActiveThreads[I].ThreadID <> ThreadID) do
Inc(I);
AlreadyInRead := I < High(FActiveThreads);
if AlreadyInRead then // This thread already has a read lock
begin // Don't grab FLock, since that could deadlock with
if not FWriting then // a waiting BeginWrite
begin // Bump up ref counts and exit
InterlockedIncrement(FCount);
Inc(FActiveThreads[I].RecursionCount); // thread safe = unique to threadid
end;
end
finally
FReallocFlag := 0;
end;
if not AlreadyInRead then
begin // Ok, we don't already have a lock, so do the hard work of making one
EnterCriticalSection(FLock);
try
if not FWriting then
begin
// This will call ResetEvent more than necessary on win95, but still work
if InterlockedIncrement(FCount) = 1 then
ResetEvent(FReadExit); // Make writer wait until all readers are finished.
I := 0; // scan for empty slot in activethreads list
ZeroSlot := -1;
while (I < High(FActiveThreads)) and (FActiveThreads[I].ThreadID <> ThreadID) do
begin
if (FActiveThreads[I].ThreadID = 0) and (ZeroSlot < 0) then ZeroSlot := I;
Inc(I);
end;
if I >= High(FActiveThreads) then // didn't find our threadid slot
begin
if ZeroSlot < 0 then // no slots available. Grow array to make room
begin // spin loop. wait for EndRead to put zero back into FReallocFlag
while InterlockedExchange(FReallocFlag, ThreadID) <> 0 do Sleep(0);
try
SetLength(FActiveThreads, High(FActiveThreads) + 3);
finally
FReallocFlag := 0;
end;
end
else // use an empty slot
I := ZeroSlot;
// no concurrency issue here. We're the only thread interested in this record.
FActiveThreads[I].ThreadID := ThreadID;
FActiveThreads[I].RecursionCount := 1;
end
else // found our threadid slot.
Inc(FActiveThreads[I].RecursionCount); // thread safe = unique to threadid
end;
finally
LeaveCriticalSection(FLock);
end;
end;
end;
procedure TMultiReadExclusiveWriteSynchronizer.EndRead;
var
I, ThreadID, Len: Integer;
begin
if not FWriting then
begin
// Remove our threadid from the list of active threads
I := 0;
ThreadID := GetCurrentThreadID;
// wait for BeginRead to finish any pending realloc of FActiveThreads
while InterlockedExchange(FReallocFlag, ThreadID) <> 0 do Sleep(0);
try
Len := High(FActiveThreads);
while (I < Len) and (FActiveThreads[I].ThreadID <> ThreadID) do Inc(I);
assert(I < Len);
// no concurrency issues here. We're the only thread interested in this record.
Dec(FActiveThreads[I].RecursionCount); // threadsafe = unique to threadid
if FActiveThreads[I].RecursionCount = 0 then
FActiveThreads[I].ThreadID := 0; // must do this last!
finally
FReallocFlag := 0;
end;
if (InterlockedDecrement(FCount) = 0) or WriterIsOnlyReader then
SetEvent(FReadExit); // release next writer
end;
end;
procedure FreeAndNil(var Obj);
var
P: TObject;
begin
P := TObject(Obj);
TObject(Obj) := nil; // clear the reference before destroying the object
P.Free;
end;
{ Interface support routines }
function Supports(const Instance: IUnknown; const Intf: TGUID; out Inst): Boolean;
begin
Result := (Instance <> nil) and (Instance.QueryInterface(Intf, Inst) = 0);
end;
function Supports(Instance: TObject; const Intf: TGUID; out Inst): Boolean;
var
Unk: IUnknown;
begin
Result := (Instance <> nil) and Instance.GetInterface(IUnknown, Unk) and
Supports(Unk, Intf, Inst);
end;
{ TLanguages }
{ Query the OS for information for a specified locale. Unicode version. Works correctly on Asian WinNT. }
function GetLocaleDataW(ID: LCID; Flag: DWORD): string;
var
Buffer: array[0..1023] of WideChar;
begin
Buffer[0] := #0;
GetLocaleInfoW(ID, Flag, Buffer, SizeOf(Buffer) div 2);
Result := Buffer;
end;
{ Query the OS for information for a specified locale. ANSI Version. Works correctly on Asian Win95. }
function GetLocaleDataA(ID: LCID; Flag: DWORD): string;
var
Buffer: array[0..1023] of Char;
begin
Buffer[0] := #0;
SetString(Result, Buffer, GetLocaleInfoA(ID, Flag, Buffer, SizeOf(Buffer)) - 1);
end;
{ Called for each supported locale. }
function TLanguages.LocalesCallback(LocaleID: PChar): Integer; stdcall;
var
AID: LCID;
ShortLangName: string;
GetLocaleDataProc: function (ID: LCID; Flag: DWORD): string;
begin
if Win32Platform = VER_PLATFORM_WIN32_NT then
GetLocaleDataProc := @GetLocaleDataW
else
GetLocaleDataProc := @GetLocaleDataA;
AID := StrToInt('$' + Copy(LocaleID, 5, 4));
ShortLangName := GetLocaleDataProc(AID, LOCALE_SABBREVLANGNAME);
if ShortLangName <> '' then
begin
SetLength(FSysLangs, Length(FSysLangs) + 1);
with FSysLangs[High(FSysLangs)] do
begin
FName := GetLocaleDataProc(AID, LOCALE_SLANGUAGE);
FLCID := AID;
FExt := ShortLangName;
end;
end;
Result := 1;
end;
constructor TLanguages.Create;
type
TCallbackThunk = packed record
POPEDX: Byte;
MOVEAX: Byte;
SelfPtr: Pointer;
PUSHEAX: Byte;
PUSHEDX: Byte;
JMP: Byte;
JmpOffset: Integer;
end;
var
Callback: TCallbackThunk;
begin
inherited Create;
Callback.POPEDX := $5A;
Callback.MOVEAX := $B8;
Callback.SelfPtr := Self;
Callback.PUSHEAX := $50;
Callback.PUSHEDX := $52;
Callback.JMP := $E9;
Callback.JmpOffset := Integer(@TLanguages.LocalesCallback) - Integer(@Callback.JMP) - 5;
EnumSystemLocales(TFNLocaleEnumProc(@Callback), LCID_SUPPORTED);
end;
function TLanguages.GetCount: Integer;
begin
Result := High(FSysLangs) + 1;
end;
function TLanguages.GetExt(Index: Integer): string;
begin
Result := FSysLangs[Index].FExt;
end;
function TLanguages.GetID(Index: Integer): string;
begin
Result := HexDisplayPrefix + IntToHex(FSysLangs[Index].FLCID, 8);
end;
function TLanguages.GetLCID(Index: Integer): LCID;
begin
Result := FSysLangs[Index].FLCID;
end;
function TLanguages.GetName(Index: Integer): string;
begin
Result := FSysLangs[Index].FName;
end;
function TLanguages.GetNameFromLocaleID(ID: LCID): string;
var
Index: Integer;
begin
Index := IndexOf(ID);
if Index <> - 1 then Result := Name[Index];
if Result = '' then Result := sUnknown;
end;
function TLanguages.GetNameFromLCID(const ID: string): string;
begin
Result := NameFromLocaleID[StrToIntDef(ID, 0)];
end;
function TLanguages.IndexOf(ID: LCID): Integer;
begin
for Result := Low(FSysLangs) to High(FSysLangs) do
if FSysLangs[Result].FLCID = ID then Exit;
Result := -1;
end;
var
FLanguages: TLanguages;
function Languages: TLanguages;
begin
if FLanguages = nil then
FLanguages := TLanguages.Create;
Result := FLanguages;
end;
function SafeLoadLibrary(const Filename: string; ErrorMode: UINT): HMODULE;
var
OldMode: UINT;
FPUControlWord: Word;
begin
OldMode := SetErrorMode(ErrorMode);
try
asm
FNSTCW FPUControlWord
end;
try
Result := LoadLibrary(PChar(Filename));
finally
asm
FNCLEX
FLDCW FPUControlWord
end;
end;
finally
SetErrorMode(OldMode);
end;
end;
initialization
if ModuleIsCpp then HexDisplayPrefix := '0x';
InitExceptions;
GetFormatSettings;
InitPlatformId;
InitDriveSpacePtr;
finalization
FreeAndNil(FLanguages);
FreeTerminateProcs;
DoneExceptions;
end.
|
unit uFrmOrdemServico;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ExtCtrls, DB, StdCtrls, DBCtrls, Mask, ToolEdit,
RXDBCtrl, Buttons, Grids, DBGrids, FMTBcd, SqlExpr, DBClient, Provider;
type
TfrmOrdemServico = class(TForm)
StatusBar1: TStatusBar;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
dsRequerimento: TDataSource;
Label2: TLabel;
dbxDTMOVI: TDBDateEdit;
Label3: TLabel;
dbxHOMOVI: TDBEdit;
Label4: TLabel;
dbxCDCLIE: TDBEdit;
Label5: TLabel;
dbxSolicitante: TDBEdit;
Label6: TLabel;
dbxDTPREV: TDBDateEdit;
dbxHOPREV: TDBEdit;
Label8: TLabel;
Label9: TLabel;
pnlBotoes1: TPanel;
btAdicionar: TBitBtn;
btnPesquisa: TBitBtn;
btnGravar: TBitBtn;
btnCancelar: TBitBtn;
spLocCliente: TSpeedButton;
DBText2: TDBText;
Label7: TLabel;
DBText3: TDBText;
dsAtendimento: TDataSource;
Label11: TLabel;
dbxTipoAtendimento: TDBLookupComboBox;
Label12: TLabel;
Label13: TLabel;
dbxHora: TDBEdit;
Label14: TLabel;
Label15: TLabel;
dbmDiagnotisco: TDBMemo;
Label16: TLabel;
dbxSituacao: TDBEdit;
dbxDataAtendimento: TDBDateEdit;
Panel2: TPanel;
btnNovo: TBitBtn;
btnPesquisa2: TBitBtn;
btnGravar2: TBitBtn;
btnCancelar2: TBitBtn;
dstConsulta: TSQLDataSet;
cdpConsulta: TDataSetProvider;
cdsConsulta: TClientDataSet;
dsConsulta: TDataSource;
cbxTecnico: TDBLookupComboBox;
dbxDefeito: TDBMemo;
GroupBox1: TGroupBox;
DBText1: TDBText;
DBRadioGroup1: TDBRadioGroup;
PageControl2: TPageControl;
TabSheet3: TTabSheet;
TabSheet4: TTabSheet;
dstAtividades: TSQLDataSet;
dspAtividades: TDataSetProvider;
cdsAtividades: TClientDataSet;
dsAtividades: TDataSource;
cdsAtividadesATI_ATENDIMENTO: TIntegerField;
cdsAtividadesATI_ITEM: TIntegerField;
cdsAtividadesATI_DESCRICAO: TMemoField;
cdsAtividadesATI_VALOR: TFMTBCDField;
DBNavigator1: TDBNavigator;
Label1: TLabel;
dbmDescricao: TDBMemo;
Label10: TLabel;
dbxValor: TDBEdit;
Label17: TLabel;
DBEdit1: TDBEdit;
spSalvar: TSpeedButton;
spCancelar: TSpeedButton;
spNovaAtividade: TSpeedButton;
dstPecas: TSQLDataSet;
dstPecasPEC_ATENDIMENTO: TIntegerField;
dstPecasPEC_ITEM: TIntegerField;
dstPecasPEC_DESCRICAO: TStringField;
dstPecasPEC_QUANTIDADE: TFMTBCDField;
dstPecasPEC_VALOR: TFMTBCDField;
dstAtividadesATI_ATENDIMENTO: TIntegerField;
dstAtividadesATI_ITEM: TIntegerField;
dstAtividadesATI_DESCRICAO: TMemoField;
dstAtividadesATI_VALOR: TFMTBCDField;
dspPecas: TDataSetProvider;
cdsPecas: TClientDataSet;
dsPecas: TDataSource;
cdsPecasPEC_ATENDIMENTO: TIntegerField;
cdsPecasPEC_ITEM: TIntegerField;
cdsPecasPEC_DESCRICAO: TStringField;
cdsPecasPEC_QUANTIDADE: TFMTBCDField;
cdsPecasPEC_VALOR: TFMTBCDField;
Label18: TLabel;
dbxDescricaoPeca: TDBEdit;
Label19: TLabel;
dbxQuantidade: TDBEdit;
Label20: TLabel;
dbxValorPeca: TDBEdit;
Panel1: TPanel;
dbGridDados: TDBGrid;
cdsConsultaATE_IDREQUERIMENTO: TIntegerField;
cdsConsultaATE_ID: TIntegerField;
cdsConsultaATE_DATA: TDateField;
cdsConsultaATE_CDTECNICO: TStringField;
cdsConsultaREQ_DEFEITO: TMemoField;
cdsConsultaDEFEITO: TStringField;
Panel3: TPanel;
DBNavigator2: TDBNavigator;
spNovaPeca: TSpeedButton;
spGravarPeca: TSpeedButton;
spCancelarPeca: TSpeedButton;
dbgPecas: TDBGrid;
cbxNMTECN: TDBLookupComboBox;
cdsConsultaNMTECNICO: TStringField;
DBRadioGroup2: TDBRadioGroup;
procedure FormShow(Sender: TObject);
procedure btAdicionarClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure dbxDTMOVIExit(Sender: TObject);
procedure dbxHOMOVIExit(Sender: TObject);
procedure dbxHOPREVExit(Sender: TObject);
procedure dbxDTPREVExit(Sender: TObject);
procedure spLocClienteClick(Sender: TObject);
procedure dbxCDCLIEChange(Sender: TObject);
procedure dbxCDCLIEExit(Sender: TObject);
procedure dbxCDCLIEKeyPress(Sender: TObject; var Key: Char);
procedure btnNovoClick(Sender: TObject);
procedure btnGravar2Click(Sender: TObject);
procedure btnCancelar2Click(Sender: TObject);
procedure dspAtividadesGetTableName(Sender: TObject; DataSet: TDataSet;
var TableName: String);
procedure cdsAtividadesAfterInsert(DataSet: TDataSet);
procedure PageControl1Change(Sender: TObject);
procedure cdsAtividadesAfterPost(DataSet: TDataSet);
procedure spCancelarClick(Sender: TObject);
procedure spSalvarClick(Sender: TObject);
procedure DBNavigator1Click(Sender: TObject; Button: TNavigateBtn);
procedure dsAtividadesStateChange(Sender: TObject);
procedure spNovaAtividadeClick(Sender: TObject);
procedure dspPecasGetTableName(Sender: TObject; DataSet: TDataSet;
var TableName: String);
procedure cdsPecasAfterPost(DataSet: TDataSet);
procedure cdsPecasAfterInsert(DataSet: TDataSet);
procedure spCancelarPecaClick(Sender: TObject);
procedure spGravarPecaClick(Sender: TObject);
procedure dsPecasStateChange(Sender: TObject);
procedure spNovaPecaClick(Sender: TObject);
procedure TabSheet2Show(Sender: TObject);
procedure cdsConsultaCalcFields(DataSet: TDataSet);
procedure dsAtendimentoStateChange(Sender: TObject);
procedure btnPesquisaClick(Sender: TObject);
procedure dbxCDTECNKeyPress(Sender: TObject; var Key: Char);
procedure dsRequerimentoStateChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure dbxDefeitoKeyPress(Sender: TObject; var Key: Char);
procedure dbmDiagnotiscoKeyPress(Sender: TObject; var Key: Char);
procedure dbmDescricaoKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
procedure AtivarBotoes(AEdicao : Boolean);
procedure AtivarBotoes2(AEdicao : Boolean);
procedure AbrirDBRequerimento;
procedure AbrirDBAtendimento(M_NRREQU : Integer);
procedure AbrirDBAtividades(M_NRREQU : Integer);
procedure AbrirDBPecas(M_NRREQU : Integer);
procedure CONSULTA(M_CDREQU : Integer);
function GetIdAtendimento(M_NRREQU : Integer) : Integer;
procedure REGISTRO(M_NRREQU : Integer);
procedure DisplayHint(Sender: TObject);
public
{ Public declarations }
end;
var
frmOrdemServico: TfrmOrdemServico;
M_NRITEM, M_NRPECA : Integer;
implementation
uses udmADM2, uFuncoes, uLocCliente, udmADM, Math, uFrmLocRequerimento;
{$R *.dfm}
procedure TfrmOrdemServico.AtivarBotoes(AEdicao: Boolean);
begin
btAdicionar.Enabled := not AEdicao;
btnPesquisa.Enabled := not AEdicao;
btnGravar.Enabled := AEdicao;
btnCancelar.Enabled := AEdicao;
end;
procedure TfrmOrdemServico.FormShow(Sender: TObject);
begin
PageControl1.ActivePageIndex := 0;
dmADM.qryLocClientes.close;
//
AtivarBotoes(False);
AtivarBotoes2(False);
//
end;
procedure TfrmOrdemServico.btAdicionarClick(Sender: TObject);
begin
AtivarBotoes(True);
//
PageControl1.Pages[1].TabVisible := False;
dmADM2.Parametros;
AbrirDBRequerimento;
dmADM2.cdsRequerimentos.Append;
dmADM2.cdsRequerimentos.FieldByName('REQ_ID').AsInteger :=
dmADM2.cdsConfigCFG_REQUERIMENTO.AsInteger + 1;
dmADM2.cdsRequerimentos.FieldByName('REQ_SITUACAO').AsString := 'A';
dmADM2.cdsRequerimentos.FieldByName('REQ_DATA').AsDateTime := Date();
dmADM2.cdsRequerimentos.FieldByName('REQ_HORA').AsString := Copy(TimetoStr(Time),1,5);
dmADM2.cdsRequerimentos.FieldByName('REQ_DTPREVISAO').AsDateTime := Date();
dmADM2.cdsRequerimentos.FieldByName('REQ_HOPREVISAO').AsString := Copy(TimetoStr(Time),1,5);
dmADM2.cdsRequerimentos.FieldByName('REQ_TIPO').Value := 1;
dbxDTMOVI.SetFocus;
end;
procedure TfrmOrdemServico.btnGravarClick(Sender: TObject);
begin
If uFuncoes.Empty(dbxCDCLIE.Text) Then
begin
Application.MessageBox(PChar('Digite o código do cliente!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
dbxCDCLIE.SetFocus;
Exit;
End;
//
If uFuncoes.Empty(dbxSolicitante.Text) Then
begin
Application.MessageBox(PChar('Digite o nome do solicitante!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
dbxSolicitante.SetFocus;
Exit;
End;
//
{If uFuncoes.Empty(cbxTecnico.Text) Then
begin
Application.MessageBox(PChar('Selecione o tecnico!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
cbxTecnico.SetFocus;
Exit;
End;}
//
If uFuncoes.Empty(dbxDefeito.Text) Then
begin
Application.MessageBox(PChar('Digite o defeito reclamado!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
dbxDefeito.SetFocus;
Exit;
End;
//
If uFuncoes.Empty(DBRadioGroup1.Value) Then
begin
Application.MessageBox(PChar('Selecione o tipo de requerimento!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
DBRadioGroup1.SetFocus;
Exit;
End;
//
If (dbxDTMOVI.Text = ' / / ') Then
begin
Application.MessageBox(PChar('Digite a data do requerimento!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
dbxDTMOVI.SetFocus;
Exit;
End;
//
If (dbxHOMOVI.Text = ' : ') Then
begin
Application.MessageBox(PChar('Digite a hora do requerimento!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
dbxHOMOVI.SetFocus;
Exit;
End;
//
If (dbxDTPREV.Text = ' / / ') Then
begin
Application.MessageBox(PChar('Digite a data de previsto de atendimento!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
dbxDTPREV.SetFocus;
Exit;
End;
//
If (dbxHOPREV.Text = ' : ') Then
begin
Application.MessageBox(PChar('Digite a hora de previsto de atendimento!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
dbxHOPREV.SetFocus;
Exit;
End;
//
AtivarBotoes(False);
PageControl1.Pages[1].TabVisible := True;
try
If (dmADM2.cdsRequerimentos.State = dsInsert) Then
begin
dmADM2.Parametros;
dmADM2.cdsConfig.Edit;
dmADM2.cdsConfig.FieldByName('CFG_REQUERIMENTO').AsInteger :=
dmADM2.cdsConfig.FieldByName('CFG_REQUERIMENTO').AsInteger + 1;
dmADM2.cdsRequerimentosREQ_ID.AsInteger :=
dmADM2.cdsConfig.FieldByName('CFG_REQUERIMENTO').AsInteger;
dmADM2.cdsConfig.ApplyUpdates(0);
End;
//
dmADM2.cdsRequerimentos.ApplyUpdates(0);
//
Application.MessageBox(PChar('Registro gravado com sucesso!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
Except
on Exc:Exception do
begin
Application.MessageBox(PChar('Error ao tentar gravar registro!!!'+#13
+ Exc.Message),
'ATENÇÃO', MB_OK+MB_ICONSTOP+MB_APPLMODAL);
dmADM2.cdsRequerimentos.Cancel;
End;
End;
end;
procedure TfrmOrdemServico.btnCancelarClick(Sender: TObject);
begin
AtivarBotoes(False);
PageControl1.Pages[1].TabVisible := True;
//
dmADM2.cdsRequerimentos.Cancel;
end;
procedure TfrmOrdemServico.AbrirDBRequerimento;
begin
With dmADM2.cdsRequerimentos do
begin
Close;
Params.ParamByName('pID').AsInteger := -1;
Open;
End;
end;
procedure TfrmOrdemServico.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
dmADM2.cdsRequerimentos.Close;
//
Action := caFree;
end;
procedure TfrmOrdemServico.dbxDTMOVIExit(Sender: TObject);
begin
If (dbxDTMOVI.Text <> ' / / ')
and (dsRequerimento.State in [dsInsert]) Then
Begin
try
StrToDate(dbxDTMOVI.Text);
dbxDTMOVI.Date := StrtoDate(dbxDTMOVI.Text);
except
on EConvertError do
begin
ShowMessage ('Data Inválida!');
dbxDTMOVI.Date := Date();
dbxDTMOVI.SetFocus;
Exit;
End;
end;
End;
end;
procedure TfrmOrdemServico.dbxHOMOVIExit(Sender: TObject);
begin
If uFuncoes.Empty(dbxHOMOVI.Text)
and (dsRequerimento.State in [dsInsert]) Then
Begin
try
StrToTime(dbxHOMOVI.Text);
dbxHOMOVI.Text := TimetoStr(StrtoTime(dbxHOMOVI.Text));
except
on EConvertError do
begin
ShowMessage ('Hora Inválida!');
dbxHOMOVI.Text := TimetoStr(Time);
dbxHOMOVI.SetFocus;
Exit;
End;
end;
End;
end;
procedure TfrmOrdemServico.dbxHOPREVExit(Sender: TObject);
begin
If uFuncoes.Empty(dbxHOPREV.Text)
and (dsRequerimento.State in [dsInsert]) Then
Begin
try
StrToTime(dbxHOPREV.Text);
dbxHOPREV.Text := TimetoStr(StrtoTime(dbxHOPREV.Text));
except
on EConvertError do
begin
ShowMessage ('Hora Inválida!');
dbxHOPREV.Text := TimetoStr(Time);
dbxHOPREV.SetFocus;
Exit;
End;
end;
End;
end;
procedure TfrmOrdemServico.dbxDTPREVExit(Sender: TObject);
begin
If (dbxDTPREV.Text <> ' / / ')
and (dsRequerimento.State in [dsInsert]) Then
Begin
try
StrToDate(dbxDTPREV.Text);
dbxDTPREV.Date := StrtoDate(dbxDTPREV.Text);
except
on EConvertError do
begin
ShowMessage ('Data Inválida!');
dbxDTPREV.Date := Date();
dbxDTPREV.SetFocus;
Exit;
End;
end;
End;
end;
procedure TfrmOrdemServico.spLocClienteClick(Sender: TObject);
Var
W_CDCLIE : String;
begin
dbxCDCLIE.Clear;
Try
Application.CreateForm(TfrmLocCliente, frmLocCliente);
frmLocCliente.ShowModal;
Finally
W_CDCLIE := frmLocCliente.qryConsulta.FieldByName('CLI_CDCLIE').AsString;
frmLocCliente.Free;
If not uFuncoes.Empty(W_CDCLIE) Then
Begin
dbxCDCLIE.Text := W_CDCLIE;
dbxSolicitante.SetFocus;
End
Else
dbxCDCLIE.SetFocus;
End;
end;
procedure TfrmOrdemServico.dbxCDCLIEChange(Sender: TObject);
begin
If uFuncoes.Empty(dbxCDCLIE.Text) Then
begin
dmADM.qryLocClientes.Close;
cdsConsulta.Close;
End;
end;
procedure TfrmOrdemServico.dbxCDCLIEExit(Sender: TObject);
begin
If not uFuncoes.Empty(dbxCDCLIE.Text)
and (dsRequerimento.State in [dsInsert]) Then
begin
If not uFuncoes.LOCALIZAR_CLIENTE(uFuncoes.StrZero(dbxCDCLIE.Text,7)) Then
Begin
Application.MessageBox(PChar('Cliente não cadastro!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
dbxCDCLIE.Clear;
dbxCDCLIE.SetFocus;
Exit;
End;
//
dbxCDCLIE.Text := uFuncoes.StrZero(dbxCDCLIE.Text,7);
CONSULTA(dmADM2.cdsRequerimentosREQ_ID.AsInteger);
End;
end;
procedure TfrmOrdemServico.dbxCDCLIEKeyPress(Sender: TObject;
var Key: Char);
begin
If not( key in['0'..'9',#8, #13] ) then
key:=#0;
//
If (key = #27) Then
begin
Key := #0;
btnCancelarClick(Sender);
End;
//
If (key = #13) and uFuncoes.Empty(dbxCDCLIE.Text)
and (dmADM2.cdsRequerimentos.State in [dsInsert]) Then
begin
key:=#0;
spLocClienteClick(Sender);
End;
end;
procedure TfrmOrdemServico.AtivarBotoes2(AEdicao: Boolean);
begin
btnNovo.Enabled := not AEdicao;
btnPesquisa2.Enabled := not AEdicao;
btnGravar2.Enabled := AEdicao;
btnCancelar2.Enabled := AEdicao;
end;
procedure TfrmOrdemServico.btnNovoClick(Sender: TObject);
begin
If (dmADM2.cdsRequerimentos.Active) and not (dmADM2.cdsRequerimentos.IsEmpty) Then
begin
If (dmADM2.cdsRequerimentos.FieldByName('REQ_SITUACAO').AsString = 'A' ) Then
begin
AtivarBotoes2(True);
PageControl1.Pages[0].TabVisible := False;
//
dmADM2.cdsRequerimentos.Edit;
//
dmADM2.Parametros;
dmADM2.cdsAtendimento.Append;
dmADM2.cdsAtendimento.FieldByName('ATE_ID').AsInteger :=
GetIdAtendimento(dmADM2.cdsRequerimentosREQ_ID.AsInteger);
dmADM2.cdsAtendimento.FieldByName('ATE_DATA').AsDateTime := Date();
dmADM2.cdsAtendimento.FieldByName('ATE_HORA').AsString := Copy(TimetoStr(Time),1,5);
dbxTipoAtendimento.SetFocus;
End
Else
Application.MessageBox(PChar('Requerimento já concluído.'),
'ATENÇÃO', MB_OK+MB_ICONWARNING+MB_APPLMODAL);
End
Else
Begin
PageControl1.ActivePageIndex := 0;
btAdicionar.SetFocus;
End;
end;
procedure TfrmOrdemServico.btnGravar2Click(Sender: TObject);
begin
If uFuncoes.Empty(dbxTipoAtendimento.Text) Then
begin
Application.MessageBox(PChar('Selecione o Tipo de Atendimento!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
dbxTipoAtendimento.SetFocus;
Exit;
End;
//
If uFuncoes.Empty(cbxNMTECN.Text) Then
begin
Application.MessageBox(PChar('Selecione o tecnico!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
cbxNMTECN.SetFocus;
Exit;
End;
//
If uFuncoes.Empty(dbxSituacao.Text) Then
begin
Application.MessageBox(PChar('Digite a situação!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
dbxSituacao.SetFocus;
Exit;
End;
//
If (dbxDataAtendimento.Text = ' / / ') Then
begin
Application.MessageBox(PChar('Digite a data do atendimento!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
dbxDataAtendimento.SetFocus;
Exit;
End;
//
If (dbxHora.Text = ' : ') Then
begin
Application.MessageBox(PChar('Digite a hora do atendimento!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
dbxHora.SetFocus;
Exit;
End;
//
AtivarBotoes2(False);
PageControl1.Pages[0].TabVisible := True;
//
try
If (dmADM2.cdsAtendimento.State = dsInsert) Then
begin
dmADM2.Parametros;
dmADM2.cdsAtendimentoATE_IDREQUERIMENTO.AsInteger :=
dmADM2.cdsRequerimentosREQ_ID.AsInteger;
dmADM2.cdsAtendimentoATE_ID.AsInteger :=
GetIdAtendimento(dmADM2.cdsRequerimentosREQ_ID.AsInteger);
End;
//
dmADM2.cdsAtendimento.ApplyUpdates(0);
dmADM2.cdsRequerimentos.ApplyUpdates(0);
//
Application.MessageBox(PChar('Registro gravado com sucesso!!!'),
'ATENÇÃO', MB_OK+MB_ICONINFORMATION+MB_APPLMODAL);
Except
on Exc:Exception do
begin
Application.MessageBox(PChar('Error ao tentar gravar registro!!!'+#13
+ Exc.Message),
'ATENÇÃO', MB_OK+MB_ICONSTOP+MB_APPLMODAL);
dmADM2.cdsAtendimento.Cancel;
End;
End;
end;
procedure TfrmOrdemServico.btnCancelar2Click(Sender: TObject);
begin
AtivarBotoes2(False);
PageControl1.Pages[0].TabVisible := True;
dmADM2.cdsAtendimento.Cancel;
dmADM2.cdsRequerimentos.Cancel;
//
AbrirDBAtendimento(dmADM2.cdsRequerimentosREQ_ID.AsInteger);
end;
procedure TfrmOrdemServico.AbrirDBAtendimento(M_NRREQU : Integer);
begin
With dmADM2.cdsAtendimento do
begin
Close;
Params.ParamByName('pID').AsInteger := M_NRREQU;
Open;
End;
end;
procedure TfrmOrdemServico.CONSULTA(M_CDREQU : Integer);
begin
With cdsConsulta do
begin
Close;
Params.ParamByName('pREQ').AsInteger := M_CDREQU;
Open;
End;
end;
function TfrmOrdemServico.GetIdAtendimento(M_NRREQU: Integer): Integer;
var
qraux : TSQLquery;
texto : string;
begin
texto := 'Select max(ATE_ID) from ATENDIMENTOS Where (ATE_IDREQUERIMENTO = :pREQ)';
QrAux := TSqlquery.Create(nil);
with QrAux do
try
SQLConnection := dmADM2.sqlConexao;
sql.Add(texto);
Params.ParamByName('pREQ').AsInteger := M_NRREQU;
open;
result := fields[0].AsInteger + 1;
finally
free;
end;
end;
procedure TfrmOrdemServico.dspAtividadesGetTableName(Sender: TObject;
DataSet: TDataSet; var TableName: String);
begin
TableName := 'ATIVIDADES';
end;
procedure TfrmOrdemServico.cdsAtividadesAfterInsert(DataSet: TDataSet);
begin
M_NRITEM := M_NRITEM + 1;
cdsAtividadesATI_ATENDIMENTO.AsInteger :=
dmADM2.cdsRequerimentosREQ_ID.AsInteger;
cdsAtividadesATI_ITEM.AsInteger := M_NRITEM;
end;
procedure TfrmOrdemServico.AbrirDBAtividades(M_NRREQU: Integer);
begin
With cdsAtividades do
begin
Close;
Params.ParamByName('pREQ').AsInteger := M_NRREQU;
Open;
//
If not (IsEmpty) Then
M_NRITEM := RecordCount
Else
M_NRITEM := 0;
End;
end;
procedure TfrmOrdemServico.PageControl1Change(Sender: TObject);
begin
If (PageControl1.ActivePageIndex = 1) Then
begin
dmADM2.cdsAtendimento.Close;
cdsAtividades.Close;
cdsPecas.Close;
//
If (dmADM2.cdsRequerimentos.Active) and not (dmADM2.cdsRequerimentos.IsEmpty) Then
Begin
AbrirDBAtendimento(dmADM2.cdsRequerimentosREQ_ID.AsInteger);
AbrirDBAtividades(dmADM2.cdsRequerimentosREQ_ID.AsInteger);
AbrirDBPecas(dmADM2.cdsRequerimentosREQ_ID.AsInteger);
End;
End;
end;
procedure TfrmOrdemServico.cdsAtividadesAfterPost(DataSet: TDataSet);
begin
cdsAtividades.ApplyUpdates(0);
end;
procedure TfrmOrdemServico.spCancelarClick(Sender: TObject);
begin
If (M_NRITEM > 0) Then
M_NRITEM := M_NRITEM - 1;
//
cdsAtividades.Cancel;
end;
procedure TfrmOrdemServico.spSalvarClick(Sender: TObject);
begin
If uFuncoes.Empty(dbmDescricao.Lines.Text) Then
begin
dbmDescricao.SetFocus;
Exit;
End;
//
If uFuncoes.Empty(dbxValor.Text) Then
begin
dbxValor.SetFocus;
Exit;
End;
//
try
cdsAtividades.Post;
Except
on Exc:Exception do
begin
Application.MessageBox(PChar('Error ao tentar gravar registro!!!'),
'ATENÇÃO', MB_OK+MB_ICONSTOP+MB_APPLMODAL);
spCancelarClick(Self);
End;
End;
end;
procedure TfrmOrdemServico.DBNavigator1Click(Sender: TObject;
Button: TNavigateBtn);
begin
If (cdsAtividades.State in [dsInsert]) Then
dbmDescricao.SetFocus;
end;
procedure TfrmOrdemServico.dsAtividadesStateChange(Sender: TObject);
begin
If (dsAtividades.DataSet.Active) Then
begin
spNovaAtividade.Enabled := dsAtividades.State in [dsBrowse];
spSalvar.Enabled := dsAtividades.State in [dsInsert, dsEdit];
spCancelar.Enabled := dsAtividades.State in [dsInsert, dsEdit];
End;
end;
procedure TfrmOrdemServico.spNovaAtividadeClick(Sender: TObject);
begin
If (dmADM2.cdsRequerimentos.FieldByName('REQ_SITUACAO').AsString = 'A' ) Then
begin
cdsAtividades.Append;
dbmDescricao.SetFocus;
End
Else
Application.MessageBox(PChar('Requerimento já concluído.'),
'ATENÇÃO', MB_OK+MB_ICONWARNING+MB_APPLMODAL);
end;
procedure TfrmOrdemServico.dspPecasGetTableName(Sender: TObject;
DataSet: TDataSet; var TableName: String);
begin
TableName := 'PECAS';
end;
procedure TfrmOrdemServico.cdsPecasAfterPost(DataSet: TDataSet);
begin
cdsPecas.ApplyUpdates(0);
end;
procedure TfrmOrdemServico.cdsPecasAfterInsert(DataSet: TDataSet);
begin
M_NRPECA := M_NRPECA + 1;
cdsPecasPEC_ATENDIMENTO.AsInteger :=
dmADM2.cdsRequerimentosREQ_ID.AsInteger;
cdsPecasPEC_ITEM.AsInteger := M_NRPECA;
end;
procedure TfrmOrdemServico.spCancelarPecaClick(Sender: TObject);
begin
If (M_NRPECA > 0) Then
M_NRPECA := M_NRPECA - 1;
//
dbgPecas.Visible := True;
DBNavigator2.Enabled := True;
cdsPecas.Cancel;
end;
procedure TfrmOrdemServico.spGravarPecaClick(Sender: TObject);
begin
If uFuncoes.Empty(dbxDescricaoPeca.Text) Then
begin
//dbxDescricaoPeca.SetFocus;
dbgPecas.SelectedIndex := 1;
Exit;
End;
//
If uFuncoes.Empty(dbxQuantidade.Text) Then
begin
dbxQuantidade.SetFocus;
Exit;
End;
//
If uFuncoes.Empty(dbxValorPeca.Text) Then
begin
dbxValorPeca.SetFocus;
Exit;
End;
//
dbgPecas.Visible := True;
DBNavigator2.Enabled := True;
try
cdsPecas.Post;
Except
on Exc:Exception do
begin
Application.MessageBox(PChar('Error ao tentar gravar registro!!!'),
'ATENÇÃO', MB_OK+MB_ICONSTOP+MB_APPLMODAL);
spCancelarPecaClick(Self);
End;
End;
end;
procedure TfrmOrdemServico.dsPecasStateChange(Sender: TObject);
begin
spNovaPeca.Enabled := dsPecas.State in [dsBrowse];
spGravarPeca.Enabled := dsPecas.State in [dsInsert, dsEdit];
spCancelarPeca.Enabled := dsPecas.State in [dsInsert, dsEdit];
end;
procedure TfrmOrdemServico.spNovaPecaClick(Sender: TObject);
begin
If (dmADM2.cdsRequerimentos.FieldByName('REQ_SITUACAO').AsString = 'A' ) Then
begin
dbgPecas.Visible := False;
DBNavigator2.Enabled := False;
cdsPecas.Append;
//cdsPecas.FieldByName('PEC_QUANTIDADE').AsInteger := 1;
dbxDescricaoPeca.SetFocus;
End
Else
Application.MessageBox(PChar('Requerimento já concluído.'),
'ATENÇÃO', MB_OK+MB_ICONWARNING+MB_APPLMODAL);
end;
procedure TfrmOrdemServico.TabSheet2Show(Sender: TObject);
begin
PageControl2.ActivePageIndex := 0;
end;
procedure TfrmOrdemServico.AbrirDBPecas(M_NRREQU: Integer);
begin
With cdsPecas do
begin
Close;
Params.ParamByName('pREQ').AsInteger := M_NRREQU;
Open;
//
If not (IsEmpty) Then
M_NRPECA := RecordCount
Else
M_NRPECA := 0;
End;
end;
procedure TfrmOrdemServico.cdsConsultaCalcFields(DataSet: TDataSet);
begin
cdsConsultaDEFEITO.AsString :=
Copy(cdsConsultaREQ_DEFEITO.AsString,1,60);
end;
procedure TfrmOrdemServico.dsAtendimentoStateChange(Sender: TObject);
begin
If (dsAtendimento.DataSet.Active) Then
begin
spNovaAtividade.Enabled := dsAtendimento.DataSet.RecordCount > 0;
spNovaPeca.Enabled := dsAtendimento.DataSet.RecordCount > 0;
End;
end;
procedure TfrmOrdemServico.btnPesquisaClick(Sender: TObject);
Var
W_NRREQU : Integer;
begin
frmLocReclamacao := TfrmLocReclamacao.Create(Self);
try
if (frmLocReclamacao.ShowModal = mrOK)
and not (frmLocReclamacao.cdsConsulta.IsEmpty) then
begin
W_NRREQU := frmLocReclamacao.cdsConsulta.FieldByName('REQ_ID').AsInteger;
REGISTRO(W_NRREQU);
uFuncoes.LOCALIZAR_CLIENTE(dmADM2.cdsRequerimentosREQ_CLIENTE.AsString);
//getNMCLIENTE(dmADM2.cdsRequerimentosREQ_CLIENTE.AsString);
AbrirDBAtendimento(W_NRREQU);
CONSULTA(W_NRREQU);
LOCALIZAR_FUNCIONARIO(dmADM2.cdsAtendimentoATE_CDTECNICO.AsString);
AbrirDBAtividades(W_NRREQU);
AbrirDBPecas(W_NRREQU);
End;
Finally
frmLocReclamacao.Free;
End;
end;
procedure TfrmOrdemServico.REGISTRO(M_NRREQU: Integer);
begin
With dmADM2.cdsRequerimentos do
begin
DisableControls;
Close;
Params.ParamByName('pID').AsInteger := M_NRREQU;
Open;
EnableControls;
End;
end;
procedure TfrmOrdemServico.dbxCDTECNKeyPress(Sender: TObject;
var Key: Char);
begin
If not( key in['0'..'9',#8, #13] ) then
key:=#0;
end;
procedure TfrmOrdemServico.dsRequerimentoStateChange(Sender: TObject);
begin
spLocCliente.Enabled := dsRequerimento.State in [dsInsert, dsEdit];
end;
procedure TfrmOrdemServico.DisplayHint(Sender: TObject);
begin
StatusBar1.Panels[0].Text := Application.Hint;
end;
procedure TfrmOrdemServico.FormCreate(Sender: TObject);
begin
Application.OnHint := DisplayHint;
end;
procedure TfrmOrdemServico.dbxDefeitoKeyPress(Sender: TObject;
var Key: Char);
begin
Key:= Upcase(Key);
end;
procedure TfrmOrdemServico.dbmDiagnotiscoKeyPress(Sender: TObject;
var Key: Char);
begin
Key:= Upcase(Key);
end;
procedure TfrmOrdemServico.dbmDescricaoKeyPress(Sender: TObject;
var Key: Char);
begin
Key := Upcase(Key);
end;
end.
|
unit MD5.FileList;
INTERFACE
uses
System.Classes,
shared.ProgressMessage,
shared.FileUtils;
(*
1 читаем все файлы *.md5
2 читаем строчки из каждого файла *.md5
3 генерируем список всех файлов
4 сортируем список по пути
5 ищем дубликаты. Если контрольные суммы совпадают (один и тот же файл), то пропускаем такие дубликаты
если контрольные суммы не совпадают, информируем
например,
19870429817424 *readme.rus.txt
11902890128904 *readme.rus.txt
файл один и тот же, а контрольные суммы разные. Что делать в этом случае?
варианты:
1. показать различия и пропустить
2. вычислить контрольную сумму подозрительного файла, и сравнить с контрольными суммами. Если одна из них
всё таки совпадает, проинформировать. А иначе - неверная контрольная сумма.
6 читаем все файлы из папки
7 сравниваем список файлов из папки и список файлов из п3. Показываем отсутствующие файлы и новые файлы
(новые файлы нужны для вычисления контрольных сумм только этих файлов)
*)
type
TFileListObject = class
FileName: String; // Путь и имя файла
Char: TFileCharacteristics; // Характеристики файла (размер, атрибуты)
Sums: String; // Контрольная сумма
end;
//
TFileList = class
private
MD5FileList: TStringList; // список файлов с контрольными суммами
//
public
constructor Create;
destructor Destroy; override;
//
end;
IMPLEMENTATION
{ TFileList }
constructor TFileList.Create;
begin
inherited;
SetLength(FList, 0);
end;
destructor TFileList.Destroy;
begin
SetLength(FList, 0);
inherited;
end;
end.
|
unit UToolsM;
interface
uses
FFMPEG,
FMX.Graphics,
System.types,
UFormatsM,
math;
type
TVideoProps = record
Width, Height, TrueHeight: integer;
FrameRate: integer;
nrVideostreams, nrAudiostreams: integer;
VideoCodec, AudioCodec: TAVCodecID;
Duration: int64;
end;
TEnvelopeFunction = function(t: double): double;
TZoomSpeedEnvelope = (zeSlowSlow, zeFastSlow, zeSlowFast, zeLinear,
zeExperiment);
/// <summary> (lScale,tScale): LeftTop as fractions of (Width,Height). sScale: Size as Fraction of Width/Height </summary>
TZoom = record
lScale, tScale, sScale: double;
function ToRect(Width, Height: integer): TRectF; inline;
end;
function RectToZoom(r: TRectF; Width, Height: integer): TZoom; inline;
function MakeZoom(l, t, s: double): TZoom; inline;
procedure open_decoder_context(stream_idx: PInteger; dec_ctx: PPAVCodecContext;
fmt_ctx: PAVFormatContext; type_: TAVMediaType);
/// <summary> Get video properties. TrueHeight is the height when not square pixels sizes are made square (sar) </summary>
function GetVideoProps(const Videofile: string): TVideoProps;
/// <summary> Store frame number FrameNumber of Videofile in the bitmap bm </summary>
/// fails under Windows for Videofiles encoded with DVvideo
procedure GrabFrame(const bm: TBitmap; const Videofile: string;
FrameNumber: integer);
// TRectF utility functions
/// <summary> Compute an in between rect of SourceR and TargetR </summary>
/// <param name="SourceR"> TRectF </param>
/// <param name="TargetR"> TRectF </param>
/// <param name="t"> Double between 0 and 1. Weight Source is t, weight Target is 1-t </param>
function Interpolate(SourceR, TargetR: TRectF; t: double): TRectF; inline;
/// <summary> Scale a TRectF by a factor </summary>
/// <param name="SourceR"> TRectF </param>
/// <param name="fact"> Scaling factor (e.g. 2 doubles the size) </param>
function ScaleRect(SourceR: TRectF; fact: double): TRectF; inline;
/// <summary> Center aRect in BigR </summary>
/// <param name="aRect"> (TRectF) Input rect to modify </param>
/// <param name="BigR"> (TRectF) Rect to center aRect in </param>
procedure CenterRect(var aRect: TRectF; BigR: TRectF);
inline
// Zoom-Pan speed modifiers
function SlowSlow(t: double): double;
inline;
function SlowFast(t: double): double; inline;
function FastSlow(t: double): double; inline;
function Linear(t: double): double; inline;
function Experiment(t: double): double; inline;
const
EnvelopeFunction: array [TZoomSpeedEnvelope] of TEnvelopeFunction = (SlowSlow,
FastSlow, SlowFast, Linear, Experiment);
Procedure ExpandSizeToAspect(Width, Height: integer; AR: TAVRational;
var NewWidth, NewHeight: integer);
implementation
uses
System.SysUtils;
function Experiment(t: double): double; inline;
begin
result := 0.5 * sin(2 * Pi * t) + t;
end;
function SlowSlow(t: double): double; inline;
begin
result := 3 * t * t - 2 * t * t * t;
end;
function SlowFast(t: double): double; inline;
begin
result := t * t;
end;
function FastSlow(t: double): double; inline;
begin
result := 2 * t - t * t;
end;
function Linear(t: double): double; inline;
begin
result := t;
end;
function TZoom.ToRect(Width, Height: integer): TRectF;
begin
Assert((tScale + sScale <= 1) and (lScale + sScale <= 1),
'Zoom would be outside of picture bounds');
result.Left := lScale * Width;
result.Top := tScale * Height;
result.Right := result.Left + sScale * Width;
result.Bottom := result.Top + sScale * Height;
end;
function RectToZoom(r: TRectF; Width, Height: integer): TZoom; inline;
begin
// the result only makes sense if r has the same aspect ratio as Width x Height
Assert((r.Right - r.Left > 0) and (Width > 0) and (Height > 0));
result.sScale := (r.Right - r.Left) / Width;
result.lScale := r.Left / Width;
result.tScale := r.Top / Height;
end;
function MakeZoom(l, t, s: double): TZoom; inline;
begin
result.lScale := l;
result.tScale := t;
result.sScale := s;
end;
function Interpolate(SourceR, TargetR: TRectF; t: double): TRectF;
begin
result.Left := SourceR.Left + t * (TargetR.Left - SourceR.Left);
result.Top := SourceR.Top + t * (TargetR.Top - SourceR.Top);
result.Right := SourceR.Right + t * (TargetR.Right - SourceR.Right);
result.Bottom := SourceR.Bottom + t * (TargetR.Bottom - SourceR.Bottom);
end;
function ScaleRect(SourceR: TRectF; fact: double): TRectF;
begin
result.Left := fact * SourceR.Left;
result.Top := fact * SourceR.Top;
result.Right := fact * SourceR.Right;
result.Bottom := fact * SourceR.Bottom;
end;
procedure CenterRect(var aRect: TRectF; BigR: TRectF);
begin
offsetRect(aRect, BigR.Left - aRect.Left, BigR.Top - aRect.Top);
offsetRect(aRect, 0.5 * (BigR.Right - BigR.Left - aRect.Right + aRect.Left),
0.5 * (BigR.Bottom - BigR.Top - aRect.Bottom + aRect.Top));
end;
function GetVideoProps(const Videofile: string): TVideoProps;
var
ret: integer;
fmt_ctx: PAVFormatContext;
p: PPAVStream;
vsn, { asn, } sn: Cardinal; // No. of first video/audio stream
sar: TAVRational;
begin
fmt_ctx := nil;
(* open input file, and allocate format context *)
ret := avformat_open_input(@fmt_ctx, MarshaledAString(UTF8String(Videofile)),
nil, nil);
try
Assert(ret >= 0);
ret := avformat_find_stream_info(fmt_ctx, nil);
Assert(ret >= 0);
p := fmt_ctx.streams;
sn := 0;
result.nrVideostreams := 0;
result.nrAudiostreams := 0;
vsn := 0;
// asn := 0; //future version: info about 1st audio stream
while (sn < fmt_ctx.nb_streams) do
begin
if p^.codec.codec_type = AVMEDIA_TYPE_VIDEO then
begin
inc(result.nrVideostreams);
if result.nrVideostreams = 1 then
begin
vsn := sn;
result.VideoCodec := p^.codec.codec_id;
end;
end;
if p^.codec.codec_type = AVMEDIA_TYPE_AUDIO then
begin
inc(result.nrAudiostreams);
if result.nrAudiostreams = 1 then
begin
// asn := sn;
result.AudioCodec := p^.codec.codec_id;
end;
end;
inc(p);
inc(sn);
end;
Assert(result.nrVideostreams > 0, 'No video stream found in ' + Videofile);
p := fmt_ctx.streams;
sn := 0;
while sn < vsn do
begin
inc(p);
inc(sn);
end; // p^ now is the 1st video stream
sar := p^.codecpar.sample_aspect_ratio;
result.Width := p^.codecpar.Width;
result.Height := p^.codecpar.Height;
if (sar.num > 0) and (sar.den > 0) then
result.TrueHeight := round(p^.codecpar.Height * sar.den / sar.num)
else
result.TrueHeight := p^.codecpar.Height;
if p^.avg_frame_rate.den > 0 then // this should always be true ...
result.FrameRate := round(p^.avg_frame_rate.num / p^.avg_frame_rate.den)
else
result.FrameRate := p^.r_frame_rate.num; // ?
if p^.Duration <> AV_NOPTS_VALUE then
result.Duration :=
round(1000 * (p^.time_base.num / p^.time_base.den * p^.Duration))
else
result.Duration := round(1000 * (fmt_ctx.Duration / AV_TIME_BASE));
finally
avformat_close_input(@fmt_ctx);
end;
end;
// dec_ctx is allocated and must be freed. stream_idx^ contains the stream index for the type_
procedure open_decoder_context(stream_idx: PInteger; dec_ctx: PPAVCodecContext;
fmt_ctx: PAVFormatContext; type_: TAVMediaType);
var
ret, stream_index: integer;
st: PAVStream;
avdec: PAVCodec;
opts: PAVDictionary;
p: PPAVStream;
begin
opts := nil;
ret := av_find_best_stream(fmt_ctx, type_, -1, -1, nil, 0);
Assert(ret >= 0);
stream_index := ret;
p := fmt_ctx.streams;
inc(p, stream_index);
st := PAVStream(p^);
(* find decoder for the stream *)
avdec := avcodec_find_decoder(st.codecpar.codec_id);
Assert(avdec <> nil);
(* Allocate a codec context for the decoder *)
dec_ctx^ := avcodec_alloc_context3(avdec);
Assert(dec_ctx^ <> nil);
(* Copy codec parameters from input stream to output codec context *)
ret := avcodec_parameters_to_context(dec_ctx^, st.codecpar);
Assert(ret >= 0);
(* Init the decoders, without reference counting *)
av_dict_set(@opts, 'refcounted_frames', '0', 0);
ret := avcodec_open2(dec_ctx^, avdec, @opts);
Assert(ret >= 0);
stream_idx^ := stream_index;
end;
procedure GrabFrame(const bm: TBitmap; const Videofile: string;
FrameNumber: integer);
var
fmt_ctx: PAVFormatContext;
video_dec_ctx: PAVCodecContext;
Width, Height: integer;
pix_fmt, pix_fmt_target: TAVPixelFormat;
video_stream_idx: integer;
frame: PAVFrame;
pkt: TAVPacket;
video_frame_count: integer;
ret: integer;
got_frame: integer;
video_dst_data: array [0 .. 3] of PByte;
video_dst_linesize: array [0 .. 3] of integer;
convertCtx: PSwsContext;
X: integer;
row: PByte;
bps: integer;
sar: TAVRational;
nh: integer;
BitData: TBitmapData;
begin
fmt_ctx := nil;
video_dec_ctx := nil;
frame := nil;
for X := 0 to 3 do
video_dst_data[X] := nil;
(* open input file, and allocate format context *)
ret := avformat_open_input(@fmt_ctx, MarshaledAString(UTF8String(Videofile)),
nil, nil);
Assert(ret >= 0);
(* retrieve stream information *)
ret := avformat_find_stream_info(fmt_ctx, nil);
Assert(ret >= 0);
open_decoder_context(@video_stream_idx, @video_dec_ctx, fmt_ctx,
AVMEDIA_TYPE_VIDEO);
(* allocate image where the decoded image will be put *)
Width := video_dec_ctx.Width;
Height := video_dec_ctx.Height;
pix_fmt := video_dec_ctx.pix_fmt;
// get the pixel aspect ratio, so we rescale the bitmap to the right size
sar := video_dec_ctx.sample_aspect_ratio;
if (sar.num > 0) and (sar.den > 0) then
nh := round(Height * sar.den / sar.num)
else
nh := Height;
ret := av_image_alloc(@video_dst_data[0], @video_dst_linesize[0], Width,
Height, pix_fmt, 1);
Assert(ret >= 0);
// Conversion Context to BGRA
{$IFDEF ANDROID}
pix_fmt_target := AV_PIX_FMT_RGBA;
{$ELSE}
pix_fmt_target := AV_PIX_FMT_BGRA;
{$ENDIF}
convertCtx := sws_getContext(Width, Height, pix_fmt, Width, nh,
pix_fmt_target, SWS_Lanczos, nil, nil, nil);
frame := av_frame_alloc();
Assert(frame <> nil);
try
(* initialize packet, set data to NULL, let the demuxer fill it *)
av_init_packet(@pkt);
pkt.data := nil;
pkt.size := 0;
video_frame_count := 0;
(* read frame FrameNumber-1 frames from the file *)
while (video_frame_count < FrameNumber - 1) do
begin
ret := av_read_frame(fmt_ctx, @pkt);
Assert(ret >= 0);
if pkt.stream_index <> video_stream_idx then
begin
av_packet_unref(@pkt);
Continue;
end;
// without decoding each frame, the grabbing doesn't work
// except for some formats
got_frame := 0;
ret := avcodec_decode_video2(video_dec_ctx, frame, @got_frame, @pkt);
if got_frame <> 0 then
inc(video_frame_count);
Assert(ret >= 0);
av_packet_unref(@pkt);
end;
while (video_frame_count = FrameNumber - 1) do
begin
ret := av_read_frame(fmt_ctx, @pkt);
Assert(ret >= 0);
if pkt.stream_index <> video_stream_idx then
begin
av_packet_unref(@pkt);
Continue;
end;
(* decode video frame *)
// !avcodec_decode_video2 is deprecated, but I couldn't get
// the replacement avcode_send_packet and avcodec_receive_frame to work
got_frame := 0;
ret := avcodec_decode_video2(video_dec_ctx, frame, @got_frame, @pkt);
Assert(ret >= 0);
if got_frame <> 0 then
begin
// Convert the frame to 32bit-Bitmap
bm.SetSize(Width, nh);
Assert(bm.Map(TMapAccess.ReadWrite, BitData));
row := BitData.data;
// Always use Pitch instead of BytesPerLine!
bps := BitData.Pitch;
ret := sws_scale(convertCtx, @frame.data, @frame.linesize, 0, Height,
@row, @bps);
Assert(ret >= 0);
bm.Unmap(BitData);
inc(video_frame_count);
end;
end;
finally
av_packet_unref(@pkt);
av_frame_free(@frame);
avcodec_free_context(@video_dec_ctx);
sws_freeContext(convertCtx);
avformat_close_input(@fmt_ctx);
end;
end;
Procedure ExpandSizeToAspect(Width, Height: integer; AR: TAVRational;
var NewWidth, NewHeight: integer);
begin
if Width / Height < AR.num / AR.den then
// Add background right and left
begin
NewHeight := Height;
NewWidth := round(Height / AR.den * AR.num);
end
else
begin
NewWidth := Width;
NewHeight := round(Width * AR.den / AR.num);
end;
end;
end.
|
unit WebAppDbgAbout;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, ExtCtrls;
type
TAboutBox = class(TForm)
OKButton: TButton;
Bevel1: TBevel;
PhysMem: TLabel;
OS: TLabel;
Label3: TLabel;
DetailsPanel: TPanel;
Painter: TPaintBox;
Copyright: TLabel;
Version: TLabel;
SKUName: TLabel;
Logo: TImage;
CompanyName: TLabel;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
procedure InitializeCaptions;
procedure SetOSInfo;
public
{ Public declarations }
end;
procedure ShowAboutBox;
resourcestring
sMemKB = '#,###,###" KB"';
implementation
uses SvrConst, ShellAPI;
const
BltSize = 12;
{$R *.dfm}
procedure ShowAboutBox;
var
AboutBox: TAboutBox;
begin
AboutBox := TAboutBox.Create(Application);
try
AboutBox.ShowModal;
finally
AboutBox.Free;
end;
end;
procedure TAboutBox.SetOSInfo;
var
Platform: string;
BuildNumber: Integer;
Version: string;
begin
Version := '%d.%d ';
case Win32Platform of
VER_PLATFORM_WIN32_WINDOWS:
begin
Platform := 'Windows 95'; // do not localize
BuildNumber := Win32BuildNumber and $0000FFFF;
if Win32MinorVersion = 10 then
Platform := 'Windows 98'; // do not localize
end;
VER_PLATFORM_WIN32_NT:
begin
if Win32MajorVersion >= 5 then
begin
Platform := 'Windows 2000'; // do not localize
Version := '';
end else Platform := 'Windows NT'; // do not localize
BuildNumber := Win32BuildNumber;
end;
else
begin
Platform := 'Windows'; // do not localize
BuildNumber := 0; // set to avoid compiler warning
end;
end;
if (Win32Platform = VER_PLATFORM_WIN32_WINDOWS) or
(Win32Platform = VER_PLATFORM_WIN32_NT) then
begin
if (Win32MajorVersion = 4) and (Win32MinorVersion = 10) then
OS.Caption := Format('%s (%s %d.%d.%d %s)', [Platform, sBuild,
Win32MajorVersion, Win32MinorVersion, BuildNumber, Win32CSDVersion])
else if Win32CSDVersion = '' then
OS.Caption := Format('%s %s(%s %d)', [Platform, Format(Version,
[Win32MajorVersion, Win32MinorVersion]), sBuild, BuildNumber])
else
OS.Caption := Format('%s %s(%s %d: %s)', [Platform, Format(Version,
[Win32MajorVersion, Win32MinorVersion]), sBuild, BuildNumber, Win32CSDVersion]);
end
else
OS.Caption := Format('%s %d.%d', [Platform, Win32MajorVersion,
Win32MinorVersion])
end;
procedure TAboutBox.InitializeCaptions;
var
MS: TMemoryStatus;
begin
SetOSInfo;
MS.dwLength := SizeOf(TMemoryStatus);
GlobalMemoryStatus(MS);
PhysMem.Caption := FormatFloat(sMemKB, MS.dwTotalPhys / 1024);
end;
procedure TAboutBox.FormCreate(Sender: TObject);
begin
InitializeCaptions;
end;
end.
|
unit UnDadosCR;
interface
Uses Classes;
Type
TRBDTransferenciaExternaCheques = class
public
SeqCheque,
NumCheque : Integer;
IndMarcado : Boolean;
NomEmitente : String;
ValCheque : Double;
DatVencimento : TDateTime;
constructor cria;
destructor destroy;override;
end;
Type
TRBDTransferenciaExternaFormaPagamento = class
public
SeqItem,
CodFormaPagamento : Integer;
NomFormaPagamento : String;
ValInicial,
ValFinal : Double;
IndMarcado,
IndPossuiCheques : Boolean;
Cheques : TList;
constructor cria;
destructor destroy;override;
function addCheque : TRBDTransferenciaExternaCheques;
end;
Type
TRBDTransferenciaExterna = class
public
SeqTransferencia,
SeqCaixa : Integer;
FormasPagamento : TList;
constructor cria;
destructor destroy;override;
function AddFormaPagamento : TRBDTransferenciaExternaFormaPagamento;
end;
type
TRBDParcelaCP = class
public
CodFilial,
LanPagar,
NumParcela,
NumParcelaParcial,
CodCliente,
CodFormaPagamento,
NumNotaFiscal,
NumDiasAtraso,
QtdParcelas : Integer;
NumContaCorrente,
NomCliente,
NomFormaPagamento,
NumDuplicata,
DesObservacoes,
CodBarras : String;
DatEmissao,
DatVencimento,
DatPagamento : TDateTime;
ValParcela,
ValPago,
ValAcrescimo,
ValDesconto,
PerMora,
PerJuros,
PerMulta: Double;
IndValorQuitaEssaParcela,
IndGeraParcial,
IndContaOculta : Boolean;
constructor Cria;
destructor Destroy; override;
end;
Type
TRBDCondicaoPagamentoGrupoUsuario = class
public
CodCondicao : Integer;
NomCondicao : String;
constructor cria;
destructor destroy;override;
end;
Type
TRBTipoParcela = (tpProximoMes,tpQtdDias,tpDiaFixo,tpDataFixa);
TRBDParcelaCondicaoPagamento = class
public
NumParcela,
QtdDias,
DiaFixo,
CodFormaPagamento : Integer;
PerParcela,
PerAcrescimoDesconto : Double;
TipAcrescimoDesconto: String;
DatFixa : TDatetime;
TipoParcela : TRBTipoParcela;
constructor cria;
destructor destroy;override;
end;
Type
TRBDCondicaoPagamento = class
public
CodCondicaoPagamento,
QtdParcelas : Integer;
NomCondicaoPagamento : String;
Parcelas : TList;
constructor cria;
destructor destroy;override;
function AddParcela : TRBDParcelaCondicaoPagamento;
end;
Type
TRBDDERVendedor = class
public
CodVendedor : Integer;
NomVendedor : String;
ValMeta,
ValRealizado : Double;
constructor cria;
destructor destroy;override;
end;
Type
TRBDDERCorpo = class
public
Mes,
Ano : Integer;
IndMensal : Boolean;
Vendedores : TList;
constructor Cria;
destructor destroy;override;
function addVendedor : TRBDDERVendedor;
end;
Type
TRBDTipoFormaPagamento = (fpDinheiro,fpCheque,fpCartaoCredito,fpCobrancaBancaria,fpChequeTerceiros,fpCarteira,fpCartaoDebito,fpDepositoCheque);
TRBDCheque = class
public
SeqCheque,
CodBanco,
CodFormaPagamento,
CodCliente,
NumCheque,
CodUsuario,
NumConta,
NumAgencia : Integer;
NumContaCaixa,
NomContaCaixa,
NomEmitente,
NomNomimal,
NomFormaPagamento,
TipCheque,
TipContaCaixa,
NomCliente,
IdeOrigem : String;
ValCheque : Double;
DatCadastro,
DatVencimento,
DatCompensacao,
DatDevolucao,
DatEmissao : TDatetime;
TipFormaPagamento : TRBDTipoFormaPagamento;
constructor cria;
destructor destroy;override;
end;
type
TRBDParcelaBaixaCR = class
public
CodFilial,
LanReceber,
NumParcela,
NumParcelaParcial,
CodCliente,
CodFormaPagamento,
NumNotaFiscal,
NumDiasAtraso,
NumDiasCarencia,
QtdParcelas : Integer;
NumContaCorrente,
NomCliente,
NomFormaPagamento,
NumDuplicata,
DesObservacoes: String;
DatEmissao,
DatVencimento,
DatPagamento,
DatPromessaPagamento : TDateTime;
ValParcela,
ValPago,
ValAcrescimo,
ValDesconto,
ValDescontoAteVencimento,
ValTarifaDesconto,
PerDescontoFormaPagamento,
PerMora,
PerJuros,
PerMulta: Double;
IndValorQuitaEssaParcela,
IndGeraParcial,
IndContaOculta,
IndDescontado : Boolean;
constructor Cria;
destructor Destroy; override;
end;
Type
TRBDFluxoCaixaDia = Class
public
Dia : Integer;
ValCRPrevisto,
ValCRDuvidoso,
ValCobrancaPrevista,
ValDescontoDuplicata,
ValChequesCR,
ValCP,
ValChequesCP,
ValTotalReceita,
ValTotalReceitaAcumulada,
ValTotalDespesa,
ValTotalDespesaAcumulada,
Valtotal,
ValTotalAcumulado :Double;
ParcelasCR,
ParcelasCP,
ParcelasDuvidosas,
ChequesCR,
ChequesCP : TList;
constructor cria;
destructor destroy;override;
function addParcelaCR : TRBDParcelaBaixaCR;
function AddParcelaCP : TRBDParcelaCP;
function addParcelaDuvidosa : TRBDParcelaBaixaCR;
function AddChequeCR(VpaDatVencimento : TDateTime) : TRBDCheque;
function AddChequeCP(VpaDatVencimento : TDateTime) : TRBDCheque;
end;
Type
TRBDFluxoCaixaMes = Class
public
Mes,
Ano : Integer;
ValCRPrevisto,
ValCRDuvidoso,
ValCobrancaPrevista,
ValDescontoDuplicata,
ValChequesCR,
ValCP,
ValChequesCP,
ValTotalReceita,
ValTotalReceitaAcumulada,
ValTotalDespesa,
ValTotalDespesaAcumulada,
Valtotal,
ValTotalAcumulado :Double;
Dias : TList;
constructor cria;
destructor destroy;override;
function addDia(VpaDia : Integer) : TRBDFluxoCaixaDia;
function RDia(VpaDia : Integer):TRBDFluxoCaixaDia;
end;
Type
TRBDTipoLinhaFluxo = (lfCRPrevisto,lfCRDuvidoso,lfCRCheques,lfCRTotalDia,lfCRTotalAcumulado,lfCPPrevisto,lfCPCheques,lfCPTotalDia,lfCPTotalAcumaldo,lfTotalConta,lfTotalContaAcumulada);
TRBDFluxoCaixaConta = Class
public
NumContaCaixa,
NomContaCaixa : String;
LinContasReceberPrevisto,
LinContasReceberDuvidoso,
LinChequesaCompensarCR,
LinReceitasAcumuladas,
LinContasAPagar,
LinChequesaCompensarCP,
LinDespesasAcumuladas,
LinTotalConta,
LinTotalAcumulado : Integer;
ValSaldoAtual,
ValChequeCRSaldoAnterior,
ValChequeCPSaldoAnterior,
ValSaldoAnteriorCR,
ValSaldoAnteriorCP,
ValAplicado,
ValLimiteCredito,
ValTotalReceitas,
ValTotalDespesas,
ValTotalReceitasAcumuladas,
ValTotalDespesasAcumuladas : Double;
ParcelasSaldoAnterior,
ParcelasSaldoAnteriorCP,
ChequeCRSaldoAnterior,
ChequeCPSaldoAnterior,
Meses : TList;
constructor cria;
destructor destroy;override;
function RMes(VpaMes,VpaAno : Integer):TRBDFluxoCaixaMes;
function RDia(VpaDatVencimento : TDatetime;VpaCriarSeNaoEncontrar : Boolean = true):TRBDFluxoCaixaDia;
function addMes(VpaMes,VpaAno : Integer) : TRBDFluxoCaixaMes;
function addParcelaSaldoAnteriorCR : TRBDParcelaBaixaCR;
function addParcelaSaldoAnteriorCP : TRBDParcelaCP;
function addParcelaCR(VpaData : TDateTime) : TRBDParcelaBaixaCR;
function AddParcelaCP(VpaData : TDateTime) : TRBDParcelaCP;
function AddParcelaDuvidosa(VpaData : TDateTime) : TRBDParcelaBaixaCR;
function addChequeCR(VpaDatVencimento : TDateTime) : TRBDCheque;
function AddChequeCRSaldoAnterior : TRBDCheque;
function AddChequeCPSaldoAnterior : TRBDCheque;
function addChequeCP(VpaDatVencimento : TDateTime) : TRBDCheque;
end;
Type
TRBDFluxoCaixaCorpo = Class
public
CodFilial,
Mes,
Ano,
QtdColunas,
LinTotalAcumulado : Integer;
IndDiario : Boolean;
IndSeparaCRDuvidoso,
IndMostrarCobrancaPrevista,
IndSomenteClientesQuePagamEmDia,
IndMostraContasSeparadas,
IndMostrarContasaPagarProrrogado : Boolean;
ValChequeCRSaldoAnterior,
ValChequeCPSaldoAnterior,
ValSaldoAnteriorCR,
ValSaldoAnteriorCP,
ValSaldoAtual,
ValAplicacao,
ValTotalAcumulado : Double;
DatInicio,
DatFim : TDateTime;
ParcelasSaldoAnterior,
ContasCaixa,
Dias : TList;
ContaGeral : TRBDFluxoCaixaConta;
constructor cria;
destructor destroy;override;
function addContaCaixa : TRBDFluxoCaixaConta;
procedure OrdenaDias(VpaDias : TList);
procedure OrdenaDiasContas;
procedure CalculaValoresTotais;
function RDia(VpaDia: Integer) : TRBDFluxoCaixaDia;
end;
Type
TRBDCaixaFormaPagamento = class
public
CodFormaPagamento : Integer;
NomFormaPagamento : String;
ValInicial,
ValAtual,
ValFinal : Double;
constructor cria;
destructor destroy;override;
end;
Type
TRBDCaixaItem = class
public
seqItem,
CodUsuario,
CodFilial,
LanReceber,
LanPagar,
NumParcelaReceber,
NumParcelaPagar,
SeqCheque,
CodFormaPagamento : Integer;
DesLancamento,
DesDebitoCredito : String;
ValLancamento : Double;
DatPagamento,
DatLancamento : TDatetime;
TipFormaPagamento : TRBDTipoFormaPagamento;
constructor cria;
destructor destroy;override;
end;
Type
TRBDTipoConta = (tcCaixa,tcContaCorrente);
TRBDCaixa = class
public
SeqCaixa,
CodUsuarioAbertura,
CodUsuarioFechamento : Integer;
NumConta : String;
ValInicial,
ValInicialCheque,
ValAtual,
ValAtualCheque,
ValFinal : double;
DatAbertura,
DatFechamento : TDateTime;
TipoConta : TRBDTipoConta;
FormasPagamento,
Items : TList;
constructor cria;
destructor destroy;override;
function AddCaixaItem : TRBDCaixaItem;
function AddFormaPagamento : TRBDCaixaFormaPagamento;
end;
Type
TRBDContasaPagarProjeto = class
public
CodProjeto : Integer;
NomProjeto : String;
PerDespesa,
ValDespesa : Double;
constructor cria;
destructor destroy;override;
end;
type
TRBDContasaPagar = Class
public
CodFilial,
LanPagar,
NumNota,
SeqNota,
CodFornecedor,
CodCentroCusto,
CodFormaPagamento,
CodBancoBoleto,
CodMoeda,
CodProjeto,
CodUsuario,
CodCondicaoPagamento,
FatorVencimento : integer;
DatEmissao : TDateTime;
NomFornecedor,
NumContaCaixa,
CodPlanoConta,
DesIdentificacaoBancarioFornecedor,
CodBarras,
DesPathFoto : string;
ValParcela,
ValTotal,
ValBoleto,
ValUtilizadoCredito,
ValSaldoDebitoFornecedor : double;
PerDescontoAcrescimo : double;
IndDespesaPrevista,
IndBaixarConta,
IndMostrarParcelas,
IndEsconderConta : Boolean;
DesTipFormaPagamento : String;
DesObservacao : String;
Parcelas,
DespesaProjeto : TList;
constructor cria;
destructor Destroy;override;
function addParcela : TRBDParcelaCP;
function addDespesaProjeto : TRBDContasaPagarProjeto;
end;
Type
TRBDComissaoItem = class
public
NumParcela : Integer;
ValComissaoParcela,
ValBaseComissao : Double;
DatVencimento,
DatPagamento,
DatLiberacao : TDateTime;
IndLiberacaoAutomatica : Boolean;
constructor cria;
destructor destroy;override;
end;
Type
TRBDComissao = class
public
CodFilial,
SeqComissao,
LanReceber,
CodVendedor,
TipComissao : Integer;
DesObservacao : string;
PerComissao,
ValTotalComissao,
ValTotalProdutos : Double;
DatEmissao : TDateTime;
Parcelas : TList;
constructor cria;
destructor destroy;override;
function AddParcela : TRBDComissaoItem;
end;
Type
TRBDECobrancaItem = class
public
CodFilial,
LanReceber,
NumParcela : Integer;
UsuarioEmail,
DesEmail,
DesEstatus,
NomCliente,
NomFantasiaFilial : String;
DatEnvio : TDatetime;
IndEnviado : Boolean;
constructor cria;
destructor destroy;override;
end;
Type
TRBDECobrancaCorpo = class
public
SeqEmail,
SeqItemEmailDisponivel : Integer;
DatEnvio : TDateTime;
QtdEnvidados,
QtdNaoEnviados,
CodUsuario : Integer;
Items : TList;
constructor cria;
destructor destroy; override;
function AddECobrancaItem : TRBDECobrancaItem;
end;
Type
TRBDFormaPagamento = class
public
CodForma : Integer;
NomForma : String;
FlaTipo : TRBDTipoFormaPagamento;
IndBaixarConta : Boolean;
constructor cria;
destructor destroy;override;
end;
type
TRBDMovContasCR = class
public
NumParcela,
CodFormaPagamento,
CodBanco,
NumDiasAtraso,
DiasCarencia,
DiasCompensacao : integer;
Valor,
ValorBruto,
ValAcrescimo,
ValDesconto,
ValTarifasBancarias,
PerJuros,
PerMora,
PerMulta,
PerDescontoVencimento,
PerDesconto,
ValCheque,
ValAcrescimoFrm,
ValSinal : Double;
DatVencimento,
DatProrrogacao,
DatPagamento: TDateTime;
NroAgencia,
NumContaCaixa,
NroContaBoleto,
NroDuplicata,
NroDocumento,
NossoNumero,
DesObservacoes : String;
IndBaixarConta : Boolean;
constructor cria;
destructor destroy;override;
end;
Type
TRBDContasCR = class
public
CodEmpFil,
LanReceber,
NroNota,
SeqNota,
LanOrcamento,
SeqParcialCotacao,
CodCondicaoPgto,
CodCliente,
CodFrmPagto,
CodMoeda,
CodUsuario : Integer;
DatMov,
DatEmissao,
DatPagamentoSinal : TDateTime;
NomCliente,
PlanoConta,
NumContaCaixa,
NumContaCorrente,
DesObservacao: string;
MostrarParcelas,
EsconderConta,
IndDevolucao,
IndGerarComissao,
IndCobrarFormaPagamento,
IndSinalPagamento,
IndPossuiSinalPagamento : Boolean;
CodVendedor,
CodPreposto : Integer;
ValTotal,
ValTotalAcrescimoFormaPagamento,
PercentualDesAcr,
PerComissao,
PerComissaoPreposto,
ValComissao,
ValBaseComissao,
ValTotalProdutos,
ValComissaoPreposto,
ValUtilizadoCredito,
ValSaldoCreditoCliente,
ValSinal : Double;
TipComissao,
TipValorComissao,
TipComissaoPreposto : Integer; // 0 direta 1 produtos
DPNumDuplicata : Integer;
Parcelas : TList;
constructor cria;
destructor destroy;override;
function AddParcela : TRBDMovContasCR;
end;
type
TDadosNovaContaCR = Class
CodEmpFil,
NroNota,
SeqNota,
CodCondicaoPgto,
CodCliente,
CodFrmPagto,
CodMoeda,
CodUsuario: Integer;
DataMov,
DataEmissao : TDateTime;
PlanoConta: string;
ValorTotal : Double;
PercentualDescAcr : double;
VerificarCaixa,
BaixarConta,
MostrarParcelas,
MostrarTelaCaixa,
GerarComissao,
EsconderConta : Boolean;
TipoFrmPAgto : String;
ValorPro, PercPro : TstringList;
CodVendedor : Integer;
PercComissaoPro,
PercComissaoServ,
ValorComPro,
ValorComServ : Double;
TipoComissao : Integer; // 0 direta 1 produtos
end;
type
TDadosNovaParcelaCR = Class
EmpresaFilial : integer;
LancamentoCR : integer;
ValorTotal : double;
CodigoFrmPagto : Integer;
CodigoConPagamento : integer;
CodMoeda : Integer;
NumeroDup : string;
PercentualDesAcr : Double;
DataEmissao : TDateTime;
ParcelaPerson : Boolean;
DataVenPerson,
ValorVenPrson : TStringList;
SeqTef : Integer;
end;
type
TRBDBaixaCP = class
public
CodFormaPagamento,
CodFornecedor: Integer;
TipFormaPagamento,
NumContaCaixa : String;
ValorAcrescimo,
ValorDesconto,
ValorPago,
ValParcialFaltante,
ValParaGerardeDebito : Double;
DatPagamento,
DatVencimentoParcial : TDateTime;
IndPagamentoParcial,
IndBaixaUtilizandoODebitoFornecedor : Boolean;
Parcelas,
Cheques,
Caixas : TList;
constructor Cria;
destructor Destroy; override;
function AddParcela: TRBDParcelaCP;
function AddCheque : TRBDCheque;
function AddCaixa : TRBDCaixa;
end;
type
TRBDBaixaCR = class
public
CodFormaPagamento,
DiasVencimentoCartao : Integer;
NumContaCaixa: String;
TipFormaPagamento:TRBDTipoFormaPagamento;
ValorAcrescimo,
ValorDesconto,
ValorPago,
ValParcialFaltante,
ValParaGerardeCredito : Double;
DatPagamento,
DatVencimentoParcial : TDateTime;
IndPagamentoParcial,
IndBaixaRetornoBancario,
IndDesconto,
IndBaixaUtilizandoOCreditodoCliente,
IndContaOculta : Boolean;
Parcelas,
Cheques,
Caixas : TList;
constructor Cria;
destructor Destroy; override;
function AddParcela: TRBDParcelaBaixaCR;
function AddCheque : TRBDCheque;
function AddCaixa : TRBDCaixa;
end;
implementation
Uses FunObjeto, FunData;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDFluxoCaixaConta
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDFluxoCaixaMes.cria;
begin
inherited create;
Dias := TList.create;
end;
{******************************************************************************}
destructor TRBDFluxoCaixaMes.destroy;
begin
FreeTObjectsList(Dias);
Dias.Free;
inherited destroy;
end;
{******************************************************************************}
function TRBDFluxoCaixaMes.RDia(VpaDia: Integer): TRBDFluxoCaixaDia;
var
VpfLaco : Integer;
VpfDDia : TRBDFluxoCaixaDia;
begin
result := nil;
for VpfLaco := 0 to Dias.Count - 1 do
begin
VpfDDia := TRBDFluxoCaixaDia(Dias.Items[VpfLaco]);
if (VpaDia = VpfDDia.Dia) then
begin
result := VpfDDia;
break;
end;
end;
end;
{******************************************************************************}
function TRBDFluxoCaixaMes.addDia(VpaDia : Integer) : TRBDFluxoCaixaDia;
begin
Result := TRBDFluxoCaixaDia.cria;
result.Dia := VpaDia;
Dias.add(result);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDFluxoCaixaConta
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDFluxoCaixaConta.cria;
begin
inherited create;
Meses := TList.create;
ParcelasSaldoAnterior := TList.Create;
ParcelasSaldoAnteriorCP := TList.Create;
ChequeCRSaldoAnterior := TList.Create;
ChequeCPSaldoAnterior := TList.Create;
end;
{******************************************************************************}
destructor TRBDFluxoCaixaConta.destroy;
begin
FreeTObjectsList(Meses);
Meses.free;
FreeTObjectsList(ChequeCRSaldoAnterior);
ChequeCRSaldoAnterior.Free;
FreeTObjectsList(ParcelasSaldoAnterior);
ParcelasSaldoAnterior.free;
FreeTObjectsList(ParcelasSaldoAnteriorCP);
ParcelasSaldoAnteriorCP.Free;
FreeTObjectsList(ChequeCPSaldoAnterior);
ChequeCPSaldoAnterior.Free;
inherited destroy;
end;
{******************************************************************************}
function TRBDFluxoCaixaConta.RDia(VpaDatVencimento : TDatetime;VpaCriarSeNaoEncontrar : Boolean = true):TRBDFluxoCaixaDia;
var
VpfLacoDia : Integer;
VpfDFluxoMes : TRBDFluxoCaixaMes;
begin
result := nil;
VpfDFluxoMes := nil;
if DiaSemanaNumerico(VpaDatVencimento) = 1 then
VpaDatVencimento := IncDia(VpaDatVencimento,1)
else
if DiaSemanaNumerico(VpaDatVencimento) = 7 then
VpaDatVencimento := IncDia(VpaDatVencimento,2);
VpfDFluxoMes := RMes(mes(VpaDatVencimento),ano(VpaDatVencimento));
if VpfDFluxoMes <> nil then
begin
for VpfLacoDia := 0 to VpfDFluxoMes.Dias.Count - 1 do
begin
if (dia(VpaDatVencimento) = TRBDFluxoCaixaDia(VpfDFluxoMes.Dias.Items[VpfLacoDia]).Dia) then
result := TRBDFluxoCaixaDia(VpfDFluxoMes.Dias.Items[VpfLacoDia]);
end;
end;
if VpaCriarSeNaoEncontrar then
begin
if result = nil then
begin
if VpfDFluxoMes = nil then
VpfDFluxoMes := addMes(Mes(VpaDatVencimento),Ano(VpaDatVencimento));
result := VpfDFluxoMes.addDia(Dia(VpaDatVencimento));
end;
end;
end;
{******************************************************************************}
function TRBDFluxoCaixaConta.RMes(VpaMes, VpaAno: Integer): TRBDFluxoCaixaMes;
var
VpfLacoMes : Integer;
begin
result := nil;
for VpfLacoMes := 0 to Meses.Count - 1 do
begin
if (VpaMes = TRBDFluxoCaixaMes(Meses.Items[VpfLacoMes]).Mes) and
(VpaAno = TRBDFluxoCaixaMes(Meses.Items[VpfLacoMes]).Ano) then
begin
result := TRBDFluxoCaixaMes(Meses.Items[VpfLacoMes]);
break;
end;
end;
end;
{******************************************************************************}
function TRBDFluxoCaixaConta.addMes(VpaMes,VpaAno : Integer) : TRBDFluxoCaixaMes;
begin
Result := TRBDFluxoCaixaMes.cria;
result.Mes := VpaMes;
Result.Ano := VpaAno;
Meses.add(result);
end;
{******************************************************************************}
function TRBDFluxoCaixaConta.AddParcelaCP(VpaData: TDateTime): TRBDParcelaCP;
begin
result := RDia(VpaData).AddParcelaCP;
end;
{******************************************************************************}
function TRBDFluxoCaixaConta.addParcelaSaldoAnteriorCR : TRBDParcelaBaixaCR;
begin
result := TRBDParcelaBaixaCR.Cria;
ParcelasSaldoAnterior.add(result);
end;
{******************************************************************************}
function TRBDFluxoCaixaConta.addParcelaSaldoAnteriorCP: TRBDParcelaCP;
begin
result := TRBDParcelaCP.Cria;
ParcelasSaldoAnteriorCP.Add(result);
end;
{******************************************************************************}
function TRBDFluxoCaixaConta.addParcelaCR(VpaData : TDateTime) : TRBDParcelaBaixaCR;
begin
result := RDia(VpaData).addParcelaCR;
end;
{******************************************************************************}
function TRBDFluxoCaixaConta.AddParcelaDuvidosa(VpaData: TDateTime): TRBDParcelaBaixaCR;
begin
result := RDia(VpaData).addParcelaDuvidosa;
end;
{******************************************************************************}
function TRBDFluxoCaixaConta.AddChequeCPSaldoAnterior: TRBDCheque;
begin
result := TRBDCheque.cria;
ChequeCPSaldoAnterior.Add(result);
end;
{******************************************************************************}
function TRBDFluxoCaixaConta.addChequeCR(VpaDatVencimento : TDateTime) : TRBDCheque;
begin
result := RDia(VpaDatVencimento).AddChequeCR(VpaDatVencimento);
end;
{******************************************************************************}
function TRBDFluxoCaixaConta.AddChequeCRSaldoAnterior: TRBDCheque;
begin
result := TRBDCheque.cria;
ChequeCRSaldoAnterior.Add(result);
end;
{******************************************************************************}
function TRBDFluxoCaixaConta.addChequeCP(VpaDatVencimento : TDateTime) : TRBDCheque;
begin
result := RDia(VpaDatVencimento).AddChequeCP(VpaDatVencimento);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDFluxoCaixaCorpo
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDFluxoCaixaCorpo.cria;
begin
inherited create;
ContasCaixa := TList.Create;
ParcelasSaldoAnterior := TList.Create;
Dias := TList.Create;
end;
{******************************************************************************}
destructor TRBDFluxoCaixaCorpo.destroy;
begin
FreeTObjectsList(ContasCaixa);
ContasCaixa.free;
ParcelasSaldoAnterior.Free;
FreeTObjectsList(Dias);
Dias.Free;
inherited destroy;
end;
{******************************************************************************}
function TRBDFluxoCaixaCorpo.addContaCaixa : TRBDFluxoCaixaConta;
begin
result := TRBDFluxoCaixaConta.cria;
ContasCaixa.add(result);
end;
{******************************************************************************}
procedure TRBDFluxoCaixaCorpo.OrdenaDias(VpaDias: TList);
var
VpfLacoDiaInterno, VpfLacoDiaExterno : Integer;
VpfDDia : TRBDFluxoCaixaDia;
begin
for VpfLacoDiaExterno := 0 to VpaDias.Count - 2 do
begin
VpfDDia := TRBDFluxoCaixaDia(VpaDias.Items[VpfLacoDiaExterno]);
for VpfLacoDiaInterno := VpfLacoDiaExterno + 1 to VpaDias.Count - 1 do
begin
if TRBDFluxoCaixaDia(VpaDias.Items[VpfLacoDiaInterno]).Dia < VpfDDia.Dia then
begin
VpaDias.Items[VpfLacoDiaExterno] := VpaDias.Items[VpfLacoDiaInterno];
VpaDias.Items[VpfLacoDiaInterno] := VpfDDia;
VpfDDia := TRBDFluxoCaixaDia(VpaDias.Items[VpfLacoDiaExterno]);
end;
end;
end;
end;
{******************************************************************************}
procedure TRBDFluxoCaixaCorpo.OrdenaDiasContas;
var
VpfLacoContas, VpfLacoMes, VpfLacoDiaInterno, VpfLacoDiaExterno : Integer;
VpfDConta : TRBDFluxoCaixaConta;
VpfDMes : TRBDFluxoCaixaMes;
VpfDDia : TRBDFluxoCaixaDia;
begin
for VpfLacoContas := 0 to ContasCaixa.Count - 1 do
begin
VpfDConta := TRBDFluxoCaixaConta(ContasCaixa.Items[VpfLacoContas]);
for VpfLacoMes := 0 to VpfDConta.Meses.Count - 1 do
begin
VpfDMes := TRBDFluxoCaixaMes(VpfDConta.Meses.Items[VpfLacoMes]);
OrdenaDias(VpfDMes.Dias);
end;
end;
end;
{******************************************************************************}
function TRBDFluxoCaixaCorpo.RDia(VpaDia: Integer): TRBDFluxoCaixaDia;
var
VpfLaco : Integer;
begin
result := nil;
for VpfLaco := 0 to Dias.Count - 1 do
begin
if VpaDia = TRBDFluxoCaixaDia(Dias.Items[VpfLaco]).dia then
begin
result :=TRBDFluxoCaixaDia(Dias.Items[VpfLaco]);
break;
end;
end;
if result = nil then
begin
result := TRBDFluxoCaixaDia.cria;
Dias.add(result);
Result.Dia := VpaDia;
end;
end;
{******************************************************************************}
procedure TRBDFluxoCaixaCorpo.CalculaValoresTotais;
var
VpfLacoContas, VpfLacoMes, VpfLacoDia, VpfLacoParcela : Integer;
VpfDConta : TRBDFluxoCaixaConta;
VpfDMes : TRBDFluxoCaixaMes;
VpfDDia, VpfDDiaFluxo : TRBDFluxoCaixaDia;
VpfDParcela : TRBDParcelaBaixaCR;
VpfDParcelaCP : TRBDParcelaCP;
VpfDCheque : TRBDCheque;
begin
OrdenaDiasContas;
FreeTObjectsList(Dias); //apaga os dias para zeras or valores gerais do fluxo.
ValTotalAcumulado := 0;
ValSaldoAnteriorCR := 0;
ValSaldoAnteriorCP := 0;
ValChequeCRSaldoAnterior := 0;
ValChequeCPSaldoAnterior := 0;
for VpfLacoContas := 0 to ContasCaixa.Count - 1 do
begin
VpfDConta := TRBDFluxoCaixaConta(ContasCaixa.Items[VpfLacoContas]);
VpfDConta.ValTotalReceitas := 0;
// VpfDConta.ValTotalReceitasAcumuladas := VpfDConta.ValAplicado +VpfDConta.ValSaldoAnteriorCR + VpfDConta.ValChequeCRSaldoAnterior+ VpfDConta.ValSaldoAtual ;
VpfDConta.ValTotalReceitasAcumuladas := VpfDConta.ValSaldoAnteriorCR + VpfDConta.ValChequeCRSaldoAnterior;
VpfDConta.ValTotalDespesasAcumuladas := VpfDConta.ValSaldoAnteriorCP + VpfDConta.ValChequeCPSaldoAnterior;
for VpfLacoMes := 0 to VpfDConta.Meses.Count - 1 do
begin
VpfDMes := TRBDFluxoCaixaMes(VpfDConta.Meses.Items[VpfLacoMes]);
VpfDMes.ValCRPrevisto := 0;
VpfDMes.ValCRDuvidoso := 0;
VpfDMes.ValCobrancaPrevista := 0;
VpfDMes.ValDescontoDuplicata := 0;
VpfDMes.ValCP := 0;
VpfDMes.ValTotalReceita := 0;
VpfDMes.ValTotalAcumulado := VpfDConta.ValAplicado +VpfDConta.ValSaldoAnteriorCR + VpfDConta.ValSaldoAtual+ VpfDConta.ValChequeCRSaldoAnterior-VpfDConta.ValSaldoAnteriorCP -VpfDConta.ValChequeCPSaldoAnterior ;
VpfDMes.ValTotalDespesaAcumulada := VpfDConta.ValSaldoAnteriorCP + VpfDConta.ValChequeCPSaldoAnterior;
VpfDMes.ValTotalReceitaAcumulada := VpfDConta.ValSaldoAnteriorCR + VpfDConta.ValChequeCRSaldoAnterior;
for VpfLacoDia := 0 to VpfDMes.Dias.Count - 1 do
begin
VpfDDia := TRBDFluxoCaixaDia(VpfDMes.Dias.Items[VpfLacoDia]);
VpfDDia.ValCRPrevisto := 0;
VpfDDia.ValCRDuvidoso := 0;
VpfDDia.ValCP := 0;
VpfDDia.ValChequesCP :=0;
VpfDDia.ValCobrancaPrevista := 0;
VpfDDia.ValDescontoDuplicata := 0;
VpfDDia.Valtotal := 0;
VpfDDia.ValTotalReceitaAcumulada := VpfDMes.ValTotalReceitaAcumulada;
VpfDDia.ValTotalDespesaAcumulada := VpfDMes.ValTotalDespesaAcumulada;
VpfDDia.ValTotalAcumulado := VpfDMes.ValTotalAcumulado;
VpfDDia.ValTotalReceita := 0;
VpfDDia.ValTotalDespesa := 0;
VpfDDiaFluxo := RDia(VpfDDia.Dia);
//contas a receber
for VpfLacoParcela := 0 to VpfDDia.ParcelasCR.Count - 1 do
begin
VpfDParcela := TRBDParcelaBaixaCR(VpfDDia.ParcelasCR.Items[VpfLacoParcela]);
VpfDDia.ValCRPrevisto := VpfDDia.ValCRPrevisto + VpfDParcela.ValParcela;
VpfDDiaFluxo.ValCRPrevisto := VpfDDiaFluxo.ValCRPrevisto + VpfDParcela.ValParcela;
VpfDMes.ValCRPrevisto := VpfDMes.ValCRPrevisto + VpfDParcela.ValParcela;
if VpfDParcela.IndDescontado then
begin
VpfDDia.ValDescontoDuplicata := VpfDDia.ValDescontoDuplicata + VpfDParcela.ValParcela;
VpfDDiaFluxo.ValDescontoDuplicata := VpfDDiaFluxo.ValDescontoDuplicata + VpfDParcela.ValParcela;
VpfDMes.ValDescontoDuplicata := VpfDMes.ValDescontoDuplicata + VpfDParcela.ValParcela;
end
else
begin
VpfDDia.ValTotalReceita := VpfDDia.ValTotalReceita + VpfDParcela.ValParcela;
VpfDDiaFluxo.ValTotalReceita := VpfDDiaFluxo.ValTotalReceita + VpfDParcela.ValParcela;
VpfDMes.ValTotalReceita := VpfDMes.ValTotalReceita + VpfDParcela.ValParcela;
VpfDConta.ValTotalReceitas := VpfDConta.ValTotalReceitas + VpfDParcela.ValParcela;
end;
VpfDMes.ValTotalReceitaAcumulada := VpfDMes.ValTotalReceitaAcumulada +VpfDParcela.ValParcela ;
VpfDDia.ValTotalReceitaAcumulada := VpfDDia.ValTotalReceitaAcumulada + VpfDParcela.ValParcela;
VpfDConta.ValTotalReceitasAcumuladas := VpfDConta.ValTotalReceitasAcumuladas + VpfDParcela.ValParcela;
VpfDMes.ValTotalAcumulado := VpfDMes.ValTotalAcumulado + VpfDParcela.ValParcela;
end;
for VpfLacoParcela := 0 to VpfDDia.ParcelasDuvidosas.Count - 1 do
begin
VpfDParcela := TRBDParcelaBaixaCR(VpfDDia.ParcelasDuvidosas.Items[VpfLacoParcela]);
VpfDDia.ValCRDuvidoso := VpfDDia.ValCRDuvidoso + VpfDParcela.ValParcela;
VpfDDiaFluxo.ValCRDuvidoso := VpfDDiaFluxo.ValCRDuvidoso + VpfDParcela.ValParcela;
VpfDMes.ValCRDuvidoso := VpfDMes.ValCRDuvidoso + VpfDParcela.ValParcela;
if VpfDParcela.IndDescontado then
begin
VpfDDia.ValDescontoDuplicata := VpfDDia.ValDescontoDuplicata + VpfDParcela.ValParcela;
VpfDDiaFluxo.ValDescontoDuplicata := VpfDDiaFluxo.ValDescontoDuplicata + VpfDParcela.ValParcela;
VpfDMes.ValDescontoDuplicata := VpfDMes.ValDescontoDuplicata + VpfDParcela.ValParcela;
end
else
begin
VpfDDia.ValTotalReceita := VpfDDia.ValTotalReceita + VpfDParcela.ValParcela;
VpfDDiaFluxo.ValTotalReceita := VpfDDiaFluxo.ValTotalReceita + VpfDParcela.ValParcela;
VpfDMes.ValTotalReceita := VpfDMes.ValTotalReceita + VpfDParcela.ValParcela;
VpfDConta.ValTotalReceitas := VpfDConta.ValTotalReceitas + VpfDParcela.ValParcela;
end;
VpfDMes.ValTotalReceitaAcumulada := VpfDMes.ValTotalReceitaAcumulada +VpfDParcela.ValParcela ;
VpfDDia.ValTotalReceitaAcumulada := VpfDDia.ValTotalReceitaAcumulada + VpfDParcela.ValParcela;
VpfDDiaFluxo.ValTotalReceitaAcumulada := VpfDDiaFluxo.ValTotalReceitaAcumulada + VpfDParcela.ValParcela;
VpfDConta.ValTotalReceitasAcumuladas := VpfDConta.ValTotalReceitasAcumuladas + VpfDParcela.ValParcela;
VpfDMes.ValTotalAcumulado := VpfDMes.ValTotalAcumulado + VpfDParcela.ValParcela;
end;
for VpfLacoParcela := 0 to VpfDDia.ChequesCR.Count - 1 do
begin
VpfDCheque := TRBDCheque(VpfDDia.ChequesCR.Items[VpfLacoParcela]);
VpfDDia.ValChequesCR := VpfDDia.ValChequesCR + VpfDCheque.ValCheque;
VpfDDiaFluxo.ValChequesCR := VpfDDiaFluxo.ValChequesCR + VpfDCheque.ValCheque;
VpfDMes.ValChequesCR := VpfDMes.ValChequesCR + VpfDCheque.ValCheque;
VpfDDia.ValTotalReceita := VpfDDia.ValTotalReceita + VpfDCheque.ValCheque;
VpfDDiaFluxo.ValTotalReceita := VpfDDiaFluxo.ValTotalReceita + VpfDCheque.ValCheque;
VpfDMes.ValTotalReceita := VpfDMes.ValTotalReceita + VpfDCheque.ValCheque;
VpfDConta.ValTotalReceitas := VpfDConta.ValTotalReceitas + VpfDCheque.ValCheque;
VpfDMes.ValTotalReceitaAcumulada := VpfDMes.ValTotalReceitaAcumulada +VpfDCheque.ValCheque ;
VpfDDia.ValTotalReceitaAcumulada := VpfDDia.ValTotalReceitaAcumulada + VpfDCheque.ValCheque ;
VpfDConta.ValTotalReceitasAcumuladas := VpfDConta.ValTotalReceitasAcumuladas + VpfDCheque.ValCheque;
VpfDMes.ValTotalAcumulado := VpfDMes.ValTotalAcumulado + VpfDCheque.ValCheque;
end;
//contas a pagar
for VpfLacoParcela := 0 to VpfDDia.ParcelasCP.Count - 1 do
begin
VpfDParcelaCP := TRBDParcelaCP(VpfDDia.ParcelasCP.Items[VpfLacoParcela]);
VpfDDia.ValCP := VpfDDia.ValCP + VpfDParcelaCP.ValParcela;
VpfDDia.ValTotalDespesa := VpfDDia.ValTotalDespesa + VpfDParcelaCP.ValParcela;
VpfDDiaFluxo.ValCP := VpfDDiaFluxo.ValCP + VpfDParcelaCP.ValParcela;
VpfDDiaFluxo.ValTotalDespesa := VpfDDiaFluxo.ValTotalDespesa + VpfDParcelaCP.ValParcela;
VpfDMes.ValCP := VpfDMes.ValCP + VpfDParcelaCP.ValParcela;
VpfDMes.ValTotalDespesa := VpfDMes.ValTotalDespesa + VpfDParcelaCP.ValParcela;
VpfDConta.ValTotalDespesas := VpfDConta.ValTotalDespesas + VpfDParcelaCP.ValParcela;
VpfDMes.ValTotalDespesaAcumulada := VpfDMes.ValTotalDespesaAcumulada +VpfDParcelaCP.ValParcela ;
VpfDDia.ValTotalDespesaAcumulada := VpfDDia.ValTotalDespesaAcumulada + VpfDParcelaCP.ValParcela;
VpfDConta.ValTotalDespesasAcumuladas := VpfDConta.ValTotalDespesasAcumuladas + VpfDParcelaCP.ValParcela;
VpfDMes.ValTotalAcumulado := VpfDMes.ValTotalAcumulado - VpfDParcelaCP.ValParcela;
end;
for VpfLacoParcela := 0 to VpfDDia.ChequesCP.Count - 1 do
begin
VpfDCheque := TRBDCheque(VpfDDia.ChequesCP.Items[VpfLacoParcela]);
VpfDDia.ValChequesCP := VpfDDia.ValChequesCP + VpfDCheque.ValCheque;
VpfDDiaFluxo.ValChequesCP := VpfDDiaFluxo.ValChequesCP + VpfDCheque.ValCheque;
VpfDMes.ValChequesCP := VpfDMes.ValChequesCP + VpfDCheque.ValCheque;
VpfDDia.ValTotalDespesa := VpfDDia.ValTotalDespesa + VpfDCheque.ValCheque;
VpfDDiaFluxo.ValTotalDespesa := VpfDDiaFluxo.ValTotalDespesa + VpfDCheque.ValCheque;
VpfDMes.ValTotalDespesa := VpfDMes.ValTotalDespesa + VpfDCheque.ValCheque;
VpfDConta.ValTotalDespesas := VpfDConta.ValTotalDespesas + VpfDCheque.ValCheque;
VpfDMes.ValTotalDespesaAcumulada := VpfDMes.ValTotalDespesaAcumulada +VpfDCheque.ValCheque ;
VpfDDia.ValTotalDespesaAcumulada := VpfDDia.ValTotalDespesaAcumulada + VpfDCheque.ValCheque ;
VpfDConta.ValTotalDespesasAcumuladas := VpfDConta.ValTotalDespesasAcumuladas + VpfDCheque.ValCheque;
VpfDMes.ValTotalAcumulado := VpfDMes.ValTotalAcumulado - VpfDCheque.ValCheque;
end;
VpfDDia.Valtotal := VpfDDia.ValTotalReceita - VpfDDia.ValTotalDespesa;
VpfDDiaFluxo.Valtotal := VpfDDiaFluxo.ValTotalReceita - VpfDDiaFluxo.ValTotalDespesa;
VpfDDia.ValTotalAcumulado := VpfDDia.ValTotalAcumulado + VpfDDia.Valtotal;
end;
end;
ValSaldoAnteriorCR := ValSaldoAnteriorCR + VpfDConta.ValSaldoAnteriorCR + VpfDConta.ValChequeCRSaldoAnterior;
ValSaldoAnteriorCP := ValSaldoAnteriorCP + VpfDConta.ValSaldoAnteriorCP + VpfDConta.ValChequeCPSaldoAnterior;
end;
OrdenaDias(Dias);
ValTotalAcumulado := ValAplicacao + ValSaldoAtual +ValChequeCRSaldoAnterior+ ValSaldoAnteriorCR - ValChequeCPSaldoAnterior - ValSaldoAnteriorCP;
for VpfLacoDia := 0 to Dias.Count - 1 do
begin
VpfDDiaFluxo := TRBDFluxoCaixaDia(dias.Items[VpfLacoDia]);
ValTotalAcumulado := ValTotalAcumulado + VpfDDiaFluxo.Valtotal;
VpfDDiaFluxo.ValTotalAcumulado := ValTotalAcumulado;
end;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDFluxoCaixaItem
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDFluxoCaixaDia.cria;
begin
inherited create;
ParcelasCR := TList.create;
ParcelasCP := TList.Create;
ParcelasDuvidosas := TList.create;
ChequesCR := TList.create;
ChequesCP := TList.create;
end;
{******************************************************************************}
destructor TRBDFluxoCaixaDia.destroy;
begin
FreeTObjectsList(ParcelasCR);
ParcelasCR.free;
FreeTObjectsList(ParcelasCP);
ParcelasCP.Free;
FreeTObjectsList(ParcelasDuvidosas);
ParcelasDuvidosas.Free;
FreeTObjectsList(ChequesCR);
ChequesCR.free;
FreeTObjectsList(ChequesCP);
ChequesCP.free;
inherited destroy;
end;
{******************************************************************************}
function TRBDFluxoCaixaDia.addParcelaCR : TRBDParcelaBaixaCR;
begin
result := TRBDParcelaBaixaCR.cria;
ParcelasCR.add(result);
end;
{******************************************************************************}
function TRBDFluxoCaixaDia.addParcelaDuvidosa: TRBDParcelaBaixaCR;
begin
result := TRBDParcelaBaixaCR.cria;
ParcelasDuvidosas.add(result);
end;
{******************************************************************************}
function TRBDFluxoCaixaDia.AddChequeCR(VpaDatVencimento : TDateTime) : TRBDCheque;
var
VpfLaco : Integer;
VpfInseriu : Boolean;
begin
VpfInseriu := false;
result := TRBDCheque.cria;
result.DatVencimento := VpaDatVencimento;
for VpfLaco := 0 to ChequesCR.Count - 1 do
begin
if VpaDatVencimento < TRBDCheque(ChequesCR).DatVencimento then
begin
ChequesCR.Insert(VpfLaco,Result);
VpfInseriu := true;
end;
end;
if not VpfInseriu then
ChequesCR.add(result);
end;
{******************************************************************************}
function TRBDFluxoCaixaDia.AddParcelaCP: TRBDParcelaCP;
begin
result := TRBDParcelaCP.cria;
ParcelasCP.add(result);
end;
{******************************************************************************}
function TRBDFluxoCaixaDia.AddChequeCP(VpaDatVencimento : TDateTime) : TRBDCheque;
var
VpfLaco : Integer;
VpfInseriu : Boolean;
begin
VpfInseriu := false;
result := TRBDCheque.cria;
result.DatVencimento := VpaDatVencimento;
for VpfLaco := 0 to ChequesCP.Count - 1 do
begin
if VpaDatVencimento < TRBDCheque(ChequesCP).DatVencimento then
begin
ChequesCP.Insert(VpfLaco,Result);
VpfInseriu := true;
end;
end;
if not VpfInseriu then
ChequesCP.add(result);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDParcelaBaixaCR
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDCaixaFormaPagamento.cria;
begin
inherited create;
end;
{******************************************************************************}
destructor TRBDCaixaFormaPagamento.destroy;
begin
inherited destroy;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDParcelaBaixaCR
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
constructor TRBDCaixaItem.cria;
begin
inherited create;
end;
{******************************************************************************}
destructor TRBDCaixaItem.Destroy;
begin
inherited destroy;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDParcelaBaixaCR
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDCaixa.cria;
begin
inherited create;
Items := TList.create;
FormasPagamento := TList.Create;
end;
{******************************************************************************}
destructor TRBDCaixa.destroy;
begin
FreeTObjectsList(Items);
FreeTObjectsList(FormasPagamento);
Items.free;
FormasPagamento.Free;
inherited destroy;
end;
{******************************************************************************}
function TRBDCaixa.AddCaixaItem : TRBDCaixaItem;
begin
result := TRBDCaixaItem.cria;
Items.add(result);
end;
{******************************************************************************}
function TRBDCaixa.AddFormaPagamento : TRBDCaixaFormaPagamento;
begin
result := TRBDCaixaFormaPagamento.cria;
FormasPagamento.add(result);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDDERCorpo
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDDERVendedor.cria;
begin
inherited create;
end;
{******************************************************************************}
destructor TRBDDERVendedor.destroy;
begin
inherited destroy;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDDERCorpo
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDDERCorpo.Cria;
begin
inherited create;
Vendedores := TList.Create;
end;
{******************************************************************************}
destructor TRBDDERCorpo.destroy;
begin
FreeTObjectsList(Vendedores);
Vendedores.free;
inherited destroy;
end;
{******************************************************************************}
function TRBDDERCorpo.addVendedor : TRBDDERVendedor;
begin
result := TRBDDERVendedor.cria;
Vendedores.add(result);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDParcelaBaixaCR
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDParcelaBaixaCR.Cria;
begin
inherited Create;
ValAcrescimo:= 0;
ValDesconto:= 0;
IndValorQuitaEssaParcela := true;
IndGeraParcial := false;
end;
{******************************************************************************}
destructor TRBDParcelaBaixaCR.Destroy;
begin
inherited Destroy;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDBaixaCR
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDBaixaCP.Cria;
begin
inherited Create;
Parcelas:= TList.Create;
Cheques := TList.Create;
Caixas := TList.Create;
ValParaGerardeDebito := 0;
end;
{******************************************************************************}
destructor TRBDBaixaCP.Destroy;
begin
FreeTObjectsList(Parcelas);
Parcelas.Free;
FreeTObjectsList(Cheques);
Cheques.free;
FreeTObjectsList(Caixas);
Caixas.free;
inherited Destroy;
end;
{******************************************************************************}
function TRBDBaixaCP.AddParcela: TRBDParcelaCP;
begin
Result:= TRBDParcelaCP.Cria;
Parcelas.Add(Result);
end;
{******************************************************************************}
function TRBDBaixaCP.AddCheque : TRBDCheque;
begin
result := TRBDCheque.cria;
Cheques.add(result);
end;
{******************************************************************************}
function TRBDBaixaCP.AddCaixa : TRBDCaixa;
begin
result := TRBDCaixa.cria;
Caixas.add(result);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDBaixaCR
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDBaixaCR.Cria;
begin
inherited Create;
Parcelas:= TList.Create;
Cheques := TList.Create;
Caixas := TList.Create;
IndBaixaRetornoBancario := false;
IndDesconto := false;
IndBaixaUtilizandoOCreditodoCliente := false;
ValParaGerardeCredito := 0;
end;
{******************************************************************************}
destructor TRBDBaixaCR.Destroy;
begin
FreeTObjectsList(Parcelas);
Parcelas.Free;
FreeTObjectsList(Cheques);
Cheques.free;
FreeTObjectsList(Caixas);
Caixas.free;
inherited Destroy;
end;
{******************************************************************************}
function TRBDBaixaCR.AddParcela: TRBDParcelaBaixaCR;
begin
Result:= TRBDParcelaBaixaCR.Cria;
Parcelas.Add(Result);
end;
{******************************************************************************}
function TRBDBaixaCR.AddCheque : TRBDCheque;
begin
result := TRBDCheque.cria;
Cheques.add(result);
end;
{******************************************************************************}
function TRBDBaixaCR.AddCaixa : TRBDCaixa;
begin
result := TRBDCaixa.cria;
Caixas.add(result);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Parcela Baixa CP
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDParcelaCP.Cria;
begin
inherited Create;
ValAcrescimo:= 0;
ValDesconto:= 0;
IndValorQuitaEssaParcela := true;
IndGeraParcial := false;
end;
{******************************************************************************}
destructor TRBDParcelaCP.Destroy;
begin
inherited destroy;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Dados da ComissaoItem
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
Constructor TRBDContasaPagar.Cria;
begin
inherited;
IndEsconderConta := false;
Parcelas := TList.create;
DespesaProjeto := TList.create;
end;
{******************************************************************************}
destructor TRBDContasaPagar.Destroy;
begin
FreeTObjectsList(DespesaProjeto);
FreeTObjectsList(Parcelas);
DespesaProjeto.free;
Parcelas.free;
inherited destroy;
end;
{******************************************************************************}
function TRBDContasaPagar.addDespesaProjeto: TRBDContasaPagarProjeto;
begin
result := TRBDContasaPagarProjeto.cria;
DespesaProjeto.add(result);
end;
{******************************************************************************}
function TRBDContasaPagar.addParcela : TRBDParcelaCP;
begin
result := TRBDParcelaCP.cria;
Parcelas.add(result);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Dados da ComissaoItem
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDComissaoItem.cria;
begin
Inherited create;
IndLiberacaoAutomatica := false;
end;
{******************************************************************************}
destructor TRBDComissaoItem.destroy;
begin
inherited destroy;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Dados da Comissao
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDComissao.cria;
begin
inherited Create;
Parcelas := TList.create;
end;
{******************************************************************************}
destructor TRBDComissao.destroy;
begin
FreeTObjectsList(Parcelas);
Parcelas.free;
inherited destroy;
end;
{******************************************************************************}
function TRBDComissao.AddParcela : TRBDComissaoItem;
begin
result := TRBDComissaoItem.cria;
Parcelas.add(result);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Dados da ecobrancaitem
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDECobrancaItem.cria;
begin
inherited create;
end;
{******************************************************************************}
destructor TRBDECobrancaitem.destroy;
begin
inherited destroy;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Dados da ecobrancacorpo
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDECobrancaCorpo.cria;
begin
inherited create;
Items := TList.create;
end;
{******************************************************************************}
destructor TRBDECobrancaCorpo.destroy;
begin
FreeTObjectsList(Items);
Items.free;
inherited destroy;
end;
{******************************************************************************}
function TRBDECobrancaCorpo.AddECobrancaItem : TRBDECobrancaItem;
begin
Result := TRBDECobrancaItem.cria;
Items.add(result);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Dados da forma de pagamento
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDFormaPagamento.cria;
begin
inherited create;
end;
{******************************************************************************}
destructor TRBDFormaPagamento.destroy;
begin
inherited destroy;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Dados da parcela da nova contas a receber
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDMovContasCR.cria;
begin
inherited create;
ValDesconto := 0;
ValSinal := 0;
DiasCompensacao := 0;
end;
{******************************************************************************}
destructor TRBDMovContasCR.destroy;
begin
inherited destroy;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Dados da nova contas a receber
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDContasCR.cria;
begin
inherited create;
Parcelas := TList.create;
MostrarParcelas := false;
EsconderConta := false;
SeqParcialCotacao := 0;
LanOrcamento := 0;
ValSinal := 0;
IndCobrarFormaPagamento := false;
IndDevolucao := false;
IndSinalPagamento := false;
IndPossuiSinalPagamento := false;
end;
{******************************************************************************}
destructor TRBDContasCR.destroy;
begin
FreeTObjectsList(Parcelas);
Parcelas.free;
inherited destroy;
end;
{******************************************************************************}
function TRBDContasCR.AddParcela : TRBDMovContasCR;
begin
result := TRBDMovContasCR.Cria;
Parcelas.add(result);
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Dados do Cheque
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDCheque.cria;
begin
SeqCheque := 0;
end;
{******************************************************************************}
destructor TRBDCheque.destroy;
begin
inherited;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Dados da condicao de pagamento
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
function TRBDCondicaoPagamento.AddParcela: TRBDparcelaCondicaoPagamento;
begin
result := TRBDParcelaCondicaoPagamento.cria;
Parcelas.add(result);
end;
{******************************************************************************}
constructor TRBDCondicaoPagamento.cria;
begin
inherited create;
Parcelas := TList.Create;
end;
{******************************************************************************}
destructor TRBDCondicaoPagamento.destroy;
begin
FreeTObjectsList(Parcelas);
Parcelas.free;
inherited;
end;
{ TRBDCondicaoPagamento }
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDPercentuaisCondicaoPagamento
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDParcelaCondicaoPagamento.cria;
begin
inherited create;
end;
{******************************************************************************}
destructor TRBDParcelaCondicaoPagamento.destroy;
begin
inherited;
end;
{ TRBDPercentuaisCondicaoPagamento }
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
TRBDPercentuaisCondicaoPagamento
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDCondicaoPagamentoGrupoUsuario.cria;
begin
inherited create;
end;
{******************************************************************************}
destructor TRBDCondicaoPagamentoGrupoUsuario.destroy;
begin
inherited;
end;
{ TRBDCondicaoPagamentoGrupoUsuario }
{((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
dados da classe do contas a pagar do projeto
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
constructor TRBDContasaPagarProjeto.cria;
begin
inherited create;
end;
{******************************************************************************}
destructor TRBDContasaPagarProjeto.destroy;
begin
inherited;
end;
{ TRBDContasaPagarProjeto }
{******************************************************************************}
{ TRBDTransferenciaExterna }
{******************************************************************************}
{******************************************************************************}
function TRBDTransferenciaExterna.AddFormaPagamento: TRBDTransferenciaExternaFormaPagamento;
begin
result := TRBDTransferenciaExternaFormaPagamento.cria;
FormasPagamento.Add(result);
end;
{******************************************************************************}
constructor TRBDTransferenciaExterna.cria;
begin
inherited create;
FormasPagamento := TList.Create;
end;
{******************************************************************************}
destructor TRBDTransferenciaExterna.destroy;
begin
FreeTObjectsList(FormasPagamento);
FormasPagamento.Free;
inherited;
end;
{******************************************************************************}
{ TRBDTransferenciaExternaFormaPagamento }
{******************************************************************************}
{******************************************************************************}
function TRBDTransferenciaExternaFormaPagamento.addCheque: TRBDTransferenciaExternaCheques;
begin
result := TRBDTransferenciaExternaCheques.cria;
Cheques.Add(Result);
end;
{******************************************************************************}
constructor TRBDTransferenciaExternaFormaPagamento.cria;
begin
inherited create;
IndPossuiCheques := false;
Cheques := TList.Create;
end;
{******************************************************************************}
destructor TRBDTransferenciaExternaFormaPagamento.destroy;
begin
FreeTObjectsList(Cheques);
Cheques.Free;
inherited;
end;
{******************************************************************************}
{ TRBDTransferenciaExternaCheques }
{******************************************************************************}
{******************************************************************************}
constructor TRBDTransferenciaExternaCheques.cria;
begin
inherited create;
end;
{******************************************************************************}
destructor TRBDTransferenciaExternaCheques.destroy;
begin
inherited;
end;
end.
|
unit ApplyQueryFrame;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, DBRecordHolder;
type
TfrmApplyQuery = class(TFrame)
FDQuery: TFDQuery;
FDUpdateSQL: TFDUpdateSQL;
private
FPKFieldName: string;
function GetPKValue: Integer;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
procedure DeleteRecord(APKValue: Integer);
function InsertRecord(ARecordHolder: TRecordHolder): Integer;
function Search(AID: Integer): Integer;
function UpdateRecord(ARecordHolder: TRecordHolder): Boolean;
property PKFieldName: string read FPKFieldName write FPKFieldName;
property PKValue: Integer read GetPKValue;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses System.Generics.Collections, RepositoryDataModule;
constructor TfrmApplyQuery.Create(AOwner: TComponent);
begin
inherited;
PKFieldName := 'ID';
end;
procedure TfrmApplyQuery.DeleteRecord(APKValue: Integer);
begin
Search(APKValue);
Assert(FDQuery.RecordCount = 1);
// Удаляем запись
FDQuery.Delete;
end;
function TfrmApplyQuery.GetPKValue: Integer;
begin
Result := FDQuery.FieldByName(PKFieldName).AsInteger;
end;
function TfrmApplyQuery.InsertRecord(ARecordHolder: TRecordHolder): Integer;
var
AFieldHolder: TFieldHolder;
AFieldName: string;
I: Integer;
begin
I := Search(-1);
Assert(I = 0);
FDQuery.Insert;
try
for I := 0 to FDQuery.FieldCount - 1 do
begin
AFieldName := FDQuery.Fields[I].FieldName;
// if AFieldName.ToUpper = PKFieldName.ToUpper then
// Continue;
// Ищем такое поле в коллекции вставляемых значений
AFieldHolder := ARecordHolder.Find(AFieldName);
// Если нашли
if (AFieldHolder <> nil) and not VarIsNull(AFieldHolder.Value) then
begin
FDQuery.Fields[I].Value := AFieldHolder.Value;
end;
end;
FDQuery.Post;
Assert(not FDQuery.FieldByName(PKFieldName).IsNull);
Result := FDQuery.FieldByName(PKFieldName).AsInteger;
except
FDQuery.Cancel;
raise;
end;
end;
function TfrmApplyQuery.Search(AID: Integer): Integer;
begin
FDQuery.Close;
FDQuery.ParamByName(PKFieldName).AsInteger := AID;
FDQuery.Open;
Result := FDQuery.RecordCount;
end;
function TfrmApplyQuery.UpdateRecord(ARecordHolder: TRecordHolder): Boolean;
var
AChangedFields: TDictionary<String, Variant>;
AFieldHolder: TFieldHolder;
AFieldName: string;
AID: Integer;
I: Integer;
begin
AID := ARecordHolder.Field[PKFieldName];
// Result :=
// Выбираем запись, которую будем обновлять
I := Search(AID);
Assert(I = 1);
// Создаём словарь тех полей что нужно будет обновить
AChangedFields := TDictionary<String, Variant>.Create;
try
for I := 0 to FDQuery.FieldCount - 1 do
begin
AFieldName := FDQuery.Fields[I].FieldName;
// Первичный ключ обновлять не будем
if AFieldName.ToUpper = PKFieldName.ToUpper then
Continue;
// Ищем такое поле в коллекции обновляемых значений
AFieldHolder := ARecordHolder.Find(AFieldName);
// Запоминаем в словаре какое поле нужно будет обновить
if (AFieldHolder <> nil) and
(FDQuery.Fields[I].Value <> AFieldHolder.Value) then
AChangedFields.Add(AFieldName, AFieldHolder.Value);
end;
Result := AChangedFields.Count > 0;
// Если есть те поля, которые нужно обновлять
if Result then
begin
FDQuery.Edit;
try
// Цикл по всем изменившимся полям
for AFieldName in AChangedFields.Keys do
begin
FDQuery.FieldByName(AFieldName).Value := AChangedFields[AFieldName];
end;
FDQuery.Post;
except
FDQuery.Cancel;
raise;
end;
end;
finally
FreeAndNil(AChangedFields);
end;
end;
end.
|
{ :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: QuickReport 3.0 for Delphi 3.0/4.0/5.0 ::
:: ::
:: Demo report that is populated by the OnNeedData event ::
:: ::
:: Copyright (c) 1995-1999 QuSoft AS ::
:: All Rights Reserved ::
:: ::
:: web: http://www.qusoft.com fax: +47 22 41 74 91 ::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: }
unit needdata;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, QuickRpt, Qrctrls;
type
TfrmNeedData = class(TForm)
QuickRep1: TQuickRep;
DetailBand1: TQRBand;
QRLabel1: TQRLabel;
TitleBand1: TQRBand;
QRSysData1: TQRSysData;
procedure FormCreate(Sender: TObject);
procedure QuickRep1BeforePrint(Sender: TCustomQuickRep;
var PrintReport: Boolean);
procedure QuickRep1NeedData(Sender: TObject; var MoreData: Boolean);
private
{ Private declarations }
SomeList: TStringlist;
CurrentIndex: integer;
public
{ Public declarations }
end;
var
frmNeedData: TfrmNeedData;
implementation
{$R *.dfm}
procedure TfrmNeedData.FormCreate(Sender: TObject);
var
i: integer;
begin
SomeList := TStringlist.Create;
for i := 0 to 500 do
SomeList.Add('Line ' + IntToStr(i));
end;
procedure TfrmNeedData.QuickRep1BeforePrint(Sender: TCustomQuickRep;
var PrintReport: Boolean);
begin
// You must reset your data in the BeforePrint event
// or when you print from the preview, the report will
// start with the last value(s)
CurrentIndex := 0;
end;
procedure TfrmNeedData.QuickRep1NeedData(Sender: TObject;
var MoreData: Boolean);
begin
// If MoreData is true, then QuickReport will print
// another detail band. When you set it to false,
// the report is done.
MoreData := (CurrentIndex < SomeList.Count);
if MoreData then
begin
QRLabel1.Caption := SomeList[CurrentIndex];
// Here's how to set the progress bar
QuickRep1.QRPrinter.Progress := (Longint(CurrentIndex) * 100) div SomeList.Count;
end
else
QuickRep1.QRPrinter.Progress := 100;
Inc(CurrentIndex);
end;
end.
|
unit NodeParsing;
interface
uses
SourceNode;
type
TBracketKind = (bkCurly, bkParens, bkBlock, bkAngle);
TSeperatorKind = (skSemicolon, skComma);
TNodeParser = class
public
procedure Process(Node: TSourceNode);
private
FOutput: TSourceNode;
procedure Group;
procedure GroupByBrackets(Node: TSourceNode; BracketKind: TBracketKind; Kind: TSourceNodeKind);
procedure GroupByBrackets_B(Node: TSourceNode; BracketKind: TBracketKind; Kind: TSourceNodeKind);
procedure GroupBySeperator(Node: TSourceNode; SeperatorKind: TSeperatorKind);
procedure ParseOperators;
procedure OperatorPrecedence;
end;
var
RootNodeKind: TSourceNodeKind;
ErrorNodeKind: TSourceNodeKind;
SymbolNodeKind: TSourceNodeKind;
CurlyBracketNodeKind: TSourceNodeKind;
AngleBracketNodeKind: TSourceNodeKind;
SquareBracketNodeKind: TSourceNodeKind;
ParensNodeKind: TSourceNodeKind;
implementation
uses
SourceLocation,
NodeHelper;
type
TAssociativeness = (aLR, aRL);
TFix = (fInfix, fPrefix, fPostfix);
TOperatorRecord = record
Key: Cardinal;
Data: String;
Fixness: TFix;
Precedence: Integer;
Associativeness: TAssociativeness;
end;
var
Operators : array of TOperatorRecord;
OpenBracket: array[TBracketKind] of String;
CloseBracket: array[TBracketKind] of String;
BracketRequired: array[TBracketKind] of Boolean;
Seperator: array[TSeperatorKind] of String;
procedure TNodeParser.Process(Node: TSourceNode);
begin
FOutput := Node;
Group;
ParseOperators;
OperatorPrecedence;
end;
procedure TNodeParser.Group;
begin
GroupByBrackets(FOutput, bkCurly, CurlyBracketNodeKind);
GroupByBrackets(FOutput, bkParens, ParensNodeKind);
GroupByBrackets(FOutput, bkBlock, SquareBracketNodeKind);
GroupByBrackets(FOutput, bkAngle, AngleBracketNodeKind);
GroupBySeperator(FOutput, skSemicolon);
GroupBySeperator(FOutput, skComma);
end;
procedure TNodeParser.GroupByBrackets(Node: TSourceNode; BracketKind: TBracketKind; Kind: TSourceNodeKind);
var
N: TSourceNode;
begin
N := Node;
while Node <> nil do begin
if Node.FirstChild <> nil then
GroupByBrackets(Node.FirstChild, BracketKind, Kind);
Node := Node.Next;
end;
Node := N;
while Node <> nil do begin
if (Node.Kind = SymbolNodeKind) and (Node.Data = OpenBracket[BracketKind]) then
GroupByBrackets_B(Node, BracketKind, Kind);
Node := Node.Next;
end;
end;
procedure TNodeParser.GroupByBrackets_B(Node: TSourceNode; BracketKind: TBracketKind; Kind: TSourceNodeKind);
var
Anchor: TSourceNode;
Terminator: TSourceNode;
T: TSourceNode;
EndLocation: TLocation;
begin
Anchor := Node;
Node := Node.Next;
while Node <> nil do begin
if Node.Kind = SymbolNodeKind then begin
if Node.Data = OpenBracket[BracketKind] then begin
GroupByBrackets_B(Node, BracketKind, Kind);
end;
if Node.Data = CloseBracket[BracketKind] then begin
Break;
end;
end;
Node := Node.Next;
end;
if Node = nil then begin
if not BracketRequired[BracketKind] then begin
Anchor.Data := '#' + Anchor.Data;
Exit;
end;
EndLocation := BeyondLocation(Anchor.Parent.LastChild.Position);
InsertErrorNextTo(Anchor.Parent.LastChild, 'Expected '+CloseBracket[BracketKind], @EndLocation);
Terminator := Anchor.Parent.LastChild;
end
else begin
EndLocation := Node.Position;
Terminator := Node.Previous;
Node.Unhook;
Node.Free;
end;
Anchor.Kind := Kind;
Anchor.Position.EndOffset := EndLocation.EndOffset;
if Anchor <> Terminator then begin
Node := Anchor.Next;
while True do
begin
T := Node.Next;
Node.AttachAsChildOf(Anchor);
if Node = Terminator then
Break;
Node := T;
end;
end;
end;
procedure TNodeParser.GroupBySeperator(Node: TSourceNode; SeperatorKind: TSeperatorKind);
var
N, C, CN: TSourceNode;
begin
N := Node.LastChild;
while N <> nil do begin
GroupBySeperator(N, SeperatorKind);
N:= N.Previous;
end;
N := Node.LastChild;
while N <> nil do begin
if (N.Kind = SymbolNodeKind) and (N.Data = Seperator[SeperatorKind]) then begin
C := N.Next;
while C <> nil do begin
CN := C.Next;
C.AttachAsChildOf(N);
C := CN;
end;
end;
N := N.Previous;
end;
end;
procedure TNodeParser.ParseOperators;
procedure ProcessOperator(Key: Cardinal; A: TSourceNode; B: TSourceNode; C: TSourceNode; D: TSourceNode);
var
I: Integer;
begin
if Key < $100 then
exit; // no need to process these
for I := 0 to Length(Operators)-1 do begin
if Operators[I].Key = Key then begin
A.Data := Operators[I].Data;
if Key >= $100 then begin
A.Position.EndOffset := B.Position.EndOffset;
B.Unhook;
B.Free;
end;
if Key >= $10000 then begin
A.Position.EndOffset := C.Position.EndOffset;
C.Unhook;
C.Free;
end;
if Key >= $1000000 then begin
A.Position.EndOffset := D.Position.EndOffset;
D.Unhook;
D.Free;
end;
Exit;
end;
end;
if Key >= $1000000 then
ProcessOperator(Key and $ffffff, A, B, C, D)
else if Key >= $10000 then
ProcessOperator(Key and $ffff, A, B, C, D)
else if Key >= $100 then
ProcessOperator(Key and $ff, A, B, C, D);
end;
var
Node: TSourceNode;
A, B, C, D: TSourceNode;
Key: Cardinal;
begin
Node := FOutput;
while Node <> nil do
begin
A := Node;
B := nil;
C := nil;
D := nil;
if A <> nil then
B := A.Next;
if B <> nil then
C := B.Next;
if C <> nil then
D := C.Next;
if (A = nil) or (A.Kind <> SymbolNodeKind) or (A.FirstChild <> nil) then
A := nil;
if (A = nil) or (B = nil) or (B.Kind <> SymbolNodeKind) or (B.FirstChild <> nil) then
B := nil;
if (B = nil) or (C = nil) or (C.Kind <> SymbolNodeKind) or (C.FirstChild <> nil) then
C := nil;
if (C = nil) or (D = nil) or (D.Kind <> SymbolNodeKind) or (D.FirstChild <> nil) then
D := nil;
if (A <> nil) and (A.Data = '#<') then
A.Data := '<';
if B <> nil then begin
if (B <> nil) and (B.Data = '#<') then
B.Data := '<';
if (C <> nil) and (C.Data = '#<') then
C.Data := '<';
if (D <> nil) and (D.Data = '#<') then
D.Data := '<';
Key := 0;
if A <> nil then
Key := Key or Cardinal(A.Data[1]);
if B <> nil then
Key := Key or Cardinal(B.Data[1]) shl 8;
if C <> nil then
Key := Key or Cardinal(C.Data[1]) shl 16;
if D <> nil then
Key := Key or Cardinal(D.Data[1]) shl 24;
if Key <> 0 then
ProcessOperator(Key, A, B, C, D);
end;
if Node.FirstChild <> nil then
Node := Node.FirstChild
else begin
while Node <> nil do begin
if Node.Next <> nil then begin
Node := Node.Next;
break;
end;
Node := Node.Parent;
end;
end;
end;
end;
procedure TNodeParser.OperatorPrecedence;
begin
end;
procedure BuildNodeKinds;
begin
RootNodeKind := TSourceNodeKind.Create('root');
ErrorNodeKind := TSourceNodeKind.Create('error');
SymbolNodeKind := TSourceNodeKind.Create('symbol');
CurlyBracketNodeKind := TSourceNodeKind.Create('curly');
AngleBracketNodeKind := TSourceNodeKind.Create('angle');
SquareBracketNodeKind := TSourceNodeKind.Create('square');
ParensNodeKind := TSourceNodeKind.Create('parens');
end;
procedure BuildBrackets;
begin
OpenBracket[bkCurly] := '{';
CloseBracket[bkCurly] := '}';
BracketRequired[bkCurly] := True;
OpenBracket[bkParens] := '(';
CloseBracket[bkParens] := ')';
BracketRequired[bkParens] := True;
OpenBracket[bkBlock] := '[';
CloseBracket[bkBlock] := ']';
BracketRequired[bkBlock] := True;
OpenBracket[bkAngle] := '<';
CloseBracket[bkAngle] := '>';
BracketRequired[bkAngle] := False;
Seperator[skSemicolon] := ';';
Seperator[skComma] := ',';
end;
procedure BuildOperators;
procedure Add(Operator: String; Fix: TFix; Precedence: Integer; Associativeness: TAssociativeness);
var
Op: TOperatorRecord;
Key: Cardinal;
begin
Op.Data := Operator;
Op.Fixness := Fix;
Op.Precedence := Precedence;
Op.Associativeness := Associativeness;
Key := 0;
if Length(Operator) >= 1 then
Key := Key or Cardinal(Operator[1]);
if Length(Operator) >= 2 then
Key := Key or Cardinal(Operator[2]) shl 8;
if Length(Operator) >= 3 then
Key := Key or Cardinal(Operator[3]) shl 16;
if Length(Operator) >= 4 then
Key := Key or Cardinal(Operator[4]) shl 24;
Op.Key := Key;
SetLength(Operators, Length(Operators)+1);
Operators[Length(Operators)-1] := Op;
end;
begin
SetLength(Operators, 0);
Add('::', fInfix, 1, aLR);
Add('++', fPostfix, 2, aLR);
Add('--', fPostfix, 2, aLR);
Add('(', fPostfix, 2, aLR);
Add('[', fPostfix, 2, aLR);
Add('.', fInfix, 2, aLR);
Add('->', fInfix, 2, aLR);
Add('++', fPrefix, 3, aRL);
Add('--', fPrefix, 3, aRL);
Add('+', fPrefix, 3, aRL);
Add('-', fPrefix, 3, aRL);
Add('~', fPrefix, 3, aRL);
Add('!', fPrefix, 3, aRL);
Add('?', fPrefix, 3, aRL);
Add('&', fPrefix, 3, aRL);
Add('*', fPrefix, 3, aRL);
Add('(', fPrefix, 3, aRL);
Add('**', fInfix, 4, aLR);
Add('*', fInfix, 5, aLR);
Add('/', fInfix, 5, aLR);
Add('%', fInfix, 5, aLR);
Add('+', fInfix, 6, aLR);
Add('-', fInfix, 6, aLR);
Add('<<', fInfix, 7, aLR);
Add('>>', fInfix, 7, aLR);
Add('>>>', fInfix, 7, aLR);
Add('<=', fInfix, 8, aLR);
Add('>=', fInfix, 8, aLR);
Add('<', fInfix, 8, aLR);
Add('>', fInfix, 8, aLR);
Add('==', fInfix, 9, aLR);
Add('!=', fInfix, 9, aLR);
Add('===', fInfix, 9, aLR);
Add('!==', fInfix, 9, aLR);
Add('&', fInfix, 10, aLR);
Add('^', fInfix, 11, aLR);
Add('|', fInfix, 12, aLR);
Add('&&', fInfix, 13, aLR);
Add('||', fInfix, 14, aLR);
Add('??', fInfix, 15, aLR);
Add('..', fInfix, 16, aLR);
Add('...', fInfix, 16, aLR);
Add('=', fInfix, 17, aRL);
Add('+=', fInfix, 17, aRL);
Add('-=', fInfix, 17, aRL);
Add('*=', fInfix, 17, aRL);
Add('/=', fInfix, 17, aRL);
Add('%=', fInfix, 17, aRL);
Add('&=', fInfix, 17, aRL);
Add('^=', fInfix, 17, aRL);
Add('|=', fInfix, 17, aRL);
Add('<<=', fInfix, 17, aRL);
Add('>>=', fInfix, 17, aRL);
Add('>>>=', fInfix, 17, aRL);
Add(':=:', fInfix, 17, aRL);
Add('=>', fInfix, 18, aLR);
end;
initialization
BuildOperators;
BuildBrackets;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
hrc: HGLRC;
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
wglMakeCurrent(Canvas.Handle, hrc);
glViewPort (0, 0, ClientWidth, ClientHeight); // область вывода
glClearColor (0.5, 0.5, 0.75, 1.0); // определение цвета фона
glClear (GL_COLOR_BUFFER_BIT); // очистка буфера цвета
glColor3f (1.0, 0.0, 0.5); // текущий цвет примитивов
glBegin (GL_TRIANGLE_STRIP);
glVertex2f (1, 1);
glVertex2f (-1, 1);
glVertex2f (-1, -1);
glVertex2f (1, -1);
glEnd;
SwapBuffers(Canvas.Handle); // содержимое буфера - на экран
wglMakeCurrent(0, 0);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
SetDCPixelFormat(Canvas.Handle);
hrc := wglCreateContext(Canvas.Handle);
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglDeleteContext(hrc);
end;
end.
|
unit Plots;
interface
uses
Classes, Contnrs, FGL,
SpectrumTypes;
type
TGraph = class;
TPlot = class;
TPlots = class;
TPlotOperation = (poProjectSaved, poProjectLoaded, poProjectReseting, poProjectReset,
poPlotAdded, poPlotChanged, poPlotDestroying, poPlotDestroyed, poModified,
poGraphAdded, poGraphChanged, poGraphDeleted, poGraphChangedValues,
poGraphDestroying);
TPlotOperations = set of TPlotOperation;
IPlotNotification = interface
['{57D01E74-C0FF-4AFC-B211-FF5610FDA085}']
procedure Notify(AOperation: TPlotOperation; APlot: TPlot; AGraph: TGraph);
end;
TGraphKind = (gkNormal, gkExpression);
// Diagram line
TGraph = class
private
FOwner: TPlot;
FTitle: String;
FValuesX: TValueArray;
FValuesY: TValueArray;
// Title is generated automatically. It is True for a new graph.
// Some operations can generate a graph's title (e.g. formula editing)
// if this flag is True. But when user renames graph the flag is reset.
FAutoTitle: Boolean;
// Data source of graph. It can be file path, expression or function name
// (e.g. Derivative(smth)). This value is just an information. It is
// better to store a true data source in FParams for following usage.
FSource: String;
// Kind of graph particularly determines a way to store graph in project
// file. E.g. it controls what type of additional parameters (FParams)
// must be created while graph is read from project file.
FKind: TGraphKind;
// Any additional graph params and properties. E.g. for expression graph
// it stores a plotting function and parameters (TFormulaParams).
FParams: TObject;
function GetIndex: Integer;
function GetValueX(Index: Integer): TValue;
function GetValueY(Index: Integer): TValue;
procedure SetValueX(Index: Integer; const Value: TValue);
procedure SetValueY(Index: Integer; const Value: TValue);
procedure SetValueCount(Value: Integer);
function GetValueCount: Integer;
public
constructor Create(AValues: TGraphRec; const ATitle: String); overload;
constructor Create(const AValuesX, AValuesY: TValueArray; const ATitle: String); overload;
destructor Destroy; override;
function EditFormula: Boolean;
//procedure SaveXML(Node: IXMLNode);
//procedure LoadXML(Node: IXMLNode);
//procedure Load(Params: TGraphAppendParams);
//procedure GetMinMaxX(out MinValue, MaxValue: TValue);
//procedure GetMinMaxY(out MinValue, MaxValue: TValue);
procedure Trim(var Param: TTrimParams);
procedure Offset(var Param: TOffsetParams);
procedure Normalize(var Param: TNormalizeParams);
procedure SwapXY;
procedure FlipX;
procedure FlipY;
procedure Sort;
property Index: Integer read GetIndex;
property Title: String read FTitle;
property AutoTitle: Boolean read FAutoTitle write FAutoTitle;
property ValueCount: Integer read GetValueCount write SetValueCount;
property ValuesX: TValueArray read FValuesX;
property ValuesY: TValueArray read FValuesY;
property ValueX[Indx: Integer]: TValue read GetValueX write SetValueX;
property ValueY[Indx: Integer]: TValue read GetValueY write SetValueY;
property Source: String read FSource;
property Owner: TPlot read FOwner;
property Kind: TGraphKind read FKind;
property Params: TObject read FParams;
procedure SetValuesXY(const Xs, Ys: TValueArray);
procedure SetTitle(const Value: String; AUndoable: Boolean = True);
procedure Notify(AOperation: TPlotOperation);
end;
TGraphList = specialize TFPGList<TGraph>;
TGraphArray = array of TGraph;
PGraphArray = ^TGraphArray;
// Graphs collection
TPlot = class
private
FTitle: String;
FOwner: TPlots;
FItems: TGraphList;
FFactorX, FFactorY: Integer;
//function CreateGraph(Node: IXMLNode): TGraph; overload;
//function CreateGraph(Params: TGraphAppendParams): TGraph; overload;
//function CreateGraph(ATitle: String = ''): TGraph; overload;
//function CreateNote(Node: IXMLNode): TAnnotationTool;
function GetCount: Integer;
function GetItems(Index: Integer): TGraph;
procedure CreateUndoGroup(var Graphs: TGraphArray; const Title: String);
public
// BackupIndex: Integer; // номер выделенного графика, для переключения м-у диаграммами
constructor Create(AOwner: TPlots; const ATitle: String = '');
destructor Destroy; override;
procedure Clear;
//function AddGraph: TGraph; overload; // add empty graph
procedure AddGraph(AGraph: TGraph; AIndex: Integer = -1; AUndoable: Boolean = True); overload;
//procedure AddGraph(AGraph: TGraphRec; const ATitle: String); overload;
// Основная процедура создания графиков по имеющимся данным
// FileNames - список файлов, если графики создаются из файлов. Может не задаваться.
// Params - предположительные параметры загрузки каждого файла. Параметры затем
// уточняются на основании типа файла или чего-то еще. Если список файлов не
// задан, предполагается что параметры содержат достаточно данных для создания
// графика (задан поток, или массивы готовых данных).
// Использование объекта-параметра TGraphAppendParams см. в TGraph.Load.
//function AddGraph(Params: TGraphAppendParams; FileNames: TStrings = nil): TGraph; overload;
//function AddGraph(Params: TGraphAppendParams; const FileName: String): TGraph; overload;
//
//function AddSampleGraph(ATitle: String): TGraph; overload;
//function AddSampleGraph(ATitle: String; AParams: TRandomSampleParams): TGraph; overload;
//procedure ExtractGraph(AGraph: TGraph);
procedure DeleteGraph(AGraph: TGraph; AUndoable: Boolean = True); overload;
//procedure DeleteGraph(ASeries: TChartSeries); overload;
//
//procedure SaveXML(Node: IXMLNode);
//procedure LoadXML(Node: IXMLNode);
procedure SetTitle(Value: String; AUndoable: Boolean = True);
procedure Trim(var Graphs: TGraphArray; var Param: TTrimParams);
procedure Offset(var Graphs: TGraphArray; var Param: TOffsetParams);
procedure Flip(var Graphs: TGraphArray; var Param: TMiscParams);
procedure Normalize(var Graphs: TGraphArray; var Param: TNormalizeParams);
procedure Scale(var Graphs: TGraphArray; var Param: TScaleParams);
procedure Inverse(var Graphs: TGraphArray; var Param: TMiscParams);
procedure Variance(var Graphs: TGraphArray; var Param: TVarianceParams);
procedure SwapXY(var Graphs: TGraphArray);
procedure FlipX(var Graphs: TGraphArray);
procedure FlipY(var Graphs: TGraphArray);
procedure Differentiate(var Graphs: TGraphArray);
procedure Differentiate2(var Graphs: TGraphArray);
procedure Regularity(var Graphs: TGraphArray);
procedure Midline(var Graphs: TGraphArray);
procedure Envelope(var Graphs: TGraphArray; IsTop: Boolean);
procedure Despike(var Graphs: TGraphArray; var Params: TDespikeParams);
procedure GroupOperation(var Graphs: TGraphArray; Operation: TGroupOperation);
function IsEmpty: Boolean;
property Count: Integer read GetCount;
property Items[Index: Integer]: TGraph read GetItems; default;
property Title: String read FTitle write SetTitle;
property Owner: TPlots read FOwner;
property FactorX: Integer read FFactorX write FFactorX;
property FactorY: Integer read FFactorY write FFactorY;
procedure ApplyChartSettings;
procedure Notify(AOperation: TPlotOperation; AGraph: TGraph = nil);
end;
TPlotSetStatuses = (pssLoading);
TPlotSetStatus = set of TPlotSetStatuses;
TPlotList = specialize TFPGList<TPlot>;
TPlots = class
private
FItems: TPlotList;
FUntitled: Boolean;
FPacked: Boolean;
FFileName: String;
FStatus: TPlotSetStatus;
FModified: Boolean;
FNotifyClients: TObjectList;
function CreatePlot(const ATitle: String = ''): TPlot;
function GetCount: Integer;
function GetItems(Index: Integer): TPlot;
procedure SetModified(Value: Boolean);
//procedure SaveXML(APlot: TPlot); overload;
//procedure SaveXML(Node: IXMLNode; APlot: TPlot); overload;
//procedure LoadXML(const AFileName: String; APacked: Boolean); overload;
//procedure LoadXML(Node: IXMLNode); overload;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
//function AddPlot(Node: IXMLNode): TPlot; overload;
function AddPlot(const ATitle: String = ''): TPlot; overload;
procedure DeletePlot(Index: Integer); overload;
procedure DeletePlot(APlot: TPlot); overload;
property Items[Index: Integer]: TPlot read GetItems; default;
function IndexOf(APlot: TPlot): Integer;
property Count: Integer read GetCount;
procedure RegisterNotifyClient(AObject: TObject);
procedure UnRegisterNotifyClient(AObject: TObject);
function GetNotifyClient(AClass: TClass): TObject;
procedure Notify(AOperation: TPlotOperation; APlot: TPlot = nil; AGraph: TGraph = nil);
function CanReset: Boolean;
function Reset(Silent: Boolean = False; Mode: Integer = 2): Boolean;
function Save(APlot: TPlot = nil): Boolean;
function SaveAs(APlot: TPlot = nil): Boolean;
function Load: Boolean; overload;
procedure Load(const AFileName: String; APacked: Boolean); overload;
property FileName: String read FFileName;
property Status: TPlotSetStatus read FStatus;
property Modified: Boolean read FModified write SetModified;
end;
function IsProjectPacked(const FileName: String): Boolean;
procedure IncreaseArray(var Arr: TGraphArray; Value: TGraph);
procedure IncreaseArrayUnique(var Arr: TGraphArray; Value: TGraph);
procedure DecreaseArray(var Arr: TGraphArray; Index: Integer);
var
PlotSet: TPlots;
const
CDefProjectExt = 'sprj';
PROJECT_VER = 1;
implementation
uses
SysUtils,
OriUndo,
// Controls, Dialogs, Variants, Graphics, Zlib,
// OriUndo, OriUtils, OriDialogs, TeeStoreXML,
// Common, UndoRedo, PlotMath, WinOpenArchive;
PlotMath, SpectrumStrings, SpectrumUndo;
var
UntitledIndex: Integer = 1;
const
// Set of operations making a plot modified. FModified flag is set.
ModifyingOperations: TPlotOperations = [poPlotChanged, poPlotDestroyed,
poGraphAdded, poGraphChanged, poGraphChangedValues, poGraphDeleted];
// Set of operations making a plot unmodified. FModified flag is reset.
SavingOperations: TPlotOperations = [poProjectSaved, poProjectLoaded, poProjectReset];
{%region Helpers}
function IsProjectPacked(const FileName: String): Boolean;
begin
Result := SameText(ExtractFileExt(FileName), '.' + CDefProjectExt + 'z');
end;
procedure IncreaseArray(var Arr: TGraphArray; Value: TGraph);
begin
SetLength(Arr, Length(Arr)+1);
Arr[Length(Arr)-1] := Value;
end;
procedure IncreaseArrayUnique(var Arr: TGraphArray; Value: TGraph);
var
I: Integer;
begin
for I := 0 to Length(Arr)-1 do
if Arr[I] = Value then Exit;
SetLength(Arr, Length(Arr)+1);
Arr[Length(Arr)-1] := Value;
end;
procedure DecreaseArray(var Arr: TGraphArray; Index: Integer);
var
I: Integer;
begin
if (Index > -1) and (Index < Length(Arr)) then
begin
for I := Index+1 to Length(Arr)-1 do Arr[I-1] := Arr[I];
SetLength(Arr, Length(Arr)-1);
end;
end;
{%endregion}
{%region TGraph}
constructor TGraph.Create(AValues: TGraphRec; const ATitle: String);
begin
Create(AValues.X, AValues.Y, ATitle);
end;
constructor TGraph.Create(const AValuesX, AValuesY: TValueArray; const ATitle: String);
begin
if (Length(AValuesX) < 2) or (Length(AValuesY) < 2) then
raise ESpectrumError.Create(Err_TooFewPoints);
if Length(AValuesX) <> Length(AValuesY) then
raise ESpectrumError.Create(Err_XYLengthsDiffer);
FTitle := ATitle;
FAutoTitle := True;
FValuesX := AValuesX;
FValuesY := AValuesY;
end;
destructor TGraph.Destroy;
begin
FreeAndNil(FParams);
Notify(poGraphDestroying);
inherited;
end;
procedure TGraph.Notify(AOperation: TPlotOperation);
begin
if Assigned(Owner) then Owner.Notify(AOperation, Self);
end;
{%region Working With Values}
procedure TGraph.SetValuesXY(const Xs, Ys: TValueArray);
begin
if Length(Xs) <> Length(Ys) then
raise ESpectrumError.Create(Err_XYLengthsDiffer);
FValuesX := Copy(ValuesX);
FValuesY := Copy(ValuesY);
Notify(poGraphChangedValues);
end;
function TGraph.GetValueX(Index: Integer): TValue;
begin
Result := FValuesX[Index];
end;
function TGraph.GetValueY(Index: Integer): TValue;
begin
Result := FValuesY[Index];
end;
function TGraph.GetValueCount: Integer;
begin
Result := Length(FValuesX);
end;
procedure TGraph.SetValueCount(Value: Integer);
begin
SetLength(FValuesX, Value);
SetLength(FValuesY, Value);
end;
// For internal usage only, no undo is needed
procedure TGraph.SetValueX(Index: Integer; const Value: TValue);
begin
if (Index > -1) and (Index < Length(FValuesX)) then
begin
FValuesX[Index] := Value;
Notify(poGraphChangedValues);
end;
end;
// For internal usage only, no undo is needed
procedure TGraph.SetValueY(Index: Integer; const Value: TValue);
begin
if (Index > -1) and (Index < Length(FValuesY)) then
begin
FValuesY[Index] := Value;
Notify(poGraphChangedValues);
end;
end;
{%endregion}
function TGraph.GetIndex: Integer;
begin
Result := FOwner.FItems.IndexOf(Self);
end;
{%region Undoable Properties Accessors}
procedure TGraph.SetTitle(const Value: String; AUndoable: Boolean);
begin
if Value <> FTitle then
begin
if AUndoable then
History.Append(TGraphTitleEditCommand.Create(Self));
FTitle := Value;
FAutoTitle := False;
Notify(poGraphChanged);
end;
end;
{%endregion}
function TGraph.EditFormula: Boolean;
//var
// UndoCmd: TOriUndoCommand;
begin
//Result := False;
//case FKind of
// gkExpression:
// begin
// UndoCmd := TEditFormulaCommand.Create(Self);
// if EditFormulaParams(TFormulaParams(FParams)) then
// begin
// UpdateValues;
// History.Append(UndoCmd);
// Result := True;
// end
// else UndoCmd.Free;
// end;
//end;
end;
{%region Load/Save}
{procedure TGraph.Load(Params: TGraphAppendParams);
procedure LoadFormula(Params: TFormulaParams);
begin
FKind := gkExpression;
FParams := Params;
FSource := FormulaExpression(Params.Formula);
FAutoTitle := True;
FTitle := FSource;
FillValues;
end;
begin
FSource := Params.Source;
if Params.Title = ''
then FTitle := ExtractFileName(Params.Source)
else FTitle := Params.Title;
if Assigned(Params.Reader) then
begin
Params.ValuesX := @FValuesX;
Params.ValuesY := @FValuesY;
with Params.Reader.Create(Params) do
try
ReadValues;
finally
Free;
end;
end
else if Assigned(Params.AuxParam) then
begin
// График выражения y = f(x)
if Params.AuxParam is TFormulaParams then
LoadFormula(Params.AuxParam as TFormulaParams);
end
else // данные уже загружены
if (Params.ValuesX <> nil) and (Params.ValuesY <> nil) then
begin
FValuesX := Params.ValuesX^;
FValuesY := Params.ValuesY^;
end;
ValueCount := Min(Length(FValuesX), Length(FValuesY));
if ValueCount < 2 then
raise ESpectrumError.CreateFmtDK('Err_TooFewPoints', [FTitle]);
end;}
{procedure TGraph.SaveXML(Node: IXMLNode);
procedure SaveValues;
var
i: Integer;
child, value: IXMLNode;
begin
child := Node.AddChild('Values');
child.Attributes['Count'] := ValueCount;
for i := 0 to ValueCount-1 do
begin
value := child.AddChild('Point');
value.Attributes['X'] := FValuesX[i];
value.Attributes['Y'] := FValuesY[i];
end;
end;
procedure SaveFormula(Params: TFormulaParams);
var
child, range: IXMLNode;
begin
child := Node.AddChild('Formula');
range := child.AddChild('Range');
range.Attributes['Min'] := Params.Range.Min;
range.Attributes['Max'] := Params.Range.Max;
range.Attributes['Step'] := Params.Range.Step;
range.Attributes['Points'] := Params.Range.Points;
range.Attributes['UseStep'] := Params.Range.UseStep;
child.AddChild('Code').Text := Params.Formula;
end;
var
OldDec: Char;
begin
Node.Attributes['Title'] := FTitle;
Node.Attributes['Kind'] := Ord(FKind);
Node.Attributes['AutoTitle'] := FAutoTitle;
Node.AddChild('Source').Text := FSource;
WriteLineSeries(Node, 'Line', FSeries);
OldDec := DecimalSeparator;
DecimalSeparator := '.';
try
case FKind of
gkNormal: SaveValues;
gkExpression: SaveFormula(TFormulaParams(FParams));
end;
finally
DecimalSeparator := OldDec;
end;
end; }
{procedure TGraph.LoadXML(Node: IXMLNode);
procedure LoadValues;
var
i, count: Integer;
child, value: IXMLNode;
nodes: IXMLNodeList;
begin
child := Node.ChildNodes.FindNode('Values');
if child <> nil then
begin
nodes := child.ChildNodes;
count := nodes.Count;
SetLength(FValuesX, count);
SetLength(FValuesY, count);
for i := 0 to count-1 do
begin
value := nodes[i];
FValuesX[i] := VarAsType(value.Attributes['X'], varDouble);
FValuesY[i] := VarAsType(value.Attributes['Y'], varDouble);
end;
end;
end;
procedure LoadFormula;
var
Params: TFormulaParams;
child, range: IXMLNode;
begin
Params := TFormulaParams.Create;
child := Node.ChildNodes.Nodes['Formula'];
range := child.ChildNodes.Nodes['Range'];
Params.Range.Min := VarAsType(range.Attributes['Min'], varDouble);
Params.Range.Max := VarAsType(range.Attributes['Max'], varDouble);
Params.Range.Step := VarAsType(range.Attributes['Step'], varDouble);
Params.Range.Points := VarAsType(range.Attributes['Points'], varInteger);
Params.Range.UseStep := VarAsType(range.Attributes['UseStep'], varBoolean);
Params.Formula := child.ChildNodes.Nodes['Code'].Text;
FParams := Params;
FillValues;
end;
var
OldSep: Char;
begin
FTitle := Node.Attributes['Title'];
if not VarIsNull(Node.Attributes['Kind'])
then FKind := Node.Attributes['Kind']
else FKind := gkNormal;
if not VarIsNull(Node.Attributes['AutoTitle'])
then FAutoTitle := Node.Attributes['AutoTitle']
else FAutoTitle := True;
FSource := Node.ChildNodes.Nodes['Source'].Text;
{$ifndef DBG_IGNORE_LOAD_ERRS}
try
{$endif}
ReadLineSeries(Node, 'Line', FSeries);
{$ifndef DBG_IGNORE_LOAD_ERRS}
except
on e: Exception do
MsgBoxDK('PlotErr_LoadLine', [FTitle, e.ClassName, e.Message], mbError);
end;
{$endif}
OldSep := DecimalSeparator;
DecimalSeparator := '.';
try
case FKind of
gkNormal: LoadValues;
gkExpression: LoadFormula;
end;
finally
DecimalSeparator := OldSep;
end;
end; }
{%endregion}
//procedure TGraph.UpdateValues;
//begin
// //case FKind of
// // gkExpression:
// // begin
// // FSource := FormulaExpression(TFormulaParams(FParams).Formula);
// // if FAutoTitle then SetTitle(FSource); // fire OnGraphChanged
// // end;
// //end;
// //FillValues;
// //UpdateLine;
// //if Assigned(FOwner) then FOwner.DoGraphChangedValues(Self);
//end;
//procedure TGraph.FillValues;
//begin
// //case FKind of
// // gkExpression:
// // PlotMath.PlotFormula(TFormulaParams(FParams), FValuesX, FValuesY);
// //end;
//end;
{%region Editing}
// TODO remove from TGraph to PlotMath
procedure TGraph.Trim(var Param: TTrimParams);
var
Result: Boolean;
BoundValue: TValue;
begin
//Result := False;
//if Param.TrimLeft then
//begin
// if Param.VisibleLeft
// then BoundValue := FSeries.GetHorizAxis.Minimum
// else BoundValue := Param.ValueLeft;
// Result := TrimValuesLeft(FValuesX, FValuesY, BoundValue, Param.RefineLeft);
//end;
//if Param.TrimRight then
//begin
// if Param.VisibleRight
// then BoundValue := FSeries.GetHorizAxis.Maximum
// else BoundValue := Param.ValueRight;
// Result := TrimValuesRight(FValuesX, FValuesY, BoundValue, Param.RefineRight) or Result;
//end;
//if Result and Assigned(FOwner) then FOwner.DoGraphChangedValues(Self);
end;
procedure TGraph.Offset(var Param: TOffsetParams);
begin
case Param.Direction of
adirX:
begin
case Param.Kind of
ofkMax: Param.Value := -FValuesX[MaxValueIndex(FValuesY)];
ofkMin: Param.Value := -FValuesX[MinValueIndex(FValuesY)];
ofkAvg: Param.Value := -AverageValue(FValuesX);
end;
OffsetValues(FValuesX, Param.Value);
end;
adirY: OffsetValues(FValuesY, Param.Kind, Param.Value);
end;
Notify(poGraphChangedValues);
end;
procedure TGraph.Normalize(var Param: TNormalizeParams);
begin
case Param.Direction of
adirX: NormalizeValues(FValuesX, Param.Value, Param.PerMaximum);
adirY: NormalizeValues(FValuesY, Param.Value, Param.PerMaximum);
end;
Notify(poGraphChangedValues);
end;
procedure TGraph.SwapXY;
var
I: Integer;
Tmp: TValue;
begin
for I := 0 to Length(FValuesX)-1 do
begin
Tmp := FValuesX[I];
FValuesX[I] := FValuesY[I];
FValuesY[I] := Tmp;
end;
Notify(poGraphChangedValues);
end;
procedure TGraph.FlipX;
var
I, C, C1: Integer;
Tmp: TValue;
begin
C := Length(FValuesX) - 1;
C1 := Length(FValuesX) div 2 - 1;
for I := 0 to C1 do
begin
Tmp := FValuesY[I];
FValuesY[I] := FValuesY[C-I];
FValuesY[C-I] := Tmp;
end;
Notify(poGraphChangedValues);
end;
procedure TGraph.FlipY;
var
I: Integer;
MinValue, MaxValue: TValue;
begin
//for I := 0 to Length(FValuesY)-1 do
// FValuesY[I] := -1 * FValuesY[I]; // перевернуть
//GetMinMaxY(MinValue, MaxValue);
//for I := 0 to Length(FValuesY)-1 do // на дельту min-max вверх
// FValuesY[I] := FValuesY[I] - MinValue - MaxValue;
//Notify(poGraphChangedValues);
end;
procedure TGraph.Sort;
begin
// TODO: Undo
PlotMath.Sort(FValuesX, FValuesY);
Notify(poGraphChangedValues);
end;
{%endregion Editing}
{%endregion TGraph}
//------------------------------------------------------------------------------
{%region TPlot}
constructor TPlot.Create(AOwner: TPlots; const ATitle: String = '');
begin
FOwner := AOwner;
FItems := TGraphList.Create;
if ATitle = '' then
begin
FTitle := Plot_DefTitle + ' ' + IntToStr(UntitledIndex);
Inc(UntitledIndex);
end
else FTitle := ATitle;
end;
destructor TPlot.Destroy;
begin
Clear;
FreeAndNil(FItems);
inherited;
end;
procedure TPlot.Notify(AOperation: TPlotOperation; AGraph: TGraph);
begin
if Assigned(Owner) then Owner.Notify(AOperation, Self, AGraph);
end;
//procedure TPlot.CreateChart;
//begin
// //FChart := TChart.Create(nil);
// //FChart.Visible := False;
// //FChart.Align := alClient;
// //FChart.BevelInner := bvNone;
// //FChart.BevelOuter := bvNone;
// //FChart.View3D := False;
// //FChart.Legend.LegendStyle := lsSeries;
// //FChart.BackWall.Color := clWhite;
// //FChart.BackWall.Transparent := False;
// //FChart.Zoom.Pen.Color := clGray;
// //FChart.Zoom.Pen.SmallDots := True;
// //FChart.Zoom.Pen.SmallSpace := 2;
// //FChart.BottomAxis.AxisValuesFormat := '#,##0.###############';
// //FChart.LeftAxis.AxisValuesFormat := '#,##0.###############';
// //
// //FSelector := TMultiSelectorTool.Create(FChart);
// //FSelector.AllowMultiSelect := True;
// //FSelector.AllowRightSelect := True;
// //FChart.Tools.Add(FSelector);
// //
// //FHintValuesTool := TMarksTipTool.Create(FChart);
// //FHintValuesTool.Style := smsXY;
// //FChart.Tools.Add(FHintValuesTool);
// //
// //ApplyChartSettings;
//end;
procedure TPlot.ApplyChartSettings;
//var
// I: Integer;
// T: TAxisScrollTool;
begin
//FChart.Zoom.Animated := Preferences.AnimatedChartZoom;
//if Preferences.ScrollAxesByMouse then
//begin
// T := TAxisScrollTool.Create(FChart);
// T.Axis := FChart.BottomAxis;
// FChart.Tools.Add(T);
//
// T := TAxisScrollTool.Create(FChart);
// T.Axis := FChart.LeftAxis;
// FChart.Tools.Add(T);
//end
//else
// for I := FChart.Tools.Count-1 downto 0 do
// if FChart.Tools[I] is TAxisScrollTool then
// begin
// T := TAxisScrollTool(FChart.Tools[I]);
// FChart.Tools.Delete(I);
// T.Free;
// end;
end;
procedure TPlot.Clear;
var
I: Integer;
begin
if FItems.Count > 0 then
begin
for I := 0 to FItems.Count-1 do
TGraph(FItems[I]).Free;
FItems.Clear;
Notify(poGraphDeleted);
end;
// TODO Remove from history all commands referencing graphs of this plot
end;
//function TPlot.AddGraph(Params: TGraphAppendParams; const FileName: String): TGraph;
//var
// InputFiles: TStringList;
//begin
// InputFiles := TStringList.Create;
// try
// InputFiles.Add(FileName);
// Result := AddGraph(Params, InputFiles);
// finally
// InputFiles.Free;
// end;
//end;
(*
function TPlot.AddGraph(Params: TGraphAppendParams; FileNames: TStrings = nil): TGraph;
procedure ProcessMultiReader(AReader: TDataReaderClass);
begin
// Создаем мультиридер прямо здесь, а не в TGraph.Load.
// Результатом работы ReadValues является еще несколько вызовов
// этой процедуры (TPlot.AddGraph), но с уже готовыми данными в
// объекте-параметре (TGraphAppendParams.ValuesX / ValuesY)
with AReader.Create(Params) do
try
if Configure then ReadValues;
finally
Free;
end;
end;
var
I: Integer;
begin
Result := nil;
if Assigned(Params) then
try
Params.Plot := Self;
// Если задан список файлов, то предполагается, что еще никаких потоков не
// открыто (Params.Stream не задан, Params.Source не задействован).
// В этом случае источником данных является файл.
if Assigned(FileNames) then
begin
for I := 0 to FileNames.Count-1 do
try
Params.Source := FileNames[I];
{if FileIsArchive(Params.Source) then
begin
// Если источник данных является архивным файлом, то в данный момент
// создания графика не происходит. Просто открываем окно просмотра архива.
TwndOpenArchive.Create(Params.Source, Self).Show;
end
else} if Assigned(Params.Reader) then
// Если ридер задан, то это значит что в диалоге открытия файлов был
// выбран конкретный фильтр и все файлы пытаемся открыть этим ридером.
// Привязка к фильтру нужна из-за того что одно и то же расширение
// может соотвествовать разным форматам данных (разным ридерам).
begin
if Params.Reader.IsMulti then
// Если ридер может посторить несколько графиков из одного источника
// то график создается не сразу, а в процессе работы мультиридера.
ProcessMultiReader(Params.Reader)
else
// Если это простой ридер, то сразу создаем график
Result := CreateGraph(Params);
end
else
// Если ридер не задан это означает что в диалоге был выбран фильтр
// "Все файлы". Тогда пытаемся определить нужный рилер на основании
// расширения файла. Но т.к. одно и то же расширение может соотвествовать
// разным ридерам, то не обязательно будет использоваться тот ридер,
// кторый нужен для конкретного файла.
begin
Params.Reader := TFileReaders.ReaderByExt(Params.Source);
Result := CreateGraph(Params);
end;
except
on e: Exception do
{$ifndef DBG_IGNORE_LOAD_ERRS}
if I < FileNames.Count-1 then
begin // если не последний файл, то нужно ли открывать оставшиеся
if not MsgBoxYesNo(Constant('Err_ReadData') + #13#13 + e.Message +
#13#13 + Constant('Err_FileTryNext'), [FileNames[I]]) then Break;
end
else
MsgBox(Constant('Err_ReadData') + #13#13 + e.Message, [FileNames[I]], mbError);
{$else}
raise;
{$endif}
end
end
// Если список файлов не задан, то предполагается, что должен быть задан
// либо поток Params.Stream, либо в параметрах передаются уже готовые данные,
// либо ридер сам знает, откуда ему взять данные (как TClipboardDataReader).
else
try
if Assigned(Params.Reader) and Params.Reader.IsMulti then
ProcessMultiReader(Params.Reader)
else
Result := CreateGraph(Params);
except
on e: Exception do
{$ifndef DBG_IGNORE_LOAD_ERRS}
MsgBox(Constant('Err_ReadData') + #13#13 + e.Message, [Params.Source], mbError);
{$else}
raise;
{$endif}
end;
finally
Params.Free;
end;
end;
*)
//function TPlot.AddGraph: TGraph;
//begin
// Result := CreateGraph;
// DoGraphAdded(Result);
//end;
procedure TPlot.AddGraph(AGraph: TGraph; AIndex: Integer = -1; AUndoable: Boolean = True);
begin
if AIndex > -1
then FItems.Insert(AIndex, AGraph)
else FItems.Add(AGraph);
AGraph.FOwner := Self;
if AUndoable then
History.Append(TGraphAppendCommand.Create(AGraph));
Notify(poGraphAdded, AGraph);
end;
//function TPlot.CreateGraph(Params: TGraphAppendParams): TGraph;
//begin
// try
// Result := CreateGraph;
// Result.Load(Params);
// DoGraphAdded(Result);
// except
// FItems.Extract(Result);
// FreeAndNil(Result);
// raise;
// end;
//end;
//
//function TPlot.CreateGraph(Node: IXMLNode): TGraph;
//begin
// try
// Result := CreateGraph;
// Result.LoadXML(Node);
// DoGraphAdded(Result);
// except
// FItems.Extract(Result);
// FreeAndNil(Result);
// raise;
// end;
//end;
//function TPlot.CreateGraph(ATitle: String = ''): TGraph;
//begin
// Result := TGraph.Create(Self);
// Result.FTitle := ATitle;
// Result.FSource := ATitle;
// FItems.Add(Result);
// History.Append(TGraphAppendCommand.Create(Result));
//end;
//procedure TPlot.ExtractGraph(AGraph: TGraph);
//begin
// FItems.Extract(AGraph);
// DoGraphDeleted(AGraph);
//end;
procedure TPlot.DeleteGraph(AGraph: TGraph; AUndoable: Boolean = True);
begin
if AUndoable then
History.Append(TGraphDeleteCommand.Create(AGraph, FItems.IndexOf(AGraph)));
FItems.Extract(AGraph);
Notify(poGraphDeleted, AGraph);
// Do not destroy graph, because of it is required to undo the deletion
end;
{%region Undoable Properties Accessors}
procedure TPlot.SetTitle(Value: String; AUndoable: Boolean = True);
begin
if AUndoable then
History.Append(TPlotTitleEditCommand.Create(Self));
FTitle := Value;
Notify(poPlotChanged);
end;
{%endregion}
{%region Items Access}
function TPlot.IsEmpty: Boolean;
begin
Result := FItems.Count = 0;
end;
function TPlot.GetCount: Integer;
begin
Result := FItems.Count;
end;
function TPlot.GetItems(Index: Integer): TGraph;
begin
Result := TGraph(FItems[Index]);
end;
{%endregion}
{$region Editing}
// TODO remove from TPlot to PlotMath
procedure TPlot.CreateUndoGroup(var Graphs: TGraphArray; const Title: String);
var I: Integer;
begin
//if Length(Graphs) > 1 then
// History.BeginGroup(Constant(Title));
//try
// for I := 0 to Length(Graphs)-1 do
// History.Append(TFullDataGraphCommand.Create(Graphs[I], Title));
//finally
// if History.Groupped then History.EndGroup;
//end;
end;
procedure TPlot.Trim(var Graphs: TGraphArray; var Param: TTrimParams);
var I: Integer;
begin
CreateUndoGroup(Graphs, 'Undo_Trim');
for I := 0 to Length(Graphs)-1 do Graphs[I].Trim(Param);
end;
procedure TPlot.Offset(var Graphs: TGraphArray; var Param: TOffsetParams);
var I: Integer;
begin
CreateUndoGroup(Graphs, 'Undo_Offset');
for I := 0 to Length(Graphs)-1 do Graphs[I].Offset(Param);
end;
procedure TPlot.Flip(var Graphs: TGraphArray; var Param: TMiscParams);
var I: Integer;
begin
CreateUndoGroup(Graphs, 'Undo_Flip');
for I := 0 to Length(Graphs)-1 do
begin
case Param.Direction of
adirX:
begin
FlipValues(Graphs[I].FValuesX, Param.Value);
// При воплнении опрерации Const-X все значения X оказываются
// переставленными в обратном порядке max -> min. В принципе, линия
// графика не сортированная и для отображения ничего страшного в этом
// нет. Но все-таки принято, чтобы график шел от большего к меньшему.
// Поэтому переставляем значения в обратном порядке.
ReorderValues(Graphs[I].FValuesX, Graphs[I].FValuesY);
// TODO: селектор странно себя ведет при обратном расположении
// точек - выделяются все точки. Пока не разбирался.
end;
adirY: FlipValues(Graphs[I].FValuesY, Param.Value);
end;
Notify(poGraphChangedValues, Graphs[I]);
end;
end;
procedure TPlot.Normalize(var Graphs: TGraphArray; var Param: TNormalizeParams);
var I: Integer;
begin
CreateUndoGroup(Graphs, 'Undo_Normalize');
for I := 0 to Length(Graphs)-1 do Graphs[I].Normalize(Param);
end;
procedure TPlot.Scale(var Graphs: TGraphArray; var Param: TScaleParams);
var I: Integer;
begin
CreateUndoGroup(Graphs, 'Undo_Scale');
for I := 0 to Length(Graphs)-1 do
begin
with Param do
case Direction of
adirX: ScaleValues(Graphs[I].FValuesX, CenterKind, CenterValue, Value);
adirY: ScaleValues(Graphs[I].FValuesY, CenterKind, CenterValue, Value);
end;
Notify(poGraphChangedValues, Graphs[I]);
end;
end;
procedure TPlot.Inverse(var Graphs: TGraphArray; var Param: TMiscParams);
var I: Integer;
begin
CreateUndoGroup(Graphs, 'Undo_Inverse');
for I := 0 to Length(Graphs)-1 do
begin
case Param.Direction of
adirX:
begin
InverseValues(Graphs[I].FValuesX, Graphs[I].FValuesY, Param.Value);
// При воплнении опрерации Const/X все значения X оказываются
// переставленными в обратном порядке max -> min. В принципе, линия
// графика не сортированная и для отображения ничего страшного в этом
// нет. Но все-таки принято, чтобы график шел от большего к меньшему.
// Поэтому переставляем значения в обратном порядке.
ReorderValues(Graphs[I].FValuesX, Graphs[I].FValuesY);
// TODO: селектор странно себя ведет при обратном расположении
// точек - выделяются все точки. Пока не разбирался.
end;
adirY: InverseValues(Graphs[I].FValuesY, Graphs[I].FValuesX, Param.Value);
end;
Notify(poGraphChangedValues, Graphs[I]);
end;
end;
procedure TPlot.SwapXY(var Graphs: TGraphArray);
var I: Integer;
begin
// TODO: make resort X values after swapping
for I := 0 to Length(Graphs)-1 do Graphs[I].SwapXY;
//History.Append(TReversibleGraphCommand.Create(Graphs, rgkSwapXY));
end;
procedure TPlot.FlipX(var Graphs: TGraphArray);
var I: Integer;
begin
for I := 0 to Length(Graphs)-1 do Graphs[I].FlipX;
//History.Append(TReversibleGraphCommand.Create(Graphs, rgkFlipX));
end;
procedure TPlot.FlipY(var Graphs: TGraphArray);
var I: Integer;
begin
CreateUndoGroup(Graphs, 'Undo_FlipY');
for I := 0 to Length(Graphs)-1 do Graphs[I].FlipY;
end;
procedure TPlot.Despike(var Graphs: TGraphArray; var Params: TDespikeParams);
var
I: Integer;
begin
CreateUndoGroup(Graphs, 'Undo_Despike');
for I := 0 to Length(Graphs)-1 do
begin
case Params.Kind of
drPercent: DespikePer(Graphs[I].FValuesY, Params.Min, Params.Max);
drAbsolute: DespikeAbs(Graphs[I].FValuesY, Params.Min, Params.Max);
end;
Notify(poGraphChangedValues, Graphs[I]);
end;
end;
{$endregion}
{$region Load/Save}
{procedure TPlot.SaveXML(Node: IXMLNode);
var
i: Integer;
child, tmp: IXMLNode;
begin
// save common plot settings
Node.Attributes['Title'] := FTitle;
with Node.AddChild('Factors') do
begin
Attributes['X'] := FactorX;
Attributes['Y'] := FactorY;
end;
// chart settings
child := Node.AddChild('PlotSettings');
TeeStoreXML.WriteChartSettings(child, FChart);
child := Node.AddChild('AxesLimits');
TeeStoreXML.WriteAxesLimits(child, FChart);
// save each graph
child := Node.AddChild('Graphs');
for i := 0 to FItems.Count-1 do
begin
tmp := child.AddChild('Graph');
TGraph(FItems[i]).SaveXML(tmp);
end;
// save chart notes
child := Node.AddChild('Annotations');
for i := 0 to Chart.Tools.Count-1 do
if Chart.Tools[i] is TAnnotationTool then
TeeStoreXML.WriteNoteSettings(child,
'Annotation', TAnnotationTool(Chart.Tools[i]));
end; }
{procedure TPlot.LoadXML(Node: IXMLNode);
var
i: Integer;
child: IXMLNode;
nodes: IXMLNodeList;
begin
// load common plot settings
FTitle := Node.Attributes['Title'];
child := Node.ChildNodes.FindNode('Factors');
if child <> nil then
begin
FactorX := child.Attributes['X'];
FactorY := child.Attributes['Y'];
end;
// chart settings
{$ifndef DBG_IGNORE_LOAD_ERRS}
try
{$endif}
child := Node.ChildNodes.FindNode('PlotSettings');
if child <> nil then ReadChartSettings(child, FChart);
child := Node.ChildNodes.FindNode('AxesLimits');
if child <> nil then ReadAxesLimits(child, FChart);
{$ifndef DBG_IGNORE_LOAD_ERRS}
except
on e: Exception do
MsgBoxDK('PlotErr_LoadFormat', [FTitle, e.ClassName, e.Message], mbError);
// TODO: ошибки надо отлавливать и где-то хранить, а сообщение
// выдавать только по окончание загрузки всего проекта
end;
{$endif}
// load each graph
child := Node.ChildNodes.FindNode('Graphs');
if child <> nil then
begin
nodes := child.ChildNodes;
for i := 0 to nodes.Count-1 do CreateGraph(nodes[i]);
// TODO: хорошо ли это - прекращать загрузку диаграммы, если
// один из графиков загрузился с ошибкой
end;
// load chart notes
child := Node.ChildNodes.FindNode('Annotations');
if child <> nil then
begin
nodes := child.ChildNodes;
for i := 0 to nodes.Count-1 do CreateNote(nodes[i]);
// TODO: отловить исключения, т.к. ошибки при загрузки
// примечаний не критичны для загрузки всего проекта
end;
end; }
{$endregion}
{$region Chart tools work}
{function TPlot.CreateNote(Node: IXMLNode): TAnnotationTool;
begin
try
Result := TAnnotationTool.Create(Chart);
ReadNoteSettings(Node, Result);
Chart.Tools.Add(Result);
except
FreeAndNil(Result);
raise;
end;
end;}
{$endregion}
{%region Calc and Draw procs}
// TODO remove from TPlot to PlotMath
procedure TPlot.Differentiate(var Graphs: TGraphArray);
var
I: Integer;
DiffY: TValueArray;
Graph: TGraph;
begin
if Length(Graphs) > 1 then
History.BeginGroup(Undo_AddGraph);
try
for I := 0 to Length(Graphs)-1 do
begin
PlotMath.Differentiate(Graphs[I].ValuesX, Graphs[I].ValuesY, DiffY);
// Graph := CreateGraph(Format('Derivative(%s)', [Graphs[I].Title]));
Graph.SetValuesXY(Graphs[I].ValuesX, DiffY);
Notify(poGraphAdded, Graph);
end;
finally
if History.Groupped then History.EndGroup;
end;
end;
procedure TPlot.Differentiate2(var Graphs: TGraphArray);
var
I: Integer;
DiffY: TValueArray;
Graph: TGraph;
begin
if Length(Graphs) > 1 then
History.BeginGroup(Undo_AddGraph);
try
for I := 0 to Length(Graphs)-1 do
begin
PlotMath.Differentiate2(Graphs[I].ValuesX, Graphs[I].ValuesY, DiffY);
if Length(DiffY) > 1 then
begin
// Graph := CreateGraph(Format('Derivative2(%s)', [Graphs[I].Title]));
Graph.SetValuesXY(Copy(Graphs[I].ValuesX, 1, Length(Graphs[I].ValuesX)-2), DiffY);
Notify(poGraphAdded, Graph);
end;
end;
finally
if History.Groupped then History.EndGroup;
end;
end;
procedure TPlot.Regularity(var Graphs: TGraphArray);
var
I: Integer;
X, Y: TValueArray;
Graph: TGraph;
begin
if Length(Graphs) > 1 then
History.BeginGroup(Undo_AddGraph);
try
for I := 0 to Length(Graphs)-1 do
begin
PlotMath.Regularity(Graphs[I].ValuesX, X, Y);
// Graph := CreateGraph(Format('Regularity(%s)', [Graphs[I].Title]));
Graph.SetValuesXY(X, Y);
Notify(poGraphAdded, Graph);
end;
finally
if History.Groupped then History.EndGroup;
end;
end;
procedure TPlot.Midline(var Graphs: TGraphArray);
begin
end;
procedure TPlot.Envelope(var Graphs: TGraphArray; IsTop: Boolean);
//var
// I, J: Integer;
// overlap: TGraphRec2;
// gr1, gr2: TGraphRec;
begin
//gr1 := GraphToRec(Graphs[0]);
//for I := 1 to Length(Graphs)-1 do
//begin
// gr2 := GraphToRec(Graphs[I]);
// overlap := CalcOverlapGraph(gr1, gr2, True);
// gr1.X := overlap.X;
// SetLength(gr1.Y, Length(overlap.X));
// if IsTop then
// for J := 0 to Length(overlap.X)-1 do
// gr1.Y[J] := Max(overlap.Y1[J], overlap.Y2[J])
// else
// for J := 0 to Length(overlap.X)-1 do
// gr1.Y[J] := Min(overlap.Y1[J], overlap.Y2[J]);
//end;
//AddGraph(TGraphAppendParams.Create(@gr1.X, @gr1.Y, 'Envelope'));
end;
procedure TPlot.GroupOperation(var Graphs: TGraphArray; Operation: TGroupOperation);
const
FuncName: array[TGroupOperation] of String = ('Sum', 'Difference', 'Product', 'Quotient');
//var
// I, J: Integer;
// gr1, gr2: TGraphRec;
// Overlap: TGraphRec2;
begin
//gr1 := GraphToRec(Graphs[0]);
//for I := 1 to Length(Graphs)-1 do
//begin
// gr2 := GraphToRec(Graphs[I]);
// Overlap := PlotMath.CalcOverlapGraph(gr1, gr2);
// gr1.X := Overlap.X;
// SetLength(gr1.Y, Length(Overlap.X));
// case Operation of
// gropSum:
// for J := 0 to Length(Overlap.X)-1 do
// gr1.Y[J] := Overlap.Y1[J] + Overlap.Y2[J];
// gropDiff:
// for J := 0 to Length(Overlap.X)-1 do
// gr1.Y[J] := Overlap.Y1[J] - Overlap.Y2[J];
// gropProd:
// for J := 0 to Length(Overlap.X)-1 do
// gr1.Y[J] := Overlap.Y1[J] * Overlap.Y2[J];
// gropQuot:
// for J := 0 to Length(Overlap.X)-1 do
// gr1.Y[J] := Overlap.Y1[J] / Overlap.Y2[J];
// end;
//end;
//AddGraph(TGraphAppendParams.Create(@gr1.X, @gr1.Y, FuncName[Operation]));
end;
procedure TPlot.Variance(var Graphs: TGraphArray; var Param: TVarianceParams);
var
I: Integer;
Plot: TPlot;
Graph: TGraph;
AllanX, AllanY: TValueArray;
begin
Plot := Owner.AddPlot;
if Length(Graphs) > 1 then
History.BeginGroup(Undo_AddGraph);
try
for I := 0 to Length(Graphs)-1 do
begin
PlotMath.Variance(Graphs[I].ValuesX, Graphs[I].ValuesY, AllanX, AllanY);
//Graph := Plot.CreateGraph(Format('%s(%s)',
//[VarianceNames[Param.Kind], Graphs[I].Title]));
Graph.SetValuesXY(AllanX, AllanY);
Notify(poGraphAdded, Graph);
end;
finally
if History.Groupped then History.EndGroup;
end;
end;
{%endregion}
{%endregion TPlot}
////////////////////////////////////////////////////////////////////////////////
{%region TPlots}
constructor TPlots.Create;
begin
FUntitled := True;
FItems := TPlotList.Create;
end;
destructor TPlots.Destroy;
begin
Clear;
FItems.Free;
FNotifyClients.Free;
inherited;
end;
procedure TPlots.SetModified(Value: Boolean);
begin
if FModified <> Value then
begin
FModified := Value;
Notify(poModified);
end;
end;
procedure TPlots.Clear;
var
I: Integer;
begin
if FItems.Count > 0 then
begin
for I := FItems.Count-1 downto 0 do
begin
Notify(poPlotDestroyed, FItems[I], nil);
FItems[I].Clear;
end;
for I := FItems.Count-1 downto 0 do FItems[I].Free;
FItems.Clear;
Notify(poPlotDestroyed);
end;
end;
function TPlots.AddPlot(const ATitle: String = ''): TPlot;
begin
Result := CreatePlot(ATitle);
Notify(poPlotAdded, Result);
end;
//function TPlots.AddPlot(Node: IXMLNode): TPlot;
//begin
// try
// Result := CreatePlot;
// Result.LoadXML(Node);
// DoPlotAdded(Result);
// except
// FItems.Extract(Result);
// FreeAndNil(Result);
// raise;
// end;
//end;
function TPlots.CreatePlot(const ATitle: String = ''): TPlot;
begin
Result := TPlot.Create(Self, ATitle);
FItems.Add(Result);
end;
procedure TPlots.DeletePlot(Index: Integer);
begin
DeletePlot(TPlot(FItems[Index]));
end;
procedure TPlots.DeletePlot(APlot: TPlot);
begin
Notify(poPlotDestroying, APlot);
FItems.Extract(APlot);
Notify(poPlotDestroyed, APlot);
APlot.Free;
end;
{%region Enumerate Plots}
function TPlots.GetCount: Integer;
begin
Result := FItems.Count;
end;
function TPlots.GetItems(Index: Integer): TPlot;
begin
Result := TPlot(FItems[Index]);
end;
function TPlots.IndexOf(APlot: TPlot): Integer;
begin
Result := FItems.IndexOf(APlot);
end;
{%endregion}
{%region Load/Save}
function TPlots.Load: Boolean;
begin
//with TOpenDialog.Create(nil) do
//try
// Title := Constant('Proj_LoadDlg');
// Filter := Constant('Proj_FileFilter');
// FilterIndex := Preferences.ProjectOpenFilter;
// InitialDir := Preferences.ProjectOpenCurDir;
// DefaultExt := CDefProjectExt;
// Options := Options + [ofOverwritePrompt];
// Result := Execute;
// if Result then
// begin
// Preferences.ProjectOpenFilter := FilterIndex;
// Preferences.ProjectOpenCurDir := ExtractFilePath(FileName);
// Load(FileName, IsProjectPacked(FileName));
// end;
//finally
// Free;
//end;
end;
procedure TPlots.Load(const AFileName: String; APacked: Boolean);
//var
// SavedCur: TCursor;
begin
//SavedCur := Screen.Cursor;
//Screen.Cursor := crHourGlass;
//Include(FStatus, pssLoading);
//History.Active := False;
//try
// Reset(True);
// LoadXML(AFileName, APacked);
// FUntitled := False;
// FPacked := APacked;
// FFileName := AFileName;
// DoProjectLoaded;
//finally
// History.Active := True;
// Exclude(FStatus, pssLoading);
// Screen.Cursor := SavedCur;
//end;
//History.Clear;
end;
function TPlots.Save(APlot: TPlot = nil): Boolean;
//var
// SavedCur: TCursor;
begin
//if not FUntitled then
//begin
// SavedCur := Screen.Cursor;
// Screen.Cursor := crHourGlass;
// try
// SaveXML(APlot);
// finally
// Screen.Cursor := SavedCur;
// end;
// if APlot = nil then
// DoProjectSaved;
// Result := True;
//end
//else Result := SaveAs(APlot);
end;
function TPlots.SaveAs(APlot: TPlot = nil): Boolean;
begin
//with TSaveDialog.Create(nil) do
//try
// Title := Constant('Proj_SaveDlg');
// Filter := Constant('Proj_FileFilter');
// FilterIndex := Preferences.ProjectOpenFilter;
// InitialDir := Preferences.ProjectOpenCurDir;
// DefaultExt := CDefProjectExt;
// Options := Options + [ofOverwritePrompt];
// FileName := ExtractFileName(FFileName);
// Result := Execute;
// if Result then
// begin
// Preferences.ProjectOpenFilter := FilterIndex;
// Preferences.ProjectOpenCurDir := ExtractFilePath(FileName);
// FUntitled := False;
// FPacked := FilterIndex = 2;
// FFileName := FileName;
// Save(APlot);
// end;
//finally
// Free;
//end;
end;
//procedure TPlots.SaveXML(APlot: TPlot);
//var
// ProjRoot: IXMLNode;
// OutFile: TFileStream;
// Zip: TCompressionStream;
//begin
// with TXMLDocument.Create(Application) do
// try
// Active := True;
// Version := '1.0';
// Encoding := 'utf-8';
// StandAlone := 'yes';
// if not FPacked then
// Options := Options + [doNodeAutoIndent];
//
// ProjRoot := Node.AddChild('SpectrumProject');
// ProjRoot.Attributes['Version'] := PROJECT_VER;
// SaveXML(ProjRoot, APlot);
//
// if FPacked then
// begin
// OutFile := TFileStream.Create(FFileName, fmCreate, fmShareExclusive);
// Zip := TCompressionStream.Create(clDefault, outFile);
// try
// XML.SaveToStream(Zip);
// finally
// Zip.Free;
// OutFile.Free;
// end;
// end
// else XML.SaveToFile(FFileName);
// finally
// Free;
// end;
//end;
//procedure TPlots.SaveXML(Node: IXMLNode; APlot: TPlot);
//var
// i: Integer;
// child: IXMLNode;
//begin
// // save common project settings
//
// if Assigned(APlot) then
// begin
// child := Node.AddChild('Plot');
// APlot.SaveXML(child);
// end
// else
// for i := 0 to FItems.Count-1 do
// begin
// child := Node.AddChild('Plot');
// TPlot(Items[i]).SaveXML(child);
// end;
//end;
{procedure TPlots.LoadXML(const AFileName: String; APacked: Boolean);
var
ProjRoot: IXMLNode;
InFile: TFileStream;
Zip: TDecompressionStream;
begin
{$ifndef DBG_IGNORE_LOAD_ERRS}
try
{$endif}
if not FileExists(AFileName) then
raise ESpectrumError.CreateFmtDK('ProjErr_DoesNotExist', [AFileName]);
with TXMLDocument.Create(Application) do
try
if APacked then
begin
InFile := TFileStream.Create(AFileName, fmOpenRead, fmShareDenyWrite);
Zip := TDecompressionStream.Create(InFile);
try
XML.LoadFromStream(Zip);
finally
Zip.Free;
InFile.Free;
end;
end
else XML.LoadFromFile(AFileName);
Active := True;
ProjRoot := ChildNodes.FindNode('SpectrumProject');
if ProjRoot = nil then
raise ESpectrumError.CreateDK('ProjErr_NoRoot');
if ProjRoot.Attributes['Version'] <> PROJECT_VER then
raise ESpectrumError.CreateDK('ProjErr_WrongVersion');
LoadXML(ProjRoot);
finally
Free;
end;
{$ifndef DBG_IGNORE_LOAD_ERRS}
except
on e: Exception do
raise ESpectrumError.CreateFmtDK('ProjErr_Load', [AFileName, e.Message]);
end;
{$endif}
end; }
//procedure TPlots.LoadXML(Node: IXMLNode);
//var
// i: Integer;
// child: IXMLNode;
// nodes: IXMLNodeList;
//begin
// // load common project settings
//
// // load each plot
// nodes := Node.ChildNodes;
// for i := 0 to nodes.Count-1 do
// begin
// child := nodes[i];
// if WideSameText(child.NodeName, 'Plot') then AddPlot(child);
// end;
//end;
{%endregion}
function TPlots.Reset(Silent: Boolean; Mode: Integer): Boolean;
begin
{if not Silent then
with TwndProjReset.Create(Application) do
try
Result := ShowModal = mrOk;
if not Result then Exit;
Mode := ResetMode;
finally
Free;
end
else Result := True;}
{case Mode of
1: // keep plots
for i := 0 to FItems.Count-1 do
TPlot(FItems[i]).Clear;
2: // delete all
Clear;
end;}
Notify(poProjectReseting);
Clear;
//History.Clear;
FFileName := '';
FUntitled := True;
FPacked := False;
UntitledIndex := 1;
Notify(poProjectReset);
Result := True;
end;
function TPlots.CanReset: Boolean;
var
Msg: String;
begin
//Result := True;
//if Modified then
//begin
// if FUntitled
// then Msg := Constant('Proj_SaveReq1')
// else Msg := Format(Constant('Proj_SaveReq'), [FFileName]);
// case AppMessageDlg(Msg, mtConfirmation, mbYesNoCancel) of
// mrCancel: Result := False;
// mrYes: Result := Save;
// end;
//end;
end;
{%region Notifications}
procedure TPlots.RegisterNotifyClient(AObject: TObject);
begin
if FNotifyClients = nil then
begin
FNotifyClients := TObjectList.Create(False);
FNotifyClients.Add(AObject);
end
else if FNotifyClients.IndexOf(AObject) = -1 then
FNotifyClients.Add(AObject)
end;
procedure TPlots.UnRegisterNotifyClient(AObject: TObject);
begin
if Assigned(FNotifyClients) then
begin
FNotifyClients.Extract(AObject);
if FNotifyClients.Count = 0 then
FreeAndNil(FNotifyClients);
end;
end;
function TPlots.GetNotifyClient(AClass: TClass): TObject;
var I: Integer;
begin
Result := nil;
if Assigned(FNotifyClients) then
for I := 0 to FNotifyClients.Count-1 do
if FNotifyClients[I] is AClass then
begin
Result := FNotifyClients[I];
Break;
end;
end;
procedure TPlots.Notify(AOperation: TPlotOperation; APlot: TPlot; AGraph: TGraph);
var
I: Integer;
Intf: IPlotNotification;
begin
if AOperation in ModifyingOperations then
Modified := True
else if AOperation in SavingOperations then
Modified := False;
if Assigned(FNotifyClients) then
for I := FNotifyClients.Count-1 downto 0 do
if FNotifyClients[I].GetInterface(IPlotNotification, Intf) then
Intf.Notify(AOperation, APlot, AGraph);
end;
{%endregion}
{%endregion TPlots}
end.
|
unit MobileDays.ListVertFrame.Mobile.Controller.SMPessoa;
interface
uses
System.Classes,
System.SysUtils,
System.Variants,
System.IOUtils,
{Uses necessarias para uso do FDMemTable}
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.StorageBin, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
FMX.Controls.Presentation, FMX.StdCtrls
{Uses necessarias para uso do FDMemTable}
{Uses necessarias para uso do dataset-serialize}
// GitHub: https://github.com/viniciussanchez/dataset-serialize
, DataSet.Serialize
{Uses necessarias para uso do dataset-serialize}
;
type
TSMPessoa = class
private
{ private declarations }
protected
{ protected declarations }
public
class function GetJson(ADs: TDataSet): string;
class function GetPessoa(const AFirst, AShow: Integer): TFDMemTable;
{ public declarations }
published
{ published declarations }
end;
implementation
{ TSMPessoa }
class function TSMPessoa.GetJson(ADs: TDataSet): string;
begin
Result := ADs.ToJSONArrayString;
end;
class function TSMPessoa.GetPessoa(const AFirst, AShow: Integer): TFDMemTable;
var
LStrLst: TStringList;
LFdMem: TFDMemTable;
LPathFile: string;
begin
Result := TFDMemTable.Create(nil);
try
LFdMem := TFDMemTable.Create(nil);
{$REGION 'Abstrair'}
{
Processo de Get do Servidor ou Select local
}
LStrLst := TStringList.Create;
try
{$IFDEF MSWINDOWS}
LPathFile := 'C:\Fontes Sistemas\Mobile Days\List-VertScrollBox-Frame\Lib\Files\MOCK_DATA.json';
{$ELSE}
LPathFile := System.IOUtils.TPath.GetDocumentsPath;
LPathFile := System.IOUtils.TPath.Combine(LPathFile, 'MOCK_DATA.json');
{$ENDIF}
if not(FileExists(LPathFile)) then
StrToInt('1');
LStrLst.LoadFromFile(LPathFile);
try
{$ZEROBASEDSTRINGS ON}
LFdMem.LoadFromJSON(LStrLst.Text);
finally
{$ZEROBASEDSTRINGS OFF}
end;
LFdMem.First;
// Remove registros maiores do que o limite de apresentacao desejado
while LFdMem.RecordCount > (AShow + AFirst) do
begin
LFdMem.RecNo := AShow + AFirst + 1;
LFdMem.Delete;
end;
// Remove registros maiores do que o limite de apresentacao desejado
while LFdMem.RecordCount > AShow do
begin
LFdMem.RecNo := 0;
LFdMem.Delete;
end;
finally
FreeAndNil(LStrLst);
end;
// **************
{$ENDREGION}
{$REGION 'Abstrair'}
{
Desencapsular o retorno e traduzir para algum formato conhecido
}
Result.CopyDataSet(LFdMem, [coStructure, coRestart, coAppend]);
// **************
{$ENDREGION}
finally
FreeAndNil(LFdMem);
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXOdbcMetaDataReader;
interface
uses
System.Classes,
Data.DBXCommon,
Data.DBXCommonTable,
Data.DBXMetaDataNames,
Data.DBXMetaDataReader,
Data.DBXOdbc,
Data.DBXPlatform,
System.SysUtils;
type
/// <summary> TDBXOdbcCustomMetaDataReader contains custom code for Odbc.
/// </summary>
/// <remarks> This class handles data types and type mapping for table columns and
/// procedure parameters.
/// </remarks>
TDBXOdbcCustomMetaDataReader = class(TDBXBaseMetaDataReader)
private
FAlltypes: TDBXDataTypeDescriptionArray;
public
destructor Destroy; override;
end;
TDBXOdbcMetaDataReader = class(TDBXOdbcCustomMetaDataReader)
private
FConnectionHandle: OdbcHandle;
FOdbcConnection: TDBXOdbcConnection;
FDataTypeDescriptions: TDBXDataTypeDescriptionArray;
FIndexKeyword: Word;
//Value of 0 indicates no limit or unknown
FMaxConcurrentActivities: Word;
FReservedWords: TStrings;
FCatalogsSupported: Boolean;
FSchemasSupported: Boolean;
FSupportsMultipleTransactions: Boolean;
FSqlIdentifierQuoteChar: string;
FSqlIdentifierCase: Word;
FSupportsParameterMetaData: Boolean;
FTransactionCapable: Word;
FInitialized: Boolean;
procedure CheckInitialized;
procedure CheckResult(ReturnValue: SmallInt);
procedure Init;
procedure SetDataTypeDescriptions;
procedure SetReservedWords(Buffer: TArray<Byte>);
function SqlTablesInvocation(CommandText, Catalog, Schema, TableName, TableType: string): TDBXTable;
protected
function AreCatalogFunctionsSupported: Boolean; override;
function AreCatalogsSupported: Boolean; override;
function AreSchemasSupported: Boolean; override;
function GetDataTypeDescriptions: TDBXDataTypeDescriptionArray; override;
function GetProductName: string; override;
function GetReservedWords: TDBXStringArray; override;
function GetSqlIdentifierQuoteChar: string; override;
function GetSqlIdentifierQuotePrefix: string; override;
function GetSqlIdentifierQuoteSuffix: string; override;
function GetSqlProcedureQuoteChar: string; override;
function IsDescendingIndexSupported: Boolean; override;
function IsLowerCaseIdentifiersSupported: Boolean; override;
function IsMultipleCommandsSupported: Boolean; override;
function IsNestedTransactionsSupported: Boolean; override;
function IsParameterMetadataSupported: Boolean; override;
function IsQuotedIdentifiersSupported: Boolean; override;
function IsSetRowSizeSupported: Boolean; override;
function IsTransactionsSupported: Boolean; override;
function IsUpperCaseIdentifiersSupported: Boolean; override;
procedure PopulateDataTypes(const Hash: TDBXObjectStore; const Types: TDBXArrayList; const Descr: TDBXDataTypeDescriptionArray); override;
public
constructor Create; overload;
constructor Create(OdbcConnection: TDBXOdbcConnection); overload;
destructor Destroy; override;
function FetchCatalogs: TDBXTable; override;
function FetchColumns(const Catalog: string; const Schema: string; const Table: string): TDBXTable; override;
function FetchForeignKeyColumns(const Catalog: string; const Schema: string; const Table: string; const ForeignKeyName: string; const PrimaryCatalog: string; const PrimarySchema: string; const PrimaryTable: string; const PrimaryKeyName: string): TDBXTable; override;
function FetchForeignKeys(const Catalog: string; const Schema: string; const Table: string): TDBXTable; override;
function FetchIndexColumns(const Catalog: string; const Schema: string; const Table: string; const Index: string): TDBXTable; override;
function FetchIndexes(const Catalog: string; const Schema: string; const Table: string): TDBXTable; override;
function FetchPackageProcedureParameters(const Catalog: string; const Schema: string; const PackageName: string; const ProcedureName: string; const ParameterName: string): TDBXTable; override;
function FetchPackageProcedures(const Catalog: string; const Schema: string; const PackageName: string; const ProcedureName: string; const ProcedureType: string): TDBXTable; override;
function FetchPackages(const Catalog: string; const Schema: string; const PackageName: string): TDBXTable; override;
function FetchPackageSources(const Catalog: string; const Schema: string; const PackageName: string): TDBXTable; override;
function FetchProcedures(const Catalog: string; const Schema: string; const ProcedureName: string; const ProcedureType: string): TDBXTable; override;
function FetchProcedureParameters(const Catalog: string; const Schema: string; const Proc: string; const Parameter: string): TDBXTable; override;
function FetchProcedureSources(const Catalog: string; const Schema: string; const Proc: string): TDBXTable; override;
function FetchRoles: TDBXTable; override;
function FetchSchemas(const Catalog: string): TDBXTable; override;
function FetchSynonyms(const Catalog: string; const Schema: string; const Synonym: string): TDBXTable; override;
function FetchTables(const Catalog: string; const Schema: string; const TableName: string; const TableType: string): TDBXTable; override;
function FetchUsers: TDBXTable; override;
function FetchViews(const Catalog: string; const Schema: string; const View: string): TDBXTable; override;
end;
TDBXOdbcColumnsTableCursor = class(TDBXColumnsTableCursor)
private
FDataTypesRow: TDBXSingleValueRow;
protected
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
public
constructor Create(const Reader: TDBXBaseMetaDataReader; const CheckBase: Boolean; const Cursor: TDBXTable);
destructor Destroy; override;
function Next: Boolean; override;
end;
TDBXOdbcProcedureParametersIndex = class
public
const CatalogName = 0;
const SchemaName = 1;
const TableName = 2;
const ColumnName = 3;
const Mode = 4;
const SqlDataType = 5;
const TypeName = 6;
const ColumnSize = 7;
const BufferLength = 8;
const Scale = 9;
const NumPrecRadix = 10;
const IsNullable = 11;
const Remarks = 12;
const ColumnDef = 13;
const DescSqlDataType = 14;
const SqlDatetimeSub = 15;
const CharOctetLength = 16;
const Ordinal = 17;
const IsNullableChar = 18;
const DbxDataType = 19;
const ParameterMode = 20;
const IsFixedLength = 21;
const Last = 21;
end;
TDBXOdbcColumnsIndex = class
public
const CatalogName = 0;
const SchemaName = 1;
const TableName = 2;
const ColumnName = 3;
const SqlDataType = 4;
const TypeName = 5;
const ColumnSize = 6;
const BufferLength = 7;
const Scale = 8;
const NumPrecRadix = 9;
const IsNullable = 10;
const Remarks = 11;
const ColumnDef = 12;
const DescSqlDataType = 13;
const SqlDatetimeSub = 14;
const CharOctetLength = 15;
const Ordinal = 16;
const IsNullableChar = 17;
const Last = 17;
end;
implementation
uses
Data.DBXCommonResStrs, Data.DBXMetaDataCommandFactory, System.Odbc;
destructor TDBXOdbcCustomMetaDataReader.Destroy;
begin
FreeObjectArray(TDBXFreeArray(FAlltypes));
inherited Destroy;
end;
procedure TDBXOdbcMetaDataReader.CheckInitialized;
begin
if not FInitialized then
Init;
end;
procedure TDBXOdbcMetaDataReader.CheckResult(ReturnValue: SmallInt);
var
Context: TDBXContext;
begin
if (ReturnValue <> SQL_SUCCESS) and (ReturnValue <> SQL_SUCCESS_WITH_INFO) then
begin
Context := TDBXContext.Create;
try
OdbcRaiseError(Context, ReturnValue, SQL_HANDLE_DBC, FConnectionHandle);
finally
Context.Free;
end;
end;
end;
procedure TDBXOdbcMetaDataReader.Init;
var
ErrorCode, ReturnLength: SmallInt;
Buffer: TArray<Byte>;
begin
if not Assigned(FOdbcConnection) then
begin
FOdbcConnection := TDBXOdbcConnection(TDBXDataExpressProviderContext(Self.Context).Connection);
FConnectionHandle := FOdbcConnection.ConnectionHandle;
end;
//(Character + null) * SizeOf(Char)
SetLength(Buffer, 4);
ErrorCode := SQLGetInfo(FConnectionHandle, SQL_IDENTIFIER_QUOTE_CHAR,
SQLPOINTER(@Buffer[0]), Length(Buffer), ReturnLength);
CheckResult(ErrorCode);
FSqlIdentifierQuoteChar := TMarshal.ReadStringAsAnsi(TPtrWrapper.Create(Buffer)).Trim;
ErrorCode := SQLGetInfo(FConnectionHandle, SQL_DESCRIBE_PARAMETER,
SQLPOINTER(@Buffer[0]), Length(Buffer), ReturnLength);
CheckResult(ErrorCode);
if PChar(@Buffer[0])^ = 'Y' then
FSupportsParameterMetaData := True
else
FSupportsParameterMetaData := False;
ErrorCode := SQLGetInfo(FConnectionHandle, SQL_MULTIPLE_ACTIVE_TXN,
SQLPOINTER(@Buffer[0]), Length(Buffer), ReturnLength);
CheckResult(ErrorCode);
if PChar(@Buffer[0])^ = 'Y' then
FSupportsMultipleTransactions := True
else
FSupportsMultipleTransactions := False;
ErrorCode := SQLGetInfo(FConnectionHandle, SQL_CATALOG_NAME,
SQLPOINTER(@Buffer[0]), Length(Buffer), ReturnLength);
CheckResult(ErrorCode);
if PChar(@Buffer[0])^ = 'Y' then
FCatalogsSupported := True
else
FCatalogsSupported := False;
ErrorCode := SQLGetInfo(FConnectionHandle, SQL_INDEX_KEYWORDS,
SQLPOINTER(@Buffer[0]), Length(Buffer), ReturnLength);
CheckResult(ErrorCode);
FIndexKeyword := PWord(@Buffer[0])^;
ErrorCode := SQLGetInfo(FConnectionHandle, SQL_CREATE_SCHEMA,
SQLPOINTER(@Buffer[0]), Length(Buffer), ReturnLength);
CheckResult(ErrorCode);
if (PInteger(@Buffer[0])^ and SQL_CS_CREATE_SCHEMA) = SQL_CS_CREATE_SCHEMA then
FSchemasSupported := True
else
FSchemasSupported := False;
SetLength(Buffer, SizeOf(Word));
ErrorCode := SQLGetInfo(FConnectionHandle, SQL_IDENTIFIER_CASE,
SQLPOINTER(@Buffer[0]), Length(Buffer), ReturnLength);
CheckResult(ErrorCode);
FSqlIdentifierCase := PWord(@Buffer[0])^;
ErrorCode := SQLGetInfo(FConnectionHandle, SQL_MAX_CONCURRENT_ACTIVITIES,
SQLPOINTER(@Buffer[0]), Length(Buffer), ReturnLength);
CheckResult(ErrorCode);
FMaxConcurrentActivities := PWord(@Buffer[0])^;
ErrorCode := SQLGetInfo(FConnectionHandle, SQL_TXN_CAPABLE,
SQLPOINTER(@Buffer[0]), Length(Buffer), ReturnLength);
CheckResult(ErrorCode);
FTransactionCapable := PWord(@Buffer[0])^;
ErrorCode := SQLGetInfo(FConnectionHandle, SQL_KEYWORDS,
SQLPOINTER(@Buffer[0]), 2, ReturnLength);
CheckResult(ErrorCode);
SetLength(Buffer, (ReturnLength+1)*SizeOf(Char));
ErrorCode := SQLGetInfo(FConnectionHandle, SQL_KEYWORDS,
SQLPOINTER(@Buffer[0]), Length(Buffer), ReturnLength);
CheckResult(ErrorCode);
SetReservedWords(Buffer);
SetDataTypeDescriptions;
FInitialized := True;
end;
procedure TDBXOdbcMetaDataReader.SetDataTypeDescriptions;
function GetDbxDataType(SQLDataType: SmallInt; var SubType: SmallInt): SmallInt;
begin
SubType := 0;
case SQLDataType of
SQL_CHAR:
begin
Result := TDBXDataTypes.AnsiStringType;
SubType := TDBXSubDataTypes.FixedSubType;
end;
SQL_VARCHAR: Result := TDBXDataTypes.AnsiStringType;
SQL_LONGVARCHAR:
begin
Result := TDBXDataTypes.BlobType;
SubType := TDBXSubDataTypes.MemoSubType;
end;
SQL_WCHAR:
begin
Result := TDBXDataTypes.WideStringType;
SubType := TDBXSubDataTypes.FixedSubType;
end;
SQL_WVARCHAR: Result := TDBXDataTypes.WideStringType;
SQL_WLONGVARCHAR:
begin
Result := TDBXDataTypes.BlobType;
SubType := TDBXSubDataTypes.WideMemoSubType;
end;
SQL_DECIMAL, SQL_NUMERIC: Result := TDBXDataTypes.BcdType;
SQL_SMALLINT: Result := TDBXDataTypes.Int16Type;
SQL_INTEGER: Result := TDBXDataTypes.Int32Type;
SQL_REAL: Result := TDBXDataTypes.SingleType;
SQL_DOUBLE, SQL_FLOAT: Result := TDBXDataTypes.DoubleType;
SQL_BIT: Result := TDBXDataTypes.BooleanType;
SQL_TINYINT: Result := TDBXDataTypes.Int8Type;
SQL_BIGINT: Result := TDBXDataTypes.Int64Type;
SQL_BINARY: Result := TDBXDataTypes.BytesType;
SQL_VARBINARY: Result := TDBXDataTypes.VarBytesType;
SQL_LONGVARBINARY:
begin
Result := TDBXDataTypes.BlobType;
SubType := TDBXSubDataTypes.BinarySubType;
end;
SQL_TYPE_DATE: Result := TDBXDataTypes.DateType;
SQL_TYPE_TIME: Result := TDBXDataTypes.TimeType;
SQL_TYPE_TIMESTAMP: Result := TDBXDataTypes.TimeStampType;
SQL_TYPE_NULL: Result := TDBXDataTypes.UnknownType;
else //We will treat unknown data types as strings
Result := TDBXDataTypes.AnsiStringType;
end;
end;
function GetCreateParams(CreateParamsCol: string): string;
begin
Result := StringReplace(CreateParamsCol, 'max ', '', [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, 'max,', '', [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, 'length', 'Precision', [rfReplaceAll, rfIgnoreCase]);
end;
const
TYPE_NAME_COL = 0;
DATA_TYPE_COL = 1;
COLUMN_SIZE_COL = 2;
LITERAL_PREFIX_COL = 3;
LITERAL_SUFFIX_COL = 4;
CREATE_PARAMS_COL = 5;
NULLABLE_COL = 6;
CASE_SENSITIVE_COL = 7;
SEARCHABLE_COL = 8;
UNSIGNED_ATTRIBUTE_COL = 9;
FIXED_PREC_SCALE_COL = 10;
AUTO_UNIQUE_VALUE_COL = 11;
LOCAL_TYPE_NAME_COL = 12;
MINIMUM_SCALE_COL = 13;
MAXIMUM_SCALE_COL = 14;
SQL_DATA_TYPE_COL = 15;
SQL_DATETIME_SUB_COL = 16;
NUM_PREC_RADIX_COL = 17;
INTERVAL_PRECISION_COL = 18;
var
Command: TDBXOdbcCommand;
Reader: TDBXReader;
ArrayLength, DataTypeCount: Integer;
CreateFormat, CreateParams, LiteralPrefix, LiteralSuffix, MaxVersion, MinVersion, TypeName: string;
DataType, Flags, MaxScale, MinScale: Integer;
SubType: SmallInt;
ColumnSize: Int64;
begin
ArrayLength := 20;
SetLength(FDataTypeDescriptions, ArrayLength);
DataTypeCount := 0;
Command := FOdbcConnection.CreateOdbcCommand;
try
Command.CommandType := TDBXCommandTypes.DbxMetaData;
Command.Text := 'GetDataTypes';
Command.RowSetSize := 1;
Reader := Command.ExecuteQuery;
try
while Reader.Next do
begin
if DataTypeCount >= ArrayLength then
begin
ArrayLength := ArrayLength + 20;
SetLength(FDataTypeDescriptions, ArrayLength);
end;
Flags := 0;
TypeName := Reader.Value[TYPE_NAME_COL].AsString;
DataType := GetDbxDataType(Reader.Value[DATA_TYPE_COL].AsInt32, SubType);
if SubType = TDBXSubDataTypes.FixedSubType then
Flags := Flags or TDBXTypeFlag.FixedLength;
ColumnSize := Reader.Value[COLUMN_SIZE_COL].AsInt64;
CreateFormat := TypeName;
//We use the Precision column in the typed table storage for length
CreateParams := GetCreateParams(Reader.Value[CREATE_PARAMS_COL].AsString);
if CreateParams <> '' then
begin
CreateFormat := CreateFormat + '({0}';
if CreateParams.IndexOf(',') <> -1 then
CreateFormat := CreateFormat + ', {1}';
CreateFormat := CreateFormat + ')';
end;
MaxScale := Reader.Value[MAXIMUM_SCALE_COL].AsInt32;
//Some ODBC drivers do not return MaxScale and use the maximum precision instead
if (MaxScale = 0) and (DataType = TDBXDataTypes.BcdType) then
MaxScale := Reader.Value[COLUMN_SIZE_COL].AsInt32;
MinScale := Reader.Value[MINIMUM_SCALE_COL].AsInt32;
LiteralPrefix := Reader.Value[LITERAL_PREFIX_COL].AsString;
LiteralSuffix := Reader.Value[LITERAL_SUFFIX_COL].AsString;
MaxVersion := '';
MinVersion := '';
if Reader.Value[AUTO_UNIQUE_VALUE_COL].AsInt32 = SQL_TRUE then
Flags := Flags or TDBXTypeFlag.AutoIncrementable;
if Reader.Value[CASE_SENSITIVE_COL].AsInt32 = SQL_TRUE then
Flags := Flags or TDBXTypeFlag.CaseSensitive;
if Reader.Value[FIXED_PREC_SCALE_COL].AsInt32 = SQL_TRUE then
Flags := Flags or TDBXTypeFlag.FixedPrecisionScale;
if Reader.Value[NULLABLE_COL].AsInt32 = SQL_NULLABLE then
Flags := Flags or TDBXTypeFlag.Nullable;
if (Reader.Value[SEARCHABLE_COL].AsInt32 = SQL_PRED_BASIC) or (Reader.Value[SEARCHABLE_COL].AsInt32 = SQL_SEARCHABLE) then
Flags := Flags or TDBXTypeFlag.Searchable;
if (Reader.Value[SEARCHABLE_COL].AsInt32 = SQL_PRED_CHAR) or (Reader.Value[SEARCHABLE_COL].AsInt32 = SQL_SEARCHABLE) then
Flags := Flags or TDBXTypeFlag.SearchableWithLike;
if Reader.Value[UNSIGNED_ATTRIBUTE_COL].AsInt32 = SQL_TRUE then
Flags := Flags or TDBXTypeFlag.Unsigned;
if (DataType = TDBXDataTypes.WideStringType) or ((DataType = TDBXDataTypes.BlobType) and (SubType = TDBXSubDataTypes.WideMemoSubType)) then
Flags := Flags or TDBXTypeFlag.Unicode;
if DataType = TDBXDataTypes.BlobType then
Flags := Flags or TDBXTypeFlag.Long;
FDataTypeDescriptions[DataTypeCount] := TDBXDataTypeDescription.Create(TypeName, DataType, ColumnSize, CreateFormat, CreateParams, MaxScale, MinScale, LiteralPrefix, LiteralSuffix, MaxVersion, MinVersion, Flags);
Inc(DataTypeCount);
end;
SetLength(FDataTypeDescriptions, DataTypeCount);
finally
Reader.Free;
end;
finally
Command.Free
end;
end;
procedure TDBXOdbcMetaDataReader.SetReservedWords(Buffer: TArray<Byte>);
var
TempStr: string;
begin
TempStr := TMarshal.ReadStringAsUnicode(TPtrWrapper.Create(Buffer)).Trim;
FReservedWords := TStringList.Create;
FReservedWords.Delimiter := ',';
FReservedWords.DelimitedText := TempStr;
//Some ODBC drivers do not return a list of reserved words so at least return the
//words that are reserved for use in ODBC function calls.
if FReservedWords.DelimitedText.Length = 0 then
FReservedWords.DelimitedText := SQL_ODBC_KEYWORDS;
end;
function TDBXOdbcMetaDataReader.SqlTablesInvocation(CommandText, Catalog, Schema, TableName, TableType: string): TDBXTable;
function GetMetaDataCollectionName(CommandText: string): string;
begin
if CommandText = 'GetCatalogs' then
Result := TDBXMetaDataCollectionName.Catalogs
else if CommandText = 'GetSchemas' then
Result := TDBXMetaDataCollectionName.Schemas
else if CommandText = 'GetSynonyms' then
Result := TDBXMetaDataCollectionName.Synonyms
else if CommandText = 'GetTables' then
Result := TDBXMetaDataCollectionName.Tables
else if CommandText = 'GetViews' then
Result := TDBXMetaDataCollectionName.Views;
end;
var
Command: TDBXOdbcCommand;
Reader: TDBXReader;
Cursor: TDBXTable;
Columns: TDBXValueTypeArray;
TableNameParam: TDBXParameter;
begin
CheckInitialized;
Command := FOdbcConnection.CreateOdbcCommand;
try
Command.CommandType := TDBXCommandTypes.DbxMetaData;
if TableType = 'VIEW' then
Command.Text := 'GetViews'
else
Command.Text := CommandText;
Command.RowSetSize := 1;
TableNameParam := Command.CreateParameter;
TableNameParam.DataType := TDBXDataTypes.WideStringType;
Command.Parameters.AddParameter(TableNameParam);
Command.Parameters[0].Value.SetWideString(TableName);
Reader := Command.ExecuteQuery;
if Reader = nil then
Result := nil
else
begin
Cursor := TDBXStringTrimTable.CreateTrimTableIfNeeded(TDBXReaderTableStorage.Create(Command, Reader));
// When the Result is freed, this Command will be freed.
Command := nil;
SetLength(Columns, 5);
Columns[0] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXTablesColumns.CatalogName, 'TABLE_CAT', TDBXDataTypes.WideStringType);
Columns[1] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXTablesColumns.SchemaName, 'TABLE_SCHEM', TDBXDataTypes.WideStringType);
Columns[2] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXTablesColumns.TableName, 'TABLE_NAME', TDBXDataTypes.WideStringType);
Columns[3] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXTablesColumns.TableType, 'TABLE_TYPE', TDBXDataTypes.WideStringType);
Columns[4] := TDBXMetaDataCollectionColumns.CreateValueType('Remarks', 'REMARKS', TDBXDataTypes.WideStringType);
Result := TDBXCustomMetaDataTable.Create(GetContext, GetMetaDataCollectionName(CommandText), Columns, Cursor);
end;
finally
Command.Free;
end;
end;
function TDBXOdbcMetaDataReader.AreCatalogFunctionsSupported;
begin
Result := True;
end;
function TDBXOdbcMetaDataReader.AreCatalogsSupported: Boolean;
begin
CheckInitialized;
Result := FCatalogsSupported;
end;
function TDBXOdbcMetaDataReader.AreSchemasSupported: Boolean;
begin
CheckInitialized;
Result := FSchemasSupported;
end;
function TDBXOdbcMetaDataReader.GetDataTypeDescriptions: TDBXDataTypeDescriptionArray;
begin
CheckInitialized;
Result := FDataTypeDescriptions;
end;
function TDBXOdbcMetaDataReader.GetProductName: string;
begin
Result := 'Odbc';
end;
function TDBXOdbcMetaDataReader.GetReservedWords: TDBXStringArray;
begin
CheckInitialized;
Result := TDBXStringArray(FReservedWords.ToStringArray);
end;
function TDBXOdbcMetaDataReader.GetSqlIdentifierQuoteChar: string;
begin
CheckInitialized;
Result := FSqlIdentifierQuoteChar;
end;
function TDBXOdbcMetaDataReader.GetSqlIdentifierQuotePrefix: string;
begin
CheckInitialized;
Result := FSqlIdentifierQuoteChar;
end;
function TDBXOdbcMetaDataReader.GetSqlIdentifierQuoteSuffix: string;
begin
CheckInitialized;
Result := FSqlIdentifierQuoteChar;
end;
function TDBXOdbcMetaDataReader.GetSqlProcedureQuoteChar: string;
begin
CheckInitialized;
Result := FSqlIdentifierQuoteChar;
end;
function TDBXOdbcMetaDataReader.IsDescendingIndexSupported: Boolean;
begin
CheckInitialized;
if (FIndexKeyword = SQL_IK_DESC) or (FIndexKeyword = SQL_IK_ALL) then
Result := True
else
Result := False;
end;
function TDBXOdbcMetaDataReader.IsLowerCaseIdentifiersSupported: Boolean;
begin
CheckInitialized;
if FSqlIdentifierCase = SQL_IC_LOWER then
Result := True
else
Result := False;
end;
function TDBXOdbcMetaDataReader.IsMultipleCommandsSupported: Boolean;
begin
CheckInitialized;
if FMaxConcurrentActivities <> 1 then
Result := True
else
Result := False;
end;
function TDBXOdbcMetaDataReader.IsNestedTransactionsSupported: Boolean;
begin
CheckInitialized;
Result := FSupportsMultipleTransactions;
end;
function TDBXOdbcMetaDatareader.IsParameterMetadataSupported: Boolean;
begin
CheckInitialized;
Result := FSupportsParameterMetaData;
end;
function TDBXOdbcMetaDataReader.IsQuotedIdentifiersSupported: Boolean;
begin
CheckInitialized;
if FSqlIdentifierQuoteChar = '' then
Result := False
else
Result := True;
end;
function TDBXOdbcMetaDataReader.IsSetRowSizeSupported: Boolean;
begin
CheckInitialized;
Result := True;
end;
function TDBXOdbcMetaDataReader.IsTransactionsSupported: Boolean;
begin
CheckInitialized;
if FTransactionCapable = SQL_TC_NONE then
Result := False
else
Result := True;
end;
function TDBXOdbcMetaDataReader.IsUpperCaseIdentifiersSupported: Boolean;
begin
CheckInitialized;
if FSqlIdentifierCase = SQL_IC_UPPER then
Result := True
else
Result := False
end;
procedure TDBXOdbcMetaDataReader.PopulateDataTypes(const Hash: TDBXObjectStore; const Types: TDBXArrayList; const Descr: TDBXDataTypeDescriptionArray);
var
Index: Integer;
DataType: TDBXDataTypeDescription;
TypeName: string;
begin
for Index := 0 to Length(Descr) - 1 do
begin
DataType := Descr[Index];
if DataType <> nil then
begin
TypeName := DataType.TypeName;
if (not Hash.ContainsKey(TypeName)) then
begin
Hash[TypeName] := DataType;
Types.Add(DataType);
end
else
Descr[Index].Free;
Descr[Index] := nil;
end;
end;
end;
constructor TDBXOdbcMetaDataReader.Create;
begin
inherited Create;
FInitialized := False;
end;
constructor TDBXOdbcMetaDataReader.Create(OdbcConnection: TDBXOdbcConnection);
begin
inherited Create;
FInitialized := False;
FConnectionHandle := OdbcConnection.ConnectionHandle;
FOdbcConnection := OdbcConnection;
Init;
end;
destructor TDBXOdbcMetaDataReader.Destroy;
var
I: Integer;
begin
FConnectionHandle := nil;
FOdbcConnection := nil;
FReservedWords.Free;
for I := 0 to Length(FDataTypeDescriptions) - 1 do
FDataTypeDescriptions[I].Free;
inherited Destroy;
end;
function TDBXOdbcMetaDataReader.FetchCatalogs: TDBXTable;
begin
Result := SqlTablesInvocation('GetCatalogs', '', '', '', '');
end;
function TDBXOdbcMetaDataReader.FetchColumns(const Catalog: string; const Schema: string; const Table: string): TDBXTable;
var
Command: TDBXOdbcCommand;
TableParam: TDBXParameter;
Reader: TDBXReader;
Columns: TDBXValueTypeArray;
Cursor: TDBXTable;
begin
DataTypeHash;
CheckInitialized;
Command := FOdbcConnection.CreateOdbcCommand;
try
Command.CommandType := TDBXCommandTypes.DbxMetaData;
Command.Text := 'GetColumns';
Command.RowSetSize := 1;
TableParam := Command.CreateParameter;
TableParam.DataType := TDBXDataTypes.WideStringType;
Command.Parameters.AddParameter(TableParam);
Command.Parameters[0].Value.SetWideString(Table);
Reader := Command.ExecuteQuery;
if Reader = nil then
Result := nil
else
begin
Cursor := TDBXStringTrimTable.CreateTrimTableIfNeeded(TDBXReaderTableStorage.Create(Command, Reader));
// When the Result is freed, this Command will be freed.
Command := nil;
SetLength(Columns, 18);
Columns[0] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXColumnsColumns.CatalogName, 'TABLE_CAT', TDBXDataTypes.WideStringType);
Columns[1] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXColumnsColumns.SchemaName, 'TABLE_SCHEM', TDBXDataTypes.WideStringType);
Columns[2] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXColumnsColumns.TableName, 'TABLE_NAME', TDBXDataTypes.WideStringType);
Columns[3] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXColumnsColumns.ColumnName, 'COLUMN_NAME', TDBXDataTypes.WideStringType);
Columns[4] := TDBXMetaDataCollectionColumns.CreateValueType('DATA_TYPE', 'DATA_TYPE', TDBXDataTypes.Int16Type);
Columns[5] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXColumnsColumns.TypeName, 'TYPE_NAME', TDBXDataTypes.WideStringType);
Columns[6] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXColumnsColumns.Precision, 'COLUMN_SIZE', TDBXDataTypes.Int32Type);
Columns[7] := TDBXMetaDataCollectionColumns.CreateValueType('BUFFER_LENGTH', 'BUFFER_LENGTH', TDBXDataTypes.Int32Type);
Columns[8] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXColumnsColumns.Scale, 'DECIMAL_DIGITS', TDBXDataTypes.Int16Type);
Columns[9] := TDBXMetaDataCollectionColumns.CreateValueType('NUM_PREC_RADIX', 'NUM_PREC_RADIX', TDBXDataTypes.Int16Type);
Columns[10] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXColumnsColumns.IsNullable, 'NULLABLE', TDBXDataTypes.Int16Type);
Columns[11] := TDBXMetaDataCollectionColumns.CreateValueType('REMARKS', 'REMARKS', TDBXDataTypes.WideStringType);
Columns[12] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXColumnsColumns.DefaultValue, 'COLUMN_DEF', TDBXDataTypes.WideStringType);
Columns[13] := TDBXMetaDataCollectionColumns.CreateValueType('SQL_DATA_TYPE', 'SQL_DATA_TYPE', TDBXDataTypes.Int16Type);
Columns[14] := TDBXMetaDataCollectionColumns.CreateValueType('SQL_DATETIME_SUB', 'SQL_DATETIME_SUB', TDBXDataTypes.Int16Type);
Columns[15] := TDBXMetaDataCollectionColumns.CreateValueType('CHAR_OCTET_LENGTH', 'CHAR_OCTET_LENGTH', TDBXDataTypes.Int32Type);
Columns[16] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXColumnsColumns.Ordinal, 'ORDINAL_POSITION', TDBXDataTypes.Int32Type);
Columns[17] := TDBXMetaDataCollectionColumns.CreateValueType('IS_NULLABLE', 'IS_NULLABLE', TDBXDataTypes.WideStringType);
Cursor := TDBXCustomMetaDataTable.Create(GetContext, TDBXMetaDataCollectionName.Columns, Columns, Cursor);
Result := TDBXOdbcColumnsTableCursor.Create(Self, False, Cursor);
end;
finally
Command.Free;
end;
end;
function TDBXOdbcMetaDataReader.FetchForeignKeyColumns(const Catalog: string; const Schema: string; const Table: string; const ForeignKeyName: string; const PrimaryCatalog: string; const PrimarySchema: string; const PrimaryTable: string; const PrimaryKeyName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
CheckInitialized;
Columns := TDBXMetaDataCollectionColumns.CreateForeignKeyColumnsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ForeignKeyColumns, Columns);
end;
function TDBXOdbcMetaDataReader.FetchForeignKeys(const Catalog: string; const Schema: string; const Table: string): TDBXTable;
var
Command: TDBXOdbcCommand;
TableParam: TDBXParameter;
Reader: TDBXReader;
Columns: TDBXValueTypeArray;
Cursor: TDBXTable;
begin
CheckInitialized;
Command := FOdbcConnection.CreateOdbcCommand;
try
Command.CommandType := TDBXCommandTypes.DbxMetaData;
Command.Text := 'GetForeignKeys';
Command.RowSetSize := 1;
TableParam := Command.CreateParameter;
TableParam.DataType := TDBXDataTypes.WideStringType;
Command.Parameters.AddParameter(TableParam);
Command.Parameters[0].Value.SetWideString(Table);
Reader := Command.ExecuteQuery;
if Reader = nil then
Result := nil
else
begin
Cursor := TDBXStringTrimTable.CreateTrimTableIfNeeded(TDBXReaderTableStorage.Create(Command, Reader));
// When the Result is freed, this Command will be freed.
Command := nil;
SetLength(Columns, 14);
Columns[0] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXForeignKeyColumnsColumns.PrimaryCatalogName, 'PKTABLE_CAT', TDBXDataTypes.WideStringType);
Columns[1] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXForeignKeyColumnsColumns.PrimarySchemaName, 'PKTABLE_SCHEM', TDBXDataTypes.WideStringType);
Columns[2] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXForeignKeyColumnsColumns.TableName, 'PKTABLE_NAME', TDBXDataTypes.WideStringType);
Columns[3] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXForeignKeyColumnsColumns.PrimaryColumnName, 'PKCOLUMN_NAME', TDBXDataTypes.WideStringType);
Columns[4] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXForeignKeyColumnsColumns.CatalogName, 'FKTABLE_CAT', TDBXDataTypes.WideStringType);
Columns[5] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXForeignKeyColumnsColumns.SchemaName, 'FKTABLE_SCHEM', TDBXDataTypes.WideStringType);
Columns[6] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXForeignKeyColumnsColumns.TableName, 'FKTABLE_NAME', TDBXDataTypes.WideStringType);
Columns[7] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXForeignKeyColumnsColumns.ColumnName, 'FKCOLUMN_NAME', TDBXDataTypes.WideStringType);
Columns[8] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXForeignKeyColumnsColumns.Ordinal, 'KEY_SEQ', TDBXDataTypes.Int16Type);
Columns[9] := TDBXMetaDataCollectionColumns.CreateValueType('UPDATE_RULE', 'UPDATE_RULE', TDBXDataTypes.Int16Type);
Columns[10] := TDBXMetaDataCollectionColumns.CreateValueType('DELETE_RULE', 'DELETE_RULE', TDBXDataTypes.Int16Type);
Columns[11] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXForeignKeyColumnsColumns.ForeignKeyName, 'FK_NAME', TDBXDataTypes.WideStringType);
Columns[12] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXForeignKeyColumnsColumns.PrimaryKeyName, 'PK_NAME', TDBXDataTypes.WideStringType);
Columns[13] := TDBXMetaDataCollectionColumns.CreateValueType('DEFERRABILITY', 'DEFERRABILITY', TDBXDataTypes.Int16Type);
Result := TDBXCustomMetaDataTable.Create(GetContext, TDBXMetaDataCollectionName.ForeignKeys, Columns, Cursor);
end;
finally
Command.Free;
end;
end;
function TDBXOdbcMetaDataReader.FetchIndexColumns(const Catalog: string; const Schema: string; const Table: string; const Index: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
CheckInitialized;
Columns := TDBXMetaDataCollectionColumns.CreateIndexColumnsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.IndexColumns, Columns);
end;
function TDBXOdbcMetaDataReader.FetchIndexes(const Catalog: string; const Schema: string; const Table: string): TDBXTable;
var
Command: TDBXOdbcCommand;
TableParam: TDBXParameter;
Reader: TDBXReader;
Columns: TDBXValueTypeArray;
Cursor: TDBXTable;
begin
CheckInitialized;
Command := FOdbcConnection.CreateOdbcCommand;
try
Command.CommandType := TDBXCommandTypes.DbxMetaData;
Command.Text := 'GetIndexes';
Command.RowSetSize := 1;
TableParam := Command.CreateParameter;
TableParam.DataType := TDBXDataTypes.WideStringType;
Command.Parameters.AddParameter(TableParam);
Command.Parameters[0].Value.SetWideString(Table);
Reader := Command.ExecuteQuery;
if Reader = nil then
Result := nil
else
begin
Cursor := TDBXStringTrimTable.CreateTrimTableIfNeeded(TDBXReaderTableStorage.Create(Command, Reader));
// When the Result is freed, this Command will be freed.
Command := nil;
SetLength(Columns, 13);
Columns[0] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexesColumns.CatalogName, 'TABLE_CAT', TDBXDataTypes.WideStringType);
Columns[1] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexesColumns.SchemaName, 'TABLE_SCHEM', TDBXDataTypes.WideStringType);
Columns[2] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexesColumns.TableName, 'TABLE_NAME', TDBXDataTypes.WideStringType);
Columns[3] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexesColumns.IsUnique, 'NON_UNIQUE', TDBXDataTypes.BooleanType);
Columns[4] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexesColumns.IndexQualifier, 'INDEX_QUALIFIER', TDBXDataTypes.WideStringType);
Columns[5] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexesColumns.IndexName, 'INDEX_NAME', TDBXDataTypes.WideStringType);
Columns[6] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexesColumns.TypeName, 'Type', TDBXDataTypes.Int16Type);
Columns[7] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexesColumns.OrdinalPosition, 'ORDINAL_POSITION', TDBXDataTypes.Int16Type);
Columns[8] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexesColumns.ColumnName, 'COLUMN_NAME', TDBXDataTypes.WideStringType);
Columns[9] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexesColumns.AscDesc, 'ASC_OR_DESC', TDBXDataTypes.WideStringType);
Columns[10] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexesColumns.Cardinality, 'CARDINALITY', TDBXDataTypes.Int32Type);
Columns[11] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexesColumns.Pages, 'PAGES', TDBXDataTypes.Int32Type);
Columns[12] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXIndexesColumns.FilterCondition, 'FILTER_CONDITION', TDBXDataTypes.WideStringType);
Result := TDBXCustomMetaDataTable.Create(GetContext, TDBXMetaDataCollectionName.Indexes, Columns, Cursor);
end;
finally
Command.Free;
end;
end;
function TDBXOdbcMetaDataReader.FetchPackageProcedureParameters(const Catalog: string; const Schema: string; const PackageName: string; const ProcedureName: string; const ParameterName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
CheckInitialized;
Columns := TDBXMetaDataCollectionColumns.CreatePackageProcedureParametersColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedureParameters, Columns);
end;
function TDBXOdbcMetaDataReader.FetchPackageProcedures(const Catalog: string; const Schema: string; const PackageName: string; const ProcedureName: string; const ProcedureType: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
CheckInitialized;
Columns := TDBXMetaDataCollectionColumns.CreatePackageProceduresColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedures, Columns);
end;
function TDBXOdbcMetaDataReader.FetchPackages(const Catalog: string; const Schema: string; const PackageName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
CheckInitialized;
Columns := TDBXMetaDataCollectionColumns.CreatePackagesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Packages, Columns);
end;
function TDBXOdbcMetaDataReader.FetchPackageSources(const Catalog: string; const Schema: string; const PackageName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
CheckInitialized;
Columns := TDBXMetaDataCollectionColumns.CreatePackageSourcesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageSources, Columns);
end;
function TDBXOdbcMetaDataReader.FetchProcedures(const Catalog: string; const Schema: string; const ProcedureName: string; const ProcedureType: string): TDBXTable;
var
Command: TDBXOdbcCommand;
Reader: TDBXReader;
Columns: TDBXValueTypeArray;
Cursor: TDBXTable;
ProcNameParam: TDBXParameter;
begin
CheckInitialized;
Command := FOdbcConnection.CreateOdbcCommand;
try
Command.CommandType := TDBXCommandTypes.DbxMetaData;
Command.Text := 'GetProcedures';
Command.RowSetSize := 1;
ProcNameParam := Command.CreateParameter;
ProcNameParam.DataType := TDBXDataTypes.WideStringType;
Command.Parameters.AddParameter(ProcNameParam);
Command.Parameters[0].Value.SetWideString(ProcedureName);
Reader := Command.ExecuteQuery;
if Reader = nil then
Result := nil
else
begin
Cursor := TDBXStringTrimTable.CreateTrimTableIfNeeded(TDBXReaderTableStorage.Create(Command, Reader));
// When the Result is freed, this Command will be freed.
Command := nil;
SetLength(Columns, 8);
Columns[0] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProceduresColumns.CatalogName, 'PROCEDURE_CAT', TDBXDataTypes.WideStringType);
Columns[1] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProceduresColumns.SchemaName, 'PROCEDURE_SCHEM', TDBXDataTypes.WideStringType);
Columns[2] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProceduresColumns.ProcedureName, 'PROCEDURE_NAME', TDBXDataTypes.WideStringType);
Columns[3] := TDBXMetaDataCollectionColumns.CreateValueType('NUM_INPUT_PARAMS', 'NUM_INPUT_PARAMS', TDBXDataTypes.Int32Type);
Columns[4] := TDBXMetaDataCollectionColumns.CreateValueType('NUM_OUTPUT_PARAMS', 'NUM_OUTPUT_PARAMS', TDBXDataTypes.Int32Type);
Columns[5] := TDBXMetaDataCollectionColumns.CreateValueType('NUM_RESULT_SETS', 'NUM_RESULT_SETS', TDBXDataTypes.Int32Type);
Columns[6] := TDBXMetaDataCollectionColumns.CreateValueType('REMARKS', 'REMARKS', TDBXDataTypes.WideStringType);
Columns[7] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProceduresColumns.ProcedureType, 'PROCEDURE_TYPE', TDBXDataTypes.Int16Type);
Result := TDBXCustomMetaDataTable.Create(GetContext, TDBXMetaDataCollectionName.Procedures, Columns, Cursor);
end;
finally
Command.Free;
end;
end;
function TDBXOdbcMetaDataReader.FetchProcedureParameters(const Catalog: string; const Schema: string; const Proc: string; const Parameter: string): TDBXTable;
var
Command: TDBXOdbcCommand;
ProcParam: TDBXParameter;
Reader: TDBXReader;
Columns: TDBXValueTypeArray;
Cursor: TDBXTable;
function GetProcName(OriginalName: string): string;
var
LStr: string;
begin
Result := OriginalName;
if OriginalName.Chars[0] <> Self.SqlIdentifierQuoteChar.Chars[0] then
begin
if IsLowerCaseIdentifiersSupported then
begin
LStr := OriginalName.ToLower;
if LStr <> OriginalName then
Result := AnsiQuotedStr(OriginalName, Self.SqlIdentifierQuoteChar.Chars[0])
end
else if IsUpperCaseIdentifiersSupported then
begin
LStr := OriginalName.ToUpper;
if LStr <> OriginalName then
Result := AnsiQuotedStr(OriginalName, Self.SqlIdentifierQuoteChar.Chars[0])
end
end;
end;
begin
CheckInitialized;
Command := FOdbcConnection.CreateOdbcCommand;
try
Command.CommandType := TDBXCommandTypes.DbxMetaData;
Command.Text := 'GetProcedureParameters';
Command.RowSetSize := 1;
ProcParam := Command.CreateParameter;
ProcParam.DataType := TDBXDataTypes.WideStringType;
Command.Parameters.AddParameter(ProcParam);
Command.Parameters[0].Value.SetWideString(GetProcName(Proc));
Reader := Command.ExecuteQuery;
if Reader = nil then
Result := nil
else
begin
Cursor := TDBXStringTrimTable.CreateTrimTableIfNeeded(TDBXReaderTableStorage.Create(Command, Reader));
// When the Result is freed, this Command will be freed.
Command := nil;
SetLength(Columns, 22);
Columns[0] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProcedureParametersColumns.CatalogName, 'PROCEDURE_CAT', TDBXDataTypes.WideStringType);
Columns[1] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProcedureParametersColumns.SchemaName, 'PROCEDURE_SCHEM', TDBXDataTypes.WideStringType);
Columns[2] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProcedureParametersColumns.ProcedureName, 'PROCEDURE_NAME', TDBXDataTypes.WideStringType);
Columns[3] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProcedureParametersColumns.ParameterName, 'COLUMN_NAME', TDBXDataTypes.WideStringType);
Columns[4] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProcedureParametersColumns.ParameterMode, 'COLUMN_TYPE', TDBXDataTypes.Int16Type);
Columns[5] := TDBXMetaDataCollectionColumns.CreateValueType('DATA_TYPE', 'DATA_TYPE', TDBXDataTypes.Int16Type);
Columns[6] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProcedureParametersColumns.TypeName, 'TYPE_NAME', TDBXDataTypes.WideStringType);
Columns[7] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProcedureParametersColumns.Precision, 'COLUMN_SIZE', TDBXDataTypes.Int32Type);
Columns[8] := TDBXMetaDataCollectionColumns.CreateValueType('BUFFER_LENGTH', 'BUFFER_LENGTH', TDBXDataTypes.Int32Type);
Columns[9] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProcedureParametersColumns.Scale, 'DECIMAL_DIGITS', TDBXDataTypes.Int16Type);
Columns[10] := TDBXMetaDataCollectionColumns.CreateValueType('NUM_PREC_RADIX', 'NUM_PREC_RADIX', TDBXDataTypes.Int16Type);
Columns[11] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProcedureParametersColumns.IsNullable, 'NULLABLE', TDBXDataTypes.Int16Type);
Columns[12] := TDBXMetaDataCollectionColumns.CreateValueType('REMARKS', 'REMARKS', TDBXDataTypes.WideStringType);
Columns[13] := TDBXMetaDataCollectionColumns.CreateValueType('COLUMN_DEF', 'COLUMN_DEF', TDBXDataTypes.WideStringType);
Columns[14] := TDBXMetaDataCollectionColumns.CreateValueType('SQL_DATA_TYPE', 'SQL_DATA_TYPE', TDBXDataTypes.Int16Type);
Columns[15] := TDBXMetaDataCollectionColumns.CreateValueType('SQL_DATETIME_SUB', 'SQL_DATETIME_SUB', TDBXDataTypes.Int16Type);
Columns[16] := TDBXMetaDataCollectionColumns.CreateValueType('CHAR_OCTET_LENGTH', 'CHAR_OCTET_LENGTH', TDBXDataTypes.Int32Type);
Columns[17] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProcedureParametersColumns.Ordinal, 'ORDINAL_POSITION', TDBXDataTypes.Int32Type);
Columns[18] := TDBXMetaDataCollectionColumns.CreateValueType('IS_NULLABLE', 'IS_NULLABLE', TDBXDataTypes.WideStringType);
Columns[19] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProcedureParametersColumns.DbxDataType, SDbxDataType, TDBXDataTypes.Int32Type, True);
Columns[20] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProcedureParametersColumns.ParameterMode, SParameterMode, TDBXDataTypes.WideStringType, True);
Columns[21] := TDBXMetaDataCollectionColumns.CreateValueType(TDBXProcedureParametersColumns.IsFixedLength, SIsFixedLength, TDBXDataTypes.BooleanType, True);
Cursor := TDBXCustomMetaDataTable.Create(GetContext, TDBXMetaDataCollectionName.ProcedureParameters, Columns, Cursor);
Result := TDBXOdbcColumnsTableCursor.Create(Self, False, Cursor);
end;
finally
Command.Free;
end;
end;
function TDBXOdbcMetaDataReader.FetchProcedureSources(const Catalog: string; const Schema: string; const Proc: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
CheckInitialized;
Columns := TDBXMetaDataCollectionColumns.CreateProcedureSourcesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ProcedureSources, Columns);
end;
function TDBXOdbcMetaDataReader.FetchRoles: TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
CheckInitialized;
Columns := TDBXMetaDataCollectionColumns.CreateRolesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Roles, Columns);
end;
function TDBXOdbcMetaDataReader.FetchSchemas(const Catalog: string): TDBXTable;
begin
Result := SqlTablesInvocation('GetSchemas', Catalog, '', '', '');
end;
function TDBXOdbcMetaDataReader.FetchSynonyms(const Catalog: string; const Schema: string; const Synonym: string): TDBXTable;
begin
Result := SqlTablesInvocation('GetSynonyms', Catalog, Schema, Synonym, '');
end;
function TDBXOdbcMetaDataReader.FetchTables(const Catalog: string; const Schema: string; const TableName: string; const TableType: string): TDBXTable;
begin
Result := SqlTablesInvocation('GetTables', Catalog, Schema, TableName, TableType);
end;
function TDBXOdbcMetaDataReader.FetchUsers: TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
CheckInitialized;
Columns := TDBXMetaDataCollectionColumns.CreateUsersColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Users, Columns);
end;
function TDBXOdbcMetaDataReader.FetchViews(const Catalog: string; const Schema: string; const View: string): TDBXTable;
begin
Result := SqlTablesInvocation('GetViews', Catalog, Schema, View, '');
end;
{ TDBXOdbcColumnsTableCursor }
function TDBXOdbcColumnsTableCursor.GetWritableValue(
const Ordinal: Integer): TDBXWritableValue;
begin
if DBXTableName = TDBXMetaDataCollectionName.ProcedureParameters then
begin
if Ordinal + FOrdinalOffset >= TDBXOdbcProcedureParametersIndex.DbxDataType then
Result := FDataTypesRow.Value[Ordinal - (TDBXOdbcProcedureParametersIndex.DbxDataType - FOrdinalOffset)]
else
Result := FTable.Value[Ordinal];
end
else
Result := FTable.Value[Ordinal];
end;
constructor TDBXOdbcColumnsTableCursor.Create(const Reader: TDBXBaseMetaDataReader; const CheckBase: Boolean; const Cursor: TDBXTable);
var
DataTypeColumns: TDBXValueTypeArray;
Ordinal: Integer;
begin
inherited Create;
Table := Cursor;
FDataTypeHash := Reader.DataTypeHash;
FReader := Reader;
FCheckBase := CheckBase;
FOrdinalOffset := 0;
FOrdinalTypeName := TDBXOdbcProcedureParametersIndex.TypeName;
if (DBXTableName = TDBXMetaDataCollectionName.ProcedureParameters) then
begin
FOrdinalOffset := 0;
SetLength(DataTypeColumns, TDBXOdbcProcedureParametersIndex.Last - TDBXOdbcProcedureParametersIndex.DbxDataType + 1);
for Ordinal := 0 to Length(DataTypeColumns) - 1 do
DataTypeColumns[Ordinal] := TDBXValueType(Cursor.Columns[Ordinal + TDBXOdbcProcedureParametersIndex.DbxDataType - FOrdinalOffset].Clone());
end
else
SetLength(DataTypeColumns, 0);
FDataTypesRow := TDBXSingleValueRow.Create;
FDataTypesRow.Columns := DataTypeColumns;
end;
destructor TDBXOdbcColumnsTableCursor.Destroy;
begin
FreeAndNil(FDataTypesRow);
inherited Destroy;
end;
function TDBXOdbcColumnsTableCursor.Next: Boolean;
function GetModeString(ColumnType: SmallInt): string;
begin
case ColumnType of
SQL_PARAM_INPUT: Result := 'IN';
SQL_PARAM_INPUT_OUTPUT: Result := 'INOUT';
SQL_PARAM_OUTPUT: Result := 'OUT';
SQL_RETURN_VALUE: Result := 'RETURN';
SQL_RESULT_COL: Result := 'RESULT';
else
Result := 'UNKNOWN';
end;
end;
function GetDataType(SQLType: Integer): TDBXType;
begin
case SQLType of
SQL_CHAR, SQL_VARCHAR:
Result := TDBXDataTypes.AnsiStringType;
SQL_LONGVARCHAR, SQL_WLONGVARCHAR, SQL_LONGVARBINARY:
Result := TDBXDataTypes.BlobType;
SQL_WCHAR, SQL_WVARCHAR:
Result := TDBXDataTypes.WideStringType;
SQL_DECIMAL, SQL_NUMERIC:
Result := TDBXDataTypes.BcdType;
SQL_SMALLINT:
Result := TDBXDataTypes.Int16Type;
SQL_INTEGER:
Result := TDBXDataTypes.Int32Type;
SQL_REAL:
Result := TDBXDataTypes.SingleType;
SQL_DOUBLE, SQL_FLOAT:
Result := TDBXDataTypes.DoubleType;
SQL_BIT:
Result := TDBXDataTypes.BooleanType;
SQL_TINYINT:
Result := TDBXDataTypes.Int8Type;
SQL_BIGINT:
Result := TDBXDataTypes.Int64Type;
SQL_BINARY:
Result := TDBXDataTypes.BytesType;
SQL_VARBINARY:
Result := TDBXDataTypes.VarBytesType;
SQL_TYPE_DATE:
Result := TDBXDataTypes.DateType;
SQL_TYPE_TIME:
Result := TDBXDataTypes.TimeType;
SQL_TYPE_TIMESTAMP:
Result := TDBXDataTypes.TimeStampType;
SQL_TYPE_NULL:
Result := TDBXDataTypes.UnknownType;
else //We will treat unknown data types as strings
Result := TDBXDataTypes.AnsiStringType;
end;
end;
var
ReturnValue: Boolean;
begin
ReturnValue := FTable.Next;
if ReturnValue then
begin
FDataType := TDBXDataTypeDescription(FDataTypeHash[FTable.Value[FOrdinalTypeName].AsString]);
if DBXTableName = TDBXMetaDataCollectionName.ProcedureParameters then
begin
if FDataType = nil then
begin
FDataTypesRow.Value[0].AsInt32 := GetDataType(FTable.Value[TDBXOdbcProcedureParametersIndex.SqlDataType].AsInt32);
FDataTypesRow.Value[TDBXOdbcProcedureParametersIndex.ParameterMode - TDBXOdbcProcedureParametersIndex.DbxDataType].AsString := 'IN';
FDataTypesRow.Value[TDBXOdbcProcedureParametersIndex.IsFixedLength - TDBXOdbcProcedureParametersIndex.DbxDataType].AsBoolean := False;
end
else
begin
FDataTypesRow.Value[0].AsInt32 := FDataType.DbxDataType;
FDataTypesRow.Value[TDBXOdbcProcedureParametersIndex.ParameterMode - TDBXOdbcProcedureParametersIndex.DbxDataType].AsString := GetModeString(FTable.Value[TDBXOdbcProcedureParametersIndex.Mode].AsInt16);
FDataTypesRow.Value[TDBXOdbcProcedureParametersIndex.IsFixedLength - TDBXOdbcProcedureParametersIndex.DbxDataType].AsBoolean := FDataType.FixedLength;
end;
end;
end;
Result := ReturnValue;
end;
end.
|
unit rReports;
interface
uses Windows, SysUtils, Classes, ORNet, ORFn, ComCtrls, Chart, graphics;
{ Consults }
procedure ListConsults(Dest: TStrings);
procedure LoadConsultText(Dest: TStrings; IEN: Integer);
{ Reports }
procedure ListReports(Dest: TStrings);
procedure ListLabReports(Dest: TStrings);
procedure ListReportDateRanges(Dest: TStrings);
procedure ListHealthSummaryTypes(Dest: TStrings);
procedure ListImagingExams(Dest: TStrings);
procedure ListProcedures(Dest: TStrings);
procedure ListNutrAssessments(Dest: TStrings);
procedure ListSurgeryReports(Dest: TStrings);
procedure ColumnHeaders(Dest: TStrings; AReportType: String);
procedure SaveColumnSizes(aColumn: String);
procedure LoadReportText(Dest: TStrings; ReportType: string; const Qualifier: string; ARpc, AHSTag: string);
procedure RemoteQueryAbortAll;
procedure RemoteQuery(Dest: TStrings; AReportType: string; AHSType, ADaysback,
AExamID: string; Alpha, AOmega: Double; ASite, ARemoteRPC, AHSTag: String);
procedure DirectQuery(Dest: TStrings; AReportType: string; AHSType, ADaysback,
AExamID: string; Alpha, AOmega: Double; ASite, ARemoteRPC, AHSTag: String);
function ReportQualifierType(ReportType: Integer): Integer;
function ImagingParams: String;
function AutoRDV: String;
function HDRActive: String;
procedure PrintReportsToDevice(AReport: string; const Qualifier, Patient,
ADevice: string; var ErrMsg: string; aComponents: TStringlist;
ARemoteSiteID, ARemoteQuery, AHSTag: string);
function HSFileLookup(aFile: String; const StartFrom: string;
Direction: Integer): TStrings;
procedure HSComponentFiles(Dest: TStrings; aComponent: String);
procedure HSSubItems(Dest: TStrings; aItem: String);
procedure HSReportText(Dest: TStrings; aComponents: TStringlist);
procedure HSComponents(Dest: TStrings);
procedure HSABVComponents(Dest: TStrings);
procedure HSDispComponents(Dest: TStrings);
procedure HSComponentSubs(Dest: TStrings; aItem: String);
procedure HealthSummaryCheck(Dest: TStrings; aQualifier: string);
function GetFormattedReport(AReport: string; const Qualifier, Patient: string;
aComponents: TStringlist; ARemoteSiteID, ARemoteQuery, AHSTag: string): TStrings;
procedure PrintWindowsReport(ARichEdit: TRichEdit; APageBreak, ATitle: string;
var ErrMsg: string; IncludeHeader: Boolean = false);
function DefaultToWindowsPrinter: Boolean;
procedure PrintGraph(GraphImage: TChart; PageTitle: string);
procedure PrintBitmap(Canvas: TCanvas; DestRect: TRect; Bitmap: TBitmap);
procedure CreatePatientHeader(var HeaderList: TStringList; PageTitle: string);
procedure SaveDefaultPrinter(DefPrinter: string) ;
function GetRemoteStatus(aHandle: string): String;
function GetAdhocLookup: integer;
procedure SetAdhocLookup(aLookup: integer);
procedure GetRemoteData(Dest: TStrings; aHandle: string; aItem: PChar);
procedure ModifyHDRData(Dest: string; aHandle: string; aID: string);
procedure PrintVReports(Dest, ADevice, AHeader: string; AReport: TStringList);
implementation
uses uCore, rCore, Printers, clipbrd, uReports, fReports;
var
uTree: TStringList;
uReportsList: TStringList;
uLabReports: TStringList;
uDateRanges: TStringList;
uHSTypes: TStringList;
{ Consults }
procedure ListConsults(Dest: TStrings);
var
i: Integer;
x: string;
begin
CallV('ORWCS LIST OF CONSULT REPORTS', [Patient.DFN]);
with RPCBrokerV do
begin
SortByPiece(TStringList(Results), U, 2);
InvertStringList(TStringList(Results));
SetListFMDateTime('mmm dd,yy', TStringList(Results), U, 2);
for i := 0 to Results.Count - 1 do
begin
x := Results[i];
x := Pieces(x, U, 1, 2) + U + Piece(x, U, 3) + ' (' + Piece(x, U, 4) + ')';
Results[i] := x;
end;
FastAssign(Results, Dest);
end;
end;
procedure LoadConsultText(Dest: TStrings; IEN: Integer);
begin
CallV('ORWCS REPORT TEXT', [Patient.DFN, IEN]);
QuickCopy(RPCBrokerV.Results,Dest);
end;
{ Reports }
procedure ExtractSection(Dest: TStrings; const Section: string; Mixed: Boolean);
var
i: Integer;
begin
with RPCBrokerV do
begin
i := -1;
repeat Inc(i) until (i = Results.Count) or (Results[i] = Section);
Inc(i);
while (i < Results.Count) and (Results[i] <> '$$END') do
begin
{if (Pos('OR_ECS',UpperCase(Results[i]))>0) and (not uECSReport.ECSPermit) then
begin
Inc(i);
Continue;
end;}
if Mixed = true then
Dest.Add(MixedCase(Results[i]))
else
Dest.Add(Results[i]);
Inc(i);
end;
end;
end;
procedure LoadReportLists;
begin
CallV('ORWRP REPORT LISTS', [nil]);
uDateRanges := TStringList.Create;
uHSTypes := TStringList.Create;
uReportsList := TStringList.Create;
ExtractSection(uDateRanges, '[DATE RANGES]', true);
ExtractSection(uHSTypes, '[HEALTH SUMMARY TYPES]', true);
ExtractSection(uReportsList, '[REPORT LIST]', true);
end;
procedure LoadLabReportLists;
begin
CallV('ORWRP LAB REPORT LISTS', [nil]);
uLabReports := TStringList.Create;
ExtractSection(uLabReports, '[LAB REPORT LIST]', true);
end;
procedure LoadTree(Tab: String);
begin
CallV('ORWRP3 EXPAND COLUMNS', [Tab]);
uTree := TStringList.Create;
ExtractSection(uTree, '[REPORT LIST]', false);
end;
procedure ListReports(Dest: TStrings);
var
i: Integer;
begin
if uTree = nil
then LoadTree('REPORTS')
else
begin
uTree.Clear;
LoadTree('REPORTS');
end;
for i := 0 to uTree.Count - 1 do Dest.Add(Pieces(uTree[i], '^', 1, 20));
end;
procedure ListLabReports(Dest: TStrings);
var
i: integer;
begin
{if uLabreports = nil then LoadLabReportLists;
for i := 0 to uLabReports.Count - 1 do Dest.Add(Pieces(uLabReports[i], U, 1, 10)); }
if uTree = nil
then LoadTree('LABS')
else
begin
uTree.Clear;
LoadTree('LABS');
end;
for i := 0 to uTree.Count - 1 do Dest.Add(Pieces(uTree[i], '^', 1, 20));
end;
procedure ListReportDateRanges(Dest: TStrings);
begin
if uDateRanges = nil then LoadReportLists;
FastAssign(uDateRanges, Dest);
end;
procedure ListHealthSummaryTypes(Dest: TStrings);
begin
if uHSTypes = nil then LoadReportLists;
MixedCaseList(uHSTypes);
FastAssign(uHSTypes, Dest);
end;
procedure HealthSummaryCheck(Dest: TStrings; aQualifier: string);
begin
if aQualifier = '1' then
begin
ListHealthSummaryTypes(Dest);
end;
end;
procedure ColumnHeaders(Dest: TStrings; AReportType: String);
begin
CallV('ORWRP COLUMN HEADERS',[AReportType]);
FastAssign(RPCBrokerV.Results, Dest);
end;
procedure SaveColumnSizes(aColumn: String);
begin
CallV('ORWCH SAVECOL', [aColumn]);
end;
procedure ListImagingExams(Dest: TStrings);
var
x: string;
i: Integer;
begin
CallV('ORWRA IMAGING EXAMS1', [Patient.DFN]);
with RPCBrokerV do
begin
SetListFMDateTime('mm/dd/yyyy hh:nn', TStringList(Results), U, 3);
for i := 0 to Results.Count - 1 do
begin
x := Results[i];
if Piece(x,U,7) = 'Y' then SetPiece(x,U,7, ' - Abnormal');
x := Piece(x,U,1) + U + 'i' + Pieces(x,U,2,3)+ U + Piece(x,U,4)
+ U + Piece(x,U,6) + Piece(x,U,7) + U
+ MixedCase(Piece(Piece(x,U,9),'~',2)) + U + Piece(x,U,5) + U + '[+]'
+ U + Pieces(x, U, 15,17);
(* x := Piece(x,U,1) + U + 'i' + Pieces(x,U,2,3)+ U + Piece(x,U,4)
+ U + Piece(x,U,6) + Piece(x,U,7) + U + Piece(x,U,5) + U + '[+]' + U + Piece(x, U, 15);*)
Results[i] := x;
end;
FastAssign(Results, Dest);
end;
end;
procedure ListProcedures(Dest: TStrings);
var
x,sdate: string;
i: Integer;
begin
CallV('ORWMC PATIENT PROCEDURES1', [Patient.DFN]);
with RPCBrokerV do
begin
for i := 0 to Results.Count - 1 do
begin
x := Results[i];
if length(piece(x, U, 8)) > 0 then
begin
sdate := ShortDateStrToDate(piece(piece(x, U, 8),'@',1)) + ' ' + piece(piece(x, U, 8),'@',2);
end;
x := Piece(x, U, 1) + U + 'i' + Piece(x, U, 2) + U + sdate + U + Piece(x, U, 3) + U + Piece(x, U, 9) + '^[+]';
Results[i] := x;
end;
FastAssign(Results, Dest);
end;
end;
procedure ListNutrAssessments(Dest: TStrings);
var
x: string;
i: Integer;
begin
CallV('ORWRP1 LISTNUTR', [Patient.DFN]);
with RPCBrokerV do
begin
for i := 0 to Results.Count - 1 do
begin
x := Results[i];
x := Piece(x, U, 1) + U + 'i' + Piece(x, U, 3) + U + Piece(x, U, 3);
Results[i] := x;
end;
FastAssign(Results, Dest);
end;
end;
procedure ListSurgeryReports(Dest: TStrings);
{ returns a list of surgery cases for a patient, without documents}
//Facility^Case #^Date/Time of Operation^Operative Procedure^Surgeon name)
var
i: integer;
x, AFormat: string;
begin
CallV('ORWSR RPTLIST', [Patient.DFN]);
with RPCBrokerV do
begin
for i := 0 to Results.Count - 1 do
begin
x := Results[i];
if Piece(Piece(x, U, 3), '.', 2) = '' then AFormat := 'mm/dd/yyyy' else AFormat := 'mm/dd/yyyy hh:nn';
x := Piece(x, U, 1) + U + 'i' + Piece(x, U, 2) + U + FormatFMDateTimeStr(AFormat, Piece(x, U, 3))+ U +
Piece(x, U, 4)+ U + Piece(x, U, 5);
if Piece(Results[i], U, 6) = '+' then x := x + '^[+]';
Results[i] := x;
end;
FastAssign(Results, Dest);
end;
end;
procedure LoadReportText(Dest: TStrings; ReportType: string; const Qualifier: string; ARpc, AHSTag: string);
var
HSType, DaysBack, ExamID, MaxOcc, AReport, x: string;
Alpha, Omega, Trans: double;
begin
HSType := '';
DaysBack := '';
ExamID := '';
Alpha := 0;
Omega := 0;
if CharAt(Qualifier, 1) = 'T' then
begin
Alpha := StrToFMDateTime(Piece(Qualifier,';',1));
Omega := StrToFMDateTime(Piece(Qualifier,';',2));
if Alpha > Omega then
begin
Trans := Omega;
Omega := Alpha;
Alpha := Trans;
end;
MaxOcc := Piece(Qualifier,';',3);
SetPiece(AHSTag,';',4,MaxOcc);
end;
if CharAt(Qualifier, 1) = 'd' then
begin
MaxOcc := Piece(Qualifier,';',2);
SetPiece(AHSTag,';',4,MaxOcc);
x := Piece(Qualifier,';',1);
DaysBack := Copy(x, 2, Length(x));
end;
if CharAt(Qualifier, 1) = 'h' then HSType := Copy(Qualifier, 2, Length(Qualifier));
if CharAt(Qualifier, 1) = 'i' then ExamID := Copy(Qualifier, 2, Length(Qualifier));
AReport := ReportType + '~' + AHSTag;
if Length(ARpc) > 0 then
begin
CallV(ARpc, [Patient.DFN, AReport, HSType, DaysBack, ExamID, Alpha, Omega]);
QuickCopy(RPCBrokerV.Results,Dest);
end
else
begin
Dest.Add('RPC is missing from report definition (file 101.24).');
Dest.Add('Please contact Technical Support.');
end;
end;
procedure RemoteQueryAbortAll;
begin
CallV('XWB DEFERRED CLEARALL',[nil]);
end;
procedure RemoteQuery(Dest: TStrings; AReportType: string; AHSType, ADaysback,
AExamID: string; Alpha, AOmega: Double; ASite, ARemoteRPC, AHSTag: String);
var
AReport: string;
begin
AReport := AReportType + ';1' + '~' + AHSTag;
if length(AHSType) > 0 then
AHSType := piece(AHSType,':',1) + ';' + piece(AHSType,':',2); //format for backward compatibility
CallV('XWB REMOTE RPC', [ASite, ARemoteRPC, 0, Patient.DFN + ';' + Patient.ICN,
AReport, AHSType, ADaysBack, AExamID, Alpha, AOmega]);
QuickCopy(RPCBrokerV.Results,Dest);
end;
procedure DirectQuery(Dest: TStrings; AReportType: string; AHSType, ADaysback,
AExamID: string; Alpha, AOmega: Double; ASite, ARemoteRPC, AHSTag: String);
var
AReport: string;
begin
AReport := AReportType + ';1' + '~' + AHSTag;
if length(AHSType) > 0 then
AHSType := piece(AHSType,':',1) + ';' + piece(AHSType,':',2); //format for backward compatibility
CallV('XWB DIRECT RPC', [ASite, ARemoteRPC, 0, Patient.DFN + ';' + Patient.ICN,
AReport, AHSType, ADaysBack, AExamID, Alpha, AOmega]);
QuickCopy(RPCBrokerV.Results,Dest);
end;
function ReportQualifierType(ReportType: Integer): Integer;
var
i: Integer;
begin
Result := 0;
for i := 0 to uReportsList.Count - 1 do
if StrToIntDef(Piece(uReportsList[i], U, 1), 0) = ReportType
then Result := StrToIntDef(Piece(uReportsList[i], U, 3), 0);
end;
function ImagingParams: String;
begin
Result := sCallV('ORWTPD GETIMG',[nil]);
end;
function AutoRDV: String;
begin
Result := sCallV('ORWCIRN AUTORDV', [nil]);
end;
function HDRActive: String;
begin
Result := sCallV('ORWCIRN HDRON', [nil]);
end;
procedure PrintVReports(Dest, ADevice, AHeader: string; AReport: TStringList);
begin
CallV('ORWRP PRINT V REPORT', [ADevice, Patient.DFN, AHeader, AReport]);
end;
procedure PrintReportsToDevice(AReport: string; const Qualifier, Patient, ADevice: string;
var ErrMsg: string; aComponents: TStringlist; ARemoteSiteID, ARemoteQuery, AHSTag: string);
{ prints a report on the selected device }
var
HSType, DaysBack, ExamID, MaxOcc, ARpt, x: string;
Alpha, Omega: double;
j: integer;
RemoteHandle,Report: string;
aHandles: TStringlist;
begin
HSType := '';
DaysBack := '';
ExamID := '';
Alpha := 0;
Omega := 0;
aHandles := TStringList.Create;
if CharAt(Qualifier, 1) = 'T' then
begin
Alpha := StrToFMDateTime(Piece(Qualifier,';',1));
Omega := StrToFMDateTime(Piece(Qualifier,';',2));
MaxOcc := Piece(Qualifier,';',3);
SetPiece(AHSTag,';',4,MaxOcc);
end;
if CharAt(Qualifier, 1) = 'd' then
begin
MaxOcc := Piece(Qualifier,';',2);
SetPiece(AHSTag,';',4,MaxOcc);
x := Piece(Qualifier,';',1);
DaysBack := Copy(x, 2, Length(x));
end;
if CharAt(Qualifier, 1) = 'h' then HSType := Copy(Qualifier, 2, Length(Qualifier));
if CharAt(Qualifier, 1) = 'i' then ExamID := Copy(Qualifier, 2, Length(Qualifier));
if Length(ARemoteSiteID) > 0 then
begin
RemoteHandle := '';
for j := 0 to RemoteReports.Count - 1 do
begin
Report := TRemoteReport(RemoteReports.ReportList.Items[j]).Report;
if Report = ARemoteQuery then
begin
RemoteHandle := TRemoteReport(RemoteReports.ReportList.Items[j]).Handle
+ '^' + Pieces(Report,'^',9,10);
break;
end;
end;
if Length(RemoteHandle) > 1 then
with RemoteSites.SiteList do
aHandles.Add(ARemoteSiteID + '^' + RemoteHandle);
end;
ARpt := AReport + '~' + AHSTag;
if aHandles.Count > 0 then
begin
ErrMsg := sCallV('ORWRP PRINT REMOTE REPORT',[ADevice, Patient, ARpt, aHandles]);
if Piece(ErrMsg, U, 1) = '0' then ErrMsg := '' else ErrMsg := Piece(ErrMsg, U, 2);
end
else
begin
ErrMsg := sCallV('ORWRP PRINT REPORT',[ADevice, Patient, ARpt, HSType,
DaysBack, ExamID, aComponents, Alpha, Omega]);
if Piece(ErrMsg, U, 1) = '0' then ErrMsg := '' else ErrMsg := Piece(ErrMsg, U, 2);
end;
aHandles.Clear;
aHandles.Free;
end;
function GetFormattedReport(AReport: string; const Qualifier, Patient: string;
aComponents: TStringlist; ARemoteSiteID, ARemoteQuery, AHSTag: string): TStrings;
{ prints a report on the selected device }
var
HSType, DaysBack, ExamID, MaxOcc, ARpt, x: string;
Alpha, Omega: double;
j: integer;
RemoteHandle,Report: string;
aHandles: TStringlist;
begin
HSType := '';
DaysBack := '';
ExamID := '';
Alpha := 0;
Omega := 0;
aHandles := TStringList.Create;
if CharAt(Qualifier, 1) = 'T' then
begin
Alpha := StrToFMDateTime(Piece(Qualifier,';',1));
Omega := StrToFMDateTime(Piece(Qualifier,';',2));
MaxOcc := Piece(Qualifier,';',3);
SetPiece(AHSTag,';',4,MaxOcc);
end;
if CharAt(Qualifier, 1) = 'd' then
begin
MaxOcc := Piece(Qualifier,';',2);
SetPiece(AHSTag,';',4,MaxOcc);
x := Piece(Qualifier,';',1);
DaysBack := Copy(x, 2, Length(x));
end;
if CharAt(Qualifier, 1) = 'h' then HSType := Copy(Qualifier, 2, Length(Qualifier));
if CharAt(Qualifier, 1) = 'i' then ExamID := Copy(Qualifier, 2, Length(Qualifier));
if Length(ARemoteSiteID) > 0 then
begin
RemoteHandle := '';
for j := 0 to RemoteReports.Count - 1 do
begin
Report := TRemoteReport(RemoteReports.ReportList.Items[j]).Report;
if Report = ARemoteQuery then
begin
RemoteHandle := TRemoteReport(RemoteReports.ReportList.Items[j]).Handle
+ '^' + Pieces(Report,'^',9,10);
break;
end;
end;
if Length(RemoteHandle) > 1 then
with RemoteSites.SiteList do
aHandles.Add(ARemoteSiteID + '^' + RemoteHandle);
end;
ARpt := AReport + '~' + AHSTag;
if aHandles.Count > 0 then
begin
CallV('ORWRP PRINT WINDOWS REMOTE',[Patient, ARpt, aHandles]);
Result := RPCBrokerV.Results;
end
else
begin
CallV('ORWRP PRINT WINDOWS REPORT',[Patient, ARpt, HSType,
DaysBack, ExamID, aComponents, Alpha, Omega]);
Result := RPCBrokerV.Results;
end;
aHandles.Clear;
aHandles.Free;
end;
function DefaultToWindowsPrinter: Boolean;
begin
Result := (StrToIntDef(sCallV('ORWRP WINPRINT DEFAULT',[]), 0) > 0);
end;
procedure PrintWindowsReport(ARichEdit: TRichEdit; APageBreak, Atitle: string; var ErrMsg: string; IncludeHeader: Boolean = false);
var
i, j, x, y, LineHeight: integer;
aGoHead: string;
aHeader: TStringList;
const
TX_ERR_CAP = 'Print Error';
TX_FONT_SIZE = 10;
TX_FONT_NAME = 'Courier New';
TX_FONT_COLOR = clBlack;
begin
aHeader := TStringList.Create;
aGoHead := '';
if piece(Atitle,';',2) = '1' then
begin
Atitle := piece(Atitle,';',1);
aGoHead := '1';
end;
CreatePatientHeader(aHeader ,ATitle);
with ARichEdit do
begin
(* if Lines[Lines.Count - 1] = APageBreak then // remove trailing form feed
Lines.Delete(Lines.Count - 1);
while (Lines[0] = '') or (Lines[0] = APageBreak) do
Lines.Delete(0); // remove leading blank lines and form feeds*)
{v20.4 - SFC-0602-62899 - RV}
while (Lines.Count > 0) and ((Lines[Lines.Count - 1] = '') or (Lines[Lines.Count - 1] = APageBreak)) do
Lines.Delete(Lines.Count - 1); // remove trailing blank lines and form feeds
while (Lines.Count > 0) and ((Lines[0] = '') or (Lines[0] = APageBreak)) do
Lines.Delete(0); // remove leading blank lines and form feeds
if Lines.Count > 1 then
begin
(* i := Lines.IndexOf(APageBreak);
if ((i >= 0 ) and (i < Lines.Count - 1)) then // removed in v15.9 (RV)
begin*)
Printer.Canvas.Font.Size := TX_FONT_SIZE;
Printer.Canvas.Font.Name := TX_FONT_NAME;
Printer.Canvas.Font.Color := TX_FONT_COLOR;
Printer.Title := ATitle;
x := Trunc(Printer.Canvas.TextWidth(StringOfChar('=', TX_FONT_SIZE)) * 0.75);
LineHeight := Printer.Canvas.TextHeight(TX_FONT_NAME);
y := LineHeight * 5; // 5 lines = .83" top margin v15.9 (RV)
// try
// Printer.Copies := Printer.Copies; // RTC 1223892
Printer.BeginDoc;
//Do we need to add the header?
IF IncludeHeader then begin
for j := 0 to aHeader.Count - 1 do
begin
Printer.Canvas.TextOut(x, y, aHeader[j]);
y := y + LineHeight;
end;
end;
for i := 0 to Lines.Count - 1 do
begin
if Lines[i] = APageBreak then
begin
Printer.NewPage;
y := LineHeight * 5; // 5 lines = .83" top margin v15.9 (RV)
if (IncludeHeader) then
begin
for j := 0 to aHeader.Count - 1 do
begin
Printer.Canvas.TextOut(x, y, aHeader[j]);
y := y + LineHeight;
end;
end;
end
else
begin
Printer.Canvas.TextOut(x, y, Lines[i]);
y := y + LineHeight;
end;
end;
Printer.EndDoc;
// except
// on E: Exception do
// InfoBox(E.Message, 'Printing error',MB_OK);
// end;
(* end
else // removed in v15.9 (RV) TRichEdit.Print no longer used.
try
Font.Size := TX_FONT_SIZE;
Font.Name := TX_FONT_NAME;
Print(ATitle);
except
ErrMsg := TX_ERR_CAP;
end;*)
end
else if ARichEdit.Lines.Count = 1 then
if Piece(ARichEdit.Lines[0], U, 1) <> '0' then
ErrMsg := Piece(ARichEdit.Lines[0], U, 2);
end;
aHeader.Free;
end;
procedure CreatePatientHeader(var HeaderList: TStringList; PageTitle: string);
// standard patient header, from HEAD^ORWRPP
var
tmpStr, tmpItem: string;
begin
with HeaderList do
begin
Add(' ');
Add(StringOfChar(' ', (74 - Length(PageTitle)) div 2) + PageTitle);
Add(' ');
tmpStr := Patient.Name + ' ' + Patient.SSN;
tmpItem := tmpStr + StringOfChar(' ', 39 - Length(tmpStr)) + Encounter.LocationName;
tmpStr := FormatFMDateTime('mmm dd, yyyy', Patient.DOB) + ' (' + IntToStr(Patient.Age) + ')';
tmpItem := tmpItem + StringOfChar(' ', 74 - (Length(tmpItem) + Length(tmpStr))) + tmpStr;
Add(tmpItem);
Add(StringOfChar('=', 74));
Add('*** WORK COPY ONLY ***' + StringOfChar(' ', 24) + 'Printed: ' + FormatFMDateTime('mmm dd, yyyy hh:nn', FMNow));
Add(' ');
Add(' ');
end;
end;
procedure PrintGraph(GraphImage: TChart; PageTitle: string);
var
AHeader: TStringList;
i, y, LineHeight: integer;
GraphPic: TBitMap;
Magnif: integer;
const
TX_FONT_SIZE = 12;
TX_FONT_NAME = 'Courier New';
CF_BITMAP = 2; // from Windows.pas
begin
ClipBoard;
AHeader := TStringList.Create;
CreatePatientHeader(AHeader, PageTitle);
GraphPic := TBitMap.Create;
try
GraphImage.CopyToClipboardBitMap;
GraphPic.LoadFromClipBoardFormat(CF_BITMAP, ClipBoard.GetAsHandle(CF_BITMAP), 0);
with Printer do
begin
Canvas.Font.Size := TX_FONT_SIZE;
Canvas.Font.Name := TX_FONT_NAME;
Title := PageTitle;
Magnif := (Canvas.TextWidth(StringOfChar('=', 74)) div GraphImage.Width);
LineHeight := Printer.Canvas.TextHeight(TX_FONT_NAME);
y := LineHeight;
BeginDoc;
try
for i := 0 to AHeader.Count - 1 do
begin
Canvas.TextOut(0, y, AHeader[i]);
y := y + LineHeight;
end;
y := y + (4 * LineHeight);
//GraphImage.PrintPartial(Rect(0, y, Canvas.TextWidth(StringOfChar('=', 74)), y + (Magnif * GraphImage.Height)));
PrintBitmap(Canvas, Rect(0, y, Canvas.TextWidth(StringOfChar('=', 74)), y + (Magnif * GraphImage.Height)), GraphPic);
finally
EndDoc;
end;
end;
finally
ClipBoard.Clear;
GraphPic.Free;
AHeader.Free;
end;
end;
procedure SaveDefaultPrinter(DefPrinter: string) ;
begin
CallV('ORWRP SAVE DEFAULT PRINTER', [DefPrinter]);
end;
function HSFileLookup(aFile: String; const StartFrom: string;
Direction:Integer): TStrings;
begin
CallV('ORWRP2 HS FILE LOOKUP', [aFile, StartFrom, Direction]);
MixedCaseList(RPCBrokerV.Results);
Result := RPCBrokerV.Results;
end;
procedure HSComponentFiles(Dest: TStrings; aComponent: String);
begin
CallV('ORWRP2 HS COMP FILES', [aComponent]);
QuickCopy(RPCBrokerV.Results,Dest);
end;
procedure HSSubItems(Dest: TStrings; aItem: String);
begin
CallV('ORWRP2 HS SUBITEMS', [aItem]);
MixedCaseList(RPCBrokerV.Results);
QuickCopy(RPCBrokerV.Results,Dest);
end;
procedure HSReportText(Dest: TStrings; aComponents: TStringlist);
begin
CallV('ORWRP2 HS REPORT TEXT', [aComponents, Patient.DFN]);
QuickCopy(RPCBrokerV.Results,Dest);
end;
procedure HSComponents(Dest: TStrings);
begin
CallV('ORWRP2 HS COMPONENTS', [nil]);
QuickCopy(RPCBrokerV.Results,Dest);
end;
procedure HSABVComponents(Dest: TStrings);
begin
CallV('ORWRP2 COMPABV', [nil]);
QuickCopy(RPCBrokerV.Results,Dest);
end;
procedure HSDispComponents(Dest: TStrings);
begin
CallV('ORWRP2 COMPDISP', [nil]);
QuickCopy(RPCBrokerV.Results,Dest);
end;
procedure HSComponentSubs(Dest: TStrings; aItem: String);
begin
CallV('ORWRP2 HS COMPONENT SUBS',[aItem]);
MixedCaseList(RPCBrokerV.Results);
QuickCopy(RPCBrokerV.Results,Dest);
end;
function GetRemoteStatus(aHandle: string): String;
begin
CallV('XWB REMOTE STATUS CHECK', [aHandle]);
Result := RPCBrokerV.Results[0];
end;
function GetAdhocLookup: integer;
begin
CallV('ORWRP2 GETLKUP', [nil]);
if RPCBrokerV.Results.Count > 0 then
Result := StrToInt(RPCBrokerV.Results[0])
else
Result := 0;
end;
procedure SetAdhocLookup(aLookup: integer);
begin
CallV('ORWRP2 SAVLKUP', [IntToStr(aLookup)]);
end;
procedure GetRemoteData(Dest: TStrings; aHandle: string; aItem: PChar);
begin
CallV('XWB REMOTE GETDATA', [aHandle]);
if RPCBrokerV.Results.Count < 1 then
RPCBrokerV.Results[0] := 'No data found.';
if (RPCBrokerV.Results.Count < 2) and (RPCBrokerV.Results[0] = '') then
RPCBrokerV.Results[0] := 'No data found.';
QuickCopy(RPCBrokerV.Results,Dest);
end;
procedure ModifyHDRData(Dest: string; aHandle: string; aID: string);
begin
CallV('ORWRP4 HDR MODIFY', [aHandle, aID]);
end;
procedure PrintBitmap(Canvas: TCanvas; DestRect: TRect; Bitmap: TBitmap);
var
BitmapHeader: pBitmapInfo;
BitmapImage : POINTER;
HeaderSize : DWORD; // Use DWORD for D3-D5 compatibility
ImageSize : DWORD;
begin
GetDIBSizes(Bitmap.Handle, HeaderSize, ImageSize);
GetMem(BitmapHeader, HeaderSize);
GetMem(BitmapImage, ImageSize);
try
GetDIB(Bitmap.Handle, Bitmap.Palette, BitmapHeader^, BitmapImage^);
StretchDIBits(Canvas.Handle,
DestRect.Left, DestRect.Top, // Destination Origin
DestRect.Right - DestRect.Left, // Destination Width
DestRect.Bottom - DestRect.Top, // Destination Height
0, 0, // Source Origin
Bitmap.Width, Bitmap.Height, // Source Width & Height
BitmapImage,
TBitmapInfo(BitmapHeader^),
DIB_RGB_COLORS,
SRCCOPY)
finally
FreeMem(BitmapHeader);
FreeMem(BitmapImage)
end
end {PrintBitmap};
initialization
{ nothing to initialize }
finalization
uTree.Free;
uReportsList.Free;
uLabReports.Free;
uDateRanges.Free;
uHSTypes.Free;
end.
|
{
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.net/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* HproseSynaHttpClient.pas *
* *
* hprose synapse http client unit for delphi. *
* *
* LastModified: Dec 29, 2012 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
}
unit HproseSynaHttpClient;
{$I Hprose.inc}
interface
uses Classes, HproseCommon, HproseClient;
type
{ THproseSynaHttpClient }
THproseSynaHttpClient = class(THproseClient)
private
FHttpPool: IList;
FProtocol: string;
FUser: string;
FPassword: string;
FHost: string;
FPort: string;
FPath: string;
FPara: string;
FHeaders: TStringList;
FKeepAlive: Boolean;
FKeepAliveTimeout: integer;
FStatus100: Boolean;
FProxyHost: string;
FProxyPort: Integer;
FProxyUser: string;
FProxyPass: string;
FUserAgent: string;
FTimeout: Integer;
protected
function GetInvokeContext: TObject; override;
function GetOutputStream(var Context: TObject): TStream; override;
procedure SendData(var Context: TObject); override;
function GetInputStream(var Context: TObject): TStream; override;
procedure EndInvoke(var Context: TObject); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure UseService(const AUri: string); override;
published
{:Before HTTP operation you may define any non-standard headers for HTTP
request, except of: 'Expect: 100-continue', 'Content-Length', 'Content-Type',
'Connection', 'Authorization', 'Proxy-Authorization' and 'Host' headers.}
property Headers: TStringList read FHeaders;
{:If @true (default value is @false), keepalives in HTTP protocol 1.1 is enabled.}
property KeepAlive: Boolean read FKeepAlive write FKeepAlive;
{:Define timeout for keepalives in seconds! Default value is 300.}
property KeepAliveTimeout: integer read FKeepAliveTimeout write FKeepAliveTimeout;
{:if @true, then server is requested for 100status capability when uploading
data. Default is @true (on).}
property Status100: Boolean read FStatus100 write FStatus100;
{:Address of proxy server (IP address or domain name).}
property ProxyHost: string read FProxyHost write FProxyHost;
{:Port number for proxy connection. Default value is 8080.}
property ProxyPort: Integer read FProxyPort write FProxyPort;
{:Username for connect to proxy server.}
property ProxyUser: string read FProxyUser write FProxyUser;
{:Password for connect to proxy server.}
property ProxyPass: string read FProxyPass write FProxyPass;
{:Here you can specify custom User-Agent indentification. By default is
used: 'Hprose Http Client for Delphi (Synapse)'}
property UserAgent: string read FUserAgent write FUserAgent;
{:UserName for user authorization.}
property UserName: string read FUser write FUser;
{:Password for user authorization.}
property Password: string read FPassword write FPassword;
{:Specify default timeout for socket operations.}
property Timeout: Integer read FTimeout write FTimeout;
end;
procedure Register;
implementation
uses httpsend, synautil, SysUtils, Variants;
var
cookieManager: IMap;
procedure SetCookie(Header: TStringList; const Host: string);
var
I, Pos: Integer;
Name, Value, CookieString, Path: string;
Cookie: IMap;
begin
for I := 0 to Header.Count - 1 do begin
Value := Header.Strings[I];
Pos := AnsiPos(':', Value);
Name := LowerCase(Copy(Value, 1, Pos - 1));
if (Name = 'set-cookie') or (Name = 'set-cookie2') then begin
Value := Trim(Copy(Value, Pos + 1, MaxInt));
Pos := AnsiPos(';', Value);
CookieString := Copy(Value, 1, Pos - 1);
Value := Copy(Value, Pos + 1, MaxInt);
Cookie := TCaseInsensitiveHashMap.Split(Value, ';', '=', 0, True, False, True);
Pos := AnsiPos('=', CookieString);
Cookie['name'] := Copy(CookieString, 1, Pos - 1);
Cookie['value'] := Copy(CookieString, Pos + 1, MaxInt);
if Cookie.ContainsKey('path') then begin
Path := Cookie['path'];
if (Length(Path) > 0) then begin
if (Path[1] = '"') then Delete(Path, 1, 1);
if (Path[Length(Path)] = '"') then SetLength(Path, Length(Path) - 1);
end;
if (Length(Path) > 0) then
Cookie['path'] := Path
else
Cookie['path'] := '/';
end
else
Cookie['path'] := '/';
if Cookie.ContainsKey('expires') then begin
Cookie['expires'] := DecodeRfcDateTime(Cookie['expires']);
end;
if Cookie.ContainsKey('domain') then
Cookie['domain'] := LowerCase(Cookie['domain'])
else
Cookie['domain'] := Host;
Cookie['secure'] := Cookie.ContainsKey('secure');
CookieManager.BeginWrite;
try
if not CookieManager.ContainsKey(Cookie['domain']) then
CookieManager[Cookie['domain']] := THashMap.Create(False, True) as IMap;
VarToMap(CookieManager[Cookie['domain']])[Cookie['name']] := Cookie;
finally
CookieManager.EndWrite;
end;
end;
end;
end;
function GetCookie(const Host, Path: string; Secure: Boolean): string;
var
Cookies, CookieMap, Cookie: IMap;
Names: IList;
Domain: string;
I, J: Integer;
begin
Cookies := THashMap.Create(False);
CookieManager.BeginRead;
try
for I := 0 to CookieManager.Count - 1 do begin
Domain := VarToStr(CookieManager.Keys[I]);
if AnsiPos(Domain, Host) <> 0 then begin
CookieMap := VarToMap(CookieManager.Values[I]);
CookieMap.BeginRead;
try
Names := TArrayList.Create(False);
for J := 0 to CookieMap.Count - 1 do begin
Cookie := VarToMap(CookieMap.Values[J]);
if Cookie.ContainsKey('expires') and (Cookie['expires'] < Now) then
Names.Add(Cookie['name'])
else if AnsiPos(Cookie['path'], Path) = 1 then begin
if ((Secure and Cookie['secure']) or not Cookie['secure']) and
(Cookie['value'] <> '') then
Cookies[Cookie['name']] := Cookie['value'];
end;
end;
finally
CookieMap.EndRead;
end;
if Names.Count > 0 then begin
CookieMap.BeginWrite;
try
for J := 0 to Names.Count - 1 do CookieMap.Delete(Names[J]);
finally
CookieMap.EndWrite;
end;
end;
end;
end;
Result := Cookies.Join('; ');
finally
CookieManager.EndRead;
end;
end;
{ THproseSynaHttpClient }
function THproseSynaHttpClient.GetInvokeContext: TObject;
begin
FHttpPool.Lock;
try
if FHttpPool.Count > 0 then
Result := VarToObj(FHttpPool.Delete(FHttpPool.Count - 1))
else
Result := THttpSend.Create;
finally
FHttpPool.Unlock;
end;
end;
function THproseSynaHttpClient.GetOutputStream(var Context: TObject): TStream;
begin
if Context <> nil then
Result := THTTPSend(Context).Document
else
raise EHproseException.Create('Can''t get output stream.');
end;
procedure THproseSynaHttpClient.SendData(var Context: TObject);
var
Cookie: string;
begin
if Context <> nil then
with THTTPSend(Context) do begin
Headers.Assign(FHeaders);
KeepAlive := FKeepAlive;
KeepAliveTimeout := FKeepAliveTimeout;
Status100 := FStatus100;
UserName := FUser;
Password := FPassword;
ProxyHost := FProxyHost;
if FProxyPort = 0 then
ProxyPort := ''
else
ProxyPort := IntToStr(FProxyPort);
ProxyUser := FProxyUser;
ProxyPass := FProxyPass;
UserAgent := FUserAgent;
Timeout := FTimeout;
Protocol := '1.1';
MimeType := 'application/hprose';
Cookie := GetCookie(FHost,
FPath,
LowerCase(FProtocol) = 'https');
if Cookie <> '' then Headers.Add('Cookie: ' + Cookie);
HTTPMethod('POST', FUri);
SetCookie(Headers, FHost);
end
else
raise EHproseException.Create('Can''t send data.');
end;
function THproseSynaHttpClient.GetInputStream(var Context: TObject): TStream;
begin
if Context <> nil then
Result := THTTPSend(Context).Document
else
raise EHproseException.Create('Can''t get input stream.');
end;
procedure THproseSynaHttpClient.EndInvoke(var Context: TObject);
begin
if Context <> nil then begin
FHttpPool.Lock;
try
with THTTPSend(Context) do begin
Clear;
Cookies.Clear;
end;
FHttpPool.Add(ObjToVar(Context));
finally
FHttpPool.Unlock;
end;
end;
end;
constructor THproseSynaHttpClient.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHttpPool := TArrayList.Create(10);
FHeaders := TStringList.Create;
FUser := '';
FPassword := '';
FKeepAlive := False;
FKeepAliveTimeout := 300;
FStatus100 := False;
FProxyHost := '';
FProxyPort := 8080;
FProxyUser := '';
FProxyPass := '';
FUserAgent := 'Hprose Http Client for Delphi (Synapse)';
FTimeout := 30000;
end;
destructor THproseSynaHttpClient.Destroy;
var
I: Integer;
begin
FHttpPool.Lock;
try
for I := FHttpPool.Count - 1 downto 0 do
THTTPSend(VarToObj(FHttpPool.Delete(I))).Free;
finally
FHttpPool.Unlock;
end;
FreeAndNil(FHeaders);
inherited;
end;
procedure THproseSynaHttpClient.UseService(const AUri: string);
begin
inherited UseService(AUri);
ParseURL(FUri, FProtocol, FUser, FPassword, FHost, FPort, FPath, FPara);
end;
procedure Register;
begin
RegisterComponents('Hprose',[THproseSynaHttpClient]);
end;
initialization
CookieManager := TCaseInsensitiveHashMap.Create(False, True);
end.
|
{******************************************}
{ TeeChart OHLC Compression Function }
{ Copyright (c) 2000-2004 by David Berneda }
{ All Rights Reserved }
{******************************************}
unit TeeCompressOHLC;
{$I TeeDefs.inc}
interface
Uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
Classes,
{$IFDEF CLX}
QForms, QControls, QStdCtrls, QComCtrls,
{$ELSE}
Forms, Controls, StdCtrls, ComCtrls,
{$ENDIF}
TeEngine, OHLChart, TeeBaseFuncEdit, TeCanvas;
{
This unit contains a "TeeFunction" ( TCompressOHLCFunction class )
The purpose of this function is to "compress" an OHLC series
(for example a financial Candle series).
( OHLC stands for "Open High Low Close" in financial terms )
To "compress" means to find out the OHLC of a date-time period from
the original data.
This function also works with non-OHLC source series.
}
type
TCompressFuncEditor = class(TBaseFunctionEditor)
CBDatePeriod: TComboFlat;
RadioDate: TRadioButton;
ENum: TEdit;
RadioPoints: TRadioButton;
UpDown1: TUpDown;
RadioTime: TRadioButton;
CBTimePeriod: TComboFlat;
procedure CBDatePeriodChange(Sender: TObject);
procedure RadioDateClick(Sender: TObject);
procedure RadioPointsClick(Sender: TObject);
procedure ENumChange(Sender: TObject);
procedure ENumClick(Sender: TObject);
procedure CBDatePeriodClick(Sender: TObject);
procedure RadioTimeClick(Sender: TObject);
procedure CBTimePeriodChange(Sender: TObject);
private
{ Private declarations }
protected
procedure ApplyFormChanges; override;
procedure SetFunction; override;
public
{ Public declarations }
end;
TCompressionPeriod=( ocDay, ocWeek, ocMonth, ocBiMonth, ocQuarter, ocYear,
ocSecond, ocTenSecond, ocMinute, ocTwoMinutes,
ocFiveMinutes, ocTenMinutes, ocFifteenMinutes,
ocTwentyMinutes, ocHalfHour, ocHour, ocTwoHours,
ocThreeHour, ocSixHour, ocTwelveHour);
TCompressGetDate=procedure(Sender:TTeeFunction; Source:TChartSeries;
ValueIndex:Integer; Var Date:TDateTime) of object;
TCompressFunction=class(TTeeFunction)
private
FCompress: TCompressionPeriod;
FOnGetDate: TCompressGetDate;
procedure SetCompress(const Value: TCompressionPeriod);
protected
class function GetEditorClass: String; override;
class procedure PrepareForGallery(Chart:TCustomAxisPanel); override;
public
Constructor Create(AOwner: TComponent); override;
procedure AddPoints(Source: TChartSeries); override;
Procedure CompressSeries(Source:TChartSeries;
DestOHLC:TOHLCSeries;
Volume:TChartSeries=nil;
DestVolume:TChartSeries=nil);
published
property Compress:TCompressionPeriod read FCompress write SetCompress default ocWeek;
property OnGetDate:TCompressGetDate read FOnGetDate write FOnGetDate;
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses
{$IFDEF D6}
DateUtils,
{$ENDIF}
SysUtils, Chart, TeeProCo, CandleCh;
{ TCompressFunction }
constructor TCompressFunction.Create(AOwner: TComponent);
begin
inherited;
CanUsePeriod:=False;
SingleSource:=True;
HideSourceList:=True;
FCompress:=ocWeek;
end;
class function TCompressFunction.GetEditorClass: String;
begin
result:='TCompressFuncEditor';
end;
procedure TCompressFunction.AddPoints(Source: TChartSeries);
begin
if ParentSeries is TOHLCSeries then
CompressSeries(Source,TOHLCSeries(ParentSeries),nil,nil);
end;
Procedure TCompressFunction.CompressSeries(Source:TChartSeries;
DestOHLC:TOHLCSeries;
Volume:TChartSeries=nil;
DestVolume:TChartSeries=nil);
var t : Integer;
tmpGroup : Integer;
OldGroup : Integer;
tmp : Integer;
Year : Word;
Month : Word;
Day : Word;
Hour : Word;
Minute : Word;
Second : Word;
MilliSecond : Word;
DoIt : Boolean;
tmpDate : TDateTime;
tmpValue : TChartValue;
tmpList : TChartValueList;
tmpPeriod : Integer;
begin
DestOHLC.Clear;
if Assigned(DestVolume) then DestVolume.Clear;
OldGroup:=0;
tmpList:=ValueList(Source);
tmpPeriod:=Round(Period);
for t:=0 to Source.Count-1 do
begin
tmpDate:=Source.NotMandatoryValueList.Value[t];
if tmpPeriod=0 then
begin
// user event
if Assigned(FOnGetDate) then FOnGetDate(Self,Source,t,tmpDate);
{$IFDEF D6}
DecodeDateTime(tmpDate,Year,Month,Day,Hour,Minute,Second,MilliSecond);
{$ELSE}
DecodeDate(tmpDate,Year,Month,Day);
DecodeTime(tmpDate,Hour,Minute,Second,MilliSecond);
{$ENDIF}
case Compress of
// Date
ocDay: tmpGroup:=Trunc(tmpDate);
ocWeek: begin
tmpGroup:=DayOfWeek(tmpDate)-1;
if tmpGroup=0 then tmpGroup:=7;
end;
ocMonth: tmpGroup:=Month;
ocBiMonth: tmpGroup:=(Month-1) div 2;
ocQuarter: tmpGroup:=(Month-1) div 3;
ocYear: tmpGroup:=Year;
// Time
ocSecond: tmpGroup:=Second;
ocTenSecond: tmpGroup:=Second div 10;
ocMinute: tmpGroup:=Minute;
ocTwoMinutes: tmpGroup:=Minute div 2;
ocFiveMinutes: tmpGroup:=Minute div 5;
ocTenMinutes: tmpGroup:=Minute div 10;
ocFifteenMinutes: tmpGroup:=Minute div 15;
ocTwentyMinutes: tmpGroup:=Minute div 20;
ocHalfHour: tmpGroup:=Minute div 30;
ocHour: tmpGroup:=Hour;
ocTwoHours: tmpGroup:=Hour div 2;
ocThreeHour: tmpGroup:=Hour div 3;
ocSixHour: tmpGroup:=Hour div 6;
else
// ocTwelveHour:
tmpGroup:=Hour div 12;
end;
if Compress=ocWeek then DoIt:=tmpGroup<OldGroup
else DoIt:=tmpGroup<>OldGroup;
OldGroup:=tmpGroup;
end
else DoIt:=(t mod tmpPeriod)=0;
if (t=0) or DoIt then
begin
case PeriodAlign of
paFirst: ;
paCenter: ;
else
// paLast:
end;
if Source is TOHLCSeries then
With TOHLCSeries(Source) do
tmp:=DestOHLC.AddOHLC(
tmpDate,
OpenValues.Value[t],
HighValues.Value[t],
LowValues.Value[t],
CloseValues.Value[t])
else
With Source do
begin
tmpValue:=tmpList.Value[t];
tmp:=DestOHLC.AddOHLC(
tmpDate,
tmpValue,
tmpValue,
tmpValue,
tmpValue);
end;
DestOHLC.Labels[tmp]:=Source.Labels[t];
if Assigned(DestVolume) then
DestVolume.AddXY(Source.NotMandatoryValueList.Value[t],
Volume.YValues.Value[t]);
end
else
begin
tmp:=DestOHLC.Count-1;
if Source is TOHLCSeries then
with TOHLCSeries(Source) do
begin
DestOHLC.CloseValues.Value[tmp]:=CloseValues.Value[t];
DestOHLC.DateValues.Value[tmp] :=DateValues.Value[t];
if HighValues[t]>DestOHLC.HighValues.Value[tmp] then
DestOHLC.HighValues.Value[tmp]:=HighValues.Value[t];
if LowValues[t]<DestOHLC.LowValues.Value[tmp] then
DestOHLC.LowValues.Value[tmp]:=LowValues.Value[t];
end
else
with Source do
begin
tmpValue:=tmpList.Value[t];
DestOHLC.CloseValues.Value[tmp]:=tmpValue;
DestOHLC.DateValues.Value[tmp] :=NotMandatoryValueList.Value[t];
if tmpValue>DestOHLC.HighValues.Value[tmp] then
DestOHLC.HighValues.Value[tmp]:=tmpValue;
if tmpValue<DestOHLC.LowValues.Value[tmp] then
DestOHLC.LowValues.Value[tmp]:=tmpValue;
end;
DestOHLC.Labels[tmp]:=Source.Labels[t];
if Assigned(DestVolume) then
begin
With DestVolume.YValues do
Value[tmp]:=Value[tmp]+Volume.YValues.Value[t];
DestVolume.XValues.Value[tmp]:=Volume.XValues.Value[t];
end;
end;
end;
if Assigned(DestVolume) then // 5.01
begin
DestVolume.XValues.Modified:=True; // 5.01
DestVolume.YValues.Modified:=True;
end;
end;
procedure TCompressFunction.SetCompress(const Value: TCompressionPeriod);
begin
if FCompress<>Value then
begin
FCompress:=Value;
ReCalculate;
end;
end;
type TSeriesAccess=class(TChartSeries);
class Procedure TCompressFunction.PrepareForGallery(Chart:TCustomAxisPanel);
var tmpSeries : TChartSeries;
begin
Chart.FreeAllSeries;
tmpSeries:=CreateNewSeries(Chart.Owner,Chart,TCandleSeries,TCompressFunction);
TSeriesAccess(tmpSeries).PrepareForGallery(True);
end;
// TCompressFuncEditor
procedure TCompressFuncEditor.CBDatePeriodChange(Sender: TObject);
begin
RadioDate.Checked:=True;
EnableApply;
end;
procedure TCompressFuncEditor.SetFunction;
begin
inherited;
CBDatePeriod.ItemIndex:=0;
CBTimePeriod.ItemIndex:=0;
with TCompressFunction(IFunction) do
begin
if Period=0 then
begin
if Ord(Compress)<Ord(ocSecond) then
begin
CBDatePeriod.ItemIndex:=Ord(Compress);
RadioDate.Checked:=True;
end
else
begin
CBTimePeriod.ItemIndex:=Ord(Compress)-Ord(ocSecond);
RadioTime.Checked:=True;
end;
end
else
begin
UpDown1.Position:=Round(Period);
RadioPoints.Checked:=True;
end;
end;
end;
procedure TCompressFuncEditor.ApplyFormChanges;
begin
inherited;
with TCompressFunction(IFunction) do
begin
if RadioDate.Checked then
Compress:=TCompressionPeriod(CBDatePeriod.ItemIndex)
else
Compress:=TCompressionPeriod(CBTimePeriod.ItemIndex+Ord(ocSecond));
Period:=UpDown1.Position;
end;
end;
procedure TCompressFuncEditor.RadioDateClick(Sender: TObject);
begin
UpDown1.Position:=0;
CBDatePeriod.SetFocus;
EnableApply;
end;
procedure TCompressFuncEditor.RadioPointsClick(Sender: TObject);
begin
ENum.SetFocus;
EnableApply;
end;
procedure TCompressFuncEditor.ENumChange(Sender: TObject);
begin
EnableApply;
end;
procedure TCompressFuncEditor.ENumClick(Sender: TObject);
begin
RadioPoints.Checked:=True;
EnableApply;
end;
procedure TCompressFuncEditor.CBDatePeriodClick(Sender: TObject);
begin
RadioDate.Checked:=True;
EnableApply;
end;
procedure TCompressFuncEditor.RadioTimeClick(Sender: TObject);
begin
UpDown1.Position:=0;
CBTimePeriod.SetFocus;
EnableApply;
end;
procedure TCompressFuncEditor.CBTimePeriodChange(Sender: TObject);
begin
RadioTime.Checked:=True;
EnableApply;
end;
initialization
RegisterClass(TCompressFuncEditor);
RegisterTeeFunction( TCompressFunction, {$IFNDEF CLR}@{$ENDIF}TeeMsg_FunctionCompress,
{$IFNDEF CLR}@{$ENDIF}TeeMsg_GalleryFinancial );
finalization
UnRegisterTeeFunctions([TCompressFunction]);
end.
|
unit FC.StockWizards.frmStockWizardFiles_B;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,ufrmFrame_B, StdCtrls, Grids, DBGrids,
MultiSelectDBGrid, ColumnSortDBGrid, EditDBGrid, ImgList,
ActnList, Menus, DB, MemoryDS, ComCtrls, ToolWin, ExtCtrls, DBClient,
RecentlyList,FC.Definitions, Mask, ExtendControls;
type
TfrmStockDataConnectionWizardFiles_B = class(TfrmFrame_B)
grSources : TEditDBGrid;
paToolbar : TPanel;
laHeader : TLabel;
ToolBar1 : TToolBar;
buBrowseForFolder: TToolButton;
dlgFileOpen : TOpenDialog;
alMain : TActionList;
acInsertFromDir : TAction;
ilImages : TImageList;
taFiles : TClientDataSet;
taFilesPATH : TStringField;
dsFiles : TDataSource;
rlRecentlyDirs : TRecentlyList;
pmRecentlyDirs : TPopupMenu;
taFilesINT: TIntegerField;
edInstrument: TExtendComboBox;
laSpace: TLabel;
laSymbol: TLabel;
procedure taFilesINTGetText(Sender: TField; var Text: string; DisplayText: Boolean);
procedure acInsertFromDirExecute(Sender: TObject);
procedure grSourcesEditorCreating(Sender: TObject; var InplaceEditor: TInplaceEditEx);
procedure rlRecentlyDirsRecentlyMenuClick(Sender: TRecentlyList; RecentlyValue: String);
procedure grSourcesCanEdit(Sender: TObject; var CanEdit: Boolean);
private
FFilterSymbol: string;
FAllowedIntervals: array [TStockTimeInterval] of boolean;
FSingleMode: boolean;
procedure OnBtnEditClick(Sender:TObject; var Text:string);
procedure LoadFromDir(const aDir: string);
function GetFiles: TStockTimeIntervalStringArray;
procedure WMSize (var Message: TWMSize); message WM_SIZE;
protected
procedure Init;
function CreateConnection(const aSymbol: string; aInterval: TStockTimeInterval; const aFileName: string): IStockDataSourceConnection; virtual; abstract;
function FileExt: string; virtual; abstract;
public
function Validate: boolean;
function GetSelectedSymbol: string;
procedure SetSelectedSymbol(const aSymbol: string);
procedure OnOK(out aDataSources: TStockTimeIntervalDataSourceArray); overload;
procedure OnOK(const aInterval: TStockTimeInterval; out aDataSource:IStockDataSource); overload;
//Запретить пользоватую смену пары
procedure Filter(const aStockSymbol: string); overload;
procedure Filter(const aStockSymbol: string; const aInterval: TStockTimeInterval); overload;
procedure SetSingleMode;
constructor Create (aOwner:TComponent); override;
destructor Destroy;override;
end;
//Напрямую TFrame нельзя выдавать наружу в виде интерфейса, так как у него
//заглушены AddRef/Release
TStockDataConnectionWizard_B = class (TComponentContainer,IStockDataConnectionWizard)
private
function Target : TfrmStockDataConnectionWizardFiles_B;
protected
//from IStockControl
function Control: TWinControl;
//from IStockDataConnectionWizard
function Title: string; virtual; abstract;
function Validate: boolean;
function GetSelectedSymbol: string;
procedure SetSelectedSymbol(const aSymbol: string);
procedure SetSingleMode;
procedure Filter(const aStockSymbol: string; const aInterval: TStockTimeInterval); overload;
//Запретить пользоватую смену пары
procedure Filter(const aStockSymbol: string); overload;
//По закрытию мастер должен вернуть массив всех DataSource для всех интервалов выбранной пары
procedure OnOK(out aDataSources: TStockTimeIntervalDataSourceArray); overload;
//Тоже самое, только возвращает 1 указанный DataSource
procedure OnOK(const aInterval: TStockTimeInterval; out aDataSource:IStockDataSource); overload;
end;
implementation
uses SystemService,BaseUtils,Application.Definitions, FC.Factory,FC.DataUtils,FC.Singletons;
{$R *.dfm}
type
TInplaceFileEditor = class (TInplaceEditBtn)
end;
const
fnINT = 'INT';
fnPATH = 'PATH';
{ TStockDataConnectionWizard_B }
procedure TStockDataConnectionWizard_B.Filter(const aStockSymbol: string; const aInterval: TStockTimeInterval);
begin
Target.Filter(aStockSymbol,aInterval);
end;
procedure TStockDataConnectionWizard_B.OnOK(const aInterval: TStockTimeInterval; out aDataSource: IStockDataSource);
begin
Target.OnOK(aInterval,aDataSource);
end;
procedure TStockDataConnectionWizard_B.Filter(const aStockSymbol: string);
begin
Target.Filter(aStockSymbol);
end;
function TStockDataConnectionWizard_B.GetSelectedSymbol: string;
begin
result:=Target.GetSelectedSymbol;
end;
procedure TStockDataConnectionWizard_B.SetSelectedSymbol(const aSymbol: string);
begin
Target.SetSelectedSymbol(aSymbol);
end;
procedure TStockDataConnectionWizard_B.SetSingleMode;
begin
Target.SetSingleMode;
end;
function TStockDataConnectionWizard_B.Control: TWinControl;
begin
result:=Target;
end;
function TStockDataConnectionWizard_B.Target: TfrmStockDataConnectionWizardFiles_B;
begin
result:=TfrmStockDataConnectionWizardFiles_B(inherited Target);
end;
function TStockDataConnectionWizard_B.Validate: boolean;
begin
result:=Target.Validate;
end;
procedure TStockDataConnectionWizard_B.OnOK(out aDataSources: TStockTimeIntervalDataSourceArray);
begin
Target.OnOK(aDataSources);
end;
{ TfrmStockDataConnectionWizardFiles_B }
constructor TfrmStockDataConnectionWizardFiles_B.Create(aOwner: TComponent);
var
i : TStockTimeInterval;
begin
inherited;
rlRecentlyDirs.RegistryKey:=Workspace.MainRegistryKey+'\'+Self.ClassName+'\RecentlyDirs';
edInstrument.Text:=Workspace.Storage(self).ReadString(self,'Instrument',edInstrument.Text);
for i:=Low(TStockTimeInterval) to High(TStockTimeInterval) do
FAllowedIntervals[i]:=true;
Init;
end;
destructor TfrmStockDataConnectionWizardFiles_B.Destroy;
begin
Workspace.Storage(self).WriteString(Self,'Instrument',edInstrument.Text);
inherited;
end;
procedure TfrmStockDataConnectionWizardFiles_B.Init;
var
i : TStockTimeInterval;
j : integer;
aSymbols: TStockSymbolInfoArray;
begin
taFiles.Close;
taFiles.CreateDataSet;
taFiles.DisableControls;
try
for i:=Low(StockTimeIntervalValues) to High(StockTimeIntervalValues) do
begin
if FAllowedIntervals[i] then
begin
taFiles.Append;
taFiles[fnINT]:=StockTimeIntervalValues[i];
taFiles.Post;
end;
end;
taFiles.First;
finally
taFiles.EnableControls;
end;
if FSingleMode then
grSources.Options1:=grSources.Options1+[dgFitColumnsToSize]
else
grSources.Options1:=grSources.Options1-[dgFitColumnsToSize];
grSources.Columns[0].Width:=100;
grSources.ColumnSizes.FitLastColumn;
grSources.ScrollBars:=ssNone;
aSymbols:=StockDataStorage.GetSymbols;
edInstrument.Items.Clear;
for j := Low(aSymbols) to High(aSymbols) do
edInstrument.Items.Add(aSymbols[j].Name);
edInstrument.Sorted:=true;
if FFilterSymbol<>'' then
begin
edInstrument.Text:=FFilterSymbol;
edInstrument.Enabled:=false
end
else begin
edInstrument.Enabled:=true;
end;
buBrowseForFolder.Visible:=not FSingleMode;
laSymbol.Visible:=not FSingleMode;
edInstrument.Visible:=not FSingleMode;
laSpace.Visible:=not FSingleMode;
taFilesINT.Visible:=not FSingleMode;
end;
procedure TfrmStockDataConnectionWizardFiles_B.Filter(const aStockSymbol: string);
begin
SetSelectedSymbol(aStockSymbol);
edInstrument.Enabled:=false;
end;
procedure TfrmStockDataConnectionWizardFiles_B.Filter(const aStockSymbol: string; const aInterval: TStockTimeInterval);
var
i : TStockTimeInterval;
begin
FFilterSymbol:=aStockSymbol;
for i:=Low(TStockTimeInterval) to High(TStockTimeInterval) do
FAllowedIntervals[i]:=false;
FAllowedIntervals[aInterval]:=true;
Init;
end;
function TfrmStockDataConnectionWizardFiles_B.GetFiles: TStockTimeIntervalStringArray;
var
aBookmark: TBookmark;
i: TStockTimeInterval;
begin
taFiles.CheckBrowseMode;
aBookmark:=taFiles.Bookmark;
//i:=low(TStockTimeIntervalStringArray);
taFiles.DisableControls;
try
taFiles.First;
while not taFiles.EOF do
begin
if not TStockDataUtils.GetTimeIntervalByValue(taFiles.FieldByName(fnINT).AsInteger,i) then
raise EAlgoError.Create;
result[i]:=taFiles.FieldByName(fnPATH).AsString;
taFiles.Next;
end;
taFiles.Bookmark:=aBookmark;
finally
taFiles.EnableControls;
end;
end;
function TfrmStockDataConnectionWizardFiles_B.Validate: boolean;
var
aFiles: TStockTimeIntervalStringArray;
i: TStockTimeInterval;
begin
result:= (not grSources.EditorMode) and (GetSelectedSymbol<>'');
if result then
begin
aFiles:=GetFiles;
for i:=Low(aFiles) to High(aFiles) do
if FAllowedIntervals[i] then
result:=result and FileExists(aFiles[i]);
end;
end;
procedure TfrmStockDataConnectionWizardFiles_B.WMSize(var Message: TWMSize);
begin
inherited;
if not (dgFitColumnsToSize in grSources.Options1) then
grSources.ColumnSizes.FitLastColumn;
end;
procedure TfrmStockDataConnectionWizardFiles_B.OnOK(out aDataSources: TStockTimeIntervalDataSourceArray);
var
aFiles : TStockTimeIntervalStringArray;
i : TStockTimeInterval;
aConnection : IStockDataSourceConnection;
begin
taFiles.CheckBrowseMode;
aFiles:=GetFiles;
for i:=Low(aFiles) to High(aFiles) do
begin
aConnection:=CreateConnection(edInstrument.Text, i, aFiles[i]);
aDataSources[i]:=aConnection.CreateDataSource;
end;
end;
procedure TfrmStockDataConnectionWizardFiles_B.OnOK(const aInterval: TStockTimeInterval; out aDataSource: IStockDataSource);
var
aConnection : IStockDataSourceConnection;
begin
if FSingleMode then //В режиме Single Mode нельзя знать, что грузится
aConnection:=CreateConnection('', aInterval, GetFiles[aInterval])
else
aConnection:=CreateConnection(edInstrument.Text, aInterval, GetFiles[aInterval]);
aDataSource:=aConnection.CreateDataSource;
end;
procedure TfrmStockDataConnectionWizardFiles_B.LoadFromDir(const aDir: string);
var
aFileList : TStringList;
b : boolean;
i : integer;
j : TStockTimeInterval;
aIntName : string;
aMask : string;
begin
TWaitCursor.SetUntilIdle;
aFileList:= TStringList.Create;
if (edInstrument.Text='') or (edInstrument.Text='*') then
aMask:='*.'+FileExt
else
aMask:=edInstrument.Text+'*.'+FileExt;
try
FindFiles(aDir,aMask,aFileList, faAnyFile,true);
if aFileList.Count=0 then
begin
MsgBox.MessageAttention(0,'There are no files in the folder',[]);
exit;
end;
aFileList.Sort;
rlRecentlyDirs.AddRecently(aDir);
b:=false;
for j:=High(TStockTimeInterval) downto Low(TStockTimeInterval) do
begin
aIntName:=IntToStr(StockTimeIntervalValues[j]);
for i:=0 to aFileList.Count-1 do
begin
if StrIPos(aIntName+'.',ExtractFileBaseName(aFileList[i])+'.')<>0 then
begin
b:=true;
if not (taFiles.Locate(fnINT,StockTimeIntervalValues[j],[])) then
continue;
taFiles.Edit;
taFiles[fnPATH]:=aFileList[i];
taFiles.Post;
end;
end;
end;
finally
aFileList.Free;
end;
if not b then
MsgBox.MessageAttention(0,'There are no files in the folder, that conform naming template',[]);
end;
procedure TfrmStockDataConnectionWizardFiles_B.acInsertFromDirExecute(Sender: TObject);
var
sSelDir : String;
begin
sSelDir:=BrowseForFolder(Handle,'Get files from folder',rlRecentlyDirs.MostRecentlyDef(AppPath),'');
if sSelDir<>'' then
LoadFromDir(sSelDir);
end;
procedure TfrmStockDataConnectionWizardFiles_B.OnBtnEditClick(Sender: TObject; var Text: string);
begin
if not (taFiles.State in [dsEdit,dsInsert]) then
taFiles.Edit;
dlgFileOpen.Options:=dlgFileOpen.Options-[ofAllowMultiSelect];
dlgFileOpen.FileName:=Text;
if dlgFileOpen.FileName='' then
dlgFileOpen.FileName:='*'+GetSelectedSymbol+'*';
dlgFileOpen.InitialDir:=rlRecentlyDirs.MostRecentlyDef(AppPath);
if dlgFileOpen.Execute then
begin
Text:=dlgFileOpen.FileName;
rlRecentlyDirs.AddRecently(ExtractFileDir(dlgFileOpen.FileName));
end;
end;
procedure TfrmStockDataConnectionWizardFiles_B.grSourcesEditorCreating(Sender: TObject; var InplaceEditor: TInplaceEditEx);
begin
InplaceEditor:=TInplaceFileEditor.Create(self);
TInplaceEditBtn(InplaceEditor).OnButtonClick:=OnBtnEditClick;
end;
procedure TfrmStockDataConnectionWizardFiles_B.grSourcesCanEdit(Sender: TObject; var CanEdit: Boolean);
begin
CanEdit:=AnsiSameText(grSources.SelectedField.FieldName,fnPATH);
end;
procedure TfrmStockDataConnectionWizardFiles_B.rlRecentlyDirsRecentlyMenuClick(Sender: TRecentlyList; RecentlyValue: String);
begin
LoadFromDir(RecentlyValue);
end;
function TfrmStockDataConnectionWizardFiles_B.GetSelectedSymbol: string;
begin
result:=edInstrument.Text;
end;
procedure TfrmStockDataConnectionWizardFiles_B.SetSelectedSymbol(const aSymbol: string);
begin
edInstrument.Text:=aSymbol;
end;
procedure TfrmStockDataConnectionWizardFiles_B.SetSingleMode;
begin
FSingleMode:=true;
Filter('',sti1); //sti1 - это не важно, лишь бы один источник
end;
procedure TfrmStockDataConnectionWizardFiles_B.taFilesINTGetText(Sender: TField; var Text: string;
DisplayText: Boolean);
var
I: TStockTimeInterval;
begin
inherited;
if DisplayText then
begin
if TStockDataUtils.GetTimeIntervalByValue(Sender.AsInteger,I) then
Text:=StockTimeIntervalNames[i]+' ['+Sender.AsString+']'
else
Text:=Sender.AsString;
end;
end;
end.
|
{****************************************************}
{* NexusDB Client Messaging *}
{* Provides the ability for NexusDB clients to send messages *}
{* to other clients. *}
{******************************************************************}
{* Unit contains client side components *}
{******************************************************************}
{* Released as freeware *}
{* Authors: Nathan Sutcliffe, Terry Haan *}
{******************************************************************}
{
ResourceString: Dario 13/03/13
Nada para fazer
}
unit ncNXServRemoto;
interface
uses
Windows,
Classes,
Messages,
Forms,
nxllComponent,
nxllMemoryManager,
nxllTypes,
nxllTransport,
nxllPluginBase,
nxllDataMessageQueue,
nxptBasePooledTransport,
nxlgEventLog,
ncNetMsg,
nxllBDE,
ncErros,
ncClassesBase;
const
cm_ncnxProcessMsg = WM_USER + 4000;
type
TncnxProcessMsgProc = procedure (Msg : PnxDataMessage) of object;
TncnxRemotePlugin = class(TnxBasePluginEngine)
private
FMsgQueue: TnxDataMessageQueue;
FProcessMsgProc : TncnxProcessMsgProc;
FHWnd: HWND;
procedure PluginMsgHandler( var aMsg: TMessage );
procedure msgProcessMsg( var aMsg: TMessage ); message cm_ncnxProcessMsg;
protected
procedure LogEvent(aString: string);
class function bpeIsRemote: Boolean; override;
procedure ProcessReceivedMessage( aMsg: PnxDataMessage );
public
constructor Create( aOwner: TComponent ); override;
destructor Destroy; override;
property ProcessMsgProc: TncnxProcessMsgProc
read FProcessMsgProc write FProcessMsgProc;
end;
TncnxRemoteCmdHandler = class(TnxBasePluginCommandHandler)
private
procedure rmchSetPluginEngine( const aPlugin: TncnxRemotePlugin );
function rmchGetPluginEngine: TncnxRemotePlugin;
public
procedure bpchProcess( aMsg: PnxDataMessage;
var aHandled: Boolean ); override;
published
property PluginEngine: TncnxRemotePlugin
read rmchGetPluginEngine
write rmchSetPluginEngine;
end;
TncSalvaTelaEv = procedure (Sender: TObject; aMaq: Word; aJpg: TMemoryStream) of object;
TncProgressoArqEv = procedure(Perc: Integer; Etapa: Byte; NomeArq: String; Download: Boolean) of object;
TncNXServRemoto = class(TncServidorBase)
private
FTransp : TnxBasePooledTransport;
FRemPlugin : TncnxRemotePlugin;
FCmdHandler : TncnxRemoteCmdHandler;
FSalvaTelaEv : TncSalvaTelaEv;
FOnProgressoArq : TncProgressoArqEv;
FTicksLastCom : Cardinal;
FEventLog : TnxBaseLog;
FEventLogEnabled : Boolean;
FWaitingSock : Boolean;
function GetCmdHandler: TnxBaseCommandHandler;
function GetSession: TnxStateComponent;
procedure SetCmdHandler(const Value: TnxBaseCommandHandler);
procedure SetSession(const Value: TnxStateComponent);
procedure ProcessMsgProc(Msg : PnxDataMessage);
procedure LogEvent(S: String);
function ProcessRequest(aMsgID : TnxMsgID;
aRequestData : Pointer;
aRequestDataLen : TnxWord32;
aReply : PPointer;
aReplyLen : PnxWord32;
aReplyType : TnxNetMsgDataType)
: TnxResult;
procedure SetEventLog(const Value: TnxBaseLog);
procedure SetEventLogEnabled(const Value: Boolean);
procedure OnTerminateSock(Sender: TObject);
protected
procedure SetAtivo(Valor: Boolean); override;
procedure nmMsgComEv(var Msg : TnxDataMessage);
message ncnmMsgComEv;
procedure nmChecaLicEv(var Msg : TnxDataMessage);
message ncnmChecaLicEv;
procedure nmHorarioEv(var Msg : TnxDataMessage);
message ncnmHorarioEv;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function KeepAlive: Integer;
function Upload(aFonte, aDestino: String): Integer; override;
function Download(aFonte, aDestino: String): Integer; override;
function DownloadArqInterno(aArq: String; aVerCli: Integer; aDestino: String): Integer; override;
function SalvaStreamObj(Novo: Boolean; S: TStream): Integer; override;
function ObtemStreamConfig(S: TStream): Integer; override;
function ObtemStreamListaObj(Cliente: Integer; TipoClasse: Integer; S: TStream): Integer; override;
function ApagaObj(Cliente: Integer; TipoClasse: Integer; Chave: String): Integer; override;
function AbreCaixa(aFunc: String; aSaldo: Currency; var NovoCx: Integer): Integer; override;
function FechaCaixa(aFunc: String; aSaldo: Currency; aID: Integer): Integer; override;
function CorrigeDataCaixa(aFunc: String; aID: Integer; aNovaAbertura, aNovoFechamento: TDateTime): integer; override;
function AjustaPontosFid(aFunc: String; aCliente: Integer; aFator: Smallint; aPontos: Double; aObs: String): Integer; override;
function TableUpdated(aIDTab: Byte): integer; override;
function SalvaMovEst(aObj: TObject): Integer; override;
function SalvaDebito(aObj: TObject): Integer; override;
function SalvaLancExtra(aObj: TObject): Integer; override;
function SalvaCredito(aObj: TObject): Integer; override;
function InutilizarNFCE(aNFe: Boolean; aAno: Word; aInicio, aFim: Cardinal; aJust: String; aResposta: TStrings): integer; override;
function GeraXMLProt(aChave: String): integer; override;
function GetLoginData(var aVer, aConta, aUsers: String): integer;
function ZerarEstoque(aFunc: String): integer; override;
function CancelaTran(aID: Integer; aFunc: String): integer; override;
function ObtemPastaServ(var NomePastaServ: String): Integer; override;
function SalvaApp(aApp: String): Integer; override;
function ReemitirNFCe(aTran: TGuid): integer; override;
function InstalaNFeDepend : Integer; override;
function InstalaNFCeDepend : integer; override;
function Login(aUsername, aSenha: String; aFuncAtual: Boolean; aRemoto: Boolean; aWndHandle: HWND; aProxyHandle: Integer; aSocket: Integer; aSession: Integer; aIP: String; var Handle: Integer): Integer; override;
function SalvaLic(aLic: String): Integer; override;
function ObtemCertificados(sl: TStrings): integer; override;
procedure Logout(Cliente: Integer); override;
property TicksLastCom: Cardinal read FTicksLastCom;
published
property EventLog: TnxBaseLog
read FEventLog write SetEventLog;
property EventLogEnabled: Boolean
read FEventLogEnabled write SetEventLogEnabled;
property OnProgressoArq: TncProgressoArqEv
read FOnProgressoArq write FOnProgressoArq;
property Transp: TnxBasePooledTransport
read FTransp write FTransp;
property CmdHandler : TnxBaseCommandHandler
read GetCmdHandler write SetCmdHandler;
property Session : TnxStateComponent
read GetSession write SetSession;
property OnSalvaTela: TncSalvaTelaEv
read FSalvaTelaEv write FSalvaTelaEv;
end;
var
nxsr_ActiveFormHWND : HWND = 0;
procedure Register;
implementation
uses
SysUtils,
nxstMessages, nxllFastMove, SyncObjs,
nxllStreams, ncMsgCom, ncMovEst, ncSalvaCredito, ncDebito,
ncLancExtra, ncDebug;
// START resource string wizard section
resourcestring
SÉNecessárioInformarOEndereçoDoSe = 'É necessário informar o endereço do servidor NexCafé';
// END resource string wizard section
type
TThreadSockConn = class ( TThread )
private
FTransp : TnxBasePooledTransport;
Fexecuting : Boolean;
protected
procedure Execute; override;
public
constructor Create(aTransp: TnxBasePooledTransport);
property Executing: Boolean
read FExecuting;
end;
procedure Register;
begin
RegisterComponents('NexCafe', [TncNXServRemoto]); // do not localize
end;
{ TncnxRemotePlugin }
constructor TncnxRemotePlugin.Create(aOwner: TComponent);
begin
inherited;
FMsgQueue := TnxDataMessageQueue.Create;
FHWnd := Classes.AllocateHWnd(PluginMsgHandler);
DebugMsg('TncnxRemotePlugin.Create - FHWND: ' + IntToStr(FHWND)); // do not localize
FProcessMsgProc := nil;
end;
destructor TncnxRemotePlugin.Destroy;
begin
DebugMsg('TncnxRemotePlugin.Destroy'); // do not localize
Classes.DeallocateHWnd(FHWnd);
FreeAndNil(FMsgQueue);
inherited;
end;
procedure TncnxRemotePlugin.LogEvent(aString: string);
begin
DebugMsg('TncnxRemotePlugin.'+aString); // do not localize
end;
class function TncnxRemotePlugin.bpeIsRemote: Boolean;
begin
Result := True;
end;
procedure TncnxRemotePlugin.ProcessReceivedMessage( aMsg: PnxDataMessage );
var M : PnxDataMessage;
begin
try
with aMsg^ do
LogEvent('ProcessReceivedMessage - dmMsg: ' + MsgToString(dmMsg) + ' - dmDataLen: ' + IntToStr(dmDataLen)); // do not localize
except
on E: Exception do
try LogEvent('ProcessReceivedMessage - Exception: ' + E.Message); except end; // do not localize
end;
try
M := nxGetZeroMem(SizeOf(TnxDataMessage));
if (aMsg^.dmDataLen > 0) then begin
M^.dmData := nxGetMem(aMsg^.dmDataLen);
nxMove(aMsg^.dmData^, M^.dmData^, aMsg^.dmDataLen);
end;
M^.dmMsg := aMsg^.dmMsg;
M^.dmSource := aMsg^.dmSource;
M^.dmSessionID := aMsg^.dmSessionID;
M^.dmErrorCode := aMsg^.dmErrorCode;
M^.dmDataLen := aMsg^.dmDataLen;
Windows.PostMessage(FHWnd, cm_ncnxProcessMsg, Integer(M), 0);
DebugMsg('Windwos.PostMessage - HWND: ' + IntToStr(FHwnd)); // do not localize
{ with aMsg^ do
try
FMsgQueue.Push( Self,
dmMsg,
dmSessionId,
0,
0,
dmData,
dmDataLen );
// Post a message to our window handle. This way, we don't call the events
// in the context of the NexusDB thread. Also, we can return control to the
// calling thread right away.
finally
Windows.PostMessage(FHWnd, cm_ncnxProcessMsg, 0, 0);
DebugMsg('Windwos.PostMessage - HWND: ' + IntToStr(FHwnd));
end;}
except
on E: Exception do
try LogEvent('ProcessReceviedMessage - Exception: '+E.Message); except end; // do not localize
end;
end;
procedure TncnxRemotePlugin.msgProcessMsg( var aMsg: TMessage );
var M : PnxDataMessage;
begin
DebugMsg('TncnxRemotePlugin.msgProcessMsg'); // do not localize
try
M := PnxDataMessage(aMsg.WParam);
try
try DebugMsg('TncnxRemotePlugin.msgProcessMsg - dmMsg: '+MsgToString(M^.dmMsg)); except end; // do not localize
if Assigned(FProcessMsgProc) then
FProcessMsgProc(M) else
DebugMsg('TncnxRemotePlugin.msgProcessMsg - FProcessMsgProc NOT ASSIGNED'); // do not localize
finally
if Assigned( M^.dmData) then
nxFreeMem( M^.dmData);
nxFreeMem(M);
end;
{ Msg := FMsgQueue.Pop;
while Assigned( Msg ) do begin
try
try LogEvent('msgProcessMsg - dmMsg: '+MsgToString(Msg^.dmMsg)); except end;
if Assigned(FProcessMsgProc) then
FProcessMsgProc(Msg);
finally
// better free the message
if Assigned( Msg^.dmData ) then
nxFreeMem( Msg^.dmData);
nxFreeMem( Msg );
end;
Msg := FMsgQueue.Pop;
end;}
except
on E: Exception do
DebugMsgEsp('TncnxRemotePlugin. msgProcessMsg - Exception: ' + E.Message, False, True); // do not localize
end;
end;
procedure TncnxRemotePlugin.PluginMsgHandler(var aMsg: TMessage);
begin
DebugMsg('TncnxRemotePlugin.PluginMsgHandler - ' + IntToStr(aMsg.Msg)); // do not localize
if aMsg.Msg = cm_ncnxProcessMsg then begin
DebugMsg('TncnxRemotePlugin.PluginMsgHandler - Dispatch'); // do not localize
Dispatch( aMsg );
end else begin
DebugMsg('TncnxRemotePlugin.PluginMsgHandler - DEFWINDOWPROC - FHWND: '+IntToStr(FHWND)); // do not localize
DefWindowProc( FHWnd, aMsg.Msg, aMsg.WParam, aMsg.LParam );
end;
end;
{ TncnxRemoteCmdHandler }
procedure TncnxRemoteCmdHandler.bpchProcess( aMsg: PnxDataMessage;
var aHandled: Boolean);
begin
with aMsg^ do
if (dmMsg>=ncnmFirstEv) and (dmMsg<=ncnmLastEv) then begin
PluginEngine.ProcessReceivedMessage( aMsg );
aHandled := True;
end else
DebugMsg('TncnxRemoteCmdHandler.bpchProcess - dmMsg: ' + IntToStr(dmMsg) + ' - Fora da faixa de processamento'); // do not localize
end;
procedure TncnxRemoteCmdHandler.rmchSetPluginEngine( const aPlugin: TncnxRemotePlugin );
begin
bpchSetPluginEngine( aPlugin );
end;
function TncnxRemoteCmdHandler.rmchGetPluginEngine: TncnxRemotePlugin;
begin
Result := TncnxRemotePlugin( bpchPluginEngine );
end;
{ TncNXServRemoto }
constructor TncNXServRemoto.Create(AOwner: TComponent);
begin
inherited;
FEventLog := nil;
FTicksLastCom := 0;
FRemPlugin := TncnxRemotePlugin.Create(Self);
FCmdHandler := TncnxRemoteCmdHandler.Create(Self);
FCmdHandler.PluginEngine := FRemPlugin;
FRemPlugin.ProcessMsgProc := Self.ProcessMsgProc;
FTransp := nil;
FSalvaTelaEv := nil;
FOnProgressoArq := nil;
end;
destructor TncNXServRemoto.Destroy;
begin
DebugMsg('TncNXServRemoto - Destroy'); // do not localize
FCmdHandler.Active := False;
if Assigned(FCmdHandler) then
FCmdHandler.Active := False;
FCmdHandler.CommandHandler := nil;
FreeAndNil(FCmdHandler);
FreeAndNil(FRemPlugin);
inherited;
end;
function TncNXServRemoto.Download(aFonte, aDestino: String): Integer;
var
S: TMemoryStream;
Req : TnmNomeArq;
begin
Req.nmNomeArq := aFonte;
S := TMemoryStream.Create;
try
if Assigned(FOnProgressoArq) then FOnProgressoArq(0, 0, aDestino, True);
Result := ProcessRequest(ncnmDownloadArq, @Req, SizeOf(Req), @S, nil, nmdStream);
if Result=0 then begin
S.SaveToFile(aDestino);
end;
finally
S.Free;
end;
if (Result=0) and Assigned(FOnProgressoArq) then
FOnProgressoArq(100, 2, aDestino, True);
end;
function TncNXServRemoto.DownloadArqInterno(aArq: String; aVerCli: Integer;
aDestino: String): Integer;
var
S: TMemoryStream;
Req : TnmDownArqInt;
begin
Req.nmArq := aArq;
Req.nmVer := aVerCli;
S := TMemoryStream.Create;
try
Result := ProcessRequest(ncnmDownloadArqInterno, @Req, SizeOf(Req), @S, nil, nmdStream);
if Result=0 then begin
S.SaveToFile(aDestino);
end;
finally
S.Free;
end;
end;
function TncNXServRemoto.GeraXMLProt(aChave: String): integer;
var Req: TnmNFCeReq;
begin
Req.nmChave := aChave;
Result := ProcessRequest(ncnmGeraXMLProt, @Req, SizeOf(Req), nil, nil, nmdByteArray);
end;
function TncNXServRemoto.GetCmdHandler: TnxBaseCommandHandler;
begin
Result := FCmdHandler.CommandHandler;
end;
function TncNXServRemoto.GetSession: TnxStateComponent;
begin
Result := FRemPlugin.Session;
end;
function TncNXServRemoto.InstalaNFCeDepend: integer;
begin
Result := ProcessRequest(ncnmInstalaNFCeDepend, nil, 0, nil, 0, nmdStream);
end;
function TncNXServRemoto.InstalaNFeDepend: Integer;
begin
Result := ProcessRequest(ncnmInstalaNFeDepend, nil, 0, nil, 0, nmdStream);
end;
function TncNXServRemoto.InutilizarNFCE(aNFe: Boolean; aAno: Word; aInicio, aFim: Cardinal;
aJust: String; aResposta: TStrings): integer;
var
R: TnmInutilizarNFCE_Req;
S : TStream;
begin
R.nmNFe := aNFe;
R.nmAno := aAno;
R.nmInicio := aInicio;
R.nmFim := aFim;
R.nmJust := aJust;
S := TnxMemoryStream.Create;
try
Result := ProcessRequest(ncnmInutilizarNFCE, @R, SizeOf(R), @S, 0, nmdStream);
aResposta.Clear;
if Result=0 then
aResposta.LoadFromStream(S);
finally
S.Free;
end;
end;
procedure TncNXServRemoto.nmChecaLicEv(var Msg: TnxDataMessage);
begin
LogEvent('nmChecaLicEv'); // do not localize
EnviaEvento(ncmc_ChecaLicEv, nil);
end;
procedure TncNXServRemoto.nmHorarioEv(var Msg: TnxDataMessage);
var M : PmsgHorarioEv;
begin
LogEvent('nmHorarioEv'); // do not localize
New(M);
Move(Msg.dmData^, M^, Msg.dmDataLen);
EnviaEvento(ncmc_HorarioEv, M);
end;
procedure TncNXServRemoto.nmMsgComEv(var Msg: TnxDataMessage);
var
S: TMemoryStream;
Dados : Pointer;
begin
LogEvent('nmMsgComEv'); // do not localize
with TnmMsgCom(Msg.dmData^) do begin
if ObtemTipoDados(nmMsgID)=tdStream then begin
S := TMemoryStream.Create;
S.SetSize(nmDataLength);
Move(nmData, S.Memory^, nmDataLength);
EnviaEvento(nmMsgID, S);
end else begin
GetMem(Dados, nmDataLength);
Move(nmData, Dados^, nmDataLength);
EnviaEvento(nmMsgID, Dados);
end;
end;
end;
procedure TncNXServRemoto.ProcessMsgProc(Msg: PnxDataMessage);
begin
FTicksLastCom := GetTickCount;
DebugMsg('TncNXServRemoto.ProcessMsgProc'); // do not localize
Dispatch(Msg^);
end;
function TncNXServRemoto.ProcessRequest(aMsgID: TnxMsgID; aRequestData: Pointer;
aRequestDataLen: TnxWord32; aReply: PPointer; aReplyLen: PnxWord32;
aReplyType: TnxNetMsgDataType): TnxResult;
var SaveTimeout : TnxWord32;
begin
if (aMsgID=ncnmDownloadArq) or (aMsgID=ncnmUploadArq) then begin
SaveTimeout := FremPlugin.Timeout;
if FRemPlugin.Timeout<60000 then
FRemPlugin.Timeout := 60000;
end;
try
Result := FRemPlugin.bpeProcessRequest(aMsgID, aRequestData, aRequestDataLen, aReply, aReplyLen, aReplyType);
finally
if (aMsgID=ncnmDownloadArq) or (aMsgID=ncnmUploadArq) then
FRemPlugin.Timeout := SaveTimeout;
end;
// FTicksLastCom := GetTickCount;
if (Result>ncerrUltimo) and (aMsgID<>ncnmLogout) then begin
Result := ncerrConexaoPerdida;
SetAtivo(False);
end;
end;
procedure ProcessMsgConn;
var Msg : TMsg;
begin
while PeekMessage(Msg, nxsr_ActiveFormHWND, 0, 0, PM_REMOVE) do begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
procedure TncNXServRemoto.SetAtivo(Valor: Boolean);
var T : TThreadSockConn; Dummy: Integer;
begin
DebugMsg('TncNCServRemoto.SetAtivo - 0'); // do not localize
try
if Valor and Assigned(FTransp) then begin
FTransp.Active := False;
if Trim(FTransp.ServerName)='' then
raise exception.Create(SÉNecessárioInformarOEndereçoDoSe);
if Win32MajorVersion>5 then begin
DebugMsg('TncNCServRemoto.SetAtivo A-1'); // do not localize
T := TThreadSockConn.Create(FTransp);
DebugMsg('TncNCServRemoto.SetAtivo A-2'); // do not localize
FWaitingSock := True;
T.Resume;
while T.Executing do begin
DebugMsg('TncNXServRemoto.SetAtivo - Waiting 1'); // do not localize
MsgWaitForMultipleObjects(0, Dummy, False, 500, QS_ALLINPUT);
DebugMsg('TncNXServRemoto.SetAtivo - Waiting 2'); // do not localize
ProcessMsgConn;
DebugMsg('TncNXServRemoto.SetAtivo - Waiting 3'); // do not localize
end;
DebugMsg('TncNCServRemoto.SetAtivo A-3'); // do not localize
try T.Free; except end;
end else begin
DebugMsg('TncNXServRemoto.SetAtivo B-1'); // do not localize
FTransp.Active := True;
DebugMsg('TncNXServRemoto.SetAtivo B-2'); // do not localize
end;
DebugMsg('TncNCServRemoto.SetAtivo 4'); // do not localize
if not FTransp.Active then begin
DebugMsg('TncNCServRemoto.SetAtivo 5'); // do not localize
raise EErroNexCafe.Create(ncerrFalhaConexao);
end else
DebugMsg('TncNCServRemoto.SetAtivo 6'); // do not localize
end else
DebugMsg('TncNCServRemoto.SetAtivo - FALSE'); // do not localize
DebugMsg('TncNCServRemoto.SetAtivo 7'); // do not localize
FRemPlugin.Active := Valor;
DebugMsg('TncNCServRemoto.SetAtivo 8'); // do not localize
FCmdHandler.Active := Valor;
DebugMsg('TncNCServRemoto.SetAtivo 9'); // do not localize
if Assigned(FRemPlugin.Session) then
FRemPlugin.Session.Active := Valor;
DebugMsg('TncNCServRemoto.SetAtivo 10'); // do not localize
if (not Valor) and Assigned(FTransp) then
FTransp.Active := False;
DebugMsg('TncNCServRemoto.SetAtivo 11'); // do not localize
if Assigned(FCmdHandler.CommandHandler) then
FCmdHandler.CommandHandler.Active := True;
DebugMsg('TncNCServRemoto.SetAtivo 12'); // do not localize
except
On E: EnxPooledTransportException do begin
DebugMsg('TncNXServRemoto.SetAtivo - Valor: ' + BoolString[Valor] + // do not localize
' - Exception: ' + E.Message + // do not localize
' - ErrorCode: ' + IntToStr(E.ErrorCode) + // do not localize
' - OS Error: ' + IntToStr(E.OSError)); // do not localize
Raise EErroNexCafe.Create(ncerrFalhaConexao);
end;
on E: EErroNexCafe do begin
DebugMsg('TncNCServRemoto.SetAtivo - E: ErroNexCafe - '+E.Message); // do not localize
raise EErroNexCafe.Create(E.CodigoErro);
end;
On E: Exception do begin
DebugMsg('TncNCServRemoto.SetAtivo - E: Exception - '+E.Message); // do not localize
raise;
end;
end;
inherited;
end;
procedure TncNXServRemoto.SetCmdHandler(const Value: TnxBaseCommandHandler);
begin
FCmdHandler.CommandHandler := Value;
end;
procedure TncNXServRemoto.SetEventLog(const Value: TnxBaseLog);
begin
FEventLog := Value;
FRemPlugin.EventLog := Value;
FRemPlugin.EventLogEnabled := FEventLogEnabled;
FCmdHandler.EventLog := Value;
FCmdHandler.EventLogEnabled := FEventLogEnabled;
end;
procedure TncNXServRemoto.SetEventLogEnabled(const Value: Boolean);
begin
FEventLogEnabled := Value;
FCmdHandler.EventLog := FEventLog;
FCmdHandler.EventLogEnabled := Value;
FRemPlugin.EventLog := FEventLog;
FRemPlugin.EventLogEnabled := Value;
end;
procedure TncNXServRemoto.SetSession(const Value: TnxStateComponent);
begin
FRemPlugin.Session := Value;
end;
function TncNXServRemoto.FechaCaixa(aFunc: String; aSaldo: Currency; aID: Integer): Integer;
var Req: TnmFechaCaixaReq;
begin
Req.nmFunc := aFunc;
Req.nmID := aID;
Req.nmSaldo := aSaldo;
Result := ProcessRequest(ncnmFechaCaixa, @Req, SizeOf(Req), nil, nil, nmdByteArray);
end;
function TncNXServRemoto.KeepAlive: Integer;
begin
Result := ProcessRequest(ncnmKeepAlive, nil, 0, nil, nil, nmdByteArray);
end;
procedure TncNXServRemoto.LogEvent(S: String);
begin
DebugMsg('TnxNCServRemoto.'+S); // do not localize
end;
function TncNXServRemoto.Login(aUsername, aSenha: String;
aFuncAtual: Boolean; aRemoto: Boolean; aWndHandle: HWND; aProxyHandle: Integer;
aSocket: Integer; aSession: Integer; aIP: String; var Handle: Integer): Integer;
var
Request : TnmLoginReq;
ReplyLen : TnxWord32;
P : Pointer;
begin
DebugMsg('TncNXServRemoto.Login - 1'); // do not localize
Request.nmUsername := aUsername;
DebugMsg('TncNXServRemoto.Login - 2'); // do not localize
Request.nmSenha := aSenha;
DebugMsg('TncNXServRemoto.Login - 3'); // do not localize
Request.nmFuncAtual := aFuncAtual;
DebugMsg('TncNXServRemoto.Login - 4'); // do not localize
Request.nmProxyHandle := aProxyHandle;
DebugMsg('TncNXServRemoto.Login - 5'); // do not localize
try
DebugMsg('TncNXServRemoto.Login - 7'); // do not localize
Result := ProcessRequest(ncnmLogin, @Request, SizeOf(Request), @P, @ReplyLen, nmdByteArray);
DebugMsg('TncNXServRemoto.Login - 8: '+IntToStr(ReplyLen)); // do not localize
Move(P^, Handle, SizeOf(Integer));
DebugMsg('TncNXServRemoto.Login - Result: ' + IntToStr(Result)); // do not localize
finally
if Assigned(P) then nxFreeMem(P);
end;
if Result = 0 then begin
DebugMsg('TncNXServRemoto.Login - 9'); // do not localize
inherited Login(aUsername, aSenha, aFuncAtual, aRemoto, aWndHandle, aProxyHandle, aSocket, aSession, aIP, Handle);
end;
DebugMsg('TncNXServRemoto.Login - 10'); // do not localize
end;
procedure TncNXServRemoto.Logout(Cliente: Integer);
begin
inherited;
ProcessRequest(ncnmLogout, @Cliente, SizeOf(Cliente),
nil, nil, nmdByteArray);
end;
function TncNXServRemoto.ObtemStreamListaObj(Cliente,
TipoClasse: Integer; S: TStream): Integer;
var Request : TnmObtemListaReq;
begin
Request.nmCliente := Cliente;
Request.nmTipoClasse := TipoClasse;
Result := ProcessRequest(ncnmObtemLista, @Request, SizeOf(Request), @S, nil, nmdStream);
end;
procedure TncNXServRemoto.OnTerminateSock(Sender: TObject);
begin
DebugMsg('TncNXServRemoto.OnTerminateSock'); // do not localize
FWaitingSock := False;
end;
function TncNXServRemoto.ApagaObj(Cliente: Integer; TipoClasse: Integer; Chave: String): Integer;
var Request : TnmObj;
begin
Request.nmCliente := Cliente;
Request.nmTipoClasse := TipoClasse;
Request.nmChave := Chave;
Result := ProcessRequest(ncnmApagaObj, @Request, SizeOf(Request),
nil, nil, nmdByteArray);
end;
function TncNXServRemoto.SalvaMovEst(aObj: TObject): Integer;
var S: TMemoryStream;
begin
S := TMemoryStream.Create;
try
TncMovEst(aObj).SalvaStream(S, False);
S.Position := 0;
Result := ProcessRequest(ncnmSalvaMovEst, S.Memory, S.Size, nil, nil, nmdByteArray);
finally
S.Free;
end;
end;
function TncNXServRemoto.SalvaDebito(aObj: TObject): Integer;
var S: TMemoryStream;
begin
S := TMemoryStream.Create;
try
TncDebito(aObj).SalvaStream(S, False);
S.Position := 0;
Result := ProcessRequest(ncnmSalvaDebito, S.Memory, S.Size, nil, nil, nmdByteArray);
finally
S.Free;
end;
end;
function TncNXServRemoto.SalvaApp(aApp: String): Integer;
var
SL : TStrings;
S: TMemoryStream;
begin
SL := TStringList.Create;
S := TMemoryStream.Create;
try
SL.Text := aApp;
SL.SaveToStream(S);
Result := ProcessRequest(ncnmSalvaApp, S.Memory, S.Size, nil, nil, nmdByteArray);
finally
SL.Free;
S.Free;
end;
end;
function TncNXServRemoto.SalvaCredito(aObj: TObject): Integer;
var S: TMemoryStream;
begin
S := TMemoryStream.Create;
try
TncSalvaCredito(aObj).SalvaStream(S, False);
S.Position := 0;
Result := ProcessRequest(ncnmSalvaCredito, S.Memory, S.Size, nil, nil, nmdByteArray);
finally
S.Free;
end;
end;
function TncNXServRemoto.SalvaLancExtra(aObj: TObject): Integer;
var S: TMemoryStream;
begin
S := TMemoryStream.Create;
try
TncLancExtra(aObj).SalvaStream(S, False);
S.Position := 0;
Result := ProcessRequest(ncnmSalvaLancExtra, S.Memory, S.Size, nil, nil, nmdByteArray);
finally
S.Free;
end;
end;
function TncNXServRemoto.SalvaLic(aLic: String): Integer;
var
SL : TStrings;
S : TMemoryStream;
begin
SL := TStringList.Create;
try
S := TMemoryStream.Create;
try
SL.Text := aLic;
SL.SaveToStream(S);
S.Position := 0;
Result := ProcessRequest(ncnmSalvaLic, S.Memory, S.Size, nil, nil, nmdByteArray);
finally
S.Free;
end;
finally
SL.Free;
end;
end;
function TncNXServRemoto.SalvaStreamObj(Novo: Boolean; S: TStream): Integer;
const
ID_Msg : Array[Boolean] of Integer = (ncnmAlteraObj, ncnmNovoObj);
begin
with FRemPlugin do
Result :=
bpeProcessRequest(ID_Msg[Novo], TMemoryStream(S).Memory, S.Size, nil, nil, nmdByteArray);
end;
function TncNXServRemoto.TableUpdated(aIDTab: Byte): integer;
var
Req : TnmTableUpdated;
begin
Req.nmIDTab := aIDTab;
Result := ProcessRequest(ncnmTableUpdated, @Req, SizeOf(Req), nil, nil, nmdByteArray);
end;
function TncNXServRemoto.Upload(aFonte, aDestino: String): Integer;
var
Req : PnmUpload;
S : TnxMemoryStream;
ReqLen : Integer;
begin
if not FileExists(aFonte) then begin
Result := ncerrArqNaoEncontrado;
Exit;
end;
S := TnxMemoryStream.Create;
try
S.LoadFromFile(aFonte);
ReqLen := SizeOf( TnmUpload ) - SizeOf( TnxVarMsgField ) + S.Size + 1;
nxGetZeroMem(Req, ReqLen);
try
Req^.nmNomeArq := aDestino;
Req.nmTamanho := S.Size;
Move(S.Memory^, Req^.nmArq, S.Size);
Result := ProcessRequest(ncnmUploadArq, Req, ReqLen, nil, nil, nmdByteArray);
finally
nxFreeMem(Req);
end;
finally
S.Free;
end;
end;
function TncNXServRemoto.ZerarEstoque(aFunc: String): integer;
var Req : TnmZerarEstoqueReq;
begin
Req.nmFunc := aFunc;
Result := ProcessRequest(ncnmZerarEstoque, @Req, SizeOf(Req), nil, nil, nmdByteArray);
end;
function TncNXServRemoto.CancelaTran(aID: Integer; aFunc: String): integer;
var Req: TnmCancelaTranReq;
begin
Req.nmFunc := aFunc;
Req.nmTran := aID;
Result := ProcessRequest(ncnmCancelaTran,
@Req, SizeOf(Req),
nil, nil, nmdByteArray);
end;
function TncNXServRemoto.ObtemStreamConfig(S: TStream): Integer;
begin
Result := ProcessRequest(ncnmObtemStreamConfig, nil, 0, @S, nil, nmdStream);
S.Position := 0;
end;
function TncNXServRemoto.ObtemCertificados(sl: TStrings): integer;
var S : TStream;
begin
S := TnxMemoryStream.Create;
try
Result := ProcessRequest(ncnmObtemCertificados, nil, 0, @S, 0, nmdStream);
S.Position := 0;
if Result=0 then
sl.LoadFromStream(S);
finally
S.Free;
end;
end;
function TncNXServRemoto.ObtemPastaServ(var NomePastaServ: String): Integer;
var
ReplyLen : TnxWord32;
P : Pointer;
begin
try
Result := ProcessRequest(ncnmObtemPastaServ, nil, 0, @P, @ReplyLen, nmdByteArray);
if Result=0 then
NomePastaServ := PnmNomeArq(P)^.nmNomeArq;
finally
if Assigned(P) then nxFreeMem(P);
end;
end;
function TncNXServRemoto.GetLoginData(var aVer, aConta, aUsers: String): integer;
var
S: TStream;
sl : TStrings;
str: String;
begin
S := TMemoryStream.Create;
sl := TStringList.Create;
try
aVer := '';
aConta := '';
aUsers := '';
Result := ProcessRequest(ncnmGetLoginData, nil, 0, @S, nil, nmdStream);
if Result=0 then begin
S.Position := 0;
sl.LoadFromStream(S);
str := sl.Text;
if str='sadsdfsdf' then Exit;
if sl.Count>1 then begin
aVer := sl[0];
aConta := sl[1];
sl.Delete(0);
sl.Delete(0);
aUsers := sl.Text;
end;
end;
finally
S.Free;
end;
end;
function TncNXServRemoto.ReemitirNFCe(aTran: TGuid): integer;
begin
Result := ProcessRequest(ncnmReemitirNFCe, @aTran, SizeOf(aTran), nil, nil, nmdByteArray);
end;
function TncNXServRemoto.AbreCaixa(aFunc: String; aSaldo: Currency;
var NovoCx: Integer): Integer;
var
Req: TnmAbreCaixaReq;
P: Pointer;
ReplyLen : TnxWord32;
begin
Req.nmFunc := aFunc;
Req.nmSaldo := aSaldo;
try
Result := ProcessRequest(ncnmAbreCaixa, @Req, SizeOf(Req),
@P, @ReplyLen, nmdByteArray);
if Result=0 then
NovoCx := PnmAbreCaixaRpy(P)^.nmID;
finally
if Assigned(P) then nxFreeMem(P);
end;
end;
function TncNXServRemoto.CorrigeDataCaixa(aFunc: String; aID: Integer; aNovaAbertura, aNovoFechamento: TDateTime): integer;
var
Req: TnmCorrigeDataCaixaReq;
begin
Req.nmFunc := aFunc;
Req.nmCaixa := aID;
Req.nmNovaAbertura := aNovaAbertura;
Req.nmNovoFechamento := aNovoFechamento;
Result := ProcessRequest(ncnmCorrigeDataCaixa, @Req, SizeOf(Req), nil, nil, nmdByteArray);
end;
function TncNXServRemoto.AjustaPontosFid(aFunc: String; aCliente: Integer;
aFator: Smallint; aPontos: Double; aObs: String): Integer;
var
Req: TnmAjustaPontosFid;
begin
Req.nmFunc := aFunc;
Req.nmCliente := aCliente;
Req.nmFator := aFator;
Req.nmPontos := aPontos;
Req.nmObs := aObs;
Result := ProcessRequest(ncnmAjustaPontosFid, @Req, SizeOf(Req), nil, nil, nmdByteArray);
end;
{ TThreadSockConn }
constructor TThreadSockConn.Create(aTransp: TnxBasePooledTransport);
begin
inherited Create(True);
FTransp := aTransp;
FreeOnTerminate := False;
FExecuting := True;
DebugMsg('TThreadSockConn.Create'); // do not localize
end;
procedure TThreadSockConn.Execute;
begin
DebugMsg('TThreadSockConn.Execute - 1'); // do not localize
try
try
DebugMsg('TThreadSockConn.Execute - 2'); // do not localize
FTransp.Active := True;
DebugMsg('TThreadSockConn.Execute - 3'); // do not localize
except
On E: Exception do
DebugMsg('TThreadSockConn.Execute - Exception: ' + E.message); // do not localize
end;
finally
FExecuting := False;
DebugMsg('TThreadSockConn.Execute - Finally'); // do not localize
end;
end;
initialization
TncnxRemotePlugin.rcRegister;
TncnxRemoteCmdHandler.rcRegister;
finalization
TncnxRemotePlugin.rcUnRegister;
TncnxRemoteCmdHandler.rcUnRegister;
end.
|
{ Module of routines that deal with messages specifically for supplying
* information about menu entries. All routines take the menu entries
* message object as their first argument.
*
* A menu entry message supplies information about the entries of a menu.
* Such a message must adhere to a particular format within the message
* file constructs. These messages are expected to expand into one per
* menu entry. The .NFILL command must therefore be used at the start
* of each message to prevent line wrapping. Each line read from the
* message must have the format:
*
* <ID> <name> [<shortcut index>]
*
* ID is the internal number used to identify this menu entry. Menu
* entries are not identified by their position, but only by this ID.
* Therefore, the order of menu entries can be re-arranged, and the
* program will function normally as long as the IDs are rearranged
* along with the entries.
*
* NAME is the menu entry name to display to the user. This is
* parsed as one token, so must be enclosed in quotes ("") or apostrophies
* () if it contains special characters, like spaces.
*
* SHORTCUT INDEX is the character index into NAME for the shortcut
* character for this entry. The shortcut character is typically
* underlined so that the user knows pressing that key will select
* that menu entry. The index of the first character is 1. The menu
* entry will have no shortcut key if this parameter is omitted or
* explicitly set to 0. Note that SHORTCUT INDEX is the index into
* NAME as parsed. This means enclosing quotes aren't counted, since
* they are not part of the name displayed to the user.
*
* For example:
*
* 3 "Close File" 2
*
* The menu entry will be displayed as:
*
* Close File
*
* with the "l" in "Close" being the shortcut character for this entry. The
* internal program ID for this entry is 3.
}
module gui_mmsg;
define gui_mmsg_init;
define gui_mmsg_close;
define gui_mmsg_next;
%include 'gui2.ins.pas';
{
*************************************************************************
*
* Subroutine GUI_MMSG_INIT (MMSG, SUBSYS, MSG, PARMS, N_PARMS)
*
* Set up a new connection to a menu entries message. MMSG is the
* returned menu entries message object. The remaining arguments
* are the standard arguments for specifying a message and supplying
* it parameters.
}
procedure gui_mmsg_init ( {init for reading a menu entries message}
out mmsg: gui_mmsg_t; {returned menu entries message object}
in subsys: string; {name of subsystem, used to find message file}
in msg: string; {message name withing subsystem file}
in parms: univ sys_parm_msg_ar_t; {array of parameter descriptors}
in n_parms: sys_int_machine_t); {number of parameters in PARMS}
val_param;
var
vsubsys: string_var80_t; {var string subsystem name}
vmsg: string_var80_t; {var string message name}
stat: sys_err_t;
begin
vsubsys.max := size_char(vsubsys.str); {init local var strings}
vmsg.max := size_char(vmsg.str);
string_vstring (vsubsys, subsys, sizeof(subsys)); {make var strings of str parms}
string_vstring (vmsg, msg, sizeof(msg));
file_open_read_msg ( {try to open message for reading}
vsubsys, {generic message file name}
vmsg, {message name within file}
parms, {array of parameter descriptors}
n_parms, {number of parameters in PARMS}
mmsg.conn, {returned connection descriptor}
stat);
mmsg.open := not sys_error(stat); {indicate whether opened successfully}
end;
{
*************************************************************************
}
procedure gui_mmsg_close ( {close connection to menu entries message}
in out mmsg: gui_mmsg_t); {menu entries message object}
val_param;
begin
if mmsg.open then begin {message is actually open ?}
file_close (mmsg.conn); {close connection to the message}
mmsg.open := false; {indicate connection to message closed}
end;
end;
{
*************************************************************************
}
function gui_mmsg_next ( {return parameters for next menu entry}
in out mmsg: gui_mmsg_t; {menu entries message object}
in out name: univ string_var_arg_t; {name to display to user for this choice}
out shcut: string_index_t; {NAME index for shortcut key, 0 = none}
out id: sys_int_machine_t) {ID returned when this entry picked}
:boolean; {TRUE on got entry info, closed on FALSE}
val_param;
var
buf: string_var132_t; {one line from message}
p: string_index_t; {BUF parse index}
tk: string_var16_t; {token parsed from BUF}
i: sys_int_machine_t; {scratch integer}
stat: sys_err_t;
label
yes, err, no;
begin
buf.max := size_char(buf.str); {init local var strings}
tk.max := size_char(tk.str);
if not mmsg.open then goto no; {connection to message closed ?}
file_read_msg (mmsg.conn, buf.max, buf, stat); {read next line from message}
if sys_error(stat) then goto err; {didn't get message line ?}
p := 1; {init BUF parse index}
string_token_int (buf, p, id, stat); {get entry ID value}
if sys_error(stat) then goto err;
string_token (buf, p, name, stat); {get entry name string}
if sys_error(stat) then goto err;
string_token_int (buf, p, i, stat); {get shortcut character index}
if string_eos(stat)
then begin {this token was not present}
shcut := 0; {indicate no shortcut key}
goto yes; {return with info}
end
else begin {other than hit end of string}
if sys_error(stat) then goto err;
shcut := i; {pass back shortcut character index}
end
;
string_token (buf, p, tk, stat); {try to parse another token}
if not string_eos(stat) then goto err; {not hit end of string like supposed to ?}
yes: {jump here to return with entry info}
gui_mmsg_next := true; {indicate entry info successfully returned}
return; {normal return}
{
* Something went wrong. We don't try to figure out what or why, just
* terminate processing. We close the connection to the message and indicate
* no entry data was returned.
}
err: {something went wrong}
gui_mmsg_close (mmsg); {close connection to message}
no: {jump here to return with no entry info}
gui_mmsg_next := false; {init to no menu entry info returned}
end;
|
// HRBuffers v0.3.1 (03.Aug.2000)
// Simple buffer classes
// by Colin A Ridgewell
//
// Copyright (C) 1999,2000 Hayden-R Ltd
// http://www.haydenr.com
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2 of the License, or (at your
// option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along
// with this program (gnu_license.htm); if not, write to the
//
// Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// To contact us via e-mail use the following addresses...
//
// bug@haydenr.u-net.com - to report a bug
// support@haydenr.u-net.com - for general support
// wishlist@haydenr.u-net.com - add new requirement to wish list
//
unit HRBuffers;
interface
uses
Classes, SysUtils;
type
{Base buffer.}
THRBuffer=class(TObject)
private
FBuffer:PChar;
FSize:LongInt;
procedure SetSize(Value:LongInt);
procedure CreateBuffer(const Size:LongInt);
procedure ResizeBuffer(const Size:LongInt);
procedure FreeBuffer;
protected
function GetItems(Index:LongInt):Char; virtual;
procedure SetItems(Index:LongInt;Value:Char); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
property Buffer:PChar read FBuffer;
property Size:Longint read FSize write SetSize;
property Items[Index:LongInt]:Char read GetItems write SetItems; default;
end;
{Base buffer with EOB.}
THRBufferEOB=class(THRBuffer)
private
protected
function GetEOB:Boolean; virtual;
public
property EOB:Boolean read GetEOB;
end;
{Buffer for holding a series of char.}
THRBufferChar=class(THRBufferEOB)
private
FEOB:Boolean;
FPosition:Longint;
protected
function GetEOB:Boolean; override;
function GetItems(Index:LongInt):Char; override;
procedure SetItems(Index:LongInt;Value:Char); override;
function GetAsPChar:PChar;
procedure SetAsPChar(Value:PChar);
function GetAsString:string;
procedure SetAsString(Value:string);
public
constructor Create; override;
destructor Destroy; override;
property Buffer;
property Position:Longint read FPosition write FPosition;
procedure Write(const Value:Char);
function Read:Char;
procedure WritePChar(const Str:PChar);
procedure WriteString(const Str:String);
property AsPChar:PChar read GetAsPChar write SetAsPChar;
property AsString:string read GetAsString write SetAsString;
end;
{Buffer for reading from a stream.}
THRBufferStream=class(THRBufferEOB)
private
FEOB:Boolean;
FStream:TStream;
FStreamSize:Longint;
FFirstPosInBuffer:LongInt;
protected
function GetEOB:Boolean; override;
function GetItems(Index:LongInt):Char; override;
procedure SetItems(Index:LongInt;Value:Char); override;
procedure SetStream(Value:TStream);
public
constructor Create; override;
destructor Destroy; override;
property Stream:TStream read FStream write SetStream;
end;
{A buffer containing a list of smaller buffers in one piece of contiguous memory.}
THRBufferList=class(THRBuffer)
private
function GetItemPos(const Index:Integer):Integer;
function GetCount:Integer;
function GetItemSize(Index:Integer):Integer;
procedure SetItemSize(Index:Integer;Value:Integer);
function GetItemBuffer(Index:Integer):PChar;
public
constructor Create; override;
destructor Destroy; override;
procedure Add(const Index,ItemSize:Integer);
procedure Delete(const Index:Integer);
property Count:Integer read GetCount;
property ItemSize[Index:Integer]:Integer read GetItemSize write SetItemSize;
property ItemBuffer[Index:Integer]:PChar read GetItemBuffer;
end;
implementation
{ T H R B u f f e r }
constructor THRBuffer.Create;
begin
FBuffer:=nil;
FSize:=0;
end;
destructor THRBuffer.Destroy;
begin
FreeBuffer;
inherited Destroy;
end;
procedure THRBuffer.SetSize(Value:LongInt);
begin
if FBuffer=nil
then
CreateBuffer(Value)
else
if Value>0
then
ResizeBuffer(Value)
else
FreeBuffer;
end;
function THRBuffer.GetItems(Index:LongInt):Char;
begin
Result:=#0;
end;
procedure THRBuffer.SetItems(Index:LongInt;Value:Char);
begin
end;
procedure THRBuffer.CreateBuffer(const Size:LongInt);
begin
if FBuffer=nil
then
begin
FSize:=Size;
GetMem(FBuffer,FSize+1);
{Null terminate end of buffer.}
FBuffer[FSize]:=#0;
end;
end;
procedure THRBuffer.ResizeBuffer(const Size:LongInt);
var
New:PChar;
MoveSize:LongInt;
begin
if FBuffer<>nil
then
begin
GetMem(New,Size+1);
if FSize>Size then MoveSize:=Size else MoveSize:=FSize;
Move(FBuffer[0],New[0],MoveSize);
FreeMem(FBuffer,FSize+1);
FBuffer:=New;
FSize:=Size;
FBuffer[FSize]:=#0;
end;
end;
procedure THRBuffer.FreeBuffer;
begin
if FBuffer<>nil
then
begin
FreeMem(FBuffer,FSize+1);
FBuffer:=nil;
FSize:=0;
end;
end;
{ T H R B u f f e r E O B }
function THRBufferEOB.GetEOB:Boolean;
begin
Result:=True;
end;
{ T H R B u f f e r C h a r }
constructor THRBufferChar.Create;
begin
inherited Create;
FEOB:=False;
end;
destructor THRBufferChar.Destroy;
begin
inherited Destroy;
end;
function THRBufferChar.GetEOB:Boolean;
begin
Result:=FEOB;
end;
function THRBufferChar.GetItems(Index:LongInt):Char;
begin
if Index<FSize
then
begin
Result:=FBuffer[Index];
FEOB:=False;
end
else
begin
Result:=#0;
FEOB:=True;
end;
end;
procedure THRBufferChar.SetItems(Index:LongInt;Value:Char);
begin
if Index<FSize
then
begin
FBuffer[Index]:=Value;
FEOB:=False;
end
else
begin
FEOB:=True;
end;
end;
function THRBufferChar.Read:Char;
begin
if FPosition<FSize
then
begin
Result:=FBuffer[FPosition];
Inc(FPosition);
FEOB:=False;
end
else
begin
Result:=#0;
FEOB:=True;
end;
end;
procedure THRBufferChar.Write(const Value:Char);
begin
if FPosition<FSize
then
begin
FBuffer[FPosition]:=Value;
Inc(FPosition);
FEOB:=False;
end
else
begin
FEOB:=True;
end;
end;
procedure THRBufferChar.WritePChar(const Str:PChar);
var
i:Integer;
begin
for i:=0 to StrLen(Str)-1 do Write(Str[i]);
end;
procedure THRBufferChar.WriteString(const Str:String);
var
i:Integer;
begin
for i:=1 to Length(Str) do Write(Str[i]);
end;
function THRBufferChar.GetAsPChar:PChar;
begin
Result:=FBuffer;
end;
procedure THRBufferChar.SetAsPChar(Value:PChar);
var
L:Integer;
begin
L:=StrLen(Value);
if L<=FSize
then
begin
{Copies from value buffer to FBuffer.}
StrMove(FBuffer,Value,L);
FEOB:=False;
end
else
begin
FEOB:=True;
end;
end;
function THRBufferChar.GetAsString:string;
begin
Result:='';
end;
procedure THRBufferChar.SetAsString(Value:string);
begin
end;
{ T H R B u f f e r S t r e a m }
constructor THRBufferStream.Create;
begin
inherited Create;
FStream:=nil;
FFirstPosInBuffer:=-1;
end;
destructor THRBufferStream.Destroy;
begin
inherited Destroy;
end;
procedure THRBufferStream.SetStream(Value:TStream);
begin
if Value<>FStream
then
begin
FStream:=Value;
FStreamSize:=FStream.Size;
FFirstPosInBuffer:=-1;
end;
end;
function THRBufferStream.GetEOB:Boolean;
begin
Result:=FEOB;
end;
function THRBufferStream.GetItems(Index:LongInt):Char;
begin
if Index<FStreamSize
then
begin
if (Index>=FFirstPosInBuffer+FSize) or
(Index<FFirstPosInBuffer) or
(FFirstPosInBuffer=-1)
then
begin
{Read next block from stream into buffer.}
FStream.Position:=Index;
FStream.Read(FBuffer[0],FSize);
FFirstPosInBuffer:=Index;
end;
{Read from buffer}
Result:=FBuffer[Index-FFirstPosInBuffer];
FEOB:=False;
end
else
begin
{EOB}
Result:=#0;
FEOB:=True;
end;
end;
procedure THRBufferStream.SetItems(Index:LongInt;Value:Char);
begin
end;
{ T H R B u f f e r L i s t }
type
PHRInteger=^Integer;
constructor THRBufferList.Create;
begin
inherited Create;
{Set count to zero.}
Size:=SizeOf(Integer);
PHRInteger(Buffer)^:=0;
end;
destructor THRBufferList.Destroy;
begin
inherited Destroy;
end;
function THRBufferList.GetItemPos(const Index:Integer):Integer;
var
PosIndex:Integer;
Pos:Integer;
PosItemSize:Integer;
begin
{Check for out of bounds index.}
Assert(Index<PHRInteger(Buffer)^,'Index out of bounds');
{Step past count.}
Pos:=SizeOf(Integer);
{Loop thought items.}
PosIndex:=0;
while PosIndex<Index do
begin
{Get item size.}
PosItemSize:=PHRInteger(Buffer+Pos)^;
{Step over item.}
Pos:=Pos+SizeOf(Integer)+PosItemSize;
Inc(PosIndex);
end;
Result:=Pos;
end;
function THRBufferList.GetCount:Integer;
begin
Result:=PHRInteger(Buffer)^;
end;
function THRBufferList.GetItemSize(Index:Integer):Integer;
begin
Result:=PHRInteger(Buffer+GetItemPos(Index))^;
end;
procedure THRBufferList.SetItemSize(Index:Integer;Value:Integer);
var
Pos:Integer;
ItemSize:Integer;
Diff:Integer;
OldSize:Integer;
S,D:PChar;
C:Integer;
begin
Pos:=GetItemPos(Index);
{Calc diff is size.}
ItemSize:=PHRInteger(Buffer+Pos)^;
Diff:=Value-ItemSize;
{No change in size.}
if Diff=0 then Exit;
if Diff<0
then
begin
{Shrink buffer}
{Move items > index down buffer.}
S:=Buffer+Pos+SizeOf(Integer)+ItemSize;
D:=S+Diff;
C:=Size-(Pos+SizeOf(Integer)+ItemSize);
Move(S[0],D[0],C);
{Dec buffer size}
Size:=Size+Diff;
end
else
begin
{Grow buffer}
OldSize:=Size;
{Inc buffer size}
Size:=Size+Diff;
{Move items > index up buffer.}
S:=Buffer+Pos+SizeOf(Integer)+ItemSize;
D:=S+Diff;
C:=OldSize-(Pos+SizeOf(Integer)+ItemSize);
Move(S[0],D[0],C);
end;
{Set items new size.}
PHRInteger(Buffer+Pos)^:=Value;
end;
function THRBufferList.GetItemBuffer(Index:Integer):PChar;
begin
Result:=Buffer+GetItemPos(Index)+SizeOf(Integer);
end;
procedure THRBufferList.Add(const Index,ItemSize:Integer);
var
PosIndex:Integer;
Pos:Integer;
PosItemSize:Integer;
OldSize:Integer;
S,D:PChar;
C:Integer;
begin
{Step past count.}
Pos:=SizeOf(Integer);
{Step thought list until up to index or end list.}
PosIndex:=0;
while (PosIndex<Index)and(PosIndex<=PHRInteger(Buffer)^-1) do
begin
{Get item size.}
PosItemSize:=PHRInteger(Buffer+Pos)^;
{Step over item.}
Pos:=Pos+SizeOf(Integer)+PosItemSize;
Inc(PosIndex);
end;
{Pad list with empty items up to index.}
while (PosIndex<Index) do
begin
{Add item.}
Size:=Size+SizeOf(Integer);
{Set size of item to zero.}
PHRInteger(Buffer+Pos)^:=0;
{Inc count}
Inc(PHRInteger(Buffer)^);
{Step over item.}
Pos:=Pos+SizeOf(Integer);
Inc(PosIndex);
end;
{Resize buffer to accomodate new item.}
OldSize:=Size;
Size:=Size+SizeOf(Integer)+ItemSize;
{Push any items > index up buffer.}
if PosIndex<=PHRInteger(Buffer)^-1
then
begin
S:=Buffer+Pos;
D:=Buffer+Pos+SizeOf(Integer)+ItemSize;
C:=OldSize-Pos;
Move(S[0],D[0],C);
end;
{Set size of item.}
PHRInteger(Buffer+Pos)^:=ItemSize;
{Inc count.}
Inc(PHRInteger(Buffer)^);
end;
procedure THRBufferList.Delete(const Index:Integer);
begin
// find index
// get size
// move everthing > index down by sizeof(Integer) + index[size]
// dec buffer size by sizeof(Integer) + index[size]
// dec count
end;
end.
|
unit layui;
{$mode Delphi}
{$modeswitch externalclass}
interface
uses JS, Web,
Classes,
SysUtils,
Types,
Graphics,
Controls,
Forms,
StdCtrls,
ExtCtrls,
ComCtrls,
NumCtrls,
DttCtrls,
BtnCtrls,
TopCtrls,
DataGrid;
type
{ TDataModule }
TDataModule = class(TCustomDataModule)
private
FHorizontalOffset: longint;
FPPI: longint;
FVerticalOffset: longint;
published
property OnCreate;
property OnDestroy;
property OldCreateOrder;
published
/// Fake
property HorizontalOffset: longint read FHorizontalOffset write FHorizontalOffset;
property VerticalOffset: longint read FVerticalOffset write FVerticalOffset;
property PPI: longint read FPPI write FPPI;
end;
TDataModuleClass = class of TDataModule;
{ TComboBox }
TComboBox = class(TCustomComboBox)
protected
procedure Changed; override;
published
DroppedDown :Boolean;
property Align;
property Anchors;
property AutoSize;
property BorderSpacing;
property BorderStyle;
property Color;
property Enabled;
property Font;
property HandleClass;
property HandleID;
property ItemHeight;
property ItemIndex;
property Items;
property ParentColor;
property ParentFont;
property ParentShowHint;
property ShowHint;
property TabOrder;
property TabStop;
property Text;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
end;
{ TListBox }
TListBox = class(TCustomListBox)
published
property Align;
property Anchors;
property AutoSize;
property BorderSpacing;
property BorderStyle;
property Color;
property Enabled;
property Font;
property HandleClass;
property HandleID;
property ItemHeight;
property ItemIndex;
property Items;
property MultiSelect;
property ParentColor;
property ParentFont;
property ParentShowHint;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnSelectionChange;
end;
{ TEdit }
TEdit = class(TCustomEdit)
published
property Align;
property Anchors;
property Alignment;
property AutoSize;
property BorderSpacing;
property BorderStyle;
property CharCase;
property Color;
property Enabled;
property Font;
property HandleClass;
property HandleId;
property MaxLength;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property ReadOnly;
property ShowHint;
property TabStop;
property TabOrder;
property Text;
property TextHint;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnResize;
end;
{ TMemo }
TMemo = class(TCustomMemo)
published
property Align;
property Anchors;
property Alignment;
property BorderSpacing;
property BorderStyle;
property CharCase;
property Color;
property Enabled;
property Font;
property HandleClass;
property HandleId;
property Lines;
property Text;
property MaxLength;
property ParentColor;
property ParentFont;
property ParentShowHint;
property ReadOnly;
property ShowHint;
property TabOrder;
property TabStop;
property TextHint;
property Visible;
property WantReturns;
property WantTabs;
property WordWrap;
property OnChange;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnResize;
end;
{ TButton }
TButton = class(TCustomButton)
protected
procedure Changed; override;
published
property Align;
property Anchors;
property AutoSize;
property BorderSpacing;
property Caption;
property Color;
property Enabled;
property Font;
property HandleClass;
property HandleId;
property Hint;
property ModalResult;
property ParentFont;
property ParentShowHint;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnClick;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnResize;
end;
{ TCheckbox }
TCheckbox = class(TCustomCheckbox)
protected
procedure Changed; override;
published
property Align;
property Alignment;
property AllowGrayed;
property Anchors;
property AutoSize;
property BorderSpacing;
property Caption;
property Checked;
property Color;
property Enabled;
property Font;
property HandleClass;
property HandleId;
property ParentColor;
property ParentFont;
property ParentShowHint;
property ShowHint;
property State;
property TabOrder;
property TabStop;
property Visible;
property OnChange;
property OnClick;
property OnEnter;
property OnExit;
property OnKeyPress;
property OnKeyDown;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnResize;
end;
{ TLabel }
TLabel = class(TCustomLabel)
published
property Align;
property Alignment;
property Anchors;
property AutoSize;
property BorderSpacing;
property Caption;
property Color;
property Enabled;
property FocusControl;
property Font;
property HandleClass;
property HandleId;
property Layout;
property ParentColor;
property ParentFont;
property ParentShowHint;
property ShowHint;
property Transparent;
property Visible;
property WordWrap;
property OnClick;
property OnDblClick;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnResize;
end;
{ TImage }
TImage = class(TCustomImage)
published
property Align;
property Anchors;
property AutoSize;
property BorderSpacing;
property Center;
property Enabled;
property HandleClass;
property HandleId;
property ParentShowHint;
property Proportional;
property ShowHint;
property Stretch;
property StretchOutEnabled;
property StretchInEnabled;
property Transparent;
property URL;
property Visible;
property OnClick;
property OnDblClick;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnPaint;
property OnPictureChanged;
property OnResize;
end;
{ TPanel }
TPanel = class(TCustomPanel)
published
property Align;
property Alignment;
property Anchors;
property AutoSize;
property BevelColor;
property BevelInner;
property BevelOuter;
property BevelWidth;
property BorderSpacing;
property Caption;
property ClientHeight;
property Clientwidth;
property Color;
property Enabled;
property Font;
property HandleClass;
property HandleId;
property ParentColor;
property ParentFont;
property ParentShowHint;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property Wordwrap;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnPaint;
property OnResize;
end;
{ TTimer }
TTimer = class(TCustomTimer)
published
property Enabled;
property Interval;
property OnTimer;
property OnStartTimer;
property OnStopTimer;
end;
{ TPageControl }
TPageControl = class(TCustomPageControl)
published
property ActivePage;
property Align;
property Anchors;
property BorderSpacing;
property Enabled;
property Font;
property HandleClass;
property HandleId;
property ParentFont;
property ParentShowHint;
property ShowHint;
property ShowTabs;
property TabHeight;
property TabIndex;
property TabPosition;
property TabOrder;
property TabStop;
property TabWidth;
property Visible;
property OnEnter;
property OnExit;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
end;
{ TFloatEdit }
TFloatEdit = class(TCustomNumericEdit)
private
function GetValue: double;
procedure SetValue(AValue: double);
protected
procedure RealSetText(const AValue: string); override;
published
property Align;
property Alignment;
property Anchors;
property AutoSize;
property BorderSpacing;
property BorderStyle;
property Color;
property DecimalPlaces;
property Enabled;
property Font;
property HandleClass;
property HandleId;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property ReadOnly;
property ShowHint;
property TabStop;
property TabOrder;
property Text;
property TextHint;
property Value: double read GetValue write SetValue;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnResize;
end;
{ TIntegerEdit }
TIntegerEdit = class(TCustomNumericEdit)
private
function GetValue: NativeInt;
procedure SetValue(AValue: NativeInt);
protected
procedure RealSetText(const AValue: string); override;
public
constructor Create(AOwner: TComponent); override;
published
property Align;
property Alignment;
property Anchors;
property AutoSize;
property BorderSpacing;
property BorderStyle;
property Color;
property Enabled;
property Font;
property HandleClass;
property HandleId;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property ReadOnly;
property ShowHint;
property TabStop;
property TabOrder;
property Text;
property TextHint;
property Value: NativeInt read GetValue write SetValue;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnResize;
end;
{ TDateEditBox }
TDateEditBox = class(TCustomDateTimeEdit)
private
function GetValue: TDate;
procedure SetValue(AValue: TDate);
protected
function InputType: string; override;
procedure RealSetText(const AValue: string); override;
published
property Align;
property Alignment;
property Anchors;
property AutoSize;
property BorderSpacing;
property BorderStyle;
property Color;
property Enabled;
property Font;
property HandleClass;
property HandleId;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property ReadOnly;
property ShowHint;
property TabStop;
property TabOrder;
property Text;
property TextHint;
property Value: TDate read GetValue write SetValue;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnResize;
end;
{ TTimeEditBox }
TTimeEditBox = class(TCustomDateTimeEdit)
private
function GetValue: TTime;
procedure SetValue(AValue: TTime);
protected
function InputType: string; override;
procedure RealSetText(const AValue: string); override;
published
property Align;
property Alignment;
property Anchors;
property AutoSize;
property BorderSpacing;
property BorderStyle;
property Color;
property Enabled;
property Font;
property HandleClass;
property HandleId;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property ReadOnly;
property ShowHint;
property TabStop;
property TabOrder;
property Text;
property TextHint;
property Value: TTime read GetValue write SetValue;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnResize;
end;
{ TFileButton }
TFileButton = class(TCustomFileButton)
published
property Align;
property Anchors;
property AutoSize;
property BorderSpacing;
property Caption;
property Color;
property Enabled;
property Filter;
property Font;
property HandleClass;
property HandleId;
//property ModalResult;
property ParentFont;
property ParentShowHint;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnChange;
property OnClick;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnResize;
end;
{ TDataGrid }
TDataGrid = class(TCustomDataGrid)
published
property Align;
property Anchors;
property BorderSpacing;
property Columns;
property ColumnClickSorts;
property DefaultColWidth;
property DefaultRowHeight;
property Enabled;
property Font;
property HandleClass;
property HandleId;
property ParentFont;
property ParentShowHint;
property ShowHint;
property SortOrder;
property ShowHeader;
property TabOrder;
property TabStop;
property Visible;
property OnCellClick;
property OnEnter;
property OnExit;
property OnHeaderClick;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
end;
{ TPagination }
TPagination = class(TCustomPagination)
published
property Align;
property Anchors;
property BorderSpacing;
property CurrentPage;
property Enabled;
property Font;
property HandleClass;
property HandleId;
property ParentFont;
property ParentShowHint;
property RecordsPerPage;
property ShowHint;
property TabOrder;
property TabStop;
property TotalPages;
property TotalRecords;
property Visible;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnPageClick;
end;
TProgressBar = class(TCustomProgressBar)
protected
procedure Changed; override;
procedure SetPosition(Value: integer); override;
public
property Min;
property Max;
property Position;
property Step;
end;
TTrackBar = class(TCustomTrackBar)
protected
procedure Changed; override;
procedure Paint; override;
function CreateHandleElement: TJSHTMLElement; override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: integer); override;
public
constructor Create(AOwner: TComponent); override;
property Min;
property Max;
property Position;
property Frequency;
property LineSize;
property PageSize;
property Orientation;
// Run-time modification ignored; write present only for dynamical control creation purpose
property TickStyle;
// Run-time modification ignored; write present only for dynamical control creation purpose
property OnChange;
end;
TLayuiCallBack = reference to procedure; safecall;
TLayuiValueCallBack = reference to procedure(value:integer); safecall;
TLayui = Class external name 'Layui' (TJSObject)
procedure use(args: array of string; aCallBack : TLayuiCallBack);
end;
TLayuiElement = Class external name 'LayuiElement' (TJSObject)
constructor new;
Procedure progress(const aName,aValue : String);
end;
procedure layui_use;
procedure layui_open;
var
element : TLayuiElement; external name 'element';
layui : TLayui; external name 'layui';
isLoad:Boolean;
implementation
procedure layui_use;
begin
layui.use(['layer', 'form'],procedure begin end);
end;
procedure layui_open;
begin
asm
var index2= layer.open({
type:1,
title :['Form1', 'font-size:12px;'],
area:['480px','680px'],
maxmin: true,
scrollbar: false,
shade:0,
content: layui.$('#form1')
});
end;
isLoad:=True;
end;
{ TFloatEdit }
function TFloatEdit.GetValue: double;
begin
Result := StrToFloatDef(RealGetText, 0);
end;
procedure TFloatEdit.SetValue(AValue: double);
begin
RealSetText(FloatToStrF(AValue, ffFixed, 20, DecimalPlaces));
end;
procedure TFloatEdit.RealSetText(const AValue: string);
begin
inherited RealSetText(FloatToStrF(StrToFloatDef(AValue, 0), ffFixed,
20, DecimalPlaces));
end;
{ TIntegerEdit }
function TIntegerEdit.GetValue: NativeInt;
begin
Result := StrToIntDef(RealGetText, 0);
end;
procedure TIntegerEdit.SetValue(AValue: NativeInt);
begin
RealSetText(FloatToStrF(AValue, ffFixed, 20, DecimalPlaces));
end;
procedure TIntegerEdit.RealSetText(const AValue: string);
begin
inherited RealSetText(FloatToStrF(StrToFloatDef(AValue, 0), ffFixed,
20, DecimalPlaces));
end;
constructor TIntegerEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
BeginUpdate;
try
DecimalPlaces := 0;
finally
EndUpdate;
end;
end;
{ TDateEditBox }
function TDateEditBox.GetValue: TDate;
begin
Result := StrToDateDef(RealGetText, 0);
end;
procedure TDateEditBox.SetValue(AValue: TDate);
begin
RealSetText(DateToStr(AValue));
end;
function TDateEditBox.InputType: string;
begin
Result := 'date';
end;
procedure TDateEditBox.RealSetText(const AValue: string);
begin
inherited RealSetText(FormatDateTime(ShortDateFormat, StrToDateDef(AValue, 0)));
end;
{ TTimeEditBox }
function TTimeEditBox.GetValue: TTime;
begin
Result := StrToTimeDef(RealGetText, 0);
end;
procedure TTimeEditBox.SetValue(AValue: TTime);
begin
RealSetText(TimeToStr(AValue));
end;
function TTimeEditBox.InputType: string;
begin
Result := 'time';
end;
procedure TTimeEditBox.RealSetText(const AValue: string);
begin
inherited RealSetText(FormatDateTime(ShortTimeFormat, StrToTimeDef(AValue, 0)));
end;
procedure TButton.Changed;
begin
inherited Changed;
if height<30 then
HandleElement['class']:='layui-btn layui-btn-xs'
else
HandleElement['class']:='layui-btn';
// HandleElement.Attrs['class']:='layui-btn';
end;
procedure TCheckBox.Changed;
begin
inherited Changed;
HandleElement['class']:='layui-form-item';
// TForm(Owner).HandleElement['class']:='layui-form';
end;
procedure TComboBox.Changed;
begin
inherited Changed;
HandleElement['class']:='layui-form-item';
end;
procedure TProgressBar.Changed;
begin
inherited Changed;
HandleElement.style.removeProperty('background-color');
HandleElement['class']:='layui-progress ';
BarElement['class']:='layui-progress-bar lay-filter="demo"';
BarElement.style['height']:='100%';
BarElement.style['width']:=inttostr(round(Position/Max*100))+'%';
BarElement['lay-percent']:=inttostr(round(Position/Max*100))+'%';
end;
procedure TProgressBar.SetPosition(Value: integer);
begin
inherited ;
end;
constructor TTrackBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
layui.use(['slider'],procedure begin end);
end;
function TTrackBar.CreateHandleElement: TJSHTMLElement;
begin
Result := TJSHTMLElement(Document.CreateElement('div'));
end;
procedure TTrackBar.Changed;
var
id:string;
changed: TLayuiValueCallBack ;
begin
inherited Changed;
Self.HandleId:=Self.Name;
HandleElement.style.setProperty('margin','10px');
HandleElement.style.removeProperty('overflow');
HandleElement['id']:=HandleId;
id:='#'+HandleId;
changed:= procedure (value:integer)
begin
Position:=value;
if assigned(FOnChange) then FOnChange(Self);
end;
asm
layui.slider.render({
elem: id,
change:changed
});
end;
end;
procedure TTrackBar.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: integer);
begin
end;
procedure TTrackBar.Paint;
begin
end;
Initialization
layui_use;
end.
|
unit CosmoUtil;
interface
Uses Windows, SysUtils, Classes, FiceStream, FF7Ed, DebugLog, Graphics,
LGPStruct, FFLzs, PluginTypes;
Type
TFourWords = array[1..4] of Word;
var
FF7_ExtractText: TExtractTextFunc=nil;
FF7_DecodeText: TDecodeTextFunc=nil;
FF7_EncodeText: TEncodeTextFunc=nil;
FF7_GetBackground: TGetBackgroundFunc=nil;
LGP_Repair: TLGPRepairFunc=nil;
LGP_Create: TLGPCreateFunc=nil;
LGP_Pack: TLGPPackFunc=nil;
function FF7Ed_ExtractText(Src:TMemoryStream;var Table:TList;var Info:TTextInfoRec): TMemoryStream; export;
function FF7Ed_DecodeText(Src:TStream): String; export;
function FF7Ed_EncodeText(Src:String): TMemoryStream; export;
function FF7Ed_GetBackground(Src:TMemoryStream): TBitmap; export;
procedure LGPRepair(FName:Shortstring); export;
procedure LGPCreate(SrcFolder,OutputFile:ShortString;DeleteOriginal,UseErrorCheck:Boolean); export;
procedure LGPPack(FName:ShortString); export;
function MaxVer: Comp;
function MaxVerString: String;
procedure InitPlugins;
function FilterText(Orig:String): String;
function UnFilterText(Orig:String): String;
var
Plugins: TStringList;
implementation
var
MaxVersion: Comp = 0;
UnfilterTbl,FilterTbl: Array[Char] of Char;
Filter: Boolean;
function FilterText(Orig:String): String;
var
I: Integer;
begin
If Not Filter then begin
Result := Orig; Exit;
end;
SetLength(Result,Length(Orig));
For I := 1 to Length(Orig) do
Result[I] := FilterTbl[Orig[I]];
end;
function UnFilterText(Orig:String): String;
var
I: Integer;
begin
If Not Filter then begin
Result := Orig; Exit;
end;
SetLength(Result,Length(Orig));
For I := 1 to Length(Orig) do
Result[I] := UnFilterTbl[Orig[I]];
end;
procedure InitPlugins;
var
I,J: Integer;
C: Char;
S: String;
GetPlug: TGetPluginFunc;
Tmp: TStringList;
Strm: TStream;
begin
Plugins.Clear;
Tmp := TStringList.Create;
Log('Init plugins');
For I := 0 to DLLs.Count-1 do begin
Tmp.Clear;
GetPlug := GetProcAddress(Integer(DLLs.Objects[I]),'Cosmo_GetPlugins');
If @GetPlug=nil then Continue;
GetPlug(Tmp);
For J := 0 to Tmp.Count-1 do
If Plugins.IndexOf(Tmp[J])=-1 then begin
Plugins.AddObject(Tmp[J],Tmp.Objects[J]);
Log(' Plugin function '+Tmp[J]+' found in library '+DLLs[I]);
end;
end;
Log('Plugins ready');
Tmp.Clear;
Strm := InputStream('Trans_Table');
Filter := (Strm<>nil);
If Filter then begin
Tmp.LoadFromStream(Strm);
Strm.Free;
For C := #0 to #255 do begin
S := Tmp.Values[C];
If S='' then FilterTbl[C] := C
else FilterTbl[C] := S[1];
UnfilterTbl[FilterTbl[C]] := C;
end;
end;
Tmp.Free;
end;
function FF7Ed_ExtractText(Src:TMemoryStream;var Table:TList;var Info:TTextInfoRec): TMemoryStream;
begin
Result := ExtractTextRTN(Src,Table,Info);
end;
function FF7Ed_DecodeText(Src:TStream): String;
var
S: String;
begin
Result := FF7DecodeTextS(Src);
end;
function FF7Ed_EncodeText(Src:String): TMemoryStream;
begin
Result := FF7EncodeTextS(Src);
end;
function FF7Ed_GetBackground(Src:TMemoryStream): TBitmap;
begin
Result := GetFF7Background(Src);
end;
procedure LGPRepair(FName:ShortString);
begin
LGPRepairArchive(FName);
end;
procedure LGPCreate(SrcFolder,OutputFile:ShortString;DeleteOriginal,UseErrorCheck:Boolean);
begin
LGPCreateArchive(SrcFolder,OutputFile,DeleteOriginal,UseErrorCheck);
end;
procedure LGPPack(FName:ShortString);
begin
LGPPackArchive(FName);
end;
Const
VersionOrder: Array[1..4] of Byte = (2,1,4,3);
function CompWords(I1,I2: TFourWords): Integer;
var
I: Integer;
begin
For I := 1 to 4 do
If I1[VersionOrder[I]] > I2[VersionOrder[I]] then begin
Result := -1; Exit;
end else If I1[VersionOrder[I]] < I2[VersionOrder[I]] then begin
Result := 1; Exit;
end;
Result := 0;
end;
function PrioritiseLibraries(Item1, Item2: Pointer): Integer;
var
Ver1, Ver2: Function: Comp;
Vers: Array[1..2] of ^TFourWords;
R1,R2: Comp;
begin
Ver1 := GetProcAddress(Integer(Item1),'FF7Ed_EditorVersion');
Ver2 := GetProcAddress(Integer(Item2),'FF7Ed_EditorVersion');
ZeroMemory(@R1,8); ZeroMemory(@R2,8);
If @Ver1<>nil then R1 := Ver1;
If @Ver2<>nil then R2 := Ver2;
Vers[1] := @R1;
Vers[2] := @R2;
If CompWords(Vers[1]^,TFourWords(MaxVersion))=-1 then MaxVersion := R1;
If CompWords(Vers[2]^,TFourWords(MaxVersion))=-1 then MaxVersion := R2;
Result := CompWords(Vers[1]^,Vers[2]^);
end;
function MaxVer: Comp;
begin
Result := MaxVersion;
end;
function MaxVerString: String;
var
W1,W2,W3,W4: ^Word;
begin
W1 := @MaxVersion;
W2 := @MaxVersion; Inc(W2);
W3 := @MaxVersion; Inc(W3,2);
W4 := @MaxVersion; Inc(W4,3);
Result := Format('%d.%d.%d build %d', [W2^, W1^, W4^, W3^]);
end;
procedure InitFuncs;
var
I: Integer;
begin
Log('CosmoUtil: Acquiring editing functions');
FF7_ExtractText := FiceProcAddress('FF7Ed_ExtractText');
FF7_DecodeText := FiceProcAddress('FF7Ed_DecodeText');
FF7_EncodeText := FiceProcAddress('FF7Ed_EncodeText');
FF7_GetBackground := FiceProcAddress('FF7Ed_GetBackground');
LGP_Repair := FiceProcAddress('LGPRepair');
LGP_Pack := FiceProcAddress('LGPPack');
LGP_Create := FiceProcAddress('LGPCreate');
Log('CosmoUtil: Prioritising editing function sources');
ZeroMemory(@MaxVersion,8);
FiceProcSort(PrioritiseLibraries);
Log('CosmoUtil: Installed libaries:');
For I := 0 to DLLs.Count-1 do
Log(' Library '+DLLs[I]);
Log('CosmoUtil: Init done');
end;
initialization
InitFuncs;
Plugins := TStringList.Create;
finalization
Plugins.Free;
end.
|
program WMConverter;
{$mode delphi}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, CustApp, IniFiles, math, strutils, FileUtil
{ you can add units after this };
{ TWMConverter }
const
ATTRMULTIPLIER_HITMULTIPLY = 100;
ATTRMULTIPLIER_SPEED = 10;
ATTRMULTIPLIER_MOVEMENTACC = 200;
ATTRMULTIPLIER_BULLETSPREAD = 100;
ATTRMULTIPLIER_PUSH = 2500;
ATTRMULTIPLIER_INHERITEDVELOCITY = 100;
type
TWMConverter = class(TCustomApplication)
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
end;
{ TWMConverter }
procedure ConvertValue(IniFile: TMemIniFile; SectionName, ValueName: String; Delimiter: Integer);
var
Value: Extended;
begin
Value := IniFile.ReadFloat(SectionName, ValueName, NaN);
if IsNan(Value) then begin
WriteLn('Invalid value for ', ValueName, ' in section', SectionName, ': ', IniFile.ReadString(SectionName, ValueName, ''));
Exit;
end;
Value := RoundTo(Value / Delimiter, -4);
//WriteLn('[', SectionName, ']: ', ValueName, ' = ', FormatFloat('', Value));
IniFile.WriteFloat(SectionName, ValueName, Value);
end;
procedure AddHitboxValues(IniFile: TMemIniFile; SectionName: String; IsRealistic: Boolean);
begin
if IsRealistic then begin
IniFile.WriteFloat(SectionName, 'ModifierHead', 1.1);
IniFile.WriteFloat(SectionName, 'ModifierChest', 1);
IniFile.WriteFloat(SectionName, 'ModifierLegs', 0.6);
end else begin
IniFile.WriteFloat(SectionName, 'ModifierHead', 1.15);
IniFile.WriteFloat(SectionName, 'ModifierChest', 1);
IniFile.WriteFloat(SectionName, 'ModifierLegs', 0.9);
end;
end;
procedure TWMConverter.DoRun;
var
ErrorMsg: String;
IniPath, BackupPath: String;
SectionName: String;
IniFile: TMemIniFile;
SectionList: TStringList;
IsRealistic: Boolean;
i: Integer;
begin
// quick check parameters
ErrorMsg := CheckOptions('h r n w', 'help realistic normal nobackup');
if ErrorMsg <> '' then begin
ShowException(Exception.Create(ErrorMsg));
Terminate;
Exit;
end;
IniPath := Params[ParamCount];
if HasOption('n', 'normal') then begin
IsRealistic := False;
WriteLn('Forcing normal mode');
end else if HasOption('r', 'realistic') then begin
IsRealistic := False;
WriteLn('Forcing realistic mode');
end else begin
IsRealistic := AnsiContainsText(LowerCase(IniPath), 'realistic');
WriteLn('Realistic mode: ', IsRealistic);
end;
// parse parameters
if HasOption('h', 'help') or (IniPath = '') or (ParamCount < 1) then begin
WriteHelp;
Terminate;
Exit;
end;
if not FileExists(IniPath) then begin
WriteLn('File not found');
WriteHelp;
Terminate;
Exit;
end;
if not HasOption('w', 'nobackup') then begin
BackupPath := ChangeFileExt(IniPath, '.ini.bak');
CopyFile(IniPath, BackupPath);
WriteLn('Backup saved as ', BackupPath);
end;
SectionList := TStringList.Create;
IniFile := TMemIniFile.Create(IniPath);
IniFile.CacheUpdates := True;
DefaultFormatSettings.DecimalSeparator := '.';
try
IniFile.ReadSections(SectionList);
for i := 0 to SectionList.Count - 1 do begin
SectionName := SectionList[i];
if LowerCase(SectionName) = 'info' then
continue;
ConvertValue(IniFile, SectionName, 'Damage', ATTRMULTIPLIER_HITMULTIPLY);
ConvertValue(IniFile, SectionName, 'Speed', ATTRMULTIPLIER_SPEED);
ConvertValue(IniFile, SectionName, 'MovementAcc', ATTRMULTIPLIER_MOVEMENTACC);
ConvertValue(IniFile, SectionName, 'BulletSpread', ATTRMULTIPLIER_BULLETSPREAD);
ConvertValue(IniFile, SectionName, 'Push', ATTRMULTIPLIER_PUSH);
ConvertValue(IniFile, SectionName, 'InheritedVelocity', ATTRMULTIPLIER_INHERITEDVELOCITY);
AddHitboxValues(IniFile, SectionName, IsRealistic);
end;
IniFile.UpdateFile;
finally
IniFile.Free;
SectionList.Free;
end;
WriteLn('File converted successfuly!');
// stop program loop
Terminate;
end;
constructor TWMConverter.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException := True;
end;
destructor TWMConverter.Destroy;
begin
inherited Destroy;
end;
procedure TWMConverter.WriteHelp;
var
ShortExeName: String;
begin
ShortExeName := ExtractFileName(ExeName);
writeln('Usage: ', ShortExeName, '[options] path/to/weapons.ini');
writeln('Options: ');
writeln(' -r or --realistic - force realistic mode');
writeln(' -n or --normal - force normal mode');
writeln(' -w or --nobackup - don''t do backup');
writeln('Example usage: ', ShortExeName, ' -n -w weapons.ini');
end;
var
Application: TWMConverter;
begin
Application := TWMConverter.Create(nil);
Application.Title := 'WM Converter';
Application.Run;
Application.Free;
end.
|
unit umathPars;
interface
type
TMath = record
private
Left : Double;
Right : Double;
Oper : Char;
public
function Calc : string;
end;
TOperator = Set of char;
TMathParser = record
const
inNumber : set of Char = ['0'..'9', ','];
private
FPrepare : string;
FText : string;
procedure DeleteSpace;
procedure SetText(const Value: string);
function MoveLeft(AText : string; Apos: Word): Integer;
function MoveRight(AText: string; APos: Word): Integer;
procedure ParssPart(var APart: string; AOperator: TOperator);
function Parss(APart: string): string;
function Convert(AText: string): Double;
public
Function ParssString: string;
property Text : string read FText write SetText;
property Prepare: string read FPrepare write FPrepare;
end;
var
MathParser : TMathParser;
implementation
uses
SysUtils, Math;
{ TMathParser }
procedure TMathParser.ParssPart(var APart: string; AOperator: TOperator);
var
I, l, r: Integer;
M : TMath;
tmp : Double;
b : Boolean;
begin
i := 0;
b := False;
while i < Length(APart) Do
begin
If APart[i] in AOperator Then
begin
l := MoveLeft(APart, I) + 1;
r := MoveRight(APart, I) - 1;
M.Oper := APart[i];
M.Left := Convert(Copy(APart,l,I-l));
M.Right := Convert(Copy(APart,I+1,r-i));
//Change pozition
b := (L = 2) and (M.Oper = '+') and (APart[1] = '-');
If b Then
begin
tmp := M.Left;
M.Oper := '-';
M.Left := M.Right;
M.Right := tmp;
end;
// For -1 -1 = -1 + -1
If (L = 2) and (M.Oper = '-' ) and (APart[1] = '-') and (b = false) Then
M.Oper := '+';
Delete(APart, l, r-l+1);
Insert(M.Calc, APart, L);
// if M.Calc > 0 Then видаляємо попередній знак якщо це +
i := L;
end;
Inc(i);
end;
end;
function TMathParser.Convert(AText: string): Double;
begin
TryStrToFloat(AText, Result);
end;
procedure TMathParser.DeleteSpace;
begin
FText := StringReplace(FText, ' ', '', [rfReplaceAll]);
end;
procedure TMathParser.SetText(const Value: string);
begin
FText := Value;
DeleteSpace;
end;
function TMathParser.MoveLeft(AText: string; Apos: Word): Integer;
begin
Result := Apos - 1;
While (Result > 0) and (AText[Result] in inNumber) Do
Dec(Result);
end;
function TMathParser.MoveRight(AText: string; APos: Word): Integer;
begin
Result := APos + 1;
While (AText[Result] in inNumber) Do
Inc(Result);
end;
Function TMathParser.Parss(APart : string): string;
begin
Result := APart;
ParssPart(Result, ['^']);
ParssPart(Result, ['*','/']);
ParssPart(Result, ['-','+']);
end;
Function TMathParser.ParssString: string;
var
l, r, i: Integer;
Part : string;
begin
i := Length(FText);
// find term (...)
while i > 0 Do
begin
If FText[i] = '(' Then
begin
l := i;
For r := l+1 To Length(FText) Do
If FText[r] = ')' Then
Break;
// parss one term
Part := Parss(Copy(FText,l+1,r-l-1));
Delete(FText,l,r-l+1);
Insert(Part,FText, l);
end;
Dec(I);
end;
// parss text
Result := Parss(FText);
end;
{ TMath }
function TMath.Calc: String;
var
tmp : Double;
begin
Case Oper Of
'^': tmp := Round(Power(Left, Right));
'+': tmp := Left + Right;
'-': tmp := Left - Right;
'/':
begin
If Right = 0 Then
tmp := 0
else
tmp := Left / Right;
end;
'*': tmp := Left * Right;
End;
Result := FloatToStr(tmp);
end;
end.
|
unit Rx.Fibers;
interface
uses Windows, SysUtils;
type
TCustomFiber = class
const
STACK_SIZE = 1024;
type
AKill = class(EAbort);
strict private
FIsTerminated: Boolean;
FIsRunned: Boolean;
FContext: Pointer;
FKill: Boolean;
function GetRootContext: Pointer;
class procedure FarCall(Param: Pointer); stdcall; static;
protected
procedure Execute; dynamic; abstract;
public
constructor Create;
destructor Destroy; override;
property IsTerminated: Boolean read FIsTerminated;
procedure Invoke;
procedure Yield;
procedure Kill;
end;
TFiberRoutine = reference to procedure(Fiber: TCustomFiber);
TFiber = class(TCustomFiber)
strict private
FRoutine: TFiberRoutine;
protected
procedure Execute; override;
public
constructor Create(const Routine: TFiberRoutine);
end;
// used only for debugging!!!
procedure Yield;
implementation
threadvar
CurThreadAsFiber: Pointer;
{ TCustomFiber }
constructor TCustomFiber.Create;
begin
FContext := CreateFiber(STACK_SIZE, @FarCall, Self);
end;
destructor TCustomFiber.Destroy;
begin
if not FIsTerminated and FIsRunned then
Kill;
if Assigned(FContext) then
DeleteFiber(FContext);
inherited;
end;
class procedure TCustomFiber.FarCall(Param: Pointer);
var
Me: TCustomFiber;
begin
Me := TCustomFiber(Param);
try
Me.FIsRunned := True;
Me.Execute;
finally
Me.FIsTerminated := True;
SwitchToFiber(CurThreadAsFiber);
end;
end;
function TCustomFiber.GetRootContext: Pointer;
begin
if CurThreadAsFiber = nil then
CurThreadAsFiber := Pointer(ConvertThreadToFiber(nil));
Result := CurThreadAsFiber;
end;
procedure TCustomFiber.Invoke;
begin
GetRootContext;
SwitchToFiber(FContext);
if not FIsTerminated and FKill then
raise AKill.Create('Killing');
end;
procedure TCustomFiber.Kill;
begin
if not FIsTerminated then begin
FKill := True;
Invoke;
end;
end;
procedure TCustomFiber.Yield;
begin
SwitchToFiber(GetRootContext);
end;
{ TFiber }
constructor TFiber.Create(const Routine: TFiberRoutine);
begin
inherited Create;
FRoutine := Routine;
end;
procedure TFiber.Execute;
begin
FRoutine(Self)
end;
procedure Yield;
begin
SwitchToFiber(CurThreadAsFiber);
end;
end.
|
unit audio;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, SDL2, SDL2_Mixer, BaseTypes, Utility;
type
{ tAudioEngine }
rNote = record
Pitch, Velocity: word;
Duration, Position: single;
end;
rPattern = array of rNote;
{tPattern = class
A: array of ; default;
end;}
eEffect = (eNone, eUnderwater);
rTone = record
FS: tMemoryStream; //has memory pointer and loadfromfile, but sdl mixer also has load from file
end;
rTrack = record
Effect: eEffect;
Volume: single;
Patterns: array of rPattern;
Tones: array of rTone;
Sequence: array of integer;
end;
eToneKind = (tPercussion, tNormal);
{ tComposition }
tComposition = class
Seed: tSeed;
PercussionTracks: integer;
Tracks: array of rTrack;
procedure SynthesizeTones(TrackNr: integer; TK: eToneKind); //percussion in 0..n?
procedure ComposePatterns(TrackNr: integer; TK: eToneKind);
constructor Create(aSeed: tSeed);
destructor Destroy; override;
end;
{ tComposer }
tComposer = class
CurrentComp, NextComp: tComposition;
{function CompileWAV: pointer; //compiles next }
public
function GetNext: pointer; //returns pointer to wav, switches next to cur
constructor Create;
destructor Destroy; override;
end;
tAudioEngine = class //needs to be able to mix several simult as well as play in background
{queue
Files: array
function LoadFile(Filename: string): integer;
procedure PlayFile(Index: integer);
procedure StopPlayback;
procedure AddToQueue(index: integer); }
Composer: tComposer;
constructor Create;
destructor Destroy; override;
end;
var
AudioEngine: tAudioEngine;
implementation
{ tComposer }
function tComposer.GetNext: pointer;
begin
CurrentComp.Free;
CurrentComp:= NextComp;
NextComp:= tComposition.Create(random(high(tSeed)));
end;
constructor tComposer.Create;
begin
GetNext;
end;
destructor tComposer.Destroy;
begin
inherited Destroy;
CurrentComp.Free;
NextComp.Free;
end;
{ tComposition }
procedure tComposition.SynthesizeTones(TrackNr: integer; TK: eToneKind);
begin
with Tracks[TrackNr] do
begin
end;
end;
procedure tComposition.ComposePatterns(TrackNr: integer; TK: eToneKind);
begin
with Tracks[TrackNr] do
begin
end;
end;
constructor tComposition.Create(aSeed: tSeed);
var
i: integer;
TK: eToneKind;
begin
Seed:= aSeed;
setlength(Tracks, 2 + srand(4, Seed));
PercussionTracks:= length(Tracks) div 3;
TK:= tPercussion;
for i:= 0 to high(Tracks) do
begin
if i >= PercussionTracks then
TK:= tNormal;
SynthesizeTones(i, TK);
ComposePatterns(i, TK);
end;
end;
destructor tComposition.Destroy;
begin
inherited Destroy;
setlength(Tracks, 0);
end;
{ tAudioEngine }
constructor tAudioEngine.Create;
begin
Composer:= tComposer.Create;
end;
destructor tAudioEngine.Destroy;
begin
inherited Destroy;
end;
end.
|
unit TestBlankLineRemoval;
{ AFS 7 August 2001
This unit compiles but is not semantically meaningfull
it is test cases for the code formatting utility
This unit tests blank line removal }
interface
implementation
uses SysUtils;
procedure TestBlankLines1;
var
a: integer;
b: string;
c, d ,e,f: double;
begin
end;
procedure TestBlankLines2;
var
a: integer;
function GetA: integer;
begin
Result := a + 1;
end;
var
b: string;
c, d ,e,f: double;
begin
end;
procedure TestBlankLines3;
var
a: integer;
function GetA: integer;
begin
Result := a + 1;
end;
var
b: string;
function GetB: string;
begin
Result := b + IntToStr(a);
end;
var
c, d ,e,f: double;
begin
end;
procedure TestBlankLines4;
var
a: integer;
function GetA: integer;
var
x,y, z: currency;
q: string;
begin
Result := a + 1;
end;
var
b: string;
c, d ,e,f: double;
begin
end;
end.
|
unit AvailabilityDisplayForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.DateUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, pdatesw;
type
TdayPings = array[0..23,0..59] of integer;
TyearPings = array[1..12,1..31] of TdayPings;
TForm1 = class(TForm)
Panel2: TPanel;
OpenDialog1: TOpenDialog;
Button1: TButton;
Timer1: TTimer;
Button2: TButton;
Button3: TButton;
PaintBoxToday: TPaintBox;
Panel3: TPanel;
PaintBoxMonth1: TPaintBox;
PaintBoxMonth2: TPaintBox;
PaintBoxMonth3: TPaintBox;
PaintBoxCurrentMonth: TPaintBox;
PaintBoxMonth4: TPaintBox;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
StatusBar1: TStatusBar;
procedure PaintBoxTodayPaint(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure PaintBoxTodayMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure PaintBoxMonthPaint(Sender: TObject);
procedure PaintBoxCurrentMonthPaint(Sender: TObject);
procedure PaintBoxMonthMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PaintBoxCurrentMonthMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure PaintBoxCurrentMonthMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure PaintBoxMonthMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
private
yearPings: TYearPings;
displayDay: TDateTime;
procedure LoadFile(fn: string);
procedure loadText(text: string);
procedure loadStrings(s: TStrings);
procedure doPing;
procedure say(s:string);
function randomValue: integer;
function valueToColor(v: integer): TColor;
function failCountToColor(c: integer): TColor;
function getDayValue(d: TDateTime): integer;
function getHourValue(d: TDateTime): integer;
function getHourFailCount(d: TDateTime): integer;
function getDayFailCount(d: TDateTime): integer;
function getMinuteValue(d: TDateTime): integer;
procedure setMinuteValue(d: TDateTime; v:integer);
function monthXYtoDateTime(senderPaintbox: TPaintbox; x, y: integer): TDateTime;
function failPercentageToColor(c: integer): TColor;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
(***************************************************************)
const dotsize=10; margin=10;
const PINGFAILED = 0;
const PINGNODATA = -1;
(***************************************************************)
function TForm1.randomValue:integer;
begin
if random(10)<1 then
result:= PINGFAILED
else
result:=100+random(100);
end;
function TForm1.valueToColor(v:integer):TColor;
begin
if v=PINGNODATA then result:=clWhite
else if v=PINGFAILED then result:=clRed
else result:=RGB(v,200+(2*(100-v)),200);
end;
function TForm1.failPercentageToColor(c:integer): TColor;
begin
if c<0 then result:=clWhite
else if c<=10 then result:=RGB(100+c*15,100-c*10,200-c*2)
else if c<20 then result:=RGB(255,0,200-c*2)
else result:=clRed;
end;
function TForm1.failCountToColor(c: integer): TColor;
begin
if c=PINGNODATA then result:=clWhite
else if c<=10 then result:=RGB(100+c*15,100-c*10,200-c*2)
else if c<100 then result:=RGB(255,0,100-c)
else result:=clRed;
end;
(***************************************************************)
const thresholdForFailuresPerDay = 5;
const thresholdForFailuresPerHour=10;
function TForm1.getDayValue(d:TDateTime):integer;
var
i,c,r,v,cf:integer; t:TDateTime;
begin
r:=PINGNODATA;
t:=d;
cf:=0; // counter of ping fails
c:=0;
result:=PINGNODATA;
for i:=0 to 23 do
begin
t:=encodedatetime(yearof(d),monthof(d),dayof(d),i,0,0,0);
v:=getHourValue(t);
if v=PINGFAILED then
begin
inc(cf);
if cf>=thresholdForFailuresPerDay then exit;
end
else if v<>PINGNODATA then
begin
inc(c);
if r=PINGNODATA then r:=v else r:=r+v;
end;
end;
result:=r div c;
end;
function TForm1.getHourValue(d:TDateTime):integer;
var i,c,cf,r,v: Integer; t:TDateTime;
begin
r:=PINGNODATA;
t:=d;
cf:=0; // counter for failures
c:=0;
result:=PINGFAILED;
for i := 0 to 59 do
begin
t:=encodedatetime(yearof(d),monthof(d),dayof(d),hourof(d),i,0,0);
v:=getMinuteValue(t);
if v=PINGFAILED then
begin
inc(cf);
if cf>=thresholdForFailuresPerHour then exit;
end
else if v<>PINGNODATA then
begin
inc(c);
if r=PINGNODATA then r:=v else r:=r+v;
end;
end;
if c<>0 then result:=r div c else result:=PINGNODATA;
end;
function TForm1.getHourFailCount(d:TDateTime):integer;
var i,v:integer; t:TDateTime;
begin
t:=d;
result:=0;
for i := 0 to 59 do
begin
t:=encodedatetime(yearof(d),monthof(d),dayof(d),hourof(d),i,0,0);
v:=getMinuteValue(t);
if v=PINGFAILED then inc(result);
end;
end;
function TForm1.getDayFailCount(d:TDateTime):integer;
var i:integer; t:TDateTime;
begin
t:=d;
result:=0;
for i:=0 to 23 do
begin
t:=encodedatetime(yearof(d),monthof(d),dayof(d),i,0,0,0);
inc(result,getHourFailCount(t));
end;
if result<0 then result:=PINGNODATA;
end;
function TForm1.getMinuteValue(d:TDateTime):integer;
begin
result:=yearpings[monthof(d),dayof(d)][hourof(d),minuteof(d)];
end;
procedure TForm1.setMinuteValue(d: TDateTime; v:integer);
begin
yearpings[monthof(d),dayof(d)][hourof(d),minuteof(d)]:=v;
end;
(***************************************************************)
procedure TForm1.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
loadFile(openDialog1.FileName);
caption:=OpenDialog1.FileName;
end;
end;
procedure tForm1.say(s:string);
var m:string;
begin
DateTimeToString(m, 'hh:nn:ss.zzz', now);
m:=m+' '+s;
StatusBar1.SimpleText:=m;
//Listbox1.items.add(m);
//Listbox1.Itemindex:=Listbox1.Items.Count-1;
end;
procedure TForm1.PaintBoxTodayMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var i,h,m,v:integer;
begin
StatusBar1.SimpleText:='';
if (x<margin) or (y<margin) or (x>61*(dotsize+1)) or (y>25*(dotsize+1)) then
exit;
m:=(x-margin) div (dotsize+1);
h:=(y-margin) div (dotsize+1);
i:=h*60+m;
v:=getminutevalue(displayDay+encodetime(h,m,0,0));
StatusBar1.SimpleText:=format('%.2d:%.2d %d ',[h,m,v]);
end;
procedure TForm1.PaintBoxTodayPaint(Sender: TObject);
var
h,m,v:integer;
c:TColor;
begin
label3.caption:=inttostr(dayOf(displayDay))+' '+FormatSettings.LongMonthNames[MonthOf(displayDay)]+' '+inttostr(YearOf(displayDay));
// margins and numbers
PaintBoxToday.Canvas.brush.style:=bsClear;
PaintBoxToday.Canvas.Font.Size:=6;
for m := 0 to 60 do
if (m=0) or (m=15) or (m=30) or (m=45) or (m=60) then
PaintBoxToday.canvas.Textout(margin+m*(dotsize+1),1,inttostr(m));
// paintbox1.canvas.Textout(margin+m*(dotsize+1),1,inttostr(m));
for h := 0 to 24 do
if (h=0) or (h=6) or (h=12) or (h=18) or (h=24) then
PaintBoxToday.canvas.Textout(1,margin+h*(dotsize+1),inttostr(h));
//paintbox1.canvas.Textout(1,margin+h*(dotsize+1),inttostr(h));
PaintBoxToday.Canvas.brush.style:=bsSolid;
PaintBoxToday.Canvas.Pen.Style:=psClear;
for h := 0 to 23 do
begin
for m := 0 to 59 do
begin
v:=getminutevalue(displayDay+encodetime(h,m,0,0));
c:=ValueToColor(v);
PaintBoxToday.Canvas.brush.Color:=c;
PaintBoxToday.Canvas.Rectangle(margin+m*(dotsize+1),margin+h*(dotsize+1), margin-1+(m+1)*(dotsize+1),margin-1+(h+1)*(dotsize+1));
end;
end;
end;
procedure TForm1.PaintBoxCurrentMonthMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var d:integer;
begin
if (y>(daysInMonth(displayDay)+1)*(dotsize+1)) then exit;
d:=y div (dotsize+1);
displayDay:=EncodeDate(yearOf(displayDay),monthOf(displayDay),d);
paintboxToday.repaint;
end;
procedure TForm1.PaintBoxCurrentMonthMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var d,h,c:integer;
begin
StatusBar1.SimpleText:='';
if (x<margin) or (y<margin) or (y>margin+(daysInMonth(displayDay))*(dotsize+1)) or (x>margin+24*(dotsize+1)) then exit;
d:=1+(y-margin) div (dotsize+1);
if d>daysInMonth(displayDay) then d:=daysInMonth(displayDay);
h:=(x-margin) div (dotsize+1);
if h>23 then h:=23;
c:=getHourFailCount(EncodeDateTime(yearOf(displayDay),monthOf(displayDay),d,h,0,0,0));
StatusBar1.SimpleText:=format('%.2d@%.2d:00 %d %d%%',[d,h,c,trunc(100.0*c/60.0)]);
end;
procedure TForm1.PaintBoxCurrentMonthPaint(Sender: TObject);
var
d,h: integer;
fdm,cdc:TDateTime;
begin
fdm:=trunc(beginOf(iMonth,displayDay));
label2.caption:=FormatSettings.LongMonthNames[MonthOf(fdm)]+' '+inttostr(YearOf(fdm));
paintboxCurrentMonth.Canvas.Pen.Style:=psSolid;
paintboxCurrentMonth.Canvas.Pen.Color:=clBlack;
paintboxCurrentMonth.Canvas.Font.Size:=6;
for d := 1 to dayOf(endOf(iMonth,fdm)) do
paintboxCurrentMonth.canvas.Textout(1,d*(dotsize+1),inttostr(d));
for h := 0 to 24 do
if (h=6) or (h=12) or (h=18) or (h=24) then
paintboxCurrentMonth.canvas.Textout(margin+h*(dotsize+1),1,inttostr(h));
paintboxCurrentMonth.Canvas.pen.Style:=psClear;
for d := 1 to dayOf(endOf(iMonth,fdm)) do
begin
for h := 0 to 23 do
begin
cdc:=(fdm+d-1)+encodeTime(h,0,0,0);
if cdc>now then
paintboxCurrentMonth.Canvas.brush.color:=clWhite
else
//paintboxCurrentMonth.Canvas.brush.color:=valueToColor(gethourvalue(cdc));
paintboxCurrentMonth.Canvas.brush.color:=failPercentageToColor(trunc(100.0*getHourFailCount(cdc)/60.0));
paintboxCurrentMonth.Canvas.Rectangle(margin+h*(dotsize+1),d*(dotsize+1), margin-1+(h+1)*(dotsize+1),(d+1)*(dotsize+1)-1);
end;
end;
end;
function TForm1.monthXYtoDateTime(senderPaintbox:TPaintbox;x,y:integer):TDateTime;
var
fdm,fdc:TDateTime;
d,w:integer;
begin
result:=0.0;
if (x>7*(dotsize+1)) or (y>6*(dotsize+1)) then exit;
if senderPaintbox=paintboxMonth1 then
fdm:=BeginOfPrevious(iMonth,BeginOfPrevious(iMonth,BeginOfPrevious(iMonth,today)))
else if senderPaintbox=paintboxMonth2 then
fdm:=BeginOfPrevious(iMonth,BeginOfPrevious(iMonth,today))
else if senderPaintbox=paintboxMonth3 then
fdm:=BeginOfPrevious(iMonth,today)
else
fdm:=BeginOf(iMonth,today);
fdc:=beginOf(iweek,fdm);
d:=x div (dotsize+1);
w:=y div (dotsize+1);
result:=fdc+w*7+d;
end;
procedure TForm1.PaintBoxMonthMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
c:integer;
d:TDateTime;
senderPaintbox:TPaintBox;
begin
StatusBar1.SimpleText:='';
d:=monthXYtoDateTime(Sender as TPaintbox,x,y);
if trunc(d)<>0 then
begin
c:=getDayFailCount(d);
StatusBar1.SimpleText:=format('%.2d/%.2d %d %d%%',[dayof(d),monthof(d),c,trunc(100.0*c/60.0/24.0)]);
end;
end;
procedure TForm1.PaintBoxMonthMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
displayDay:=trunc(monthXYtoDateTime(Sender as TPaintbox,x,y));
paintboxToday.repaint;
paintboxCurrentMonth.repaint;
end;
procedure TForm1.PaintBoxMonthPaint(Sender: TObject);
var
w,d: integer;
fdm,fdc,cdc:TDateTime;
senderPaintbox:TPaintBox;
labelForThis:TLabel;
begin
senderpaintbox:=Sender as TPaintbox;
// first day of this month is...
if senderpaintbox=paintboxmonth1 then
fdm:=BeginOfPrevious(iMonth,BeginOfPrevious(iMonth,BeginOfPrevious(iMonth,today)))
else if senderpaintbox=paintboxmonth2 then
fdm:=BeginOfPrevious(iMonth,BeginOfPrevious(iMonth,today))
else if senderpaintbox=paintboxmonth3 then
fdm:=BeginOfPrevious(iMonth,today)
else
fdm:=BeginOf(iMonth,today);
if senderpaintbox=paintboxmonth1 then
labelForThis:=Label4
else if senderpaintbox=paintboxmonth2 then
labelForThis:=Label5
else if senderpaintbox=paintboxmonth3 then
labelForThis:=Label6
else
labelForThis:=Label7;
// first day of this calendar is ...
fdc:=beginof(iweek,fdm);
// senderPaintbox.Canvas.Pen.Style:=psSolid;
// senderPaintbox.Canvas.Pen.Color:=clBlack;
labelForThis.caption:=FormatSettings.LongMonthNames[MonthOf(fdm)]+' '+inttostr(YearOf(fdm));
senderPaintbox.Canvas.brush.style:=bsSolid;
senderPaintbox.Canvas.Pen.Style:=psClear;
for w := 1 to 6 do
begin
for d := 1 to 7 do
begin
// current day of calendar is ...
cdc:=fdc+(w-1)*7+d-1;
if (monthOf(cdc)=monthOf(fdm)) and (cdc<now) then
senderPaintbox.Canvas.brush.color:=failPercentageToColor(trunc(100.0*getDayFailCount(cdc)/60.0/24.0))
else if (monthOf(cdc)<>monthOf(fdm)) then
senderPaintbox.Canvas.brush.color:=clWhite
else
senderPaintbox.Canvas.brush.color:=clSilver;
senderPaintbox.Canvas.Rectangle((d-1)*(dotsize+1),(w-1)*(dotsize+1),d*(dotsize+1)-1,w*(dotsize+1)-1);
end;
end;
end;
(***************************************************************)
procedure TForm1.Timer1Timer(Sender: TObject);
begin
doPing;
end;
(***************************************************************)
procedure TForm1.Button2Click(Sender: TObject);
begin
Timer1.Enabled:=true;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
Timer1.Enabled:=false;
end;
(***************************************************************)
procedure TForm1.doPing;
var v:integer;
begin
v:=randomValue;
setminutevalue(now,v);
paintboxtoday.repaint;
end;
(***************************************************************)
procedure TForm1.FormCreate(Sender: TObject);
var
cd,nd:TDateTime;
mo,da,ho,mi:integer;
begin
//Pings := TStringList.Create;
for mo := 1 to 12 do
for da := 1 to 31 do
for ho := 0 to 23 do
for mi := 0 to 59 do
yearPings[mo,da][ho,mi]:=PINGNODATA;
cd:=encodedatetime(yearof(today),1,1,0,0,0,0);
nd:=now;
repeat
cd:=incminute(cd);
setminutevalue(cd,randomValue);
until cd>nd;
displayDay:=today;
end;
(***************************************************************)
procedure TForm1.LoadFile(fn:string);
var s:TStrings;
begin
s:=TStringList.Create;
s.LoadFromFile(fn);
loadStrings(s);
s.Free;
end;
procedure TForm1.loadStrings(s:TStrings);
var
i: Integer;
cd:TDateTime;
begin
cd:=encodedatetime(yearof(today),1,1,0,0,0,0);
for i := 0 to s.Count-1 do
begin
setminutevalue(cd,strtoint(s[i]));
cd:=incminute(cd);
end;
end;
procedure TForm1.loadText(text: string);
var s:TStrings;
begin
s:=TStringList.Create;
s.setText(pWideChar(text));
loadStrings(s);
s.Free;
end;
end.
|
{$nested-comments}
{ Regular expression matching and replacement
The RegEx unit provides routines to match strings against regular
expressions and perform substitutions using matched
subexpressions.
To use the RegEx unit, you will need the rx library which can be
found in http://www.gnu-pascal.de/libs/
Regular expressions are strings with some characters having
special meanings. They describe (match) a class of strings. They
are similar to wild cards used in file name matching, but much
more powerful.
There are two kinds of regular expressions supported by this unit,
basic and extended regular expressions. The difference between
them is not functionality, but only syntax. The following is a
short overview of regular expressions. For a more thorough
explanation see the literature, or the documentation of the rx
library, or man pages of programs like grep(1) and sed(1).
Basic Extended Meaning
`.' `.' matches any single character
`[aei-z]' `[aei-z]' matches either `a', `e', or any
character from `i' to `z'
`[^aei-z]' `[^aei-z]' matches any character but `a',
`e', or `i' .. `z'
To include in such a list the the
characters `]', `^', or `-', put
them first, anywhere but first, or
first or last, resp.
`[[:alnum:]]' `[[:alnum:]]' matches any alphanumeric character
`[^[:digit:]]' `[^[:digit:]]' matches anything but a digit
`[a[:space:]]' `[a[:space:]]' matches the letter `a' or a space
character (space, tab)
... (there are more classes available)
`\w' `\w' = [[:alnum:]]
`\W' `\W' = [^[:alnum:]]
`^' `^' matches the empty string at the
beginning of a line
`$' `$' matches the empty string at the
end of a line
`*' `*' matches zero or more occurences of
the preceding expression
`\+' `+' matches one or more occurences of
the preceding expression
`\?' `?' matches zero or one occurence of
the preceding expression
`\{N\}' `{N}' matches exactly N occurences of
the preceding expression (N is an
integer number)
`\{M,N\}' `{M,N}' matches M to N occurences of the
preceding expression (M and N are
integer numbers, M <= N)
`AB' `AB' matches A followed by B (A and B
are regular expressions)
`A\|B' `A|B' matches A or B (A and B are
regular expressions)
`\( \)' `( )' forms a subexpression, to override
precedence, and for subexpression
references
`\7' `\7' matches the 7'th parenthesized
subexpression (counted by their
start in the regex), where 7 is a
number from 1 to 9 ;-).
*Please note:* using this feature
can be *very* slow or take very
much memory (exponential time and
space in the worst case, if you
know what that means ...).
`\' `\' quotes the following character if
it's special (i.e. listed above)
rest rest any other character matches itself
Precedence, from highest to lowest:
* parentheses (`()')
* repetition (`*', `+', `?', `{}')
* concatenation
* alternation (`|')
When performing substitutions using matched subexpressions of a
regular expression (see `ReplaceSubExpressionReferences'), the
replacement string can reference the whole matched expression with
`&' or `\0', the 7th subexpression with `\7' (just like in the
regex itself, but using it in replacements is not slow), and the
7th subexpression converted to upper/lower case with `\u7' or
`\l7', resp. (which also works for the whole matched expression
with `\u0' or `\l0'). A verbatim `&' or `\' can be specified with
`\&' or `\\', resp.
Copyright (C) 1998-2005 Free Software Foundation, Inc.
Author: Frank Heckenbach <frank@pascal.gnu.de>
This file is part of GNU Pascal.
GNU Pascal is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2, or (at your
option) any later version.
GNU Pascal is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with GNU Pascal; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
As a special exception, if you link this file with files compiled
with a GNU compiler to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public
License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU
General Public License.
Please also note the license of the rx library. }
{$gnu-pascal,I-}
{$if __GPC_RELEASE__ < 20030303}
{$error This unit requires GPC release 20030303 or newer.}
{$endif}
unit RegEx;
interface
uses GPC;
const
{ `BasicRegExSpecialChars' contains all characters that have
special meanings in basic regular expressions.
`ExtRegExSpecialChars' contains those that have special meanings
in extended regular expressions. }
BasicRegExSpecialChars = ['.', '[', ']', '^', '$', '*', '\'];
ExtRegExSpecialChars = ['.', '[', ']', '^', '$', '*', '+', '?', '{', '}', '|', '(', ')', '\'];
type
{ The type used by the routines of the `RegEx' unit to store
regular expressions in an internal format. The fields RegEx,
RegMatch, ErrorInternal, From and Length are only used
internally. SubExpressions can be read after `NewRegEx' and will
contain the number of parenthesized subexpressions. Error should
be checked after `NewRegEx'. It will be `nil' when it succeeded,
and contain an error message otherwise. }
RegExType = record
RegEx, RegMatch: Pointer; { Internal }
ErrorInternal: CString; { Internal }
From, Length: CInteger; { Internal }
SubExpressions: CInteger;
Error: PString
end;
{ Simple interface to regular expression matching. Matches a regular
expression against a string starting from a specified position.
Returns the position of the first match, or 0 if it does not
match, or the regular expression is invalid. }
function RegExPosFrom (const Expression: String; ExtendedRegEx, CaseInsensitive: Boolean; const s: String; From: Integer) = MatchPosition: Integer;
{ Creates the internal format of a regular expression. If
ExtendedRegEx is True, Expression is assumed to denote an extended
regular expression, otherwise a basic regular expression.
CaseInsensitive determines if the case of letters will be ignored
when matching the expression. If NewLines is True, `NewLine'
characters in a string matched against the expression will be
treated as dividing the string in multiple lines, so that `$' can
match before the NewLine and `^' can match after. Also, `.' and
`[^...]' will not match a NewLine then. }
procedure NewRegEx (var RegEx: RegExType; const Expression: String; ExtendedRegEx, CaseInsensitive, NewLines: Boolean);
{ Disposes of a regular expression created with `NewRegEx'. *Must*
be used after `NewRegEx' before the RegEx variable becomes invalid
(i.e., goes out of scope or a pointer pointing to it is Dispose'd
of). }
procedure DisposeRegEx (var RegEx: RegExType); external name '_p_DisposeRegEx';
{ Matches a regular expression created with `NewRegEx' against a
string. }
function MatchRegEx (var RegEx: RegExType; const s: String; NotBeginningOfLine, NotEndOfLine: Boolean): Boolean;
{ Matches a regular expression created with `NewRegEx' against a
string, starting from a specified position. }
function MatchRegExFrom (var RegEx: RegExType; const s: String; NotBeginningOfLine, NotEndOfLine: Boolean; From: Integer): Boolean;
{ Finds out where the regular expression matched, if `MatchRegEx' or
`MatchRegExFrom' were successful. If n = 0, it returns the
position of the whole match, otherwise the position of the n'th
parenthesized subexpression. MatchPosition and MatchLength will
contain the position (counted from 1) and length of the match, or
0 if it didn't match. (Note: MatchLength can also be 0 for a
successful empty match, so check whether MatchPosition is 0 to
find out if it matched at all.) MatchPosition or MatchLength may
be Null and is ignored then. }
procedure GetMatchRegEx (var RegEx: RegExType; n: Integer; var MatchPosition, MatchLength: Integer);
{ Checks if the string s contains any quoted characters or
(sub)expression references to the regular expression RegEx created
with `NewRegEx'. These are `&' or `\0' for the whole matched
expression (if OnlySub is not set) and `\1' .. `\9' for the n'th
parenthesized subexpression. Returns 0 if it does not contain any,
and the number of references and quoted characters if it does. If
an invalid reference (i.e. a number bigger than the number of
subexpressions in RegEx) is found, it returns the negative value
of the (first) invalid reference. }
function FindSubExpressionReferences (var RegEx: RegExType; const s: String; OnlySub: Boolean): Integer;
{ Replaces (sub)expression references in ReplaceStr by the actual
(sub)expressions and unquotes quoted characters. To be used after
the regular expression RegEx created with `NewRegEx' was matched
against s successfully with `MatchRegEx' or `MatchRegExFrom'. }
function ReplaceSubExpressionReferences (var RegEx: RegExType; const s, ReplaceStr: String) = Res: TString;
{ Returns the string for a regular expression that matches exactly
one character out of the given set. It can be combined with the
usual operators to form more complex expressions. }
function CharSet2RegEx (const Characters: CharSet) = s: TString;
implementation
{$L rx, regexc.c}
procedure CNewRegEx (var RegEx: RegExType; Expression: CString; ExpressionLength: CInteger; ExtendedRegEx, CaseInsensitive, NewLines: Boolean); external name '_p_CNewRegEx';
function CMatchRegExFrom (var RegEx: RegExType; aString: CString; StrLength: CInteger; NotBeginningOfLine, NotEndOfLine: Boolean; From: CInteger): Boolean; external name '_p_CMatchRegExFrom';
procedure CGetMatchRegEx (var RegEx: RegExType; n: CInteger; var MatchPosition, MatchLength: CInteger); external name '_p_CGetMatchRegEx';
procedure NewRegEx (var RegEx: RegExType; const Expression: String; ExtendedRegEx, CaseInsensitive, NewLines: Boolean);
begin
CNewRegEx (RegEx, Expression, Length (Expression), ExtendedRegEx, CaseInsensitive, NewLines);
if RegEx.ErrorInternal = nil then
RegEx.Error := nil
else
RegEx.Error := NewString (CString2String (RegEx.ErrorInternal))
end;
function MatchRegEx (var RegEx: RegExType; const s: String; NotBeginningOfLine, NotEndOfLine: Boolean): Boolean;
begin
MatchRegEx := CMatchRegExFrom (RegEx, s, Length (s), NotBeginningOfLine, NotEndOfLine, 1)
end;
function MatchRegExFrom (var RegEx: RegExType; const s: String; NotBeginningOfLine, NotEndOfLine: Boolean; From: Integer): Boolean;
begin
MatchRegExFrom := CMatchRegExFrom (RegEx, s, Length (s), (From <> 1) or NotBeginningOfLine, NotEndOfLine, From)
end;
procedure GetMatchRegEx (var RegEx: RegExType; n: Integer; var MatchPosition, MatchLength: Integer);
var CMatchPosition, CMatchLength: CInteger;
begin
CGetMatchRegEx (RegEx, n, CMatchPosition, CMatchLength);
if @MatchPosition <> nil then MatchPosition := CMatchPosition;
if @MatchLength <> nil then MatchLength := CMatchLength
end;
function RegExPosFrom (const Expression: String; ExtendedRegEx, CaseInsensitive: Boolean; const s: String; From: Integer) = MatchPosition: Integer;
var RegEx: RegExType;
begin
MatchPosition := 0;
NewRegEx (RegEx, Expression, ExtendedRegEx, CaseInsensitive, False);
if (RegEx.Error = nil) and MatchRegExFrom (RegEx, s, False, False, From) then
GetMatchRegEx (RegEx, 0, MatchPosition, Null);
DisposeRegEx (RegEx)
end;
function FindSubExpressionReferences (var RegEx: RegExType; const s: String; OnlySub: Boolean): Integer;
var
i, j: Integer;
ch: Char;
begin
j := 0;
i := 1;
while i <= Length (s) do
begin
case s[i] of
'&': if not OnlySub then Inc (j);
'\': if i = Length (s) then
Inc (j)
else
begin
ch := s[i + 1];
if (ch in ['u', 'l']) and (i + 1 < Length (s)) then
begin
Inc (i);
ch := s[i + 1]
end;
if (ch in ['0' .. '9']) and
(Ord (ch) - Ord ('0') > RegEx.SubExpressions) then
Return -(Ord (ch) - Ord ('0'))
else
begin
if not OnlySub or (ch <> '0') then Inc (j);
Inc (i)
end
end;
end;
Inc (i)
end;
FindSubExpressionReferences := j
end;
function ReplaceSubExpressionReferences (var RegEx: RegExType; const s, ReplaceStr: String) = Res: TString;
var i: Integer;
procedure DoReplace (l, n: Integer; CaseMode: Char);
var
MatchPosition, MatchLength: Integer;
st: TString;
begin
GetMatchRegEx (RegEx, n, MatchPosition, MatchLength);
Delete (Res, i, l);
if (n <= RegEx.SubExpressions) and (MatchPosition > 0) { @@ rx-1.5 bug } and (MatchPosition + MatchLength - 1 <= Length (s)) then
begin
st := Copy (s, MatchPosition, MatchLength);
case CaseMode of
'u': UpCaseString (st);
'l': LoCaseString (st);
end;
Insert (st, Res, i);
Inc (i, MatchLength)
end;
Dec (i)
end;
begin
Res := ReplaceStr;
i := 1;
while i <= Length (Res) do
begin
case Res[i] of
'&': DoReplace (1, 0, #0);
'\': if (i < Length (Res)) and (Res[i + 1] in ['0' .. '9']) then
DoReplace (2, Ord (Res[i + 1]) - Ord ('0'), #0)
else if (i + 1 < Length (Res)) and (Res[i + 1] in ['u', 'l']) and (Res[i + 2] in ['0' .. '9']) then
DoReplace (3, Ord (Res[i + 2]) - Ord ('0'), Res[i + 1])
else
Delete (Res, i, 1);
end;
Inc (i)
end
end;
function CharSet2RegEx (const Characters: CharSet) = s: TString;
var
i: Integer;
c, c2: Char;
s2, s3: String (1) = '';
begin
if Characters = [] then Return '[^' + Low (Char) + '-' + High (Char) + ']';
if Characters = ['^'] then Return '\^'; { A `^' alone cannot be handled within `[]'! }
if Characters = ['^', '-'] then Return '[-^]';
s := '';
i := Ord (Low (Char));
{ we cannot use a Char for the loop, because it would overflow }
while i <= Ord (High (Char)) do
begin
c := Chr (i);
if c in Characters then
case c of
']': s := c + s; { `]' must come first }
'^': s2 := c; { `^' must not come first }
'-': s3 := c; { `-' must come last (or first) }
else
c2 := c;
while (c2 < High (c)) and (Succ (c2) in Characters) do Inc (c2);
if c2 = ']' then Dec (c2); { `x-]' would be interpreted as a closing bracket }
if c2 <= Succ (c) then
s := s + c
else
begin
s := s + c + '-' + c2;
c := c2
end
end;
i := Ord (c) + 1
end;
s := '[' + s + s2 + s3 + ']'
end;
end.
|
{$F-,A+,O+,G+,R-,S+,I+,Q-,V-,B-,X+,T-,P-,D-,L-,N-,E+}
unit StatBar;
interface
procedure sbClear;
procedure sbInfo(S : String; Stick : Boolean);
procedure sbReset;
procedure sbStatBar(On : Boolean);
procedure sbToggleMode;
procedure sbUpdate;
implementation
uses Crt,
Global, Misc, Strings, FastIO, DateTime;
procedure sbClear;
var Yp : Byte;
begin
if Cfg^.StatType = sbTop then Yp := 1 else Yp := 25;
if (not UserOn) or (not Cfg^.StatBarOn) then Exit;
fWrite(1,Yp,sRepeat(' ',maxX),Cfg^.StatTxt);
end;
procedure sbWrite(X : Byte; S : String; L : Integer);
var Col, P, F : Integer; Z : String; Ps, Yp : Byte;
begin
Z := S;
if Cfg^.StatType = sbTop then Yp := 1 else Yp := 25;
while Pos('|',Z) <> 0 do Delete(Z,Pos('|',Z),2);
F := L-Length(Z);
if F > 0 then for P := 1 to F do S := S + ' ' else
if F < 0 then for P := 1 to Abs(F) do Delete(S,Length(S),1);
s := ' '+s;
Col := Cfg^.StatTxt;
Ps := 1;
while S <> '' do if S[1] = '|' then
begin
case S[2] of
'L' : Col := Cfg^.StatLo;
'M' : Col := Cfg^.StatTxt;
'H' : Col := Cfg^.StatHi;
end;
Delete(S,1,2);
end else
begin
P := Pos('|',S);
if P = 0 then P := Length(S) else Dec(P,1);
fWrite(X+Ps-1,Yp,Copy(S,1,P),Col);
Inc(Ps,P);
Delete(S,1,P);
end;
end;
procedure sbUpdate;
var S : String;
begin
if (statCnt > 0) and (statCnt < 64000) then
begin
Inc(statCnt);
if statCnt = 1000 then
begin
statCnt := 0;
sbClear;
end;
end;
if (not UserOn) or (not Cfg^.StatBarOn) then Exit;
if statCnt <> 0 then sbWrite(1,'|M'+statInfo,80) else
case Cfg^.StatBar of
1 : begin
if Cfg^.RealNameSystem then
sbWrite(1, 'User |L[|H'+User^.RealName+'|L]',30) else
begin
sbWrite(1, 'User |L[|H'+User^.UserName+'|L]',30);
sbWrite(32,'Real |L[|H'+User^.RealName+'|L]',30);
end;
sbWrite(64,'Time |L[|H'+St(mTimeLeft('M'))+'|L]',14);
end;
2 : begin
sbWrite(1, 'Birth |L[|H'+User^.BirthDate+'|L] |MAge |L[|H'+St(dtAge(User^.BirthDate))+'|L]',26);
sbWrite(28,'Phone |L[|H'+User^.PhoneNum+'|L]',22);
if Cfg^.ShowPwLocal then S := User^.Password else S := strEcho(User^.Password);
sbWrite(52,'Password |L[|H'+S+'|L]',27);
end;
3 : begin
sbWrite(1, 'Sex |L[|H'+mSexString(User^.Sex)+'|L]',14);
sbWrite(16,'Location |L[|H'+User^.Location+'|L]',30);
sbWrite(50,'Address |L[|H'+User^.Address+'|L]',30);
end;
4 : begin
sbWrite(1, 'Baud |L[|H'+mBaudString(User^.BaudRate)+'|L]',12);
sbWrite(14,'Emulation |L[|H'+mEmulation(User^)+'|L]',19);
sbWrite(40,'SL |L[|H'+st(User^.SL)+'|L]',9);
sbWrite(50,'DSL |L[|H'+st(User^.DSL)+'|L]',10);
end;
5 : begin
sbWrite(1, 'Chat Reason |L[|H'+chatReason+'|L]',63);
sbWrite(65,'Attempts |L[|H'+St(numPaged)+'|L]',15);
end;
6 : begin
sbWrite(1, 'MemAvail |L[|H'+St(memAvail)+'|L]',18);
sbWrite(20,'MaxAvail |L[|H'+St(maxAvail)+'|L]',18);
sbWrite(40,'Filemode |L[|H'+St(fileMode)+'|L] '+
'|MTlo |L[|H'+b2St(tLibOpen)+'|L]',18);
{ sbWrite(60,'Tl |L[|H'+St(User^.textLib)+'|L] '+
'|MNl |L[|H'+St(textLib^.numLib)+'|L]',20);}
end;
end;
end;
procedure sbReset;
begin
scrTop := 1;
scrBot := 25;
Window(1,1,maxX,maxY);
TextAttr := $0F;
ClrScr;
statInfo := '';
statCnt := 0;
end;
procedure sbDraw;
var X,Y : Byte;
begin
if not UserOn then Exit;
X := ioWhereX; Y := ioWhereY;
Window(1,1,maxX,maxY);
case Cfg^.StatType of
sbBot : begin
scrTop := 1;
scrBot := 24;
if Y = 25 then
begin
mScroll(1,1,80,25,-1);
Dec(Y,1);
end;
end;
sbTop : begin
scrTop := 2;
scrBot := 25;
if Y = 1 then mScroll(1,1,80,25,1);
Dec(Y,1);
end;
end;
Window(1,scrTop,80,scrBot);
ioGotoXY(X,Y);
sbClear;
sbUpdate;
end;
procedure sbErase;
var X,Y,Yp : Byte;
begin
if not UserOn then Exit;
if Cfg^.StatType = sbTop then Yp := 1 else Yp := 25;
X := ioWhereX; Y := ioWhereY;
Window(1,1,maxX,maxY);
scrTop := 1;
scrBot := 25;
if Cfg^.StatType = sbTop then Inc(Y,1);
fWrite(1,Yp,sRepeat(' ',maxX),$0F);
ioGotoXY(X,Y);
end;
procedure sbStatBar(On : Boolean);
begin
if not UserOn then Exit;
if Cfg^.StatBarOn = On then Exit;
Cfg^.StatBarOn := On;
if On then sbDraw else sbErase;
end;
procedure sbToggleMode;
var X,Y : Byte;
begin
if not UserOn then Exit;
if (not ScreenOff) and (Cfg^.StatBarOn) then sbErase;
if Cfg^.StatType = sbBot then Cfg^.StatType := sbTop else Cfg^.StatType := sbBot;
if (not Cfg^.StatBarOn) or (ScreenOff) then Exit;
X := ioWhereX; Y := ioWhereY;
Window(1,1,maxX,maxY);
case Cfg^.StatType of
sbBot : begin
scrTop := 1;
scrBot := 24;
mScroll(1,1,80,25,-1);
Dec(Y,1);
end;
sbTop : begin
scrTop := 2;
scrBot := 25;
mScroll(1,1,80,25,1);
end;
end;
Window(1,scrTop,80,scrBot);
ioGotoXY(X,Y);
sbClear;
sbUpdate;
end;
procedure sbInfo(S : String; Stick : Boolean);
begin
sbClear;
if S = '' then
begin
statInfo := '';
statCnt := 0;
Exit;
end;
if Stick then statCnt := 64000 else statCnt := 1;
statInfo := S;
sbClear;
sbUpdate;
end;
end. |
unit ponteProcessa;
interface
uses
dvcrt,
dvwin,
dvform,
sysutils,
classes,
pontemsg,
pontevars,
ponteconfig;
procedure processa;
implementation
{--------------------------------------------------------}
{ Gera um form padrão a parti de uma ponte(nova ou não) }
{--------------------------------------------------------}
procedure criarFormPonte(out ponte: UserPonte);
const
tipoponte : string = 'WEB|FTP|DROPBOX';
begin
formCria;
formCampo ('PTNOME', 'Nome', ponte.Nome, 100);
formCampolista ('PTTIPO', 'Tipo (F9 Ajuda)', ponte.Tipo, 10, tipoponte);
formcampo ('PTSERVIDOR', 'Servidor', ponte.Servidor, 200);
formcampoint ('PTPORTA', 'Porta', ponte.Porta);
formCampoBool ('', 'Autenticação automática? (somente para DROPBOX)', ponte.Auth);
formcampo ('PTCONTA', 'Conta', ponte.Conta, 200);
formcampo ('PTSENHA', 'Senha', ponte.Senha, 150);
formEdita(true);
end;
{--------------------------------------------------------}
{ Gravar os dados da ponte no pontes.ini }
{--------------------------------------------------------}
procedure gravarPonteSintAmbiente(ponte: UserPonte);
var
senha: string;
begin
senha := aplicaSenha(ponte.Senha);
{inserindo no arquivo ini}
sintGravaAmbienteArq(ponte.Nome, 'Nome', ponte.Nome, arqIniPontes);
sintGravaAmbienteArq(ponte.Nome, 'Tipo', ponte.Tipo, arqIniPontes);
sintGravaAmbienteArq(ponte.Nome, 'Servidor', ponte.Servidor, arqIniPontes);
sintGravaAmbienteArq(ponte.Nome, 'Porta', intTostr(ponte.Porta), arqIniPontes);
sintGravaAmbienteArq(ponte.Nome, 'Conta', ponte.Conta, arqIniPontes);
sintGravaAmbienteArq(ponte.Nome, 'Senha', senha, arqIniPontes);
sintGravaAmbienteArq(ponte.Nome, 'Auth', BoolToStr(ponte.Auth), arqIniPontes);
end;
{--------------------------------------------------------}
{ Retornar ponte do pontes.ini }
{--------------------------------------------------------}
procedure getPonteSintAmbiente(ponteNome: string; out ponte: UserPonte);
begin
ponte.Nome := sintambientearq(ponteNome, 'Nome', 'Não registrado', arqIniPontes);
ponte.Tipo := sintambientearq(ponteNome, 'Tipo', 'Não registrado', arqIniPontes);
ponte.Servidor := sintambientearq(ponteNome, 'Servidor', 'Não registrado', arqIniPontes);
ponte.Porta := strtoint(sintambientearq(ponteNome, 'Porta', 'Não registrado', arqIniPontes));
ponte.Conta := sintambientearq(ponteNome, 'Conta', 'Não registrado', arqIniPontes);
ponte.Senha := sintambientearq(ponteNome, 'Senha', 'Não registrado', arqIniPontes);
ponte.Auth := StrToBool(sintambientearq(ponteNome, 'Auth', '0' , arqIniPontes));
end;
{--------------------------------------------------------}
{ Verificar se ponte já foi criada }
{--------------------------------------------------------}
function verificarPonteExiste(ponteNome: string) : boolean;
var
existeNome: string;
begin
Result := false;
existeNome := sintambientearq(ponteNome, 'Nome', '', arqIniPontes);
if existeNome <> '' then
begin
sintWriteLn('A ponte ' + existeNome + ' já foi criada.');
sintWriteLn('Deseja sobresceve-lá?');
if popupMenuPorLetra('SN') = 'N' then
begin
sintWriteLn('Infome um novo nome, ou deixe o nome em branco e aperte ESC para excluir.');
Result := true;
end;
end
end;
{--------------------------------------------------------}
{ editar ponte }
{--------------------------------------------------------}
procedure editar(ponteNome: string);
var
ponte: UserPonte;
validaSeExiste: boolean;
begin
clrscr;
textBackground (BLUE);
Writeln ('Editar Ponte: ');
writeln;
textBackground (BLACK);
getPonteSintAmbiente(ponteNome, ponte);
ponte.Senha := aplicaSenha(ponte.Senha);
validaSeExiste := true;
{formulario de inserção de pontes}
clrscr;
criarFormPonte(ponte);
if ponte.Nome = '' then
begin
textBackground (BLUE);
mensagem('PTBRANCO', 0); { nome em branco registro ignorado }
textBackground (BLACK);
clrscr;
exit;
end;
ponte.Senha := aplicaSenha(ponte.Senha);
sintWriteLn('Confirmar alterações?');
if popupMenuPorLetra('SN') = 'S' then
begin
{inserindo no arquivo ini}
sintremoveambientearq(ponteNome, '', arqIniPontes);
gravarPonteSintAmbiente(ponte);
sintWriteLn('Ponte ' + ponte.Nome + ' editada com sucesso.');
end;
end;
{--------------------------------------------------------}
{ listar ponte }
{--------------------------------------------------------}
procedure listar(ponteNome: string);
var
ponte: UserPonte;
begin
clrscr;
textBackground (BLUE);
Writeln ('Listar Ponte: ');
writeln;
textBackground (BLACK);
if ponteNome = '' then
begin
sintWrite('Nome dá ponte não está definida.');
exit;
end;
getPonteSintAmbiente(ponteNome, ponte);
if ponte.Nome <> 'Não registrado' then
begin
{imprimindo valores recebidos}
textBackground (BLACK);
ponte.Senha := aplicaSenha(ponte.Senha);
{formulario de exibicao de ponte}
formCria;
formCampo ('', 'Nome', ponte.Nome,50);
formCampo ('', 'Tipo', ponte.Tipo,3);
formCampo ('', 'Servidor', ponte.Servidor, 50);
formCampoint ('', 'Porta', ponte.Porta);
formCampo ('', 'Conta', ponte.Conta,20);
formcampo ('', 'Senha', ponte.Senha,15);
formCampoBool('', 'Auth automático', ponte.Auth);
formEdita(false);
end;
if ponte.Nome = 'Não registrado' then
mensagem ('PTNREGIST', 1); { ponte não registrada }
clrscr;
end;
{--------------------------------------------------------}
{ remover ponte }
{--------------------------------------------------------}
procedure remover(ponteNome: string);
begin
clrscr;
textBackground (BLUE);
Writeln ('Remover Ponte: ');
writeln;
textBackground (BLACK);
if ponteNome = '' then
begin
sintWrite('Nome dá ponte não está definida.');
exit;
end;
sintWriteLn('Confirma remoção da ponte ' + ponteNome + '?');
if popupMenuPorLetra('SN') = 'S' then
begin
sintremoveambientearq(ponteNome, '', arqIniPontes);
mensagem ('PTSUCESSO', 0); { ponte removida com sucesso }
end;
clrscr;
end;
{--------------------------------------------------------}
{ executar comando da ponte selecionada }
{--------------------------------------------------------}
procedure executarComandoSelecionado(option: char; ponteNome: string);
begin
limpaBaixo (wherey);
case upcase(option) of
'L': listar(ponteNome); { procedure de listagem de pontes }
'R': remover(ponteNome); { procedure de remoção de pontes }
'E': editar(ponteNome); { procedure de edição de ponte}
ESC: exit;
else
textBackground (MAGENTA);
mensagem ('PTOPCAOI', 0); //opção inválida
textBackground (BLACK);
clrscr;
end;
end;
{--------------------------------------------------------}
{ executar comando da ponte existente }
{--------------------------------------------------------}
function selecionarOpcaoPonte: char;
var
n: integer;
const
tabLetrasOpcao: string = 'LREV' + ESC;
begin
clrscr;
sintWrite('O que deseja fazer com a Ponte?');
popupMenuCria (wherex+1, wherey, 40, length(tabLetrasOpcao), MAGENTA);
popupMenuAdiciona ('', 'L - Listar Ponte');
popupMenuAdiciona ('', 'R - Remover Ponte');
popupMenuAdiciona ('', 'E - Editar Ponte');
popupMenuAdiciona ('PTTERMINAR', 'ESC - terminar' );
n := popupMenuSeleciona;
if n > 0 then
begin
Result := tabLetrasOpcao[n];
writeln(tabLetrasOpcao[n]);
end
else
Result := ESC;
end;
{--------------------------------------------------------}
{ folhear pontes }
{--------------------------------------------------------}
procedure folhear();
var sl: TStringList;
i, n: integer;
opcao: char;
s: string;
begin
clrscr;
textBackground (BLUE);
Writeln ('Folhear Pontes: ');
writeln;
textBackground (BLACK);
sl := sintItensAmbienteArq ('', arqIniPontes);
mensagem('PTENCONTRADOS', 0); //foram encontrados
sintwrite(intToStr (sl.count));
mensagem('PTREG', 2); // registros
popupMenuCria (wherex, wherey, 20, sl.count, blue);
for i := 0 to sl.count-1 do
begin
s := sintAmbienteArq (sl[i], 'Nome', '', arqIniPontes);
popupmenuadiciona('', s);
end;
n := popupMenuSeleciona;
if n > 0 then
begin
opcao := selecionarOpcaoPonte;
executarComandoSelecionado(opcao, sl[n-1]);
end;
end;
{--------------------------------------------------------}
{ Inserir Pontes }
{--------------------------------------------------------}
procedure inserir;
var
novaPonte: UserPonte;
validaSeExiste: boolean;
{------------------ Remover lixo variável ---------------------}
procedure limparLixo(out ponte: UserPonte);
begin
ponte.Nome := '';
ponte.Tipo := '';
ponte.Servidor := '';
ponte.Porta := 0;
ponte.Conta := '';
ponte.Senha := '';
ponte.Auth := false;
end;
{--------------------------------------------------------}
begin
clrscr;
Writeln ('Adicionar Ponte: ');
writeln;
textBackground (BLACK);
TextColor(White);
validaSeExiste := true;
limparLixo(novaPonte);
{formulario de inserção de pontes}
Repeat
clrscr;
criarFormPonte(novaPonte);
if novaPonte.Nome = '' then
begin
textBackground (BLUE);
mensagem('PTBRANCO', 0); { nome em branco registro ignorado }
textBackground (BLACK);
clrscr;
exit;
end
else
validaSeExiste := verificarPonteExiste(novaPonte.Nome);
Until not validaSeExiste;
gravarPonteSintAmbiente(novaPonte);
mensagem ('PTPONTE', 0); // a ponte
sintwrite(novaPonte.Nome);
mensagem('PTPONTEI', 0); // foi inserida com sucesso
clrscr;
end;
{--------------------------------------------------------}
{ executar comando que foi solicitado }
{--------------------------------------------------------}
procedure executarComando(option: char);
begin
case upcase(option) of
'I': inserir; { procedure de inserção de pontes }
'F': folhear; { procedure de folheamento de pontes }
else
textBackground (MAGENTA);
mensagem ('PTOPCAOI', 0); //opção inválida
textBackground (BLACK);
clrscr;
end;
end;
{--------------------------------------------------------}
{ seleciona a opção com as setas }
{--------------------------------------------------------}
function selSetasOpcao: char;
var
n: integer;
const
tabLetrasOpcao: string = 'IF' + ESC;
begin
garanteEspacoTela (9);
popupMenuCria (wherex, wherey, 40, length(tabLetrasOpcao), MAGENTA);
popupMenuAdiciona ('PTINSERIR', 'I - Inserir Ponte');
popupMenuAdiciona ('PTLISTAR', 'F - Folhear Pontes');
popupMenuAdiciona ('PTTERMINAR', 'ESC - terminar' );
n := popupMenuSeleciona;
if n > 0 then
begin
selSetasOpcao := tabLetrasOpcao[n];
writeln (tabLetrasOpcao[n]);
end
else
selSetasOpcao := ESC;
end;
{--------------------------------------------------------}
{ seleciona a teclas de ações }
{--------------------------------------------------------}
procedure selecionarOpcoes(out processa: boolean);
var opcao: char;
begin
opcao := selSetasOpcao;
if opcao = ESC then
begin
processa := false;
exit;
end;
executarComando(opcao);
end;
{--------------------------------------------------------}
{ loop de processamento }
{--------------------------------------------------------}
procedure processa;
var processa: boolean;
begin
processa := true;
while processa do
begin
textBackground (BLUE);
sintWriteLn('Qual sua opção?');
textBackground (BLACK);
selecionarOpcoes(processa);
end;
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUIMenu.pas
// Creator : Shen Min
// Date : 2002-09-01
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit SUIMenu;
interface
{$I SUIPack.inc}
uses Windows, Graphics, Menus;
procedure Menu_SetItemEvent(
MenuItem : TMenuItem;
DrawItemEvent : TMenuDrawItemEvent;
MeasureItemEvent : TMenuMeasureItemEvent
);
procedure Menu_DrawBorder(ACanvas : TCanvas; ARect : TRect; Color : TColor);
procedure Menu_DrawBackGround(ACanvas : TCanvas; ARect : TRect; Color : TColor);
procedure Menu_DrawLineItem(
ACanvas : TCanvas;
ARect : TRect;
LineColor : TColor;
BarWidth : Integer;
L2R : Boolean
);
procedure Menu_DrawWindowBorder(HandleOfWnd : HWND; BorderColor, FormColor : TColor);
procedure Menu_DrawMacOSLineItem(ACanvas : TCanvas; ARect : TRect);
procedure Menu_DrawMacOSSelectedItem(ACanvas : TCanvas; ARect : TRect);
procedure Menu_DrawMacOSNonSelectedItem(ACanvas : TCanvas; ARect : TRect);
procedure Menu_GetSystemFont(const Font : TFont);
implementation
uses SUIResDef;
procedure Menu_SetItemEvent(
MenuItem : TMenuItem;
DrawItemEvent : TMenuDrawItemEvent;
MeasureItemEvent : TMenuMeasureItemEvent
);
var
i : Integer;
begin
MenuItem.OnDrawItem := DrawItemEvent;
MenuItem.OnMeasureItem := MeasureItemEvent;
for i := 0 to MenuItem.Count - 1 do
Menu_SetItemEvent(MenuItem.Items[i], DrawItemEvent, MeasureItemEvent);
end;
procedure Menu_DrawBorder(ACanvas : TCanvas; ARect : TRect; Color : TColor);
begin
ACanvas.Brush.Color := Color;
ACanvas.FrameRect(ARect);
end;
procedure Menu_DrawBackGround(ACanvas : TCanvas; ARect : TRect; Color : TColor);
begin
ACanvas.Brush.Color := Color;
ACanvas.FillRect(ARect);
end;
procedure Menu_DrawLineItem(
ACanvas : TCanvas;
ARect : TRect;
LineColor : TColor;
BarWidth : Integer;
L2R : Boolean
);
begin
ACanvas.Pen.Color := LineColor;
if L2R then
begin
ACanvas.MoveTo(ARect.Left + BarWidth + 4, ARect.Top + 2);
ACanvas.LineTo(ARect.Right - 2, ARect.Top + 2);
end
else
begin
ACanvas.MoveTo(ARect.Left + 2, ARect.Top + 2);
ACanvas.LineTo(ARect.Right - BarWidth - 4, ARect.Top + 2);
end;
end;
procedure Menu_DrawMacOSLineItem(ACanvas : TCanvas; ARect : TRect);
var
Bmp : TBitmap;
begin
Bmp := TBitmap.Create();
Bmp.LoadFromResourceName(hInstance, 'MACOS_MENU_BAR');
Bmp.Height := 12;
ACanvas.StretchDraw(ARect, Bmp);
Bmp.Free();
end;
procedure Menu_DrawMacOSSelectedItem(ACanvas : TCanvas; ARect : TRect);
var
Bmp : TBitmap;
begin
Bmp := TBitmap.Create();
Bmp.LoadFromResourceName(hInstance, 'MACOS_MENU_SELECT');
Bmp.Height := 20;
ACanvas.StretchDraw(ARect, Bmp);
Bmp.Free();
end;
procedure Menu_DrawMacOSNonSelectedItem(ACanvas : TCanvas; ARect : TRect);
var
Bmp : TBitmap;
begin
Bmp := TBitmap.Create();
Bmp.LoadFromResourceName(hInstance, 'MACOS_MENU_BAR');
Bmp.Height := 20;
ACanvas.StretchDraw(ARect, Bmp);
Bmp.Free();
end;
procedure Menu_DrawWindowBorder(HandleOfWnd : HWND; BorderColor, FormColor : TColor);
var
Canvas : TCanvas;
R : TRect;
WndRect : TRect;
begin
Canvas := TCanvas.Create();
Canvas.Handle := GetWindowDC(GetDesktopWindow());
GetWindowRect(HandleOfWnd, WndRect);
R := WndRect;
Inc(R.Top);
Dec(R.Bottom);
Dec(R.Right);
Canvas.Brush.Color := BorderColor;
Canvas.FrameRect(R);
Inc(R.Left);
Inc(R.Top);
Dec(R.Bottom);
Dec(R.Right);
Canvas.Brush.Color := clWhite;
Canvas.FrameRect(R);
Canvas.Pen.Color := FormColor;
Canvas.MoveTo(WndRect.Left, WndRect.Bottom - 1);
Canvas.LineTo(WndRect.Right - 1, WndRect.Bottom - 1);
Canvas.LineTo(WndRect.Right - 1, WndRect.Top);
Canvas.LineTo(WndRect.Right, WndRect.Top);
Canvas.LineTo(WndRect.Left, WndRect.Top);
ReleaseDC(GetDesktopWindow, Canvas.Handle);
Canvas.Free();
end;
procedure Menu_GetSystemFont(const Font : TFont);
var
FNonCLientMetrics : TNonCLientMetrics;
begin
FNonCLientMetrics.cbSize := Sizeof(TNonCLientMetrics);
if SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, @FNonCLientMetrics, 0) then
begin
Font.Handle := CreateFontIndirect(FNonCLientMetrics.lfMenuFont);
Font.Color := clMenuText;
end;
end;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 65520,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
August '1999
Problem 12 O(E) Dfs Method
}
program
KnightsPath;
const
MaxN = 100;
const
DX : array [1 .. 8] of Integer = (2, 1, -1, -2, -2, -1, 1, 2);
DY : array [1 .. 8] of Integer = (1, 2, 2, 1, -1, -2, -2, -1);
var
N, X, Y, U, V : Integer;
A : array [-1 .. MaxN + 2, -1 .. MaxN + 2] of Byte;
P : array [-1 .. MaxN + 2, -1 .. MaxN + 2] of Integer;
I, J : Integer;
F : Text;
procedure DFS (X, Y : Integer);
var
I : Integer;
begin
for I := 1 to 8 do
if (P[X + DX[I], Y + DY[I]] = 0) and (A[X + DX[I], Y + DY[I]] = 0) then
begin
P[X + DX[I], Y + DY[I]] := 256 * X + Y;
DFS(X + DX[I], Y + DY[I]);
end;
end;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N);
FillChar(A, SizeOf(A), 1);
for I := 1 to N do
begin
for J := 1 to N do
Read(F, A[I, J]);
Readln(F);
end;
Readln(F, X, Y);
Readln(F, U, V);
Close(F);
P[U, V] := MaxInt;
DFS(U, V);
Assign(F, 'output.txt');
ReWrite(F);
I := X * 256 + Y;
J := 1;
while I <> 256 * U + V do
begin
I := P[I div 256, I mod 256];
Inc(J);
end;
Writeln(F, J);
I := X * 256 + Y;
Writeln(F, I div 256, ' ', I mod 256);
while I <> 256 * U + V do
begin
I := P[I div 256, I mod 256];
Writeln(F, I div 256, ' ', I mod 256);
end;
Close(F);
end. |
unit SEA_Base;
(*************************************************************************
DESCRIPTION : SEED Encryption basic routines
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12/D17-D18/D25S, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : 4.0 KB static data
DISPLAY MODE : ---
REFERENCES : [1] H.J. Lee et al, The SEED Encryption Algorithm, 2005
http://tools.ietf.org/html/rfc4269
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.01 03.06.07 W.Ehrhardt Initial BP7 SEA_Init
0.02 03.06.07 we FastInit/SEA_Reset
0.03 03.06.07 we SEA_XorBlock
0.04 03.06.07 we SEA_En/Decrypt
0.05 07.06.07 we Function SG: BIT16 and BASM16 versions
0.06 07.06.07 we SEA_Init/BIT16: 64 bit rotation with move()
0.07 08.06.07 we SEA_Init/BIT16: uses byte H instead of longint T
0.08 26.07.10 we SEA_Err_Invalid_16Bit_Length
0.09 28.07.10 we SEA_Err_CTR_SeekOffset
0.10 21.07.12 we 64-bit adjustments
0.11 25.12.12 we {$J+} if needed
0.12 23.11.17 we RB for CPUARM
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2007-17 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}
interface
const
SEA_Err_Invalid_Key_Size = -1; {Key size in bits not 128, 192, or 256}
SEA_Err_Invalid_Length = -3; {No full block for cipher stealing}
SEA_Err_Data_After_Short_Block = -4; {Short block must be last}
SEA_Err_MultipleIncProcs = -5; {More than one IncProc Setting}
SEA_Err_NIL_Pointer = -6; {nil pointer to block with nonzero length}
SEA_Err_CTR_SeekOffset = -15; {Negative offset in SEA_CTR_Seek}
SEA_Err_Invalid_16Bit_Length = -20; {Pointer + Offset > $FFFF for 16 bit code}
type
TSEARndKey = packed array[0..31] of longint; {Round key schedule}
TSEABlock = packed array[0..15] of byte; {128 bit block}
PSEABlock = ^TSEABlock;
type
TSEAIncProc = procedure(var CTR: TSEABlock); {user supplied IncCTR proc}
{$ifdef DLL} stdcall; {$endif}
type
TSEAContext = packed record
IV : TSEABlock; {IV or CTR }
buf : TSEABlock; {Work buffer }
bLen : word; {Bytes used in buf }
Flag : word; {Bit 1: Short block }
IncProc : TSEAIncProc; {Increment proc CTR-Mode}
RK : TSEARndKey; {Round keys }
end;
const
SEABLKSIZE = sizeof(TSEABlock); {SEED block size in bytes}
{$ifdef CONST}
function SEA_Init(const Key; KeyBits: word; var ctx: TSEAContext): integer;
{-SEED context/round key initialization}
{$ifdef DLL} stdcall; {$endif}
procedure SEA_Encrypt(var ctx: TSEAContext; const BI: TSEABlock; var BO: TSEABlock);
{-encrypt one block (in ECB mode)}
{$ifdef DLL} stdcall; {$endif}
procedure SEA_Decrypt(var ctx: TSEAContext; const BI: TSEABlock; var BO: TSEABlock);
{-decrypt one block (in ECB mode)}
{$ifdef DLL} stdcall; {$endif}
procedure SEA_XorBlock(const B1, B2: TSEABlock; var B3: TSEABlock);
{-xor two blocks, result in third}
{$ifdef DLL} stdcall; {$endif}
{$else}
function SEA_Init(var Key; KeyBits: word; var ctx: TSEAContext): integer;
{-SEED context/round key initialization}
procedure SEA_Encrypt(var ctx: TSEAContext; var BI: TSEABlock; var BO: TSEABlock);
{-encrypt one block (in ECB mode)}
procedure SEA_Decrypt(var ctx: TSEAContext; var BI: TSEABlock; var BO: TSEABlock);
{-decrypt one block (in ECB mode)}
procedure SEA_XorBlock(var B1, B2: TSEABlock; var B3: TSEABlock);
{-xor two blocks, result in third}
{$endif}
procedure SEA_Reset(var ctx: TSEAContext);
{-Clears ctx fields bLen and Flag}
{$ifdef DLL} stdcall; {$endif}
procedure SEA_SetFastInit(value: boolean);
{-set FastInit variable}
{$ifdef DLL} stdcall; {$endif}
function SEA_GetFastInit: boolean;
{-Returns FastInit variable}
{$ifdef DLL} stdcall; {$endif}
implementation
{$ifdef D4Plus}
var
{$else}
{$ifdef J_OPT} {$J+} {$endif}
const
{$endif}
FastInit : boolean = true; {Clear only necessary context data at init}
{IV and buf remain uninitialized}
type
TXSBox = packed array[0..255] of longint; {Extended S-box}
TWA4 = packed array[0..3] of longint; {Block as array of longint}
{$ifdef StrictLong}
{$warnings off}
{$R-} {avoid D9+ errors!}
{$endif}
{Extended S-boxes}
const
SS0: TXSBox = ($2989A1A8, $05858184, $16C6D2D4, $13C3D3D0, $14445054, $1D0D111C, $2C8CA0AC, $25052124,
$1D4D515C, $03434340, $18081018, $1E0E121C, $11415150, $3CCCF0FC, $0ACAC2C8, $23436360,
$28082028, $04444044, $20002020, $1D8D919C, $20C0E0E0, $22C2E2E0, $08C8C0C8, $17071314,
$2585A1A4, $0F8F838C, $03030300, $3B4B7378, $3B8BB3B8, $13031310, $12C2D2D0, $2ECEE2EC,
$30407070, $0C8C808C, $3F0F333C, $2888A0A8, $32023230, $1DCDD1DC, $36C6F2F4, $34447074,
$2CCCE0EC, $15859194, $0B0B0308, $17475354, $1C4C505C, $1B4B5358, $3D8DB1BC, $01010100,
$24042024, $1C0C101C, $33437370, $18889098, $10001010, $0CCCC0CC, $32C2F2F0, $19C9D1D8,
$2C0C202C, $27C7E3E4, $32427270, $03838380, $1B8B9398, $11C1D1D0, $06868284, $09C9C1C8,
$20406060, $10405050, $2383A3A0, $2BCBE3E8, $0D0D010C, $3686B2B4, $1E8E929C, $0F4F434C,
$3787B3B4, $1A4A5258, $06C6C2C4, $38487078, $2686A2A4, $12021210, $2F8FA3AC, $15C5D1D4,
$21416160, $03C3C3C0, $3484B0B4, $01414140, $12425250, $3D4D717C, $0D8D818C, $08080008,
$1F0F131C, $19899198, $00000000, $19091118, $04040004, $13435350, $37C7F3F4, $21C1E1E0,
$3DCDF1FC, $36467274, $2F0F232C, $27072324, $3080B0B0, $0B8B8388, $0E0E020C, $2B8BA3A8,
$2282A2A0, $2E4E626C, $13839390, $0D4D414C, $29496168, $3C4C707C, $09090108, $0A0A0208,
$3F8FB3BC, $2FCFE3EC, $33C3F3F0, $05C5C1C4, $07878384, $14041014, $3ECEF2FC, $24446064,
$1ECED2DC, $2E0E222C, $0B4B4348, $1A0A1218, $06060204, $21012120, $2B4B6368, $26466264,
$02020200, $35C5F1F4, $12829290, $0A8A8288, $0C0C000C, $3383B3B0, $3E4E727C, $10C0D0D0,
$3A4A7278, $07474344, $16869294, $25C5E1E4, $26062224, $00808080, $2D8DA1AC, $1FCFD3DC,
$2181A1A0, $30003030, $37073334, $2E8EA2AC, $36063234, $15051114, $22022220, $38083038,
$34C4F0F4, $2787A3A4, $05454144, $0C4C404C, $01818180, $29C9E1E8, $04848084, $17879394,
$35053134, $0BCBC3C8, $0ECEC2CC, $3C0C303C, $31417170, $11011110, $07C7C3C4, $09898188,
$35457174, $3BCBF3F8, $1ACAD2D8, $38C8F0F8, $14849094, $19495158, $02828280, $04C4C0C4,
$3FCFF3FC, $09494148, $39093138, $27476364, $00C0C0C0, $0FCFC3CC, $17C7D3D4, $3888B0B8,
$0F0F030C, $0E8E828C, $02424240, $23032320, $11819190, $2C4C606C, $1BCBD3D8, $2484A0A4,
$34043034, $31C1F1F0, $08484048, $02C2C2C0, $2F4F636C, $3D0D313C, $2D0D212C, $00404040,
$3E8EB2BC, $3E0E323C, $3C8CB0BC, $01C1C1C0, $2A8AA2A8, $3A8AB2B8, $0E4E424C, $15455154,
$3B0B3338, $1CCCD0DC, $28486068, $3F4F737C, $1C8C909C, $18C8D0D8, $0A4A4248, $16465254,
$37477374, $2080A0A0, $2DCDE1EC, $06464244, $3585B1B4, $2B0B2328, $25456164, $3ACAF2F8,
$23C3E3E0, $3989B1B8, $3181B1B0, $1F8F939C, $1E4E525C, $39C9F1F8, $26C6E2E4, $3282B2B0,
$31013130, $2ACAE2E8, $2D4D616C, $1F4F535C, $24C4E0E4, $30C0F0F0, $0DCDC1CC, $08888088,
$16061214, $3A0A3238, $18485058, $14C4D0D4, $22426260, $29092128, $07070304, $33033330,
$28C8E0E8, $1B0B1318, $05050104, $39497178, $10809090, $2A4A6268, $2A0A2228, $1A8A9298);
SS1: TXSBox = ($38380830, $E828C8E0, $2C2D0D21, $A42686A2, $CC0FCFC3, $DC1ECED2, $B03383B3, $B83888B0,
$AC2F8FA3, $60204060, $54154551, $C407C7C3, $44044440, $6C2F4F63, $682B4B63, $581B4B53,
$C003C3C3, $60224262, $30330333, $B43585B1, $28290921, $A02080A0, $E022C2E2, $A42787A3,
$D013C3D3, $90118191, $10110111, $04060602, $1C1C0C10, $BC3C8CB0, $34360632, $480B4B43,
$EC2FCFE3, $88088880, $6C2C4C60, $A82888A0, $14170713, $C404C4C0, $14160612, $F434C4F0,
$C002C2C2, $44054541, $E021C1E1, $D416C6D2, $3C3F0F33, $3C3D0D31, $8C0E8E82, $98188890,
$28280820, $4C0E4E42, $F436C6F2, $3C3E0E32, $A42585A1, $F839C9F1, $0C0D0D01, $DC1FCFD3,
$D818C8D0, $282B0B23, $64264662, $783A4A72, $24270723, $2C2F0F23, $F031C1F1, $70324272,
$40024242, $D414C4D0, $40014141, $C000C0C0, $70334373, $64274763, $AC2C8CA0, $880B8B83,
$F437C7F3, $AC2D8DA1, $80008080, $1C1F0F13, $C80ACAC2, $2C2C0C20, $A82A8AA2, $34340430,
$D012C2D2, $080B0B03, $EC2ECEE2, $E829C9E1, $5C1D4D51, $94148490, $18180810, $F838C8F0,
$54174753, $AC2E8EA2, $08080800, $C405C5C1, $10130313, $CC0DCDC1, $84068682, $B83989B1,
$FC3FCFF3, $7C3D4D71, $C001C1C1, $30310131, $F435C5F1, $880A8A82, $682A4A62, $B03181B1,
$D011C1D1, $20200020, $D417C7D3, $00020202, $20220222, $04040400, $68284860, $70314171,
$04070703, $D81BCBD3, $9C1D8D91, $98198991, $60214161, $BC3E8EB2, $E426C6E2, $58194951,
$DC1DCDD1, $50114151, $90108090, $DC1CCCD0, $981A8A92, $A02383A3, $A82B8BA3, $D010C0D0,
$80018181, $0C0F0F03, $44074743, $181A0A12, $E023C3E3, $EC2CCCE0, $8C0D8D81, $BC3F8FB3,
$94168692, $783B4B73, $5C1C4C50, $A02282A2, $A02181A1, $60234363, $20230323, $4C0D4D41,
$C808C8C0, $9C1E8E92, $9C1C8C90, $383A0A32, $0C0C0C00, $2C2E0E22, $B83A8AB2, $6C2E4E62,
$9C1F8F93, $581A4A52, $F032C2F2, $90128292, $F033C3F3, $48094941, $78384870, $CC0CCCC0,
$14150511, $F83BCBF3, $70304070, $74354571, $7C3F4F73, $34350531, $10100010, $00030303,
$64244460, $6C2D4D61, $C406C6C2, $74344470, $D415C5D1, $B43484B0, $E82ACAE2, $08090901,
$74364672, $18190911, $FC3ECEF2, $40004040, $10120212, $E020C0E0, $BC3D8DB1, $04050501,
$F83ACAF2, $00010101, $F030C0F0, $282A0A22, $5C1E4E52, $A82989A1, $54164652, $40034343,
$84058581, $14140410, $88098981, $981B8B93, $B03080B0, $E425C5E1, $48084840, $78394971,
$94178793, $FC3CCCF0, $1C1E0E12, $80028282, $20210121, $8C0C8C80, $181B0B13, $5C1F4F53,
$74374773, $54144450, $B03282B2, $1C1D0D11, $24250521, $4C0F4F43, $00000000, $44064642,
$EC2DCDE1, $58184850, $50124252, $E82BCBE3, $7C3E4E72, $D81ACAD2, $C809C9C1, $FC3DCDF1,
$30300030, $94158591, $64254561, $3C3C0C30, $B43686B2, $E424C4E0, $B83B8BB3, $7C3C4C70,
$0C0E0E02, $50104050, $38390931, $24260622, $30320232, $84048480, $68294961, $90138393,
$34370733, $E427C7E3, $24240420, $A42484A0, $C80BCBC3, $50134353, $080A0A02, $84078783,
$D819C9D1, $4C0C4C40, $80038383, $8C0F8F83, $CC0ECEC2, $383B0B33, $480A4A42, $B43787B3);
SS2: TXSBox = ($A1A82989, $81840585, $D2D416C6, $D3D013C3, $50541444, $111C1D0D, $A0AC2C8C, $21242505,
$515C1D4D, $43400343, $10181808, $121C1E0E, $51501141, $F0FC3CCC, $C2C80ACA, $63602343,
$20282808, $40440444, $20202000, $919C1D8D, $E0E020C0, $E2E022C2, $C0C808C8, $13141707,
$A1A42585, $838C0F8F, $03000303, $73783B4B, $B3B83B8B, $13101303, $D2D012C2, $E2EC2ECE,
$70703040, $808C0C8C, $333C3F0F, $A0A82888, $32303202, $D1DC1DCD, $F2F436C6, $70743444,
$E0EC2CCC, $91941585, $03080B0B, $53541747, $505C1C4C, $53581B4B, $B1BC3D8D, $01000101,
$20242404, $101C1C0C, $73703343, $90981888, $10101000, $C0CC0CCC, $F2F032C2, $D1D819C9,
$202C2C0C, $E3E427C7, $72703242, $83800383, $93981B8B, $D1D011C1, $82840686, $C1C809C9,
$60602040, $50501040, $A3A02383, $E3E82BCB, $010C0D0D, $B2B43686, $929C1E8E, $434C0F4F,
$B3B43787, $52581A4A, $C2C406C6, $70783848, $A2A42686, $12101202, $A3AC2F8F, $D1D415C5,
$61602141, $C3C003C3, $B0B43484, $41400141, $52501242, $717C3D4D, $818C0D8D, $00080808,
$131C1F0F, $91981989, $00000000, $11181909, $00040404, $53501343, $F3F437C7, $E1E021C1,
$F1FC3DCD, $72743646, $232C2F0F, $23242707, $B0B03080, $83880B8B, $020C0E0E, $A3A82B8B,
$A2A02282, $626C2E4E, $93901383, $414C0D4D, $61682949, $707C3C4C, $01080909, $02080A0A,
$B3BC3F8F, $E3EC2FCF, $F3F033C3, $C1C405C5, $83840787, $10141404, $F2FC3ECE, $60642444,
$D2DC1ECE, $222C2E0E, $43480B4B, $12181A0A, $02040606, $21202101, $63682B4B, $62642646,
$02000202, $F1F435C5, $92901282, $82880A8A, $000C0C0C, $B3B03383, $727C3E4E, $D0D010C0,
$72783A4A, $43440747, $92941686, $E1E425C5, $22242606, $80800080, $A1AC2D8D, $D3DC1FCF,
$A1A02181, $30303000, $33343707, $A2AC2E8E, $32343606, $11141505, $22202202, $30383808,
$F0F434C4, $A3A42787, $41440545, $404C0C4C, $81800181, $E1E829C9, $80840484, $93941787,
$31343505, $C3C80BCB, $C2CC0ECE, $303C3C0C, $71703141, $11101101, $C3C407C7, $81880989,
$71743545, $F3F83BCB, $D2D81ACA, $F0F838C8, $90941484, $51581949, $82800282, $C0C404C4,
$F3FC3FCF, $41480949, $31383909, $63642747, $C0C000C0, $C3CC0FCF, $D3D417C7, $B0B83888,
$030C0F0F, $828C0E8E, $42400242, $23202303, $91901181, $606C2C4C, $D3D81BCB, $A0A42484,
$30343404, $F1F031C1, $40480848, $C2C002C2, $636C2F4F, $313C3D0D, $212C2D0D, $40400040,
$B2BC3E8E, $323C3E0E, $B0BC3C8C, $C1C001C1, $A2A82A8A, $B2B83A8A, $424C0E4E, $51541545,
$33383B0B, $D0DC1CCC, $60682848, $737C3F4F, $909C1C8C, $D0D818C8, $42480A4A, $52541646,
$73743747, $A0A02080, $E1EC2DCD, $42440646, $B1B43585, $23282B0B, $61642545, $F2F83ACA,
$E3E023C3, $B1B83989, $B1B03181, $939C1F8F, $525C1E4E, $F1F839C9, $E2E426C6, $B2B03282,
$31303101, $E2E82ACA, $616C2D4D, $535C1F4F, $E0E424C4, $F0F030C0, $C1CC0DCD, $80880888,
$12141606, $32383A0A, $50581848, $D0D414C4, $62602242, $21282909, $03040707, $33303303,
$E0E828C8, $13181B0B, $01040505, $71783949, $90901080, $62682A4A, $22282A0A, $92981A8A);
SS3: TXSBox = ($08303838, $C8E0E828, $0D212C2D, $86A2A426, $CFC3CC0F, $CED2DC1E, $83B3B033, $88B0B838,
$8FA3AC2F, $40606020, $45515415, $C7C3C407, $44404404, $4F636C2F, $4B63682B, $4B53581B,
$C3C3C003, $42626022, $03333033, $85B1B435, $09212829, $80A0A020, $C2E2E022, $87A3A427,
$C3D3D013, $81919011, $01111011, $06020406, $0C101C1C, $8CB0BC3C, $06323436, $4B43480B,
$CFE3EC2F, $88808808, $4C606C2C, $88A0A828, $07131417, $C4C0C404, $06121416, $C4F0F434,
$C2C2C002, $45414405, $C1E1E021, $C6D2D416, $0F333C3F, $0D313C3D, $8E828C0E, $88909818,
$08202828, $4E424C0E, $C6F2F436, $0E323C3E, $85A1A425, $C9F1F839, $0D010C0D, $CFD3DC1F,
$C8D0D818, $0B23282B, $46626426, $4A72783A, $07232427, $0F232C2F, $C1F1F031, $42727032,
$42424002, $C4D0D414, $41414001, $C0C0C000, $43737033, $47636427, $8CA0AC2C, $8B83880B,
$C7F3F437, $8DA1AC2D, $80808000, $0F131C1F, $CAC2C80A, $0C202C2C, $8AA2A82A, $04303434,
$C2D2D012, $0B03080B, $CEE2EC2E, $C9E1E829, $4D515C1D, $84909414, $08101818, $C8F0F838,
$47535417, $8EA2AC2E, $08000808, $C5C1C405, $03131013, $CDC1CC0D, $86828406, $89B1B839,
$CFF3FC3F, $4D717C3D, $C1C1C001, $01313031, $C5F1F435, $8A82880A, $4A62682A, $81B1B031,
$C1D1D011, $00202020, $C7D3D417, $02020002, $02222022, $04000404, $48606828, $41717031,
$07030407, $CBD3D81B, $8D919C1D, $89919819, $41616021, $8EB2BC3E, $C6E2E426, $49515819,
$CDD1DC1D, $41515011, $80909010, $CCD0DC1C, $8A92981A, $83A3A023, $8BA3A82B, $C0D0D010,
$81818001, $0F030C0F, $47434407, $0A12181A, $C3E3E023, $CCE0EC2C, $8D818C0D, $8FB3BC3F,
$86929416, $4B73783B, $4C505C1C, $82A2A022, $81A1A021, $43636023, $03232023, $4D414C0D,
$C8C0C808, $8E929C1E, $8C909C1C, $0A32383A, $0C000C0C, $0E222C2E, $8AB2B83A, $4E626C2E,
$8F939C1F, $4A52581A, $C2F2F032, $82929012, $C3F3F033, $49414809, $48707838, $CCC0CC0C,
$05111415, $CBF3F83B, $40707030, $45717435, $4F737C3F, $05313435, $00101010, $03030003,
$44606424, $4D616C2D, $C6C2C406, $44707434, $C5D1D415, $84B0B434, $CAE2E82A, $09010809,
$46727436, $09111819, $CEF2FC3E, $40404000, $02121012, $C0E0E020, $8DB1BC3D, $05010405,
$CAF2F83A, $01010001, $C0F0F030, $0A22282A, $4E525C1E, $89A1A829, $46525416, $43434003,
$85818405, $04101414, $89818809, $8B93981B, $80B0B030, $C5E1E425, $48404808, $49717839,
$87939417, $CCF0FC3C, $0E121C1E, $82828002, $01212021, $8C808C0C, $0B13181B, $4F535C1F,
$47737437, $44505414, $82B2B032, $0D111C1D, $05212425, $4F434C0F, $00000000, $46424406,
$CDE1EC2D, $48505818, $42525012, $CBE3E82B, $4E727C3E, $CAD2D81A, $C9C1C809, $CDF1FC3D,
$00303030, $85919415, $45616425, $0C303C3C, $86B2B436, $C4E0E424, $8BB3B83B, $4C707C3C,
$0E020C0E, $40505010, $09313839, $06222426, $02323032, $84808404, $49616829, $83939013,
$07333437, $C7E3E427, $04202424, $84A0A424, $CBC3C80B, $43535013, $0A02080A, $87838407,
$C9D1D819, $4C404C0C, $83838003, $8F838C0F, $CEC2CC0E, $0B33383B, $4A42480A, $87B3B437);
KC: array[0..15] of longint = ($9E3779B9, $3C6EF373, $78DDE6E6, $F1BBCDCC,
$E3779B99, $C6EF3733, $8DDE6E67, $1BBCDCCF,
$3779B99E, $6EF3733C, $DDE6E678, $BBCDCCF1,
$779B99E3, $EF3733C6, $DE6E678D, $BCDCCF1B);
{$ifdef StrictLong}
{$warnings on}
{$ifdef RangeChecks_on}
{$R+}
{$endif}
{$endif}
{$ifndef BIT16}
{32/64-bit code}
{$ifdef BIT64}
{---------------------------------------------------------------------------}
function RB(A: longint): longint; {$ifdef HAS_INLINE} inline; {$endif}
{-reverse byte order in longint}
begin
RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24);
end;
{$else}
{$ifdef CPUARM}
{---------------------------------------------------------------------------}
function RB(A: longint): longint; {$ifdef HAS_INLINE} inline; {$endif}
{-reverse byte order in longint}
begin
RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24);
end;
{$else}
{---------------------------------------------------------------------------}
function RB(A: longint): longint; assembler; {&frame-}
{-reverse byte order in longint}
asm
{$ifdef LoadArgs}
mov eax,[A]
{$endif}
xchg al,ah
rol eax,16
xchg al,ah
end;
{$endif}
{$endif}
{$else} {16-bit}
{---------------------------------------------------------------------------}
function RB(A: longint): longint;
{-reverse byte order in longint}
inline(
$58/ {pop ax }
$5A/ {pop dx }
$86/$C6/ {xchg dh,al}
$86/$E2); {xchg dl,ah}
{$endif}
{$ifdef BASM16}
{---------------------------------------------------------------------------}
procedure SEA_XorBlock({$ifdef CONST} const {$else} var {$endif} B1, B2: TSEABlock; var B3: TSEABlock);
{-xor two blocks, result in third}
begin
asm
mov di,ds
lds si,[B1]
db $66; mov ax,[si]
db $66; mov bx,[si+4]
db $66; mov cx,[si+8]
db $66; mov dx,[si+12]
lds si,[B2]
db $66; xor ax,[si]
db $66; xor bx,[si+4]
db $66; xor cx,[si+8]
db $66; xor dx,[si+12]
lds si,[B3]
db $66; mov [si],ax
db $66; mov [si+4],bx
db $66; mov [si+8],cx
db $66; mov [si+12],dx
mov ds,di
end;
end;
{$else}
{---------------------------------------------------------------------------}
procedure SEA_XorBlock({$ifdef CONST} const {$else} var {$endif} B1, B2: TSEABlock; var B3: TSEABlock);
{-xor two blocks, result in third}
var
a1: TWA4 absolute B1;
a2: TWA4 absolute B2;
a3: TWA4 absolute B3;
begin
a3[0] := a1[0] xor a2[0];
a3[1] := a1[1] xor a2[1];
a3[2] := a1[2] xor a2[2];
a3[3] := a1[3] xor a2[3];
end;
{$endif BASM16}
{$ifndef BIT16}
{---------------------------------------------------------------------------}
function SG(x: longint): longint; {$ifdef HAS_INLINE} inline; {$endif}
begin
SG := SS3[x shr 24] xor SS2[x shr 16 and $FF] xor SS1[x shr 8 and $FF] xor SS0[x and $FF];
end;
{$else}
{$ifdef BASM16}
{---------------------------------------------------------------------------}
function SG(x: longint): longint; near; assembler;
asm
{ op eax, mem[4*bx] is calculated as }
{ lea esi, [ebx + 2*ebx] }
{ op eax, mem[ebx+esi] }
{ lea esi,[ebx+2*ebx] = db $66,$67,$8D,$34,$5B; }
mov cx,word ptr [x]
mov dx,word ptr [x+2]
db $66; sub bx,bx
mov bl,cl
db $66,$67,$8D,$34,$5B;
db $66; mov ax,word ptr SS0[bx+si]
mov bl,ch
db $66,$67,$8D,$34,$5B;
db $66; xor ax,word ptr SS1[bx+si]
mov bl,dl
db $66,$67,$8D,$34,$5B;
db $66; xor ax,word ptr SS2[bx+si]
mov bl,dh
db $66,$67,$8D,$34,$5B;
db $66; xor ax,word ptr SS3[bx+si]
db $66; mov dx,ax
db $66; shr dx,16
end;
{$else}
{---------------------------------------------------------------------------}
function SG(x: longint): longint;
var
b: packed array[0..3] of byte absolute x;
begin
SG := SS3[b[3]] xor SS2[b[2]] xor SS1[b[1]] xor SS0[b[0]];
end;
{$endif}
{$endif}
{---------------------------------------------------------------------------}
procedure SEA_SetFastInit(value: boolean);
{-set FastInit variable}
begin
FastInit := value;
end;
{---------------------------------------------------------------------------}
function SEA_GetFastInit: boolean;
{-Returns FastInit variable}
begin
SEA_GetFastInit := FastInit;
end;
{---------------------------------------------------------------------------}
procedure SEA_Reset(var ctx: TSEAContext);
{-Clears ctx fields bLen and Flag}
begin
with ctx do begin
bLen :=0;
Flag :=0;
end;
end;
{---------------------------------------------------------------------------}
function SEA_Init({$ifdef CONST} const {$else} var {$endif} Key; KeyBits: word; var ctx: TSEAContext): integer;
{-SEED context/round key initialization}
var
LK: TWA4;
i,j: integer;
{$ifndef BIT16}
T: longint;
{$else}
H: byte;
B: TSEABlock absolute LK;
{$endif}
begin
if KeyBits<>128 then begin
SEA_Init := SEA_Err_Invalid_Key_Size;
exit;
end;
SEA_Init := 0;
if FastInit then begin
{Clear only the necessary context data at init. IV and buf}
{remain uninitialized, other fields are initialized below.}
SEA_Reset(ctx);
{$ifdef CONST}
ctx.IncProc := nil;
{$else}
{TP5-6 do not like IncProc := nil;}
fillchar(ctx.IncProc, sizeof(ctx.IncProc), 0);
{$endif}
end
else fillchar(ctx, sizeof(ctx), 0);
for i:=0 to 3 do LK[i] := RB(TWA4(Key)[i]);
j := 0;
for i:=0 to 15 do begin
ctx.RK[j] := SG(LK[0]+LK[2]-KC[i]); inc(j);
ctx.RK[j] := SG(LK[1]-LK[3]+KC[i]); inc(j);
{$ifndef BIT16}
if odd(i) then begin
T := LK[3] shr 24;
LK[3] := (LK[3] shl 8) or (LK[2] shr 24);
LK[2] := (LK[2] shl 8) or T;
end
else begin
T := LK[0] and $FF;
LK[0] := (LK[0] shr 8) or ((LK[1] and $FF) shl 24);
LK[1] := (LK[1] shr 8) or (T shl 24);
end
{$else}
{for BIT16 use move for 8 bit rotation of 64 bit}
if odd(i) then begin
H := B[15];
move(B[8],B[9],7);
B[8] := H;
end
else begin
H := B[0];
move(B[1],B[0],7);
B[7] := H;
end;
{$endif}
end;
end;
{---------------------------------------------------------------------------}
procedure SEA_Encrypt(var ctx: TSEAContext; {$ifdef CONST} const {$else} var {$endif} BI: TSEABlock; var BO: TSEABlock);
{-encrypt one block (in ECB mode)}
var
T0,T1: longint;
B: TWA4;
i,j: integer;
begin
B[0] := RB(TWA4(BI)[0]);
B[1] := RB(TWA4(BI)[1]);
B[2] := RB(TWA4(BI)[2]);
B[3] := RB(TWA4(BI)[3]);
with ctx do begin
j:=0;
for i:=1 to 8 do begin
{First part of double round}
T0 := B[2] xor RK[j];
T1 := SG(T0 xor B[3] xor RK[j+1]);
T0 := SG(T1 + T0);
T1 := SG(T1 + T0);
B[1] := B[1] xor T1;
B[0] := B[0] xor (T0 + T1);
{Second part of double round}
T0 := B[0] xor RK[j+2];
T1 := SG(T0 xor B[1] xor RK[j+3]);
T0 := SG(T1 + T0);
T1 := SG(T1 + T0);
B[3] := B[3] xor T1;
B[2] := B[2] xor (T0 + T1);
inc(j,4);
end;
end;
TWA4(BO)[0] := RB(B[2]);
TWA4(BO)[1] := RB(B[3]);
TWA4(BO)[2] := RB(B[0]);
TWA4(BO)[3] := RB(B[1]);
end;
{---------------------------------------------------------------------------}
procedure SEA_Decrypt(var ctx: TSEAContext; {$ifdef CONST} const {$else} var {$endif} BI: TSEABlock; var BO: TSEABlock);
{-decrypt one block (in ECB mode)}
var
T0,T1: longint;
B: TWA4;
i,j: integer;
begin
B[0] := RB(TWA4(BI)[0]);
B[1] := RB(TWA4(BI)[1]);
B[2] := RB(TWA4(BI)[2]);
B[3] := RB(TWA4(BI)[3]);
with ctx do begin
j := 28;
for i:=1 to 8 do begin
{First part of double round}
T0 := B[2] xor RK[j+2];
T1 := SG(T0 xor B[3] xor RK[j+3]);
T0 := SG(T1 + T0);
T1 := SG(T1 + T0);
B[1] := B[1] xor T1;
B[0] := B[0] xor (T0 + T1);
{Second part of double round}
T0 := B[0] xor RK[j];
T1 := SG(T0 xor B[1] xor RK[j+1]);
T0 := SG(T1 + T0);
T1 := SG(T1 + T0);
B[3] := B[3] xor T1;
B[2] := B[2] xor (T0 + T1);
dec(j,4);
end;
end;
TWA4(BO)[0] := RB(B[2]);
TWA4(BO)[1] := RB(B[3]);
TWA4(BO)[2] := RB(B[0]);
TWA4(BO)[3] := RB(B[1]);
end;
end.
|
unit uLibraries;
interface
uses ShareMem,windows, classes, SysUtils, uTypes, uErrorConst;
type
TDllInfoProc = function:TDllInfo; stdcall;
TDllTerminateProc = procedure; stdcall;
TDllRunProc = procedure; stdcall;
TDllInitializeProc = procedure; stdcall;
TDllLastErrorProc = function :string; stdcall;
TDllSettingsProc = procedure; stdcall;
PLibrary = ^Tlibrary;
TLibrary = class
private
// Dll var's
FDllPath: string;
FDllHandle: THandle;
FDllInfo: TDllInfo;
FActivate: boolean;
// Dll procedure's
FLoadDllInfo: TDllInfoProc;
FRun: TDllRunProc;
FTerminate: TDllTerminateProc;
FInitialize: TDllTerminateProc;
FLstErrorStr: TDllLastErrorProc;
FSettings: TDllSettingsProc;
public
LAST_ERROR: integer;
constructor Create(ADllName:String; var IsValidModule:Boolean);
destructor Destroy; override;
// Call procedure's of Dll
function LoadDllInfo:TDllInfo;
procedure Run;
procedure Terminate;
procedure Initialize;
function LastError:string;
procedure Settings;
procedure ShowErrorMessage;
// property's
property DllHandle : THandle read FDllHandle;
property DllPath : string read FDllPath;
property DllInfo : TDllInfo read FDllInfo;
property Activate: boolean read FActivate;
end;
implementation
{ TLibrary }
constructor TLibrary.Create(ADllName: String; var IsValidModule: Boolean);
begin
LAST_ERROR:= 0;
if not FileExists(ADllName) then
Begin
LAST_ERROR:= ERROR_DLL_NOTFOUND;
IsValidModule:= false;
ShowErrorMessage;
exit;
End;
FDLLHandle:= LoadLibrary(PChar(ADllName));
if FDllHandle = 0 then
Begin
LAST_ERROR:= ERROR_DLL_LOAD_FAILED;
IsValidModule:= false;
ShowErrorMessage;
exit;
End;
@FLoadDllInfo := GetProcAddress(FDllHandle,'DllInfo');
if @FLoadDllInfo = nil then
Begin
LAST_ERROR:= ERROR_DLL_NOT_VALID;
IsValidModule:= false;
ShowErrorMessage;
exit;
End;
FDllPath:= ADllName;
IsValidModule:= true;
FDllInfo:= LoadDllInfo;
end;
destructor TLibrary.Destroy;
begin
FreeLibrary(DllHandle);
inherited;
end;
function TLibrary.LastError:string;
begin
@FLstErrorStr := GetProcAddress(DllHandle,'DllLastError');
if @FLstErrorStr = nil then
Begin
LAST_ERROR:= ERROR_DLL_FUNC_NOTFOUND;
ShowErrorMessage;
exit;
End;
Result:= FLstErrorStr;
end;
procedure TLibrary.Initialize;
begin
@FInitialize := GetProcAddress(DllHandle,'DllInitialize');
if @FInitialize = nil then
Begin
LAST_ERROR:= ERROR_DLL_FUNC_NOTFOUND;
ShowErrorMessage;
exit;
End;
FInitialize;
end;
function TLibrary.LoadDllInfo: TDllInfo;
begin
Result:= FLoadDllInfo;
end;
procedure TLibrary.Run;
begin
if DllHandle = 0 then
Begin
FDLLHandle:= LoadLibrary(PChar(FDllPath));
End;
@FRun:= GetProcAddress(DllHandle,'DllRun');
if @FRun = nil then
Begin
LAST_ERROR:= ERROR_DLL_FUNC_NOTFOUND;
ShowErrorMessage;
exit;
End;
FRun;
FActivate:= true;
end;
procedure TLibrary.Settings;
begin
@FSettings := GetProcAddress(DllHandle,'DllSettings');
if @FSettings = nil then
Begin
LAST_ERROR:= ERROR_DLL_FUNC_NOTFOUND;
ShowErrorMessage;
exit;
End;
FSettings;
end;
procedure TLibrary.ShowErrorMessage;
Var
sMessage: string;
sTitle: string;
begin
case LAST_ERROR of
0: sMessage:= 'All ok!';
ERROR_DLL_NOTFOUND: sMessage:= 'Dll not found.';
ERROR_DLL_NOT_VALID: sMessage:= 'Is not valid DLL.';
ERROR_DLL_LOAD_FAILED: sMessage:= 'Can''t load DLL file.';
ERROR_DLL_FUNC_NOTFOUND: sMessage:= 'Function not found in loaded DLL.';
end;
sTitle:= 'Libraries error ('+PChar(IntToStr(LAST_ERROR))+')';
MessageBox(0,PChar(sMessage),PChar(sTitle),MB_ICONERROR);
LAST_ERROR:= 0;
end;
procedure TLibrary.Terminate;
begin
@FTerminate := GetProcAddress(DllHandle,'DllTerminate');
if @FTerminate = nil then
Begin
LAST_ERROR:= ERROR_DLL_FUNC_NOTFOUND;
exit;
End;
FTerminate;
FActivate:= false;
end;
Begin
end.
|
unit UntInfoUsuario;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
UntLayoutBase, FMX.Objects, FMX.Layouts, FMX.Controls.Presentation,
System.Actions, FMX.ActnList, FMX.StdActns, FMX.MediaLibrary.Actions,
System.JSON,
System.JSON.Readers,
System.StrUtils,
System.NetEncoding, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, Data.Bind.EngExt, Fmx.Bind.DBEngExt, System.Rtti,
System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.Components,
Data.Bind.DBScope, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
ksTabControl,
UntLib, FMX.Edit, FMX.ListBox,
ULGTDataSetHelper,
Funcoes;
type
TFrmInfoUsuario = class(TFrmLayoutBase)
lytGeral: TLayout;
lytTopo: TLayout;
lytFotoDados: TLayout;
lytFoto: TLayout;
lytDados: TLayout;
cirFundo: TCircle;
cirFoto: TCircle;
lblNomeUsuario: TLabel;
lblNomeCompleto: TLabel;
lblCPF: TLabel;
lblEmail: TLabel;
imgEscolherFoto: TImage;
rctEscolherFoto: TRectangle;
btnCamera: TButton;
btnGaleria: TButton;
rctBackground: TRectangle;
actAcoes: TActionList;
actGaleria: TTakePhotoFromLibraryAction;
actCamera: TTakePhotoFromCameraAction;
btnCancelar: TButton;
tbCtrl: TksTabControl;
tbitemMain: TksTabItem;
toolSupView: TToolBar;
Label1: TLabel;
btnMenu: TButton;
btnEditar: TButton;
tbitemEdicao: TksTabItem;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
LinkPropertyToFieldText: TLinkPropertyToField;
LinkPropertyToFieldText2: TLinkPropertyToField;
LinkPropertyToFieldText3: TLinkPropertyToField;
ToolBar1: TToolBar;
Label2: TLabel;
btnBack: TButton;
btnSalvar: TButton;
lsboxEdicao: TListBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ListBoxItem3: TListBoxItem;
edtNomeCompleto: TEdit;
edtEmail: TEdit;
edtCPF: TEdit;
LinkControlToField1: TLinkControlToField;
LinkControlToField2: TLinkControlToField;
LinkPropertyToFieldText4: TLinkPropertyToField;
LinkControlToField3: TLinkControlToField;
LinkPropertyToFieldFillBitmapBitmap: TLinkPropertyToField;
procedure Button3Click(Sender: TObject);
procedure actGaleriaDidFinishTaking(Image: TBitmap);
procedure actCameraDidFinishTaking(Image: TBitmap);
procedure imgEscolherFotoClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure rctBackgroundClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
procedure btnEditarClick(Sender: TObject);
procedure cirFotoClick(Sender: TObject);
procedure btnBackClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
procedure MostrarPopup;
procedure EsconderPopup;
procedure AtualizarFoto(Image: TBitmap);
procedure GravarPerfil;
public
{ Public declarations }
end;
var
FrmInfoUsuario: TFrmInfoUsuario;
implementation
uses
UntDM,
UntDmREST;
{$R *.fmx}
procedure TFrmInfoUsuario.actCameraDidFinishTaking(Image: TBitmap);
begin
inherited;
AtualizarFoto(Image);
end;
procedure TFrmInfoUsuario.actGaleriaDidFinishTaking(Image: TBitmap);
begin
inherited;
AtualizarFoto(Image);
end;
procedure TFrmInfoUsuario.btnBackClick(Sender: TObject);
begin
inherited;
if DM.memUsuario.State in dsEditModes then
DM.memUsuario.Cancel;
TLibrary.MudarAba(tbCtrl, tbitemMain);
end;
procedure TFrmInfoUsuario.btnCancelarClick(Sender: TObject);
begin
inherited;
EsconderPopup;
end;
procedure TFrmInfoUsuario.btnEditarClick(Sender: TObject);
begin
inherited;
TLibrary.MudarAba(tbCtrl, tbitemEdicao);
end;
procedure TFrmInfoUsuario.btnSalvarClick(Sender: TObject);
begin
inherited;
GravarPerfil;
end;
procedure TFrmInfoUsuario.Button3Click(Sender: TObject);
begin
inherited;
(*
with TOpenDialog.Create(Self) do
begin
if execute then
begin
memUsuario.Active := True;
memUsuario.Append;
Image1.Bitmap.LoadFromFile(Filename);
memUsuariofoto.Assign(Image1.Bitmap);
memUsuario.Post;
end;
end;
*)
end;
procedure TFrmInfoUsuario.cirFotoClick(Sender: TObject);
begin
inherited;
{$IFDEF MSWINDOWS}
with TOpenDialog.Create(Self) do
begin
if Execute then
begin
//cirFoto.Fill.Bitmap.Bitmap.LoadFromFile(Filename);
if DM.memUsuario.State in [dsBrowse] then
DM.memUsuario.Edit;
DM.memUsuariofoto.LoadFromFile(Filename);
end;
end;
{$ENDIF}
end;
procedure TFrmInfoUsuario.EsconderPopup;
begin
rctEscolherFoto.AnimateFloat('opacity', 0);
rctBackground.AnimateFloatWait('opacity', 0);
rctBackground.Visible := False;
rctEscolherFoto.Visible := False
end;
procedure TFrmInfoUsuario.AtualizarFoto(Image: TBitmap);
begin
//cirFoto.Fill.Bitmap.Bitmap.Assign(Image);
if DM.memUsuario.State in [dsBrowse] then
DM.memUsuario.Edit;
DM.memUsuariofoto.Assign(Image);
EsconderPopup;
end;
procedure TFrmInfoUsuario.GravarPerfil;
var
jrContent : TJSONArray;
begin
//1. Validar os campos vazios
//2. Validar o CPF offline
//3. Validar os dados online
if edtNomeCompleto.Text.Equals(EmptyStr) then
begin
ShowMessage('Nome Completo é de preenchimento obrigatório.');
edtNomeCompleto.SetFocus;
end;
if edtEmail.Text.Equals(EmptyStr) then
begin
ShowMessage('Email é de preenchimento obrigatório.');
edtEmail.SetFocus;
end;
if edtCPF.Text.Equals(EmptyStr) then
begin
ShowMessage('CPF é de preenchimento obrigatório.');
edtCPF.SetFocus;
end;
if ValidaCPF(edtCPF.Text) then
begin
jrContent := DM.memUsuario.DataSetToJSON;
DmREST.AtualizarPerfil(jrContent, TLibrary.ID);
end
else
begin
ShowMessage('CPF digitado inválido.');
edtCPF.SetFocus;
end;
end;
procedure TFrmInfoUsuario.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
if DM.memUsuario.State in dsEditModes then
begin
DM.memUsuario.Post;
GravarPerfil;
end;
end;
procedure TFrmInfoUsuario.FormCreate(Sender: TObject);
begin
inherited;
EsconderPopup;
tbCtrl.ActiveTab := tbitemMain;
tbCtrl.TabPosition := TksTabBarPosition.ksTbpNone;
DmREST.Perfil(TLibrary.Usuario);
//if not (DM.memUsuariofoto.IsNull) then
//begin
//cirFoto.Fill.Bitmap.Bitmap.Assign(DM.memUsuariofoto);
//end;
DM.memUsuario.Edit;
{$IFDEF MSWINDOWS}
btnSalvar.Width := 80;
btnBack.Width := 80;
{$ENDIF}
end;
procedure TFrmInfoUsuario.imgEscolherFotoClick(Sender: TObject);
begin
inherited;
MostrarPopup;
end;
procedure TFrmInfoUsuario.MostrarPopup;
begin
rctBackground.Opacity := 0;
rctBackground.Align := TAlignLayout.Contents;
rctBackground.BringToFront;
rctBackground.Visible := True;
rctBackground.AnimateFloat('opacity', 0.5);
rctEscolherFoto.Opacity := 0;
rctEscolherFoto.Align := TAlignLayout.Center;
rctEscolherFoto.BringToFront;
rctEscolherFoto.Visible := True;
rctEscolherFoto.AnimateFloatWait('opacity', 1);
end;
procedure TFrmInfoUsuario.rctBackgroundClick(Sender: TObject);
begin
inherited;
EsconderPopup;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.