text stringlengths 14 6.51M |
|---|
(*****************************************************************************
* Pascal Solution to "Found in the Shuffle" from the *
* *
* Seventh Annual UCF ACM UPE High School Programming Tournament *
* May 15, 1993 *
* *
*****************************************************************************)
(************************************************************************
Problem: Found in the Shuffle
File Name: deck.pas
Solution By: Gregg Hamilton
************************************************************************)
Const
(* This string is used in determining if two cards are in sequence. *)
sequence = 'A23456789TJQK' ;
Var
deck : string[104] ; (* Stores the list of cards *)
temp : string[52] ; (* Temporary string for reading in cards *)
inFile : text ; (* Input file handle *)
count, (* Sequence counter *)
index, (* Position in deck *)
best, (* Longest Sequence so far *)
cur_pos : integer ; (* Current position in sequence string *)
cur_suit : char ; (* Current Same-Suit *)
Begin
(* Set up input file. *)
assign( inFile, 'deck.in' ) ;
reset( inFile ) ;
(* Loop through all input data. *)
while not eof( inFile ) do
Begin
(* There should not be any blank lines at the bottom of the input *)
(* file, but it's better to be safe than sorry! The following check *)
(* will take care of them. *)
if eoln( inFile ) then
readln( inFile )
else
Begin
(* Read in an input deck and merge it into one line (this will *)
(* eliminate a lot of code to deal with special cases later). *)
readln( inFile, deck ) ;
readln( inFile, temp ) ;
deck := deck + temp ;
(* Initialization for longest Same-Suit Sequence search. Start *)
(* index at second suit character, and consider the first suit *)
(* character to be a Same-Suit Sequence of length one. *)
index := 4 ;
cur_suit := deck[2] ;
count := 1 ;
best := 0 ;
(* Loop through the suit characters in the deck *)
while index <= 104 do
Begin
(* If the suit matches the current suit, increment the count. *)
if deck[index] = cur_suit then
inc( count )
else
Begin
(* Start of a new Same-Suit Sequence, save the last count if *)
(* it's the best so far, and reinitialize the current suit *)
(* and count. *)
if count > best then
best := count ;
cur_suit := deck[index] ;
count := 1 ;
End ;
(* Increment to the next suit character. *)
index := index + 2 ;
End ;
(* Check to see if the final count was the best. *)
if count > best then
best := count ;
(* Print the longest Same-Suit Sequence. *)
writeln( 'Longest same-suit sequence: ', best:0 ) ;
(* Initialization for longest Ascending Sequence search. *)
(* Start index at the second "value" character, and consider *)
(* the first "value" to be a Sequence of length one. *)
index := 3 ;
cur_pos := pos( deck[1], sequence ) ;
count := 1 ;
best := 0 ;
(* Loop through the "value" characters in the deck *)
while index <= 103 do
Begin
(* If the position of the "value" in the sequence string is *)
(* one past the position of the last "value", increment the *)
(* current sequence position and the Sequence count. *)
if ( pos( deck[index], sequence ) - 1 ) = cur_pos then
Begin
inc( cur_pos ) ;
inc( count ) ;
End
else
Begin
(* This take care of the special case of a King to Ace *)
(* sequence continuation. *)
if ( cur_pos = 13 ) and ( deck[index] = 'A' ) then
Begin
cur_pos := 1 ;
inc( count ) ;
End
else
Begin
(* Start of a new Ascending Sequence, save the last count *)
(* if it's the best so far, and reinitialize the current *)
(* "value" position and count. *)
if count > best then
best := count ;
count := 1 ;
cur_pos := pos( deck[index], sequence ) ;
End ;
End ;
(* Increment to the next "value" character. *)
index := index + 2 ;
End ;
(* Check to see if the final count was the best. *)
if count > best then
best := count ;
(* Print the longest Ascending Sequence. *)
writeln( 'Longest ascending sequence: ', best:0 ) ;
writeln ;
End ; (* End of else not eoln *)
End ; (* End of while not eof *)
End.
|
unit uSysInit;
interface
uses SysUtils, IniFiles, Forms;
implementation
uses uPubFunLib, uSysObj, uConst, uDBAccess, UMsgBox, uDmMain;
function ConnectService: Boolean;
var
Ini: TIniFile;
begin
DBAccess := TDBAccess.Create(nil);
try
Ini := TIniFile.Create(Sys.ConfigPath + 'service.ini');
try
with DmMain.ConMain.Params do
begin
Clear;
Add('DriverName=' + Ini.ReadString('Service', 'DriverName', 'DataSnap'));
Add('HostName=' + Ini.ReadString('Service', 'HostName', '127.0.0.7'));
Add('ConnectTimeout=' + Ini.ReadString('Service', 'ConnectTimeout', '2000'));
Add('User_Name=' + Ini.ReadString('Service', 'User_Name', ''));
Add('Password=' + Ini.ReadString('Service', 'Password', ''));
Add('Port=' + Ini.ReadString('Service', 'Port', '211'));
end;
finally
Ini.Free;
end;
DmMain.ConMain.Connected := True;
DBAccess.Connection := DmMain.ConMain.DBXConnection;
Result := True;
except
Result := False;
end;
end;
procedure InitiaApplication;
var
lSkin: string;
begin
Sys.AppPath := ExtractFilePath(ParamStr(0));
Sys.ConfigPath := Sys.AppPath + 'config\';
DmMain := TDmMain.Create(nil);
lSkin := Sys.AppPath + ReadString(Sys.ConfigPath + 'skin.ini',
'skin', 'file', 'skin\Blue.skinres');
DmMain.LoadSysSkin(lSkin);
// 连接DataSnap服务
if not ConnectService then
begin
ShowMsg('服务连接失败,请确认服务是否正常启动!', '提示');
Application.Terminate;
Exit;
end;
end;
procedure FinaApplication;
begin
if Assigned(DBAccess) then
DBAccess.Free;
DmMain.ConMain.Connected := False;
FreeAndNil(DmMain);
end;
initialization
InitiaApplication;
finalization
FinaApplication;
end.
|
program Sample;
var i : Integer;
begin
i := 6;
while i > 0 do
begin
writeln(i);
i := i -1;
end;
writeln('last i = ', i)
end.
|
unit ncsStrings;
interface
function PastaDados: String;
function PastaCopia: String;
resourcestring
rsPastaErrada =
'Você informou a pasta errada. Você informou a pasta de dados do programa Nex. É necessário informar a pasta que contém sua CÓPIA de dados';
rsDBNaoEncontrado =
'Não foi encontrado nenhum arquivo de banco de dados do programa Nex na pasta informada. Informe novamente o local. Se tiver em uma sub-pasta é necessário seleciona-la';
rsInformarPastaDestino =
'A pasta destino tem que ser informada';
rsSucessoBackup =
'Backup realizado com sucesso!';
{ rsCopia =
'Copia';}
rsIniciandoDB =
'Iniciando banco de dados ...';
rsUserNaoExiste =
'Nome de usuário não existe!';
rsSenhaIncorreta =
'Senha incorreta!';
rsAcessoNaoPermitido =
'Você não possui direito de realizar essa operação';
rsEncerrarServidor =
'Encerrar Servidor';
rsDBError =
'Erro no banco de dados: "%s"';
rsCorrigindoArq =
'Corrigindo arquivo %s. Aguarde ...';
rsReindexandoArq =
'Reindexando arquivo %s. Aguarde ...';
rsCopiandoArq =
'Copiando arquivo %s. Aguarde ...';
rsRenomeandoArq =
'Renomeando arquivo %s. Aguarde ...';
rsRestaurandoArq =
'Restaurando arquivo %s. Aguarde ...';
rsSucessoCorrecao =
'Arquivos corrigidos com sucesso!';
rsErroCopiaArq =
'Erro %s copiando arquivo %s para %s';
rsConfirmaCorrecao =
'Deseja executar o processo de correção de banco de dados do programa NEX?';
rsFimCorrecao =
'Fim do processo de correção de arquivos';
rsSucessoRestauracao =
'Arquivos restaurados com sucesso!';
rsConfirmaApagar =
'Essa operação vai apagar informações do seu banco de dados. Prosseguir?';
rsConfirmaApagar2 =
'As informações serão apagadas de forma irreversível. Deseja realmente prosseguir?';
rsSucessoApagar =
'Dados apagados com sucesso!';
rsResyncNexApp =
'Deseja sincronizar novamente todos os dados da sua loja com o NexAPP?';
implementation
uses uNexTransResourceStrings_PT, ncClassesBase;
function PastaDados: String;
begin
if LinguaPT then
Result := 'Dados' else
Result := 'db';
end;
function PastaCopia: String;
begin
if LinguaPT then
Result := 'Copia' else
Result := 'backup';
end;
end.
|
unit ncCommonProc;
interface
uses
SysUtils, Classes, Windows, forms, shellapi, strutils, winsvc, svcMgr;
type
TBatFileEndsEvent = procedure(Sender:TObject; aTextoutput:string) of object;
TExecBatFileThread = class(TThread)
private
FBat: string;
FTextoutput: string;
fCurrDir:string;
fOnBatEnds :TBatFileEndsEvent;
protected
procedure SyncOnBatEnds;
procedure Execute; override;
{ Private declarations }
public
property OnBatEnds: TBatFileEndsEvent read fOnBatEnds write fOnBatEnds;
property Bat: string read FBat write FBat;
property Textoutput: string read FTextoutput;
constructor Create(aCurrDir:string); reintroduce;
{ Public declarations }
end;
function Is64bit:boolean;
function Capitalize(s:string):string;
function GetSystem32:string;
procedure ExecBatFile(aBat, aCurrDir: string; var aTextoutput:string);
function ExecBatFileAsync(aBat, aCurrDir: string; evt: TBatFileEndsEvent):TThread;
function GetErrorString(var errnum:Cardinal): string;
function GetTempFolder:string;
function NormalizarFilePath (const fp:string):string;
function ServiceStart(sMachine, sService : string ) : boolean;
function ServiceStop( sMachine, sService : string ) : boolean;
function isServiceStarted( sMachine, sService : string ) : boolean;
implementation
function NormalizarFilePath (const fp:string):string;
var
sfp : string;
begin
sfp := fp;
sfp := replaceStr(sfp, '/', '\');
sfp := replaceStr(sfp, '\\', '\');
if (length(sfp)>0) and ( sfp[length(sfp)]<>'\' ) then
sfp := sfp + '\';
result := sfp;
end;
function GetTempFolder:string;
begin
result := NormalizarFilePath(SysUtils.GetEnvironmentVariable('TEMP'));
if not directoryexists(result) then begin
result := NormalizarFilePath(SysUtils.GetEnvironmentVariable('TMP'));
if not directoryexists(result) then begin
result := NormalizarFilePath(extractfilepath(forms.application.ExeName))+ 'temp\';
forcedirectories(result);
if not directoryexists(result) then
result := '.\temp\';
end;
end;
end;
function Is64bit:boolean;
begin
result := sametext (
SysUtils.GetEnvironmentVariable('PROCESSOR_ARCHITEW6432'),
'amd64');
end;
function GetSystem32:string;
begin
result :=
NormalizarFilePath(SysUtils.GetEnvironmentVariable('windir')+'\System32');
end;
function Capitalize(s:string):string;
begin
result := s;
if result<'' then
result[1]:=UpCase(result[1]);
end;
function GetErrorString(var errnum:Cardinal): string;
var
err: array[0..512] of Char;
begin
errnum := GetLastError;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil, errnum, 0, @err,
512, nil);
Result := string(err);
end;
procedure ExecBatFile(aBat, aCurrDir: string; var aTextoutput:string);
var
ExecBatFileThread : TExecBatFileThread;
begin
ExecBatFileThread := TExecBatFileThread.Create(aCurrDir);
try
ExecBatFileThread.bat := aBat;
ExecBatFileThread.Resume;
repeat
forms.application.ProcessMessages;
until ExecBatFileThread.Terminated;
aTextoutput := ExecBatFileThread.textoutput;
ExecBatFileThread.WaitFor;
finally
ExecBatFileThread.Free;
end;
end;
function ExecBatFileAsync(aBat, aCurrDir: string; evt: TBatFileEndsEvent):TThread;
begin
result := TExecBatFileThread.Create(aCurrDir);
with result as TExecBatFileThread do begin
OnBatEnds := evt;
FreeOnTerminate := true;
bat := aBat;
Resume;
end;
end;
{ TExecBatFileThread }
constructor TExecBatFileThread.Create(aCurrDir:string);
begin
inherited create(true);
FreeOnTerminate := false;
fCurrDir := aCurrDir;
end;
procedure TExecBatFileThread.Execute;
var
sz : array[0..255] of char;
winpath, inputfn, outputfn : string;
StartupInfo:TStartupInfo;
ProcessInfo:TProcessInformation;
err : cardinal;
txtfile : TStringList;
sCmdLine : string;
begin
txtfile := TStringList.Create;
try
chdir(fCurrDir);
inputfn := 'input_'+ inttostr(GetCurrentProcess) + '_' +inttostr(ThreadID) + '.bat';
outputfn:= 'output_'+ inttostr(GetCurrentProcess) + '_' +inttostr(ThreadID) + '.txt';
txtfile.Text := FBat;
txtfile.SaveToFile(inputfn);
Fillchar(sz, 256,0);
GetSystemDirectory (sz, 255);
{$WARNINGS OFF}
winpath := IncludeTrailingBackslash(sz);
{$WARNINGS ON}
sCmdLine := inputfn +' > '+outputfn;
FillChar(StartupInfo,Sizeof(StartupInfo),#0);
StartupInfo.cb := Sizeof(StartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow := SW_HIDE;
// If the function fails, the return value is zero. To get extended error information, call GetLastError.
if not CreateProcess( pchar(winpath+'cmd.exe'),
pchar(winpath+'cmd.exe /c "'+ sCmdLine +'"'), { pointer to command line string }
nil, { pointer to process security attributes }
nil, { pointer to thread security attributes }
false, { handle inheritance flag }
CREATE_NEW_CONSOLE or { creation flags }
NORMAL_PRIORITY_CLASS,
nil, { pointer to new environment block }
pchar(fCurrDir), { pointer to current directory name }
StartupInfo, { pointer to STARTUPINFO }
ProcessInfo) { pointer to PROCESS_INF }
then begin
// error
FTextoutput := GetErrorString(err);
end else begin
WaitforSingleObject(ProcessInfo.hProcess,INFINITE);
GetExitCodeProcess(ProcessInfo.hProcess, cardinal(err));
CloseHandle( ProcessInfo.hProcess );
CloseHandle( ProcessInfo.hThread );
end;
if fileexists (outputfn) then begin
txtfile.LoadFromFile(outputfn);
FTextoutput := txtfile.Text;
deletefile(pchar(outputfn));
end;
deletefile(pchar(inputfn));
finally
txtfile.Free
end;
Synchronize(SyncOnBatEnds);
terminate;
end;
procedure TExecBatFileThread.SyncOnBatEnds;
begin
if assigned(fOnBatEnds) then
fOnBatEnds(self, FTextoutput);
end;
// start service
// return TRUE if successful
// sMachine:
// machine name, ie: \\SERVER
// empty = local machine
// sService
// service name, ie: Alerter
var
schm : SC_Handle; // service control manager handle
schs : SC_Handle; // service handle
ss : TServiceStatus; // service status
psTemp : PChar; // temp char pointer
dwChkP : DWord; // check point
function ServiceStart(sMachine, sService : string ) : boolean;
begin
ss.dwCurrentState := maxint;
// connect to the service control manager
schm := OpenSCManager( PChar(sMachine), Nil, SC_MANAGER_CONNECT);
// if successful...
if(schm > 0)then begin
// open a handle to
// the specified service
schs := OpenService( schm, PChar(sService), SERVICE_START or SERVICE_QUERY_STATUS);
// if successful...
if(schs > 0)then begin
psTemp := Nil;
if(StartService( schs, 0, psTemp))then begin
// check status
if(QueryServiceStatus( schs, ss))then begin
while(SERVICE_RUNNING <> ss.dwCurrentState)do begin
// dwCheckPoint contains a value that the service increments periodically
// to report its progress during a lengthy operation. save current value
dwChkP := ss.dwCheckPoint;
// wait a bit before checking status again
// dwWaitHint is the estimated amount of time the calling program
// should wait before calling QueryServiceStatus() again
// idle events should be handled here...
Sleep(ss.dwWaitHint);
if(not QueryServiceStatus( schs, ss))then begin
// couldn't check status break from the loop
break;
end;
if(ss.dwCheckPoint < dwChkP)then
begin
// QueryServiceStatus didn't increment dwCheckPoint as it should have.
// avoid an infinite loop by breaking
break;
end;
end;
end;
end;
// close service handle
CloseServiceHandle(schs);
end;
// close service control manager handle
CloseServiceHandle(schm);
end;
// return TRUE if the service status is running
Result := SERVICE_RUNNING = ss.dwCurrentState;
end;
// stop service
// return TRUE if successful
// sMachine:
// machine name, ie: \\SERVER
// empty = local machine
// sService
// service name, ie: Alerter
//
function ServiceStop( sMachine, sService : string ) : boolean;
var
schm : SC_Handle; // service control manager handle
schs : SC_Handle; // service handle
ss : TServiceStatus; // service status
dwChkP : DWord; // check point
begin
// connect to the service control manager
schm := OpenSCManager( PChar(sMachine), Nil, SC_MANAGER_CONNECT);
// if successful...
if(schm > 0)then begin
// open a handle to the specified service
schs := OpenService( schm, PChar(sService), SERVICE_STOP or SERVICE_QUERY_STATUS);
// if successful...
if(schs > 0)then
begin
if(ControlService( schs, SERVICE_CONTROL_STOP, ss))then begin
// check status
if(QueryServiceStatus( schs, ss))then begin
while(SERVICE_STOPPED <> ss.dwCurrentState)do begin
// dwCheckPoint contains a value that the service increments periodically
// to report its progress during a lengthy operation. save current value
dwChkP := ss.dwCheckPoint;
// wait a bit before checking status again
// dwWaitHint is the estimated amount of time the calling program
// should wait before calling QueryServiceStatus() again
// idle events should be handled here...
Sleep(ss.dwWaitHint);
if(not QueryServiceStatus( schs, ss))then begin
// couldn't check status break from the loop
break;
end;
if(ss.dwCheckPoint < dwChkP)then begin
// QueryServiceStatus didn't increment dwCheckPoint as it should have.
// avoid an infinite loop by breaking
break;
end;
end;
end;
end;
// close service handle
CloseServiceHandle(schs);
end;
// close service control manager handle
CloseServiceHandle(schm);
end;
// return TRUE if the service status is stopped
Result := SERVICE_STOPPED = ss.dwCurrentState;
end;
function isServiceStarted( sMachine, sService : string ) : boolean;
var
schm : SC_Handle; // service control manager handle
schs : SC_Handle; // service handle
ss : TServiceStatus; // service status
begin
result := false;
// connect to the service control manager
schm := OpenSCManager( PChar(sMachine), Nil, SC_MANAGER_CONNECT);
// if successful...
if(schm > 0)then begin
// open a handle to the specified service
schs := OpenService( schm, PChar(sService), SERVICE_STOP or SERVICE_QUERY_STATUS);
// if successful...
if(schs > 0)then begin
if(QueryServiceStatus( schs, ss))then
result := (SERVICE_RUNNING = ss.dwCurrentState);
// close service handle
CloseServiceHandle(schs);
end;
// close service control manager handle
CloseServiceHandle(schm);
end;
end;
end.
|
unit ltr212api;
interface
uses SysUtils, ltrapi, ltrapitypes;
const
// Коды ошибок. Описание см. ф-ю LRT212_GetErrorString()
LTR212_NO_ERR=0;
LTR212_ERR_INVALID_DESCR= -2001;
LTR212_ERR_INVALID_CRATE_SN= -2002;
LTR212_ERR_INVALID_SLOT_NUM= -2003;
LTR212_ERR_CANT_INIT= -2004;
LTR212_ERR_CANT_OPEN_CHANNEL= -2005;
LTR212_ERR_CANT_CLOSE= -2006;
LTR212_ERR_CANT_LOAD_BIOS= -2007;
LTR212_ERR_CANT_SEND_COMMAND= -2008;
LTR212_ERR_CANT_READ_EEPROM= -2009;
LTR212_ERR_CANT_WRITE_EEPROM= -2010;
LTR212_ERR_CANT_LOAD_IIR= -2011;
LTR212_ERR_CANT_LOAD_FIR= -2012;
LTR212_ERR_CANT_RESET_CODECS= -2013;
LTR212_ERR_CANT_SELECT_CODEC= -2014;
LTR212_ERR_CANT_WRITE_REG= -2015;
LTR212_ERR_CANT_READ_REG= -2016;
LTR212_ERR_WRONG_ADC_SETTINGS= -2017;
LTR212_ERR_WRONG_VCH_SETTINGS= -2018;
LTR212_ERR_CANT_SET_ADC= -2019;
LTR212_ERR_CANT_CALIBRATE= -2020;
LTR212_ERR_CANT_START_ADC= -2021;
LTR212_ERR_INVALID_ACQ_MODE= -2022;
LTR212_ERR_CANT_GET_DATA= -2023;
LTR212_ERR_CANT_MANAGE_FILTERS= -2024;
LTR212_ERR_CANT_STOP= -2025;
LTR212_ERR_CANT_GET_FRAME= -2026;
LTR212_ERR_INV_ADC_DATA= -2026;
LTR212_ERR_TEST_NOT_PASSED= -2027;
LTR212_ERR_CANT_WRITE_SERIAL_NUM = -2028;
LTR212_ERR_CANT_RESET_MODULE = -2029;
LTR212_ERR_MODULE_NO_RESPONCE = -2030;
LTR212_ERR_WRONG_FLASH_CRC= -2031;
LTR212_ERR_CANT_USE_FABRIC_AND_USER_CALIBR_SYM=-2032;
LTR212_ERR_CANT_START_INTERFACE_TEST= -2033;
LTR212_ERR_WRONG_BIOS_FILE= -2034;
LTR212_ERR_CANT_USE_CALIBR_MODE= -2035;
LTR212_ERR_PARITY_ERROR = -2036;
LTR212_ERR_CANT_LOAD_CLB_COEFFS = -2037;
LTR212_ERR_CANT_LOAD_FABRIC_CLB_COEFFS =-2038;
LTR212_ERR_CANT_GET_VER= -2039;
LTR212_ERR_CANT_GET_DATE= -2040;
LTR212_ERR_WRONG_SN = -2041;
LTR212_ERR_CANT_EVAL_DAC= -2042;
LTR212_ERR_ERROR_OVERFLOW = -2043;
LTR212_ERR_SOME_CHENNEL_CANT_CLB = -2044;
LTR212_ERR_CANT_GET_MODULE_TYPE =-2045;
LTR212_ERR_ERASE_OR_PROGRAM_FLASH =-2046;
LTR212_ERR_CANT_SET_BRIDGE_CONNECTIONS =-2047;
LTR212_ERR_CANT_SET_BRIDGE_CONNECTIONS_FOR_THIS_MODULE_TYPE =-2048;
LTR212_ERR_QB_RESISTORS_IN_ALL_CHANNELS_MUST_BE_EQUAL =-2049;
LTR212_ERR_INVALID_EEPROM_ADDR =-2050;
LTR212_ERR_INVALID_VCH_CNT =-2051;
LTR212_ERR_FILTER_FILE_OPEN =-2052;
LTR212_ERR_FILTER_FILE_READ =-2053;
LTR212_ERR_FILTER_FILE_FORMAT =-2054;
LTR212_ERR_FILTER_ORDER =-2055;
LTR212_ERR_UNSUPPORTED_MODULE_TYPE =-2056;
LTR212_LCH_CNT_MAX = 8; // Макс. число логических. каналов
LTR212_FIR_ORDER_MAX = 255; // Максимальное значение порядка КИХ-фильтра
LTR212_FIR_ORDER_MIN = 3; // Минимальное значение порядка КИХ-фильтра
// модификации модуля
LTR212_OLD = 0; // старый модуль с поддержкой полно- и полу-мостовых подключений
LTR212_M_1 = 1; // новый модуль с поддержкой полно-, полу- и четверть-мостовых подключений
LTR212_M_2 = 2; // новый модуль с поддержкой полно- и полу-мостовых подключений
// типы возможных мостов
LTR212_FULL_OR_HALF_BRIDGE = 0;
LTR212_QUARTER_BRIDGE_WITH_200_Ohm = 1;
LTR212_QUARTER_BRIDGE_WITH_350_Ohm = 2;
LTR212_QUARTER_BRIDGE_WITH_CUSTOM_Ohm = 3;
LTR212_UNBALANCED_QUARTER_BRIDGE_WITH_200_Ohm = 4;
LTR212_UNBALANCED_QUARTER_BRIDGE_WITH_350_Ohm = 5;
LTR212_UNBALANCED_QUARTER_BRIDGE_WITH_CUSTOM_Ohm = 6;
// режимы сбора данных (AcqMode)
LTR212_ACQ_MODE_MEDIUM_PRECISION = 0;
LTR212_ACQ_MODE_HIGH_PRECISION = 1;
LTR212_ACQ_MODE_8CH_HIGH_PRECISION = 2;
// значения опорного напряжения
LTR212_REF_2_5V = 0; //2.5 В
LTR212_REF_5V = 1; //5 В
// диапазоны каналов
LTR212_SCALE_B_10 = 0; // диапазон -10мВ/+10мВ
LTR212_SCALE_B_20 = 1; // диапазон -20мВ/+20мВ
LTR212_SCALE_B_40 = 2; // диапазон -40мВ/+40мВ
LTR212_SCALE_B_80 = 3; // диапазон -80мВ/+80мВ
LTR212_SCALE_U_10 = 4; // диапазон -10мВ/+10мВ
LTR212_SCALE_U_20 = 5; // диапазон -20мВ/+20мВ
LTR212_SCALE_U_40 = 6; // диапазон -40мВ/+40мВ
LTR212_SCALE_U_80 = 7; // диапазон -80мВ/+80мВ
// режимы калибровки
LTR212_CALIBR_MODE_INT_ZERO = 0;
LTR212_CALIBR_MODE_INT_SCALE = 1;
LTR212_CALIBR_MODE_INT_FULL = 2;
LTR212_CALIBR_MODE_EXT_ZERO = 3;
LTR212_CALIBR_MODE_EXT_SCALE = 4;
LTR212_CALIBR_MODE_EXT_ZERO_INT_SCALE = 5;
LTR212_CALIBR_MODE_EXT_FULL_2ND_STAGE = 6; // вторая стадия внешней калибровки
LTR212_CALIBR_MODE_EXT_ZERO_SAVE_SCALE = 7; // внешний ноль с сохранением до этого полученных коэф. масштаба
//******** Определение структуры описания модуля *************/
type
{$A4}
TINFO_LTR212 = record
Name: array[0..14] of AnsiChar;
ModuleType: byte;
Serial: array[0..23] of AnsiChar;
BiosVersion:array[0..7] of AnsiChar; // Версия БИОСа
BiosDate: array[0..15] of AnsiChar;// Дата создания данной версии БИОСа
end;
TLTR212_Filter = record
IIR:integer; // Флаг использования БИХ-фильтра
FIR:integer; // Флаг использования КИХ-фильтра
Decimation:integer; // Значение коэффициента децимации для КИХ-фильтра
TAP:integer; // Порядок КИХ-фильтра
IIR_Name:array[0..512] of AnsiChar; // Полный путь к файлу с коэфф-ми программного БИХ-фильтра
FIR_Name:array[0..512] of AnsiChar; // Полный путь к файлу с коэфф-ми программного КИХ-фильтра
end;
TLTR212_Usr_Clb = record
Offset :array[0..LTR212_LCH_CNT_MAX-1]of LongWord;
Scale :array[0..LTR212_LCH_CNT_MAX-1]of LongWord;
DAC_Value:array[0..LTR212_LCH_CNT_MAX-1]of byte;
end;
TLTR212 = record
size:integer;
Channel:TLTR;
AcqMode:integer; // Режим сбора данных
UseClb:integer; // Флаг использования калибровочных коэфф-тов
UseFabricClb:integer;// Флаг использования заводских калибровочных коэфф-тов
LChQnt:integer; // Кол-во используемых виртуальных каналов
LChTbl:array[0..LTR212_LCH_CNT_MAX-1]of integer; //Таблица виртуальных каналов
REF:integer; // Флаг высокого опорного напряжения
AC:integer; // Флаг знакопеременного опорного напряжения
Fs:double; // Частота дискретизации АЦП
filter:TLTR212_Filter;
ModuleInfo:TINFO_LTR212;
CRC_PM:Word; // для служебного пользования
CRC_Flash_Eval:Word; // для служебного пользования
CRC_Flash_Read:Word; // для служебного пользования
end;
pTLTR212 = ^TLTR212;
ltr212filter = record
fs:double;
decimation:byte;
taps:byte;
koeff:array[0..LTR212_FIR_ORDER_MAX-1]of Smallint;
end;
{$A+}
// Доступные пользователю
Function LTR212_Init(module:pTLTR212):Integer; {$I ltrapi_callconvention};
Function LTR212_IsOpened(module:pTLTR212):Integer;{$I ltrapi_callconvention};
Function LTR212_Open(module:pTLTR212; net_addr:LongWord; net_port:WORD; crate_snCHAR:Pointer; slot_num:integer; biosnameCHAR:Pointer):Integer;{$I ltrapi_callconvention};
Function LTR212_Close(module:pTLTR212):Integer;{$I ltrapi_callconvention};
Function LTR212_CreateLChannel(PhysChannel:integer; Scale:integer):Integer;{$I ltrapi_callconvention};
Function LTR212_CreateLChannel2(PhysChannel:LongWord; Scale:LongWord; BridgeType:LongWord):Integer; {$I ltrapi_callconvention};
Function LTR212_SetADC(module:pTLTR212):Integer;{$I ltrapi_callconvention};
Function LTR212_Start(module:pTLTR212):Integer;{$I ltrapi_callconvention};
Function LTR212_Stop(module:pTLTR212):Integer;{$I ltrapi_callconvention};
Function LTR212_Recv(module:pTLTR212; dataDWORD:Pointer; tmarkDWORD:Pointer; size:LongWord; timeout:LongWord):Integer;{$I ltrapi_callconvention};
Function LTR212_ProcessData(module:pTLTR212; srcDWORD:Pointer; destDOUBLE:Pointer; sizeDWORD:Pointer; volt:Boolean):Integer;{$I ltrapi_callconvention};
Function LTR212_Calibrate(module:pTLTR212; LChannel_MaskBYTE:pointer; mode:integer; reset:integer):Integer;{$I ltrapi_callconvention};
Function LTR212_CalcFS(module:pTLTR212; fsBaseDOUBLE:pointer; fs:pointer):Integer;{$I ltrapi_callconvention};
Function LTR212_TestEEPROM(module:pTLTR212):Integer;{$I ltrapi_callconvention};
// Вспомогательные функции
Function LTR212_ProcessDataTest(module:pTLTR212; srcDWORD:pointer; destDOUBLE:Pointer; sizeDWORD:pointer; volt:boolean; bad_numDWORD:pointer):Integer;{$I ltrapi_callconvention};
Function LTR212_ReadFilter(fnameCHAR:Pointer; filter_ltr212filter:Pointer):Integer;{$I ltrapi_callconvention};
Function LTR212_WriteSerialNumber(module:pTLTR212; snCHAR:pointer; Code:WORD):Integer;{$I ltrapi_callconvention};
Function LTR212_TestInterfaceStart(module:pTLTR212; PackDelay:integer):Integer;{$I ltrapi_callconvention};
Function LTR212_CalcTimeOut(module:pTLTR212; n:LongWord):LongWord;{$I ltrapi_callconvention};
Function LTR212_ReadUSR_Clb (module:pTLTR212; CALLIBR:pointer):Integer;{$I ltrapi_callconvention};
Function LTR212_WriteUSR_Clb(module:pTLTR212; CALLIBR:pointer):Integer;{$I ltrapi_callconvention};
Function LTR212_GetErrorString(err:integer):string;{$I ltrapi_callconvention};
implementation
Function LTR212_Init(module:pTLTR212):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_IsOpened(module:pTLTR212):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_Open(module:pTLTR212; net_addr:LongWord; net_port:WORD; crate_snCHAR:Pointer; slot_num:integer; biosnameCHAR:Pointer):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_Close(module:pTLTR212):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_CreateLChannel(PhysChannel:integer; Scale:integer):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_CreateLChannel2(PhysChannel:LongWord; Scale:LongWord; BridgeType:LongWord):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_SetADC(module:pTLTR212):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_Start(module:pTLTR212):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_Stop(module:pTLTR212):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_Recv(module:pTLTR212; dataDWORD:Pointer; tmarkDWORD:Pointer; size:LongWord; timeout:LongWord):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_ProcessData(module:pTLTR212; srcDWORD:Pointer; destDOUBLE:Pointer; sizeDWORD:Pointer; volt:Boolean):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_Calibrate(module:pTLTR212; LChannel_MaskBYTE:pointer; mode:integer; reset:integer):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_CalcFS(module:pTLTR212; fsBaseDOUBLE:pointer; fs:pointer):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_TestEEPROM(module:pTLTR212):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
// Вспомогательные функции
Function LTR212_ProcessDataTest(module:pTLTR212; srcDWORD:pointer; destDOUBLE:Pointer; sizeDWORD:pointer; volt:boolean; bad_numDWORD:pointer):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_ReadFilter(fnameCHAR:Pointer; filter_ltr212filter:Pointer):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_WriteSerialNumber(module:pTLTR212; snCHAR:pointer; Code:WORD):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_TestInterfaceStart(module:pTLTR212; PackDelay:integer):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_CalcTimeOut(module:pTLTR212; n:LongWord):LongWord; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_ReadUSR_Clb (module:pTLTR212; CALLIBR:pointer):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function LTR212_WriteUSR_Clb(module:pTLTR212; CALLIBR:pointer):Integer; {$I ltrapi_callconvention}; external 'ltr212api';
Function _get_err_str(err : integer) : PAnsiChar; {$I ltrapi_callconvention}; external 'ltr212api' name 'LTR212_GetErrorString';
Function LTR212_GetErrorString(err: Integer) : string; {$I ltrapi_callconvention};
begin
LTR212_GetErrorString:=string(_get_err_str(err));
end;
end.
|
{
Quick Sort Algorithm
O(NLgN)
Input:
A: Array of integer
L, R: The range to be sorted
Output:
Ascending sorted list
Notes:
L must be <= R
Reference:
TAOCP
By Knuth
}
procedure Sort(l, r: Integer);
var
i, j, x, y: integer;
begin
i := l; j := r; x := a[(l+r) DIV 2];
repeat
while a[i] < x do i := i + 1;
while x < a[j] do j := j - 1;
if i <= j then
begin
y := a[i]; a[i] := a[j]; a[j] := y;
i := i + 1; j := j - 1;
end;
until i > j;
if l < j then Sort(l, j);
if i < r then Sort(i, r);
end;
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ Xerces XML DOM Implementation Wrapper }
{ }
{ Copyright (c) 2002 Borland Software Corporation }
{ }
{*******************************************************}
unit xercesxmldom;
interface
uses
xmldom;
{$IFDEF MSWINDOWS}
{$HPPEMIT '#pragma link "xercesxmldom.obj"'}
{$ENDIF}
{$IFDEF LINUX}
{$HPPEMIT '#pragma link "xercesxmldom.o"'}
{$ENDIF}
const
SXercesXML = 'Xerces XML'; { Do not localize }
type
{ TXercesDOMImplementationFactory }
TXercesDOMImplementationFactory = class(TDOMVendor)
private
FLibHandle: Integer;
FDescription: string;
FLibName: string;
protected
procedure InitLibrary;
public
constructor Create(const ADesc, ALibName: string);
destructor Destroy; override;
function DOMImplementation: IDOMImplementation; override;
function Description: String; override;
procedure EnablePreserveWhitespace(Value: Boolean);
end;
var
XercesDOM: TXercesDOMImplementationFactory;
implementation
uses
{$IFDEF MSWINDOWS}
Windows, ComObj, ActiveX,
{$ENDIF}
{$IFDEF LINUX}
types, Libc,
{$ENDIF}
XMLConst, Classes, SysUtils;
const
{ Wrapper specific error codes }
ERR_XMLDOM_TRANSFORMARGS = $0101;
ERR_XMLDOM_WRITEFILE = $0102;
ERR_XMLDOM_NOTSUPPORTED = $0103;
{ Standard DOM message }
DOMMessages: array[INDEX_SIZE_ERR..INVALID_ACCESS_ERR] of string =
(SINDEX_SIZE_ERR, SDOMSTRING_SIZE_ERR, SHIERARCHY_REQUEST_ERR,
SWRONG_DOCUMENT_ERR, SINVALID_CHARACTER_ERR, SNO_DATA_ALLOWED_ERR,
SNO_MODIFICATION_ALLOWED_ERR, SNOT_FOUND_ERR, SNOT_SUPPORTED_ERR,
SINUSE_ATTRIBUTE_ERR, SINVALID_STATE_ERR, SSYNTAX_ERR,
SINVALID_MODIFICATION_ERR, SNAMESPACE_ERR, SINVALID_ACCESS_ERR);
{ Library file names }
{$IFDEF MSWINDOWS}
SXercesLibName = 'xercesxmldom.dll'; { Do not localize }
{$ENDIF}
{$IFDEF LINUX}
SXercesLibName = 'libxercesxmldom.so.1'; { Do not localize }
{$ENDIF}
{ Library export names }
SDoneXML = 'DoneXML'; { Do not localize }
SGetDOMImpl = 'GetDOMImplementation'; { Do not localize }
SSetCallback = 'SetCallback'; { Do not localize }
SSetOption = 'SetOption'; { Do not localize }
type
{ Library export types & signatures }
TCallbackType = (cbExceptionMsg, cbNoVendorSppt{deprecated}, cbWStrAlloc, cbGetIStrAdapt);
TOptionType = (opEnablePreserveWhitespace);
TGetDOMProc = procedure (out DOMImplementation: IDOMImplementation); stdcall;
TSetCallbackProc = procedure (cbType: TCallbackType; Proc: Pointer); stdcall;
TSetOptionProc = procedure (opType: TOptionType; Value: ULONG); stdcall;
TDoneXMLProc = procedure; stdcall;
{$IFDEF MSWINDOWS}
function LoadXMLLibrary(const LibName: string): Integer;
begin
Result := LoadLibrary(PChar(LibName));
if Result = 0 then
RaiseLastOSError;
end;
procedure SetSafeCallExceptionMsg(const Msg: WideString);
var
ErrorInfo: ICreateErrorInfo;
begin
OleCheck(CreateErrorInfo(ErrorInfo));
OleCheck(ErrorInfo.SetDescription(PWideChar(Msg)));
OleCheck(SetErrorInfo(0, (ErrorInfo as IErrorInfo)));
end;
{$ENDIF}
{$IFDEF LINUX}
function LoadXMLLibrary(const LibName: string): Integer;
begin
Result := LoadLibrary(PChar(LibName));
if Result = 0 then
raise Exception.CreateFmt(SErrorLoadingLib, [LibName, dlerror]);
end;
{$ENDIF}
function GetErrorMessage(const Id: LongWord; const Param: string): WideString;
begin
if (id >= INDEX_SIZE_ERR) and (id <= INVALID_ACCESS_ERR) then
Result := SDOMError + DOMMessages[id]
else
begin
case Id of
ERR_XMLDOM_TRANSFORMARGS: Result := SBadTransformArgs;
ERR_XMLDOM_WRITEFILE: Result := Format(SErrorWritingFile, [Param]);
ERR_XMLDOM_NOTSUPPORTED: Result := Format(SDOMNotSupported, [Param, SXercesXML]);
else
if Param <> '' then
Result := Param
else
Result := Format(SUnhandledXercesErr, [id]);
end;
end;
end;
{ Callbacks }
procedure WideStringAlloc(var Dest: WideString; Source: PWideChar; CharLength: Integer) stdcall;
begin
SetString(Dest, Source, CharLength);
end;
procedure GetIStreamAdapter(const Stream: TStream; var Adapter: IStream); stdcall;
begin
Adapter := TStreamAdapter.Create(Stream);
end;
procedure SetExceptionMessage(const Msg: WideString; const Id: LongWord); stdcall;
begin
SetSafeCallExceptionMsg(GetErrorMessage(Id, Msg))
end;
{ TXercesDOMImplementationFactory }
constructor TXercesDOMImplementationFactory.Create(const ADesc,
ALibName: string);
begin
FDescription := ADesc;
FLibName := ALibName;
end;
destructor TXercesDOMImplementationFactory.Destroy;
var
DoneXML: TDoneXMLProc;
begin
if FLibHandle > 0 then
begin
DoneXML := GetProcAddress(FLibHandle, SDoneXML);
DoneXML;
FreeLibrary(FLibHandle);
FLibHandle := 0;
end;
end;
function TXercesDOMImplementationFactory.Description: String;
begin
Result := FDescription;
end;
procedure TXercesDOMImplementationFactory.InitLibrary;
var
SetCallbackProc: TSetCallbackProc;
begin
if FLibHandle = 0 then
begin
FLibHandle := LoadXMLLibrary(FLibName);
SetCallbackProc := GetProcAddress(FLibHandle, SSetCallback);
SetCallbackProc(cbExceptionMsg, @SetExceptionMessage);
SetCallbackProc(cbWStrAlloc, @WideStringAlloc);
SetCallbackProc(cbGetIStrAdapt, @GetIStreamAdapter);
end;
end;
function TXercesDOMImplementationFactory.DOMImplementation: IDOMImplementation;
var
GetDOMProc: TGetDOMProc;
begin
InitLibrary;
GetDOMProc := GetProcAddress(FLibHandle, SGetDOMImpl);
GetDOMProc(Result);
end;
procedure TXercesDOMImplementationFactory.EnablePreserveWhitespace(Value: Boolean);
var
SetOptionProc: TSetOptionProc;
begin
InitLibrary;
SetOptionProc := GetProcAddress(FLibHandle, SSetOption);
SetOptionProc(opEnablePreserveWhitespace, Abs(Ord(Value)));
end;
initialization
XercesDOM := TXercesDOMImplementationFactory.Create(SXercesXML, SXercesLibName);
RegisterDOMVendor(XercesDOM);
finalization
UnRegisterDOMVendor(XercesDOM);
XercesDOM.Free;
end.
|
unit testgammaunit;
interface
uses Math, Sysutils, Ap, gammafunc;
function TestGamma(Silent : Boolean):Boolean;
function testgammaunit_test_silent():Boolean;
function testgammaunit_test():Boolean;
implementation
function TestGamma(Silent : Boolean):Boolean;
var
Threshold : Double;
V : Double;
S : Double;
WasErrors : Boolean;
GammaErrors : Boolean;
LnGammaErrors : Boolean;
begin
GammaErrors := False;
LnGammaErrors := False;
WasErrors := False;
Threshold := 100*MachineEpsilon;
//
//
//
GammaErrors := GammaErrors or AP_FP_Greater(AbsReal(Gamma(0.5)-Sqrt(Pi)),Threshold);
GammaErrors := GammaErrors or AP_FP_Greater(AbsReal(Gamma(1.5)-0.5*Sqrt(Pi)),Threshold);
V := LnGamma(0.5, S);
LnGammaErrors := LnGammaErrors or AP_FP_Greater(AbsReal(V-Ln(Sqrt(Pi))),Threshold) or AP_FP_Neq(S,1);
V := LnGamma(1.5, S);
LnGammaErrors := LnGammaErrors or AP_FP_Greater(AbsReal(V-Ln(0.5*Sqrt(Pi))),Threshold) or AP_FP_Neq(S,1);
//
// report
//
WasErrors := GammaErrors or LnGammaErrors;
if not Silent then
begin
Write(Format('TESTING GAMMA FUNCTION'#13#10'',[]));
Write(Format('GAMMA: ',[]));
if GammaErrors then
begin
Write(Format('FAILED'#13#10'',[]));
end
else
begin
Write(Format('OK'#13#10'',[]));
end;
Write(Format('LN GAMMA: ',[]));
if LnGammaErrors then
begin
Write(Format('FAILED'#13#10'',[]));
end
else
begin
Write(Format('OK'#13#10'',[]));
end;
if WasErrors then
begin
Write(Format('TEST FAILED'#13#10'',[]));
end
else
begin
Write(Format('TEST PASSED'#13#10'',[]));
end;
Write(Format(''#13#10''#13#10'',[]));
end;
//
// end
//
Result := not WasErrors;
end;
(*************************************************************************
Silent unit test
*************************************************************************)
function testgammaunit_test_silent():Boolean;
begin
Result := TestGamma(True);
end;
(*************************************************************************
Unit test
*************************************************************************)
function testgammaunit_test():Boolean;
begin
Result := TestGamma(False);
end;
end. |
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit System.Mac.CFUtils;
// This unit provides helper records for dealing with Core Foundation's
// CFPropertyList types, including CFArray, CFBoolean, CFDate, CFData,
// CFDictionary, CFNumber, and CFString.
// Primarily, these helpers are intended to help reading .plist files,
// and to assist in converting between basic Delphi types and their
// equivalent Core Foundation types and vice versa.
// NOTE: Using these helpers requires familiarity with Core Foundation's
// memory management routines. These helpers aim to reduce the necessity of
// CFRetain and CFRelease calls by the user, it may still be necessary to call
// them directly.
// Constructors and Class Create functions follow Core Foundation's
// Create Rule.
// Operators from Delphi types requiring Explicit casts call Core Foundation
// Create routines and should be treated as though they follow the Create Rule
// as well.
// Accessors follow the Get Rule unless otherwise noted.
// Accessor functions that have a Release parameter call CFRelease on exit
// if Release = True.
// Each of these helper records is a thin wrapper around a
// reference to a CFType. Each record has only one field, Value, which is the
// CoreFoundation reference. They also have several helper methods and
// type casting operators.
interface
uses
Macapi.CoreFoundation,
System.RTLConsts,
System.SysUtils,
System.Classes,
System.RTTI,
System.TypInfo,
System.Generics.Collections;
type
ECFPropertyListException = class(Exception);
TCFArray = record
Value: CFArrayRef;
private
function DoAsArray<T>(Release: Boolean): TArray<T>; overload;
public
// Constructors: Create CFArray from Delphi arrays
/// Create an array with a Delphi array of CFPropertyListRefs. Useful
/// for creating arrays of arrays, or arrays of dictionaries.
constructor Create(const AValue: TArray<CFPropertyListRef>); overload;
/// Create a CFArray from an array of type T.
/// T may be Boolean, TBytes, TDateTime, a string type, or a numeric type.
/// other types will raise an exception
class function Create<T>(const AValue: TArray<T>): TCFArray; overload; static;
// Accessor functions: Convert CFArray to Delphi array
function AsArray(Release: Boolean = False): TArray<CFPropertyListRef>; overload; inline;
function AsArray<T>(Release: Boolean = False): TArray<T>; overload;
function TryAsArray(out AResult: TArray<CFPropertyListRef>; Release: Boolean = False): Boolean; overload; inline;
function TryAsArray<T>(out AResult: TArray<T>; Release: Boolean = False): Boolean; overload;
/// Determine if all elements of array are the same type. If so, return TypeInfo. Otherwise, nil.
function GetTypeInfo: PTypeInfo;
/// Determine if all elements of array are type T.
function IsArrayOf<T>: Boolean;
/// Length of the array.
function Count: CFIndex;
/// Count of occurrences in of Val in the array.
function CountOfValue(Val: CFPropertyListRef): CFIndex;
class operator Implicit(AValue: CFArrayRef): TCFArray;
end;
TCFBoolean = record
Value: CFBooleanRef;
private
function DoAsBoolean: Boolean;
public
//NOTE: TCFBoolean has no Create rountes. Core Foundation
// simply uses references to two constants
// kCFBooleanTrue and kCFBooleanFalse, thus Retain/Release needn't
// be called
// CFBoolean to Boolean
function AsBoolean: Boolean;
function TryAsBoolean(out AResult: Boolean): Boolean;
// Boolean to CFBoolean
class operator Implicit(AValue: Boolean): TCFBoolean;
// CFBoolean to Boolean
class operator Implicit(AValue: TCFBoolean): Boolean;
class operator Implicit(AValue: CFBooleanRef): TCFBoolean;
end;
TCFData = record
Value: CFDataRef;
private
function DoAsArray<T>(Release: Boolean): TArray<T>; overload;
function DoAsType<T>(Release: Boolean): T; overload;
public
// Convert Delphi TBytes to CFData
constructor Create(const AValue: TBytes);
// Serialize an array of T into byte sequence as CFData
class function CreateFromArray<T>(const AValue: TArray<T>): TCFData; static;
// Serialize a single object T into a byte sequence as CFData
class function CreateFromType<T>(const AValue: T): TCFData; static;
function AsTBytes(Release: Boolean = False): TBytes;
// Convert CFData to an array of objects of type T
function AsArray<T>(Release: Boolean = False): TArray<T>; overload;
function TryAsArray<T>(out AResult: TArray<T>; Release: Boolean = False): Boolean; overload;
// Convert CFData to single object of type T
function AsType<T>(Release: Boolean = False): T; overload;
function TryAsType<T>(out AResult: T; Release: Boolean = False): Boolean; overload;
// NOTE: Explicit operator follows Create Rule.
class operator Explicit(const AValue: TBytes): TCFData;
class operator Implicit(const AValue: TCFData): TBytes;
class operator Implicit(AValue: CFDataRef): TCFData;
end;
TCFDate = record
Value: CFDateRef;
private
function DoAsTDateTime(Release: Boolean; UTC: Boolean): TDateTime;
public
// Create CFDate from TDateTime in current locale timezone, or UTC
constructor Create(AValue: TDateTime; UTC: Boolean = False); overload;
// Convert to TDateTime in current locale timezone
function AsTDateTime(Release: Boolean = False): TDateTime;
function TryAsTDateTime(out AResult: TDateTime; Release: Boolean = False): Boolean;
// Convert to TDateTime in UTC timezone
function AsTDateTimeUTC(Release: Boolean = False): TDateTime;
function TryAsTDateTimeUTC(out AResult: TDateTime; Release: Boolean = False): Boolean;
// NOTE: Explicit operator follows Create Rule.
class operator Explicit(AValue: TDateTime): TCFDate;
class operator Implicit(AValue: TCFDate): TDateTime;
class operator Implicit(AValue: CFDateRef): TCFDate;
end;
TCFDictionary = record
Value: CFDictionaryRef;
private type
TCFKeyValueEnumerator = class
private
FIndex: Integer;
FKeys: array of string;
FValues: array of CFPropertyListRef;
public
constructor Create(DictRef: CFDictionaryRef);
function GetCurrent: TPair<string, CFPropertyListRef>; inline;
function MoveNext: Boolean;
property Current: TPair<string, CFPropertyListRef> read GetCurrent;
end;
private
function DoGetKeys: TArray<string>;
function DoGetValues: TArray<CFPropertyListRef>;
public
// Get a value from the dictionary. NOTE: CFDictionary supports keys of
// any pointer sized type, but for streaming purposes, it must be a string
function GetValue(const Key: string): CFPropertyListRef;
// Allow setting a key-value pair, if the dictionary is a CFMutableDictionary.
// Note: if Value = nil, the Key is removed from the dictionary.
procedure SetValue(const Key: string; Value: CFPropertyListRef);
// Get all the keys as a string array
function GetKeys: TArray<string>;
function TryGetKeys(out AResult: TArray<string>): Boolean;
// Get all the values as an array. NOTE: CFDictionary may also contain
// values that are any Pointer sized type, but for streaming purposes
// it must be a CFPropertyList type.
function GetValues: TArray<CFPropertyListRef>;
function TryGetValues(out AResult: TArray<CFPropertyListRef>): Boolean;
// Enumerate over all keys and values as a TPair<string, CFPropertyListRef>
function GetEnumerator: TCFKeyValueEnumerator;
// determine if a key is in the dictionary
function ContainsKey(const Key: string): Boolean;
// determine if a value is in the dictionary
function ContainsValue(Val: CFPropertyListRef): Boolean;
// The length of the dictionary
function Count: CFIndex;
// Gets the number of times a value is repeated in the dictionary
function CountOfValue(Val: CFPropertyListRef): CFIndex;
// allows accessing values with Dictionary[Key]
property Items[const Key: string] : CFPropertyListRef read GetValue write SetValue; default;
property Keys: TArray<string> read GetKeys;
property Values: TArray<CFPropertyListRef> read GetValues;
class operator Implicit(AValue: CFDictionaryRef): TCFDictionary;
end;
TCFNumber = record
Value: CFNumberRef;
private
procedure DoAsType(ATypeInfo: PTypeInfo; ABuffer: Pointer; Release: Boolean);
public
// Conversion from Delphi Type to CoreFoundation type
class function CreateFromType<T>(AValue: T): TCFNumber; static;
// Gets the TypeInfo for the best Dephi type for this value
// possible values: ShortInt, SmallInt, Integer, Int64,
// Single, Double, CFIndex, NativeInt
function GetTypeInfo: PTypeInfo;
// Conversion from CoreFoundation type to Delphi type
function AsType<T>(Release: Boolean = False): T; overload;
function TryAsType<T>(out AResult: T; Release: Boolean = False): Boolean; overload;
// Returns the value without having to know what type is apropriate
function AsTValue(Release: Boolean = False): TValue; overload;
function TryAsTValue(out AResult: TValue; Release: Boolean = False): Boolean; overload;
class operator Implicit(AValue: CFNumberRef): TCFNumber;
end;
TCFString = record
Value: CFStringRef;
private
function DoAsChar(Release: Boolean = False): Char;
function DoAsString(Release: Boolean): string;
public
// Conversion from Delphi string to CoreFoundation CFString
constructor Create(const AValue: string);
// Conversion from CoreFoundation string to Delphi types
function AsChar(Release: Boolean = False): Char;
function AsString(Release: Boolean = False): string;
function TryAsChar(out AResult: Char; Release: Boolean = False): Boolean;
function TryAsString(out AResult: string; Release: Boolean = False): Boolean;
// NOTE: Explicit operator follows Create Rule.
class operator Explicit(const AValue: string): TCFString;
class operator Implicit(AValue: TCFString): string;
class operator Implicit(AValue: CFStringRef): TCFString;
end;
TCFPropertyListKind = (vkUnknown, vkArray, vkBoolean, vkData, vkDate,
vkDictionary, vkNumber, vkString);
// TCFPropertyList aids in converting reading and writing Property Lists
// from files and streams. It also does type checking when casting a
// CFPropertyList to the other CFTypes (such as CFString or CFNumber).
TCFPropertyList = record
Value: CFPropertyListRef;
strict private
class var FTypeIDs: array[TCFPropertyListKind] of CFTypeID;
class constructor Create;
public
// Load from a .plist file
constructor CreateFromFile(const FileName: string;
Mutable: CFPropertyListMutabilityOptions = kCFPropertyListImmutable;
Format: PCFPropertyListFormat = nil);
// Load a plist from a stream
constructor CreateFromStream(AStream: TStream;
Mutable: CFPropertyListMutabilityOptions = kCFPropertyListImmutable;
Format: PCFPropertyListFormat = nil);
// Save to a .plist file
procedure SaveToFile(const FileName: string; Format: CFPropertyListFormat = kCFPropertyListXMLFormat_v1_0);
// Save a plist to a stream
procedure SaveToStream(AStream: TStream; Format: CFPropertyListFormat = kCFPropertyListXMLFormat_v1_0);
// Get the CFTypeID of this PropertyList
function TypeID: CFTypeID;
// Get the Type as a delphi enumeration for use in case statements. CFTypeIDs
// shouldn't be used directly as they may change from release to release of
// the CoreFoundation framework.
function PropertyListKind: TCFPropertyListKind;
// Create a PropertyList from a delphi type. This Creates a
// CFBoolean, CFDate, CFData, CFString, or CFNumber depending on
// the type of T.
class function Create<T>(AValue: T): TCFPropertyList; static;
// Conversion from PropertyList to TValue. Uses CFTypeID to
// determine which helper above to do the actual convesion
function AsTValue: TValue;
// Explict casts from CFPropertyList to other types.
// These casts do type checking, and raise an
// ECFPropertyListException if the requested type doesn't match.
class operator Explicit(PList: TCFPropertyList): TCFArray;
class operator Explicit(PList: TCFPropertyList): TCFBoolean;
class operator Explicit(PList: TCFPropertyList): TCFData;
class operator Explicit(PList: TCFPropertyList): TCFDate;
class operator Explicit(PList: TCFPropertyList): TCFDictionary;
class operator Explicit(PList: TCFPropertyList): TCFNumber;
class operator Explicit(PList: TCFPropertyList): TCFString;
// Conversion from a CFType back to a CFPropertyList.
// Useful to allow SaveToFile or SaveToStream after doing some
// processing.
class operator Explicit(PList: TCFArray): TCFPropertyList;
class operator Explicit(PList: TCFBoolean): TCFPropertyList;
class operator Explicit(PList: TCFData): TCFPropertyList;
class operator Explicit(PList: TCFDate): TCFPropertyList;
class operator Explicit(PList: TCFDictionary): TCFPropertyList;
class operator Explicit(PList: TCFNumber): TCFPropertyList;
class operator Explicit(PList: TCFString): TCFPropertyList;
class operator Implicit(AValue: CFPropertyListRef): TCFPropertyList;
end;
CFGregorianDateHelper = record helper for CFGregorianDate
public
class function Create(AValue: TDateTime): CFGregorianDate; static;
function ToDateTime: TDateTime;
end;
implementation
uses
System.DateUtils;
{ TCFArray }
function TCFArray.DoAsArray<T>(Release: Boolean): TArray<T>;
var
Info: PTypeInfo;
LItems: TArray<CFPropertyListRef>;
I: Integer;
begin
Info := TypeInfo(T);
SetLength(Result, Count);
if Info.Kind = tkPointer then // assume CFPropertyListRef type
CFArrayGetValues(Value, CFRangeMake(0, Count), @Result[0])
else
begin
SetLength(LItems, Count);
CFArrayGetValues(Value, CFRangeMake(0, Count), @LItems[0]);
for I := 0 to Count - 1 do
case TCFPropertyList(LItems[I]).PropertyListKind of
vkBoolean:
if Info = TypeInfo(Boolean) then
PBoolean(@Result[I])^ := TCFBoolean(LItems[I]).AsBoolean
else
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion, ['CFBoolean', Info.Name]); //DO NOT TRANSLATE
vkData:
if Info = TypeInfo(TBytes) then
Result[I] := TCFData(LItems[I]).AsType<T>
else
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion, ['CFData', Info.Name]); //DO NOT TRANSLATE
vkDate:
if Info = TypeInfo(TDateTime) then
PDateTime(@Result[I])^ := TCFDate(LItems[I]).AsTDateTime
else
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion, ['CFDate', Info.Name]); //DO NOT TRANSLATE
vkNumber:
if Info = TCFNumber(LItems[I]).GetTypeInfo then
Result[I] := TCFNumber(LItems[I]).AsType<T>
else
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion, ['CFNumber', Info.Name]); //DO NOT TRANSLATE //TODO: more specific exception message
vkString:
if Info = TypeInfo(string) then
PString(@Result[I])^ := TCFString(LItems[I]).AsString
else
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion, ['CFString', Info.Name]); //DO NOT TRANSLATE
else
raise ECFPropertyListException.CreateRes(@sInvalidPListType);
end;
end;
if Release then
CFRelease(Value);
end;
constructor TCFArray.Create(const AValue: TArray<CFPropertyListRef>);
begin
Self := TCFArray.Create<CFPropertyListRef>(AValue);
end;
class function TCFArray.Create<T>(const AValue: TArray<T>): TCFArray;
var
Info: PTypeInfo;
LArray: TArray<CFPropertyListRef>;
I: Integer;
LItem: TValue;
callback: CFArrayCallBacks;
begin
Info := TypeInfo(T);
callback := kCFTypeArrayCallBacks;
if Info.Kind = tkPointer then // Assume TCFPropertyListRefs
begin
Result.Value := CFArrayCreate(kCFAllocatorDefault, @AValue[Low(AValue)],
Length(AValue), @callback);
Exit;
end;
SetLength(LArray, Length(AValue));
try
for I := Low(AValue) to High(AValue) do
LArray[I - Low(AValue)] := TCFPropertyList.Create<T>(AValue[I]).Value;
Result.Value := CFArrayCreate(kCFAllocatorDefault, @LArray[0], Length(LArray), @callback);
except
for I := 0 to Length(LArray) - 1 do
if LArray[I] <> nil then
CFRelease(LArray[I]);
raise;
end;
end;
function TCFArray.AsArray(Release: Boolean): TArray<CFPropertyListRef>;
begin
Result := DoAsArray<CFPropertyListRef>(Release);
end;
function TCFArray.AsArray<T>(Release: Boolean): TArray<T>;
begin
Result := DoAsArray<T>(Release);
end;
function TCFArray.TryAsArray(out AResult: TArray<CFPropertyListRef>;
Release: Boolean): Boolean;
begin
Result := True;
try
AResult := DoAsArray<CFPropertyListRef>(Release);
except
Result := False;
end;
end;
function TCFArray.TryAsArray<T>(out AResult: TArray<T>;
Release: Boolean): Boolean;
begin
Result := True;
try
AResult := DoAsArray<T>(Release);
except
Result := False;
end;
end;
function TCFArray.GetTypeInfo: PTypeInfo;
var
LValues: TArray<CFPropertyListRef>;
I: Integer;
begin
Result := nil;
SetLength(LValues, Count);
CFArrayGetValues(Value, CFRangeMake(0, Count), @LValues[0]);
for I := 0 to Length(LValues) -1 do
begin
case TCFPropertyList(LValues[I]).PropertyListKind of
vkUnknown: raise ECFPropertyListException.CreateRes(@sInvalidPListType);
vkArray: raise ECFPropertyListException.CreateRes(@sConvertArrayArray);
vkDictionary: raise ECFPropertyListException.CreateRes(@sConvertArrayDictionary);
vkBoolean:
if Result = nil then
Result := TypeInfo(Boolean)
else if Result <> TypeInfo(Boolean) then
Exit(nil); // Types don't match
vkData:
if Result = nil then
Result := TypeInfo(TBytes)
else if Result <> TypeInfo(TBytes) then
Exit(nil); // Types don't match
vkDate:
if Result = nil then
Result := TypeInfo(TDateTime)
else if Result <> TypeInfo(TDateTime) then
Exit(nil); // Types don't match
vkNumber:
if Result = nil then
Result := TCFNumber(LValues[I]).GetTypeInfo
else if Result <> TCFNumber(LValues[I]).GetTypeInfo then
Exit(nil); // Types don't match
vkString:
if Result = nil then
Result := TypeInfo(string)
else if Result <> TypeInfo(string) then
Exit(nil); // Types don't match
end;
end;
end;
function TCFArray.IsArrayOf<T>: Boolean;
begin
Result := GetTypeInfo = TypeInfo(T);
end;
function TCFArray.Count: CFIndex;
begin
Result := CFArrayGetCount(Value);
end;
function TCFArray.CountOfValue(Val: CFPropertyListRef): CFIndex;
begin
Result := CFArrayGetCountOfValue(Value, CFRangeMake(0, Count), Val);
end;
class operator TCFArray.Implicit(AValue: CFArrayRef): TCFArray;
begin
Result.Value := AValue;
end;
{ TCFBoolean }
function TCFBoolean.DoAsBoolean: Boolean;
begin
Result := CFBooleanGetValue(Value)
end;
function TCFBoolean.AsBoolean: Boolean;
begin
Result := DoAsBoolean;
end;
function TCFBoolean.TryAsBoolean(out AResult: Boolean): Boolean;
begin
Result := True;
try
AResult := DoAsBoolean;
except
Result := False;
end;
end;
class operator TCFBoolean.Implicit(AValue: Boolean): TCFBoolean;
begin
if AValue then
Result.Value := kCFBooleanTrue
else
Result.Value := kCFBooleanFalse;
end;
class operator TCFBoolean.Implicit(AValue: TCFBoolean): Boolean;
begin
Result := AValue.DoAsBoolean;
end;
class operator TCFBoolean.Implicit(AValue: CFBooleanRef): TCFBoolean;
begin
Result.Value := AValue;
end;
{ TCFData }
function TCFData.DoAsArray<T>(Release: Boolean): TArray<T>;
var
Len: CFIndex;
begin
try
Len := CFDataGetLength(Value);
SetLength(Result, Len div SizeOf(T));
CFDataGetBytes(Value, CFRangeMake(0, Len), @Result[0]);
finally
if Release then
CFRelease(Value);
end;
end;
function TCFData.DoAsType<T>(Release: Boolean): T;
var
Len: CFIndex;
begin
try
Len := CFDataGetLength(Value);
CFDataGetBytes(Value, CFRangeMake(0, Len), @Result);
finally
if Release then
CFRelease(Value);
end;
end;
constructor TCFData.Create(const AValue: TBytes);
begin
Value := CFDataCreate(kCFAllocatorDefault, @AValue[Low(AValue)],
Length(AValue) * SizeOf(Byte) );
end;
class function TCFData.CreateFromArray<T>(const AValue: TArray<T>): TCFData;
begin
Result.Value := CFDataCreate(kCFAllocatorDefault, @AValue[Low(AValue)],
Length(AValue) * SizeOf(T) );
end;
class function TCFData.CreateFromType<T>(const AValue: T): TCFData;
begin
Result.Value := CFDataCreate(kCFAllocatorDefault, @AValue, SizeOf(T));
end;
function TCFData.AsArray<T>(Release: Boolean): TArray<T>;
begin
Result := DoAsArray<T>(Release);
end;
function TCFData.TryAsArray<T>(out AResult: TArray<T>;
Release: Boolean): Boolean;
begin
Result := True;
try
AResult := DoAsArray<T>(Release);
except
Result := False;
end;
end;
function TCFData.AsTBytes(Release: Boolean): TBytes;
begin
Result := DoAsArray<Byte>(Release);
end;
function TCFData.AsType<T>(Release: Boolean): T;
begin
Result := DoAsType<T>(Release);
end;
function TCFData.TryAsType<T>(out AResult: T; Release: Boolean): Boolean;
begin
Result := True;
try
AResult := DoAsType<T>(Release);
except
Result := False;
end;
end;
class operator TCFData.Explicit(const AValue: TBytes): TCFData;
begin
Result := TCFData.CreateFromArray<Byte>(AValue);
end;
class operator TCFData.Implicit(const AValue: TCFData): TBytes;
begin
Result := AValue.AsArray<Byte>;
end;
class operator TCFData.Implicit(AValue: CFDataRef): TCFData;
begin
Result.Value := AValue;
end;
{ TCFDate }
function TCFDate.DoAsTDateTime(Release, UTC: Boolean): TDateTime;
var
LTimeZone: CFTimeZoneRef;
begin
try
if UTC then
Result := CFAbsoluteTimeGetGregorianDate(CFDateGetAbsoluteTime(Value), nil).ToDateTime
else
begin
LTimeZone := CFTimeZoneCopyDefault;
try
Result := CFAbsoluteTimeGetGregorianDate(CFDateGetAbsoluteTime(Value), LTimeZone).ToDateTime;
finally
CFRelease(LTimeZone);
end;
end;
finally
if Release then
CFRelease(Value);
end;
end;
constructor TCFDate.Create(AValue: TDateTime; UTC: Boolean);
var
LTimeZone: CFTimeZoneRef;
begin
if UTC then
Value := CFDateCreate(kCFAllocatorDefault,
CFGregorianDateGetAbsoluteTime(CFGregorianDate.Create(AValue), nil))
else
begin
LTimeZone := CFTimeZoneCopyDefault;
try
Value := CFDateCreate(kCFAllocatorDefault,
CFGregorianDateGetAbsoluteTime(CFGregorianDate.Create(AValue), LTimeZone));
finally
CFRelease(LTimeZone);
end;
end;
end;
function TCFDate.AsTDateTime(Release: Boolean): TDateTime;
begin
Result := DoAsTDateTime(Release, False);
end;
function TCFDate.AsTDateTimeUTC(Release: Boolean): TDateTime;
begin
Result := DoAsTDateTime(Release, True);
end;
function TCFDate.TryAsTDateTime(out AResult: TDateTime;
Release: Boolean): Boolean;
begin
Result := True;
try
AResult := DoAsTDateTime(Release, False);
except
Result := False;
end;
end;
function TCFDate.TryAsTDateTimeUTC(out AResult: TDateTime;
Release: Boolean): Boolean;
begin
Result := True;
try
AResult := DoAsTDateTime(Release, True);
except
Result := False;
end;
end;
class operator TCFDate.Explicit(AValue: TDateTime): TCFDate;
begin
Result := TCFDate.Create(AValue);
end;
class operator TCFDate.Implicit(AValue: TCFDate): TDateTime;
begin
Result := AValue.AsTDateTime;
end;
class operator TCFDate.Implicit(AValue: CFDateRef): TCFDate;
begin
Result.Value := AValue;
end;
{ TCFDictionary.TCFKeyValueEnumerator }
constructor TCFDictionary.TCFKeyValueEnumerator.Create(
DictRef: CFDictionaryRef);
var
I: Integer;
LCount: CFIndex;
LKeys: TArray<CFStringRef>;
begin
inherited Create;
FIndex := -1;
LCount := CFDictionaryGetCount(DictRef);
if LCount <= 0 then Exit;
SetLength(FKeys, LCount);
SetLength(LKeys, LCount);
SetLength(FValues, LCount);
CFDictionaryGetKeysAndValues(DictRef, @LKeys[0], @FValues[0]);
for I := 0 to LCount - 1 do
FKeys[I] := TCFString(LKeys[I]).AsString;
end;
function TCFDictionary.TCFKeyValueEnumerator.GetCurrent: TPair<string, CFPropertyListRef>;
begin
Result := TPair<string, CFPropertyListRef>.Create(FKeys[FIndex], FValues[FIndex]);
end;
function TCFDictionary.TCFKeyValueEnumerator.MoveNext: Boolean;
begin
Result := FIndex < Length(FKeys) - 1;
if Result then
Inc(FIndex);
end;
{ TCFDictionary }
function TCFDictionary.DoGetKeys: TArray<string>;
var
I: Integer;
LCount: CFIndex;
LKeys: TArray<CFStringRef>;
begin
LCount := CFDictionaryGetCount(Value);
SetLength(Result, LCount);
SetLength(LKeys, LCount);
CFDictionaryGetKeysAndValues(Value, @LKeys[0], nil);
for I := 0 to LCount -1 do
Result[I] := TCFString(LKeys[I]).AsString;
end;
function TCFDictionary.DoGetValues: TArray<CFPropertyListRef>;
var
LCount: CFIndex;
begin
LCount := CFDictionaryGetCount(Value);
SetLength(Result, LCount);
CFDictionaryGetKeysAndValues(Value, nil, @Result[0]);
end;
function TCFDictionary.GetValue(const Key: string): CFPropertyListRef;
var
LKey: TCFString;
begin
LKey := TCFString.Create(Key);
try
if not CFDictionaryGetValueIfPresent(Value, LKey.Value, @Result) then
raise ECFPropertyListException.CreateRes(@sKeyNotPresent);
finally
CFRelease(LKey.Value);
end;
end;
procedure TCFDictionary.SetValue(const Key: string; Value: Pointer);
var
LKey: TCFString;
begin
LKey := TCFString.Create(Key);
try
if Value = nil then
CFDictionaryRemoveValue(CFMutableDictionaryRef(Self.Value), LKey.Value)
else
CFDictionarySetValue(CFMutableDictionaryRef(Self.Value), LKey.Value, Value);
finally
if LKey.Value <> nil then
CFRelease(LKey.Value);
end;
end;
function TCFDictionary.GetKeys: TArray<string>;
begin
Result := DoGetKeys;
end;
function TCFDictionary.GetValues: TArray<CFPropertyListRef>;
begin
Result := DoGetValues;
end;
function TCFDictionary.TryGetKeys(out AResult: TArray<string>): Boolean;
begin
Result := True;
try
AResult := DoGetKeys;
except
Result := False;
end;
end;
function TCFDictionary.TryGetValues(
out AResult: TArray<CFPropertyListRef>): Boolean;
begin
Result := True;
try
AResult := DoGetValues;
except
Result := False;
end;
end;
function TCFDictionary.GetEnumerator: TCFKeyValueEnumerator;
begin
Result := TCFKeyValueEnumerator.Create(Value);
end;
function TCFDictionary.ContainsKey(const Key: string): Boolean;
var
LKey: TCFString;
begin
LKey := TCFString.Create(Key);
try
Result := CFDictionaryContainsKey(Value, LKey.Value);
finally
CFRelease(LKey.Value);
end;
end;
function TCFDictionary.ContainsValue(Val: CFPropertyListRef): Boolean;
begin
Result := CFDictionaryContainsValue(Value, Val);
end;
function TCFDictionary.Count: CFIndex;
begin
Result := CFDictionaryGetCount(Value);
end;
function TCFDictionary.CountOfValue(Val: CFPropertyListRef): CFIndex;
begin
Result := CFDictionaryGetCountOfValue(Value, Val);
end;
class operator TCFDictionary.Implicit(AValue: CFDictionaryRef): TCFDictionary;
begin
Result.Value := AValue;
end;
{ TCFNumber }
procedure TCFNumber.DoAsType(ATypeInfo: PTypeInfo; ABuffer: Pointer;
Release: Boolean);
var
LResult: Boolean;
begin
try
LResult := False;
case ATypeInfo.Kind of
tkInt64: LResult := CFNumberGetValue(Value, kCFNumberLongLongType, ABuffer);
tkInteger:
case GetTypeData(ATypeInfo).OrdType of
otSByte, otUByte: LResult := CFNumberGetValue(Value, kCFNumberSInt8Type, ABuffer);
otSWord, otUWord: LResult := CFNumberGetValue(Value, kCFNumberSInt16Type, ABuffer);
otSLong, otULong: LResult := CFNumberGetValue(Value, kCFNumberLongType, ABuffer);
end;
tkFloat:
case GetTypeData(ATypeInfo).FloatType of
ftSingle: LResult := CFNumberGetValue(Value, kCFNumberFloat32Type, ABuffer);
ftDouble: LResult := CFNumberGetValue(Value, kCFNumberFloat64Type, ABuffer);
else
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion, ['CFNumber', ATypeInfo.Name]); //DO NOT TRANSLATE
end;
else
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion, ['CFNumber', ATypeInfo.Name]); //DO NOT TRANSLATE
end;
if LResult = False then
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion, ['CFNumber', ATypeInfo.Name]); //DO NOT TRANSLATE
finally
if Release then
CFRelease(Value);
end;
end;
class function TCFNumber.CreateFromType<T>(AValue: T): TCFNumber;
var
LValue: T;
Info: PTypeInfo;
begin
LValue := AValue;
Info := TypeInfo(T);
case Info.Kind of
tkInt64: Result.Value := CFNumberCreate(kCFAllocatorDefault, kCFNumberLongLongType, @LValue);
tkInteger:
case GetTypeData(Info).OrdType of
otSByte, otUByte: Result.Value := CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt8Type, @LValue);
otSWord, otUWord: Result.Value := CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt16Type, @LValue);
otSLong, otULong: Result.Value := CFNumberCreate(kCFAllocatorDefault, kCFNumberLongType, @LValue);
end;
tkFloat:
case GetTypeData(Info).FloatType of
ftSingle: Result.Value := CFNumberCreate(kCFAllocatorDefault, kCFNumberFloat32Type, @LValue);
ftDouble: Result.Value := CFNumberCreate(kCFAllocatorDefault, kCFNumberFloat64Type, @LValue);
else
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion, [Info.Name, 'CFNumber']); //DO NOT TRANSLATE
end;
else
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion, [Info.Name, 'CFNumber']); //DO NOT TRANSLATE
end;
end;
function TCFNumber.GetTypeInfo: PTypeInfo;
begin
Result := nil;
case CFNumberGetType(Value) of
kCFNumberSInt8Type,
kCFNumberCharType: Result := TypeInfo(ShortInt);
kCFNumberSInt16Type,
kCFNumberShortType: Result := TypeInfo(SmallInt);
kCFNumberSInt32Type,
kCFNumberIntType,
kCFNumberLongType: Result := TypeInfo(Integer);
kCFNumberSInt64Type,
kCFNumberLongLongType: Result := TypeInfo(Int64);
kCFNumberFloat32Type,
{$IFDEF CPUX86}
kCFNumberCGFloatType,
{$ENDIF}
kCFNumberFloatType: Result := TypeInfo(Single);
kCFNumberFloat64Type,
{$IFDEF CPUX64}
kCFNumberCGFloatType,
{$ENDIF}
kCFNumberDoubleType: Result := TypeInfo(Double);
kCFNumberCFIndexType: Result := TypeInfo(CFIndex);
kCFNumberNSIntegerType: Result := TypeInfo(NativeInt);
end;
end;
function TCFNumber.AsType<T>(Release: Boolean): T;
var
Info: PTypeInfo;
begin
Info := TypeInfo(T);
case Info^.Kind of
tkInteger, tkInt64, tkFloat:
DoAsType(TypeInfo(T), @Result, Release)
else
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion, ['CFNumber', Info^.Name]); //DO NOT TRANSLATE
end;
end;
function TCFNumber.AsTValue(Release: Boolean): TValue;
var
LValue: Int64;
Info: PTypeInfo;
begin
Info := GetTypeInfo;
DoAsType(Info, @LValue, Release);
TValue.Make(@LValue, Info, Result);
end;
function TCFNumber.TryAsTValue(out AResult: TValue; Release: Boolean): Boolean;
var
LValue: Int64;
Info: PTypeInfo;
begin
Info := nil;
Result := True;
try
Info := GetTypeInfo;
DoAsType(Info, @LValue, Release);
except
Result := False;
end;
if Result then
TValue.Make(@LValue, Info, AResult);
end;
function TCFNumber.TryAsType<T>(out AResult: T; Release: Boolean): Boolean;
begin
Result := True;
try
DoAsType(TypeInfo(T), @AResult, Release);
except
Result := False;
end;
end;
class operator TCFNumber.Implicit(AValue: CFNumberRef): TCFNumber;
begin
Result.Value := AValue;
end;
{ TCFString }
function TCFString.DoAsChar(Release: Boolean): Char;
begin
try
if CFStringGetLength(Value) > 0 then
Result := CFStringGetCharacterAtIndex(Value, 0)
else
Result := #0;
finally
if Release then
CFRelease(Value);
end;
end;
function TCFString.DoAsString(Release: Boolean): string;
var
Range: CFRange;
begin
try
Range := CFRangeMake(0, CFStringGetLength(Value));
if Range.Length > 0 then
begin
SetLength(Result, Range.Length);
CFStringGetCharacters(Value, Range, @Result[1]);
end
else
Result := EmptyStr;
finally
if Release then
CFRelease(Value);
end;
end;
constructor TCFString.Create(const AValue: string);
begin
Value := CFStringCreateWithCharacters(kCFAllocatorDefault, PChar(AValue), Length(AValue));
end;
function TCFString.AsChar(Release: Boolean): Char;
begin
Result := DoAsChar(Release);
end;
function TCFString.AsString(Release: Boolean): string;
begin
Result := DoAsString(Release);
end;
function TCFString.TryAsChar(out AResult: Char; Release: Boolean): Boolean;
begin
Result := True;
try
AResult := DoAsChar(Release);
except
Result := False;
end;
end;
function TCFString.TryAsString(out AResult: string; Release: Boolean): Boolean;
begin
Result := True;
try
AResult := DoAsString(Release);
except
Result := False;
end;
end;
class operator TCFString.Explicit(const AValue: string): TCFString;
begin
Result := TCFString.Create(AValue);
end;
class operator TCFString.Implicit(AValue: TCFString): string;
begin
Result := AValue.AsString;
end;
class operator TCFString.Implicit(AValue: CFStringRef): TCFString;
begin
Result.Value := AValue;
end;
{ TCFPropertyList }
class constructor TCFPropertyList.Create;
begin
FTypeIDs[vkUnknown] := 0; // Is this safe?
FTypeIDs[vkArray] := CFArrayGetTypeID;
FTypeIDs[vkBoolean] := CFBooleanGetTypeID;
FTypeIDs[vkData] := CFDataGetTypeID;
FTypeIDs[vkDate] := CFDateGetTypeID;
FTypeIDs[vkDictionary] := CFDictionaryGetTypeID;
FTypeIDs[vkNumber] := CFNumberGetTypeID;
FTypeIDs[vkString] := CFStringGetTypeID;
end;
constructor TCFPropertyList.CreateFromFile(const FileName: string;
Mutable: CFPropertyListMutabilityOptions; Format: PCFPropertyListFormat);
var
FileStream: TFileStream;
begin
FileStream := TFileStream.Create(FileName, fmOpenRead);
try
CreateFromStream(FileStream, Mutable, Format);
finally
FileStream.Free;
end;
end;
constructor TCFPropertyList.CreateFromStream(AStream: TStream;
Mutable: CFPropertyListMutabilityOptions; Format: PCFPropertyListFormat);
var
LData: TBytes;
LCFData: CFDataRef;
LError: CFErrorRef;
begin
SetLength(LData, AStream.Size);
AStream.Read(LData[0], AStream.Size);
LCFData := CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, @LData[0],
AStream.Size, kCFAllocatorNull);
try
Value := CFPropertyListCreateWithData(KCFAllocatorDefault, LCFData,
Mutable, Format, @LError);
finally
CFRelease(LCFData);
end;
end;
procedure TCFPropertyList.SaveToFile(const FileName: string;
Format: CFPropertyListFormat);
var
FileStream: TFileStream;
begin
FileStream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(FileStream, Format);
finally
FileStream.Free;
end;
end;
procedure TCFPropertyList.SaveToStream(AStream: TStream;
Format: CFPropertyListFormat);
var
LData: TBytes;
LCFData: CFDataRef;
LError: CFErrorRef;
begin
LCFData := CFPropertyListCreateData(kCFAllocatorDefault, Value, Format, 0, @LError);
try
LData := TCFData(LCFData).AsArray<Byte>;
AStream.Write(LData[0], Length(LData));
finally
CFRelease(LCFData);
end;
end;
function TCFPropertyList.TypeID: CFTypeID;
begin
Result := CFGetTypeID(Value);
end;
function TCFPropertyList.PropertyListKind: TCFPropertyListKind;
var
LTypeID: CFTypeID;
LValueKind: TCFPropertyListKind;
begin
Result := vkUnknown;
try
LTypeID := CFGetTypeID(Value);
for LValueKind := Low(FTypeIDs) to High(FTypeIDs) do
if LTypeID = FTypeIDs[LValueKind] then
Exit(LValueKind);
except
Result := vkUnknown;
end;
end;
class function TCFPropertyList.Create<T>(AValue: T): TCFPropertyList;
var
Info: PTypeInfo;
begin
Info := TypeInfo(T);
if Info = TypeInfo(Boolean) then
Result.Value := TCFBoolean( PBoolean(@AValue)^ ).Value
else if Info = TypeInfo(TDateTime) then
Result.Value := TCFDate.Create( PDateTime(@AValue)^ ).Value
else if Info = TypeInfo(TBytes) then
Result.Value := TCFData.CreateFromType<T>(AValue).Value
else
case Info.Kind of
tkString: Result.Value := TCFString.Create( string(PShortString(@AValue)^) ).Value;
tkLString: Result.Value := TCFString.Create( string(PAnsiString(@AValue)^) ).Value;
tkWString: Result.Value := TCFString.Create( PWideString(@AValue)^ ).Value;
tkUString: Result.Value := TCFString.Create( PUnicodeString(@AValue)^ ).Value;
tkInteger, tkInt64, tkFloat: Result.Value := TCFNumber.CreateFromType<T>(AValue).Value;
end;
end;
function TCFPropertyList.AsTValue: TValue;
begin
case PropertyListKind of
vkBoolean: Result := TCFBoolean(Self).AsBoolean;
vkData: Result := TValue.From<TBytes>(TCFData(Self).AsArray<Byte>);
vkDate: Result := TCFDate(Self).AsTDateTime;
vkNumber: Result := TCFNumber(Self).AsTValue;
vkString: Result := TCFString(Self).AsString;
vkUnknown: raise ECFPropertyListException.CreateRes(@sInvalidPListType);
vkDictionary: raise ECFPropertyListException.CreateRes(@sConvertDictionary);
end;
end;
class operator TCFPropertyList.Explicit(PList: TCFPropertyList): TCFArray;
var
ID: CFTypeID;
begin
ID:= CFGetTypeID(PList.Value);
if ID <> FTypeIDs[vkArray] then
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion,
[TCFString(CFCopyTypeIDDescription(ID)).AsString(True), 'CFArray']); //DO NOT TRANSLATE
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Explicit(PList: TCFPropertyList): TCFBoolean;
var
ID: CFTypeID;
begin
ID := CFGetTypeID(PList.Value);
if ID <> FTypeIDs[vkBoolean] then
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion,
[TCFString(CFCopyTypeIDDescription(ID)).AsString(True), 'CFBoolean']); //DO NOT TRANSLATE
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Explicit(PList: TCFPropertyList): TCFDate;
var
ID: CFTypeID;
begin
ID := CFGetTypeID(PList.Value);
if ID <> FTypeIDs[vkDate] then
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion,
[TCFString(CFCopyTypeIDDescription(ID)).AsString(True), 'CFDate']); //DO NOT TRANSLATE
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Explicit(PList: TCFPropertyList): TCFData;
var
ID: CFTypeID;
begin
ID := CFGetTypeID(PList.Value);
if ID <> FTypeIDs[vkData] then
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion,
[TCFString(CFCopyTypeIDDescription(ID)).AsString(True), 'CFData']); //DO NOT TRANSLATE
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Explicit(PList: TCFPropertyList): TCFDictionary;
var
ID: CFTypeID;
begin
ID := CFGetTypeID(PList.Value);
if ID <> FTypeIDs[vkDictionary] then
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion,
[TCFString(CFCopyTypeIDDescription(ID)).AsString(True), 'CFDictionary']); //DO NOT TRANSLATE
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Explicit(PList: TCFPropertyList): TCFNumber;
var
ID: CFTypeID;
begin
ID := CFGetTypeID(PList.Value);
if ID <> FTypeIDs[vkNumber] then
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion,
[TCFString(CFCopyTypeIDDescription(ID)).AsString(True), 'CFNumber']); //DO NOT TRANSLATE
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Explicit(PList: TCFPropertyList): TCFString;
var
ID: CFTypeID;
begin
ID := CFGetTypeID(PList.Value);
if ID <> FTypeIDs[vkString] then
raise ECFPropertyListException.CreateResFmt(@sInvalidConversion,
[TCFString(CFCopyTypeIDDescription(ID)).AsString(True), 'CFString']); //DO NOT TRANSLATE
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Explicit(PList: TCFArray): TCFPropertyList;
begin
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Explicit(PList: TCFBoolean): TCFPropertyList;
begin
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Explicit(PList: TCFData): TCFPropertyList;
begin
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Explicit(PList: TCFDate): TCFPropertyList;
begin
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Explicit(PList: TCFDictionary): TCFPropertyList;
begin
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Explicit(PList: TCFNumber): TCFPropertyList;
begin
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Explicit(PList: TCFString): TCFPropertyList;
begin
Result.Value := PList.Value;
end;
class operator TCFPropertyList.Implicit(AValue: CFPropertyListRef): TCFPropertyList;
begin
Result.Value := AValue;
end;
{ CFGregorianDateHelper }
class function CFGregorianDateHelper.Create(AValue: TDateTime): CFGregorianDate;
var
Year, Month, Day, Hour, Min, Sec, MSec: Word;
begin
DecodeDateTime(AValue, Year, Month, Day, Hour, Min, Sec, MSec);
Result.year := Year;
Result.month := Month;
Result.day := Day;
Result.hour := Hour;
Result.minute := Min;
Result.second := Sec;
end;
function CFGregorianDateHelper.ToDateTime: TDateTime;
begin
Result := EncodeDateTime(year, month, day, hour, minute, Trunc(second), 0);
end;
end.
|
unit DyObject;
interface
uses SysUtils,TypInfo,Classes,Graphics,Variants;
const
MsgNotGetProp = 'Can`t get write only property';
MsgNotSetProp = 'Can`t set read only property';
type
TDyReader = class (TReader)
private
public
procedure ReadProperty(Instance:TPersistent);
end;
TDyWriter = class (TWriter)
private
public
procedure WriteProperty(Instance:TPersistent; const Name:string);
end;
procedure LoadPropertyFromStream(Instance:TPersistent; Stream:TStream);
procedure SavePropertyToStream(Instance:TPersistent; const PropertyName:string; Stream:TStream);
function GetObjectProperty(Instance:TObject; const Name:string):variant;
function SetObjectProperty(Instance:TObject; const Name:string; const Value:variant):variant;
function GetPropValue(Instance:TObject; PropInfo:PPropInfo):variant;
procedure SetPropValue(Instance:TObject; const PropInfo:PPropInfo; const Value:variant);
function GetPropValueStr(Instance:TObject; PropInfo:PPropInfo):string;
procedure SetPropValueStr(Instance:TObject; const PropInfo:PPropInfo; const Value:string);
implementation
procedure TDyReader.ReadProperty(Instance:TPersistent);
begin
inherited ReadProperty(Instance);
end;
procedure TDyWriter.WriteProperty(Instance:TPersistent; const Name:string);
var
ClassInfo:pointer;
PropInfo:PPropInfo;
begin
ClassInfo:=Instance.ClassInfo;
if ClassInfo=nil then Exit;
PropInfo:=GetPropInfo(ClassInfo,Name);
if PropInfo=nil then Exit;
inherited WriteProperty(Instance,PropInfo);
end;
function GetPropValue(Instance:TObject; PropInfo:PPropInfo):variant;
var
PropType: PTypeInfo;
begin
if PPropInfo(PropInfo)^.GetProc = nil then raise Exception.create(MsgNotGetProp);
PropType:=PPropInfo(PropInfo)^.PropType^;
case PropType^.Kind of
tkInteger,tkChar,tkEnumeration,tkSet: Result:=GetOrdProp(Instance,PropInfo);
tkClass: begin TVarData(Result).VType:=varInteger; TVarData(Result).VInteger:=GetOrdProp(Instance,PropInfo); end;
tkFloat: Result:=GetFloatProp(Instance,PropInfo);
tkString,tkLString,tkWString: VarCast(Result,GetStrProp(Instance,PropInfo),varString);
//tkMethod: Result:=GetOrdProp(Instance,PropInfo);
tkVariant: Result:=GetVariantProp(Instance,PropInfo);
end;
end;
procedure SetPropValue(Instance:TObject; const PropInfo:PPropInfo; const Value:variant);
var
PropType: PTypeInfo;
begin
if PPropInfo(PropInfo)^.SetProc = nil then raise Exception.create(MsgNotSetProp);
PropType:=PPropInfo(PropInfo)^.PropType^;
case PropType^.Kind of
tkInteger: SetOrdProp(Instance,PropInfo,VarAsType(Value,varInteger));
tkChar: SetOrdProp(Instance,PropInfo,VarAsType(Value,varByte));
tkEnumeration: case VarType(Value) of
varOleStr,varString: SetOrdProp(Instance,PropInfo,GetEnumValue(PropType,Value))
else SetOrdProp(Instance,PropInfo,VarAsType(Value,varInteger));
end;
tkFloat: SetFloatProp(Instance,PropInfo,VarAsType(Value,varDouble));
tkString,tkLString,tkWString: SetStrProp(Instance,PropInfo,string(VarAsType(Value,varString)));
tkSet: SetOrdProp(Instance,PropInfo,VarAsType(Value,varInteger));
tkClass: SetOrdProp(Instance,PropInfo,TVarData(Value).VInteger);
//tkMethod: begin VarCast(Value,Value,varInteger); SetMethodProp(Instance,PropInfo,TMethod(pointer(integer(Value))^)); end;
tkVariant: SetVariantProp(Instance,PropInfo,Value);
end;
end;
function GetPropValueStr(Instance:TObject; PropInfo:PPropInfo):string;
var
TypeInfo: PTypeInfo;
TypeData: PTypeData;
begin
if PPropInfo(PropInfo)^.GetProc = nil then raise Exception.create(MsgNotGetProp);
TypeInfo:=PPropInfo(PropInfo)^.PropType^;
case TypeInfo^.Kind of
tkUnknown: Result:='Unknown';
tkInteger: Result:=IntToStr(GetOrdProp(Instance,PropInfo));
tkChar: Result:=IntToStr(GetOrdProp(Instance,PropInfo));
tkEnumeration: Result:=GetEnumName(TypeInfo,GetOrdProp(Instance,PropInfo));
tkSet: Result:=IntToStr(GetOrdProp(Instance,PropInfo));
tkClass: begin
TypeData:=GetTypeData(TypeInfo);
Result:=TypeData.ClassType.ClassName;
end;
tkFloat: Result:=FloatToStr(GetFloatProp(Instance,PropInfo));
tkString,tkLString,tkWString: Result:=GetStrProp(Instance,PropInfo);
tkMethod: Result:='Method';
tkVariant: Result:=VarAsType(GetVariantProp(Instance,PropInfo),varString);
end;
end;
procedure SetPropValueStr(Instance:TObject; const PropInfo:PPropInfo; const Value:string);
var
PropType: PTypeInfo;
begin
if PPropInfo(PropInfo)^.SetProc = nil then raise Exception.create(MsgNotSetProp);
PropType:=PPropInfo(PropInfo)^.PropType^;
try case PropType^.Kind of
tkInteger,tkChar: SetOrdProp(Instance,PropInfo,StrToInt(Value));
tkEnumeration: SetOrdProp(Instance,PropInfo,GetEnumValue(PropType,Value));
tkFloat: SetFloatProp(Instance,PropInfo,StrToFloat(Value));
tkString,tkLString,tkWString: SetStrProp(Instance,PropInfo,Value);
tkSet: SetOrdProp(Instance,PropInfo,StrToInt(Value));
tkVariant: SetVariantProp(Instance,PropInfo,Value);
end except
end;
end;
function GetObjectProperty(Instance:TObject; const Name:string):variant;
var
ClassInfo:pointer;
PropInfo:PPropInfo;
begin
Result:=Unassigned;
ClassInfo:=Instance.ClassInfo;
if ClassInfo=nil then Exit;
PropInfo:=GetPropInfo(ClassInfo,Name);
if PropInfo=nil then Exit;
Result:=GetPropValue(Instance,PropInfo);
end;
function SetObjectProperty(Instance:TObject; const Name:string; const Value:variant):variant;
var
ClassInfo:pointer;
PropInfo:PPropInfo;
begin
ClassInfo:=Instance.ClassInfo;
if ClassInfo=nil then Exit;
PropInfo:=GetPropInfo(ClassInfo,Name);
if PropInfo=nil then Exit;
SetPropValue(Instance,PropInfo,Value);
Result:=Value;
end;
procedure LoadPropertyFromStream(Instance:TPersistent; Stream:TStream);
var
Reader:TDyReader;
begin
Reader:=TDyReader.Create(Stream, 4096);
try
Reader.ReadProperty(Instance);
finally
Reader.Free;
end;
end;
procedure SavePropertyToStream(Instance:TPersistent; const PropertyName:string; Stream:TStream);
var
Writer:TDyWriter;
begin
Writer:=TDyWriter.Create(Stream, 4096);
try
Writer.WriteProperty(Instance,PropertyName);
finally
Writer.Free;
end;
end;
end.
|
unit Ths.Erp.Database.Table.SatisTeklifDetay;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table;
type
TSatisTeklifDetay = class(TTable)
private
FHeaderID: TFieldDB;
FSiparisDetayID: TFieldDB;
FIrsaliyeDetayID: TFieldDB;
FFaturaDetayID: TFieldDB;
FStokKodu: TFieldDB;
FStokAciklama: TFieldDB;
FAciklama: TFieldDB;
FReferans: TFieldDB;
FMiktar: TFieldDB;
FOlcuBirimi: TFieldDB;
FIskontoOrani: TFieldDB;
FFiyat: TFieldDB;
FNetFiyat: TFieldDB;
FTutar: TFieldDB;
FIskontoTutar: TFieldDB;
FNetTutar: TFieldDB;
FKdvOrani: TFieldDB;
FKdvTutar: TFieldDB;
FToplamTutar: TFieldDB;
FVadeGun: TFieldDB;
FIsAnaUrun: TFieldDB;
FAnaUrunID: TFieldDB;
FReferansAnaUrunID: TFieldDB;
FTransferHesapKodu: TFieldDB;
FKdvTransferHesapKodu: TFieldDB;
FVergiKodu: TFieldDB;
FVergiMuafiyetKodu: TFieldDB;
FDigerVergiKodu: TFieldDB;
FGtipNo: TFieldDB;
protected
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
Property HeaderID: TFieldDB read FHeaderID write FHeaderID;
Property SiparisDetayID: TFieldDB read FSiparisDetayID write FSiparisDetayID;
Property IrsaliyeDetayID: TFieldDB read FIrsaliyeDetayID write FIrsaliyeDetayID;
Property FaturaDetayID: TFieldDB read FFaturaDetayID write FFaturaDetayID;
Property StokKodu: TFieldDB read FStokKodu write FStokKodu;
Property StokAciklama: TFieldDB read FStokAciklama write FStokAciklama;
Property Aciklama: TFieldDB read FAciklama write FAciklama;
Property Referans: TFieldDB read FReferans write FReferans;
Property Miktar: TFieldDB read FMiktar write FMiktar;
Property OlcuBirimi: TFieldDB read FOlcuBirimi write FOlcuBirimi;
Property IskontoOrani: TFieldDB read FIskontoOrani write FIskontoOrani;
Property Fiyat: TFieldDB read FFiyat write FFiyat;
Property NetFiyat: TFieldDB read FNetFiyat write FNetFiyat;
Property Tutar: TFieldDB read FTutar write FTutar;
Property IskontoTutar: TFieldDB read FIskontoTutar write FIskontoTutar;
Property NetTutar: TFieldDB read FNetTutar write FNetTutar;
Property KdvOrani: TFieldDB read FKdvOrani write FKdvOrani;
Property KdvTutar: TFieldDB read FKdvTutar write FKdvTutar;
Property ToplamTutar: TFieldDB read FToplamTutar write FToplamTutar;
Property VadeGun: TFieldDB read FVadeGun write FVadeGun;
Property IsAnaUrun: TFieldDB read FIsAnaUrun write FIsAnaUrun;
Property AnaUrunID: TFieldDB read FAnaUrunID write FAnaUrunID;
Property ReferansAnaUrunID: TFieldDB read FReferansAnaUrunID write FReferansAnaUrunID;
Property TransferHesapKodu: TFieldDB read FTransferHesapKodu write FTransferHesapKodu;
Property KdvTransferHesapKodu: TFieldDB read FKdvTransferHesapKodu write FKdvTransferHesapKodu;
Property VergiKodu: TFieldDB read FVergiKodu write FVergiKodu;
Property VergiMuafiyetKodu: TFieldDB read FVergiMuafiyetKodu write FVergiMuafiyetKodu;
Property DigerVergiKodu: TFieldDB read FDigerVergiKodu write FDigerVergiKodu;
Property GtipNo: TFieldDB read FGtipNo write FGtipNo;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TSatisTeklifDetay.Create(OwnerDatabase:TDatabase);
begin
TableName := 'satis_teklif_detay';
SourceCode := '1000';
inherited Create(OwnerDatabase);
FHeaderID := TFieldDB.Create('header_id', ftInteger, 0);
FSiparisDetayID := TFieldDB.Create('siparis_detay_id', ftInteger, 0);
FIrsaliyeDetayID := TFieldDB.Create('irsaliye_detay_id', ftInteger, 0);
FFaturaDetayID := TFieldDB.Create('fatura_detay_id', ftInteger, 0);
FStokKodu := TFieldDB.Create('stok_kodu', ftString, '');
FStokAciklama := TFieldDB.Create('stok_aciklama', ftString, '');
FAciklama := TFieldDB.Create('aciklama', ftString, '');
FReferans := TFieldDB.Create('referans', ftString, '');
FMiktar := TFieldDB.Create('miktar', ftFloat, 0);
FOlcuBirimi := TFieldDB.Create('olcu_birimi', ftString, '');
FIskontoOrani := TFieldDB.Create('iskonto_orani', ftFloat, 0);
FFiyat := TFieldDB.Create('fiyat', ftFloat, 0);
FNetFiyat := TFieldDB.Create('net_fiyat', ftFloat, 0);
FTutar := TFieldDB.Create('tutar', ftFloat, 0);
FIskontoTutar := TFieldDB.Create('iskonto_tutar', ftFloat, 0);
FNetTutar := TFieldDB.Create('net_tutar', ftFloat, 0);
FKdvOrani := TFieldDB.Create('kdv_orani', ftFloat, 0);
FKdvTutar := TFieldDB.Create('kdv_tutar', ftFloat, 0);
FToplamTutar := TFieldDB.Create('toplam_tutar', ftFloat, 0);
FVadeGun := TFieldDB.Create('vade_gun', ftFloat, 0);
FIsAnaUrun := TFieldDB.Create('is_ana_urun', ftBoolean, 0);
FAnaUrunID := TFieldDB.Create('ana_urun_id', ftInteger, 0);
FReferansAnaUrunID := TFieldDB.Create('referans_ana_urun_id', ftInteger, 0);
FTransferHesapKodu := TFieldDB.Create('transfer_hesap_kodu', ftString, '');
FKdvTransferHesapKodu := TFieldDB.Create('kdv_transfer_hesap_kodu', ftString, '');
FVergiKodu := TFieldDB.Create('vergi_kodu', ftString, '');
FVergiMuafiyetKodu := TFieldDB.Create('vergi_muafiyet_kodu', ftString, '');
FDigerVergiKodu := TFieldDB.Create('diger_vergi_kodu', ftString, '');
FGtipNo := TFieldDB.Create('gtip_no', ftString, '');
end;
procedure TSatisTeklifDetay.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FHeaderID.FieldName,
TableName + '.' + FSiparisDetayID.FieldName,
TableName + '.' + FIrsaliyeDetayID.FieldName,
TableName + '.' + FFaturaDetayID.FieldName,
TableName + '.' + FStokKodu.FieldName,
TableName + '.' + FStokAciklama.FieldName,
TableName + '.' + FAciklama.FieldName,
TableName + '.' + FReferans.FieldName,
TableName + '.' + FMiktar.FieldName,
TableName + '.' + FOlcuBirimi.FieldName,
TableName + '.' + FIskontoOrani.FieldName,
TableName + '.' + FFiyat.FieldName,
TableName + '.' + FNetFiyat.FieldName,
TableName + '.' + FTutar.FieldName,
TableName + '.' + FIskontoTutar.FieldName,
TableName + '.' + FNetTutar.FieldName,
TableName + '.' + FKdvOrani.FieldName,
TableName + '.' + FKdvTutar.FieldName,
TableName + '.' + FToplamTutar.FieldName,
TableName + '.' + FVadeGun.FieldName,
TableName + '.' + FIsAnaUrun.FieldName,
TableName + '.' + FAnaUrunID.FieldName,
TableName + '.' + FReferansAnaUrunID.FieldName,
TableName + '.' + FTransferHesapKodu.FieldName,
TableName + '.' + FKdvTransferHesapKodu.FieldName,
TableName + '.' + FVergiKodu.FieldName,
TableName + '.' + FVergiMuafiyetKodu.FieldName,
TableName + '.' + FDigerVergiKodu.FieldName,
TableName + '.' + FGtipNo.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FHeaderID.FieldName).DisplayLabel := 'Header ID';
Self.DataSource.DataSet.FindField(FSiparisDetayID.FieldName).DisplayLabel := 'Sipariş Detay ID';
Self.DataSource.DataSet.FindField(FIrsaliyeDetayID.FieldName).DisplayLabel := 'İrsaliye Detay ID';
Self.DataSource.DataSet.FindField(FFaturaDetayID.FieldName).DisplayLabel := 'Fatura Detay ID';
Self.DataSource.DataSet.FindField(FStokKodu.FieldName).DisplayLabel := 'Stok Kodu';
Self.DataSource.DataSet.FindField(FStokAciklama.FieldName).DisplayLabel := 'Stok Açıklama';
Self.DataSource.DataSet.FindField(FAciklama.FieldName).DisplayLabel := 'Açıklama';
Self.DataSource.DataSet.FindField(FReferans.FieldName).DisplayLabel := 'Referans';
Self.DataSource.DataSet.FindField(FMiktar.FieldName).DisplayLabel := 'Miktar';
Self.DataSource.DataSet.FindField(FOlcuBirimi.FieldName).DisplayLabel := 'Ölçü Birimi';
Self.DataSource.DataSet.FindField(FIskontoOrani.FieldName).DisplayLabel := 'İskonto Oranı';
Self.DataSource.DataSet.FindField(FFiyat.FieldName).DisplayLabel := 'Fiyat';
Self.DataSource.DataSet.FindField(FNetFiyat.FieldName).DisplayLabel := 'Net Fiyat';
Self.DataSource.DataSet.FindField(FTutar.FieldName).DisplayLabel := 'Tutar';
Self.DataSource.DataSet.FindField(FIskontoTutar.FieldName).DisplayLabel := 'İskonto Tutar';
Self.DataSource.DataSet.FindField(FNetTutar.FieldName).DisplayLabel := 'Net Tutar';
Self.DataSource.DataSet.FindField(FKdvOrani.FieldName).DisplayLabel := 'Kdv Oranı';
Self.DataSource.DataSet.FindField(FKdvTutar.FieldName).DisplayLabel := 'Kdv Tutar';
Self.DataSource.DataSet.FindField(FToplamTutar.FieldName).DisplayLabel := 'Toplam Tutar';
Self.DataSource.DataSet.FindField(FVadeGun.FieldName).DisplayLabel := 'Vade Gün';
Self.DataSource.DataSet.FindField(FIsAnaUrun.FieldName).DisplayLabel := 'Ana Ürün?';
Self.DataSource.DataSet.FindField(FAnaUrunID.FieldName).DisplayLabel := 'Ana Ürün ID';
Self.DataSource.DataSet.FindField(FReferansAnaUrunID.FieldName).DisplayLabel := 'Referans Ana Ürün ID';
Self.DataSource.DataSet.FindField(FTransferHesapKodu.FieldName).DisplayLabel := 'Transfer Hesap Kodu';
Self.DataSource.DataSet.FindField(FKdvTransferHesapKodu.FieldName).DisplayLabel := 'Kdv Transfer Hesap Kodu';
Self.DataSource.DataSet.FindField(FVergiKodu.FieldName).DisplayLabel := 'Vergi Kodu';
Self.DataSource.DataSet.FindField(FVergiMuafiyetKodu.FieldName).DisplayLabel := 'Vergi Muafiyet Kodu';
Self.DataSource.DataSet.FindField(FDigerVergiKodu.FieldName).DisplayLabel := 'Diğer Vergi Kodu';
Self.DataSource.DataSet.FindField(FGtipNo.FieldName).DisplayLabel := 'Gtip No';
end;
end;
end;
procedure TSatisTeklifDetay.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FHeaderID.FieldName,
TableName + '.' + FSiparisDetayID.FieldName,
TableName + '.' + FIrsaliyeDetayID.FieldName,
TableName + '.' + FFaturaDetayID.FieldName,
TableName + '.' + FStokKodu.FieldName,
TableName + '.' + FStokAciklama.FieldName,
TableName + '.' + FAciklama.FieldName,
TableName + '.' + FReferans.FieldName,
TableName + '.' + FMiktar.FieldName,
TableName + '.' + FOlcuBirimi.FieldName,
TableName + '.' + FIskontoOrani.FieldName,
TableName + '.' + FFiyat.FieldName,
TableName + '.' + FNetFiyat.FieldName,
TableName + '.' + FTutar.FieldName,
TableName + '.' + FIskontoTutar.FieldName,
TableName + '.' + FNetTutar.FieldName,
TableName + '.' + FKdvOrani.FieldName,
TableName + '.' + FKdvTutar.FieldName,
TableName + '.' + FToplamTutar.FieldName,
TableName + '.' + FVadeGun.FieldName,
TableName + '.' + FIsAnaUrun.FieldName,
TableName + '.' + FAnaUrunID.FieldName,
TableName + '.' + FReferansAnaUrunID.FieldName,
TableName + '.' + FTransferHesapKodu.FieldName,
TableName + '.' + FKdvTransferHesapKodu.FieldName,
TableName + '.' + FVergiKodu.FieldName,
TableName + '.' + FVergiMuafiyetKodu.FieldName,
TableName + '.' + FDigerVergiKodu.FieldName,
TableName + '.' + FGtipNo.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FHeaderID.Value := FormatedVariantVal(FieldByName(FHeaderID.FieldName).DataType, FieldByName(FHeaderID.FieldName).Value);
FSiparisDetayID.Value := FormatedVariantVal(FieldByName(FSiparisDetayID.FieldName).DataType, FieldByName(FSiparisDetayID.FieldName).Value);
FIrsaliyeDetayID.Value := FormatedVariantVal(FieldByName(FIrsaliyeDetayID.FieldName).DataType, FieldByName(FIrsaliyeDetayID.FieldName).Value);
FFaturaDetayID.Value := FormatedVariantVal(FieldByName(FFaturaDetayID.FieldName).DataType, FieldByName(FFaturaDetayID.FieldName).Value);
FStokKodu.Value := FormatedVariantVal(FieldByName(FStokKodu.FieldName).DataType, FieldByName(FStokKodu.FieldName).Value);
FStokAciklama.Value := FormatedVariantVal(FieldByName(FStokAciklama.FieldName).DataType, FieldByName(FStokAciklama.FieldName).Value);
FAciklama.Value := FormatedVariantVal(FieldByName(FAciklama.FieldName).DataType, FieldByName(FAciklama.FieldName).Value);
FReferans.Value := FormatedVariantVal(FieldByName(FReferans.FieldName).DataType, FieldByName(FReferans.FieldName).Value);
FMiktar.Value := FormatedVariantVal(FieldByName(FMiktar.FieldName).DataType, FieldByName(FMiktar.FieldName).Value);
FOlcuBirimi.Value := FormatedVariantVal(FieldByName(FOlcuBirimi.FieldName).DataType, FieldByName(FOlcuBirimi.FieldName).Value);
FIskontoOrani.Value := FormatedVariantVal(FieldByName(FIskontoOrani.FieldName).DataType, FieldByName(FIskontoOrani.FieldName).Value);
FFiyat.Value := FormatedVariantVal(FieldByName(FFiyat.FieldName).DataType, FieldByName(FFiyat.FieldName).Value);
FNetFiyat.Value := FormatedVariantVal(FieldByName(FNetFiyat.FieldName).DataType, FieldByName(FNetFiyat.FieldName).Value);
FTutar.Value := FormatedVariantVal(FieldByName(FTutar.FieldName).DataType, FieldByName(FTutar.FieldName).Value);
FIskontoTutar.Value := FormatedVariantVal(FieldByName(FIskontoTutar.FieldName).DataType, FieldByName(FIskontoTutar.FieldName).Value);
FNetTutar.Value := FormatedVariantVal(FieldByName(FNetTutar.FieldName).DataType, FieldByName(FNetTutar.FieldName).Value);
FKdvOrani.Value := FormatedVariantVal(FieldByName(FKdvOrani.FieldName).DataType, FieldByName(FKdvOrani.FieldName).Value);
FKdvTutar.Value := FormatedVariantVal(FieldByName(FKdvTutar.FieldName).DataType, FieldByName(FKdvTutar.FieldName).Value);
FToplamTutar.Value := FormatedVariantVal(FieldByName(FToplamTutar.FieldName).DataType, FieldByName(FToplamTutar.FieldName).Value);
FVadeGun.Value := FormatedVariantVal(FieldByName(FVadeGun.FieldName).DataType, FieldByName(FVadeGun.FieldName).Value);
FIsAnaUrun.Value := FormatedVariantVal(FieldByName(FIsAnaUrun.FieldName).DataType, FieldByName(FIsAnaUrun.FieldName).Value);
FAnaUrunID.Value := FormatedVariantVal(FieldByName(FAnaUrunID.FieldName).DataType, FieldByName(FAnaUrunID.FieldName).Value);
FReferansAnaUrunID.Value := FormatedVariantVal(FieldByName(FReferansAnaUrunID.FieldName).DataType, FieldByName(FReferansAnaUrunID.FieldName).Value);
FTransferHesapKodu.Value := FormatedVariantVal(FieldByName(FTransferHesapKodu.FieldName).DataType, FieldByName(FTransferHesapKodu.FieldName).Value);
FKdvTransferHesapKodu.Value := FormatedVariantVal(FieldByName(FKdvTransferHesapKodu.FieldName).DataType, FieldByName(FKdvTransferHesapKodu.FieldName).Value);
FVergiKodu.Value := FormatedVariantVal(FieldByName(FVergiKodu.FieldName).DataType, FieldByName(FVergiKodu.FieldName).Value);
FVergiMuafiyetKodu.Value := FormatedVariantVal(FieldByName(FVergiMuafiyetKodu.FieldName).DataType, FieldByName(FVergiMuafiyetKodu.FieldName).Value);
FDigerVergiKodu.Value := FormatedVariantVal(FieldByName(FDigerVergiKodu.FieldName).DataType, FieldByName(FDigerVergiKodu.FieldName).Value);
FGtipNo.Value := FormatedVariantVal(FieldByName(FGtipNo.FieldName).DataType, FieldByName(FGtipNo.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TSatisTeklifDetay.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FHeaderID.FieldName,
FSiparisDetayID.FieldName,
FIrsaliyeDetayID.FieldName,
FFaturaDetayID.FieldName,
FStokKodu.FieldName,
FStokAciklama.FieldName,
FAciklama.FieldName,
FReferans.FieldName,
FMiktar.FieldName,
FOlcuBirimi.FieldName,
FIskontoOrani.FieldName,
FFiyat.FieldName,
FNetFiyat.FieldName,
FTutar.FieldName,
FIskontoTutar.FieldName,
FNetTutar.FieldName,
FKdvOrani.FieldName,
FKdvTutar.FieldName,
FToplamTutar.FieldName,
FVadeGun.FieldName,
FIsAnaUrun.FieldName,
FAnaUrunID.FieldName,
FReferansAnaUrunID.FieldName,
FTransferHesapKodu.FieldName,
FKdvTransferHesapKodu.FieldName,
FVergiKodu.FieldName,
FVergiMuafiyetKodu.FieldName,
FDigerVergiKodu.FieldName,
FGtipNo.FieldName
]);
NewParamForQuery(QueryOfInsert, FHeaderID);
NewParamForQuery(QueryOfInsert, FSiparisDetayID);
NewParamForQuery(QueryOfInsert, FIrsaliyeDetayID);
NewParamForQuery(QueryOfInsert, FFaturaDetayID);
NewParamForQuery(QueryOfInsert, FStokKodu);
NewParamForQuery(QueryOfInsert, FStokAciklama);
NewParamForQuery(QueryOfInsert, FAciklama);
NewParamForQuery(QueryOfInsert, FReferans);
NewParamForQuery(QueryOfInsert, FMiktar);
NewParamForQuery(QueryOfInsert, FOlcuBirimi);
NewParamForQuery(QueryOfInsert, FIskontoOrani);
NewParamForQuery(QueryOfInsert, FFiyat);
NewParamForQuery(QueryOfInsert, FNetFiyat);
NewParamForQuery(QueryOfInsert, FTutar);
NewParamForQuery(QueryOfInsert, FIskontoTutar);
NewParamForQuery(QueryOfInsert, FNetTutar);
NewParamForQuery(QueryOfInsert, FKdvOrani);
NewParamForQuery(QueryOfInsert, FKdvTutar);
NewParamForQuery(QueryOfInsert, FToplamTutar);
NewParamForQuery(QueryOfInsert, FVadeGun);
NewParamForQuery(QueryOfInsert, FIsAnaUrun);
NewParamForQuery(QueryOfInsert, FAnaUrunID);
NewParamForQuery(QueryOfInsert, FReferansAnaUrunID);
NewParamForQuery(QueryOfInsert, FTransferHesapKodu);
NewParamForQuery(QueryOfInsert, FKdvTransferHesapKodu);
NewParamForQuery(QueryOfInsert, FVergiKodu);
NewParamForQuery(QueryOfInsert, FVergiMuafiyetKodu);
NewParamForQuery(QueryOfInsert, FDigerVergiKodu);
NewParamForQuery(QueryOfInsert, FGtipNo);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TSatisTeklifDetay.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FHeaderID.FieldName,
FSiparisDetayID.FieldName,
FIrsaliyeDetayID.FieldName,
FFaturaDetayID.FieldName,
FStokKodu.FieldName,
FStokAciklama.FieldName,
FAciklama.FieldName,
FReferans.FieldName,
FMiktar.FieldName,
FOlcuBirimi.FieldName,
FIskontoOrani.FieldName,
FFiyat.FieldName,
FNetFiyat.FieldName,
FTutar.FieldName,
FIskontoTutar.FieldName,
FNetTutar.FieldName,
FKdvOrani.FieldName,
FKdvTutar.FieldName,
FToplamTutar.FieldName,
FVadeGun.FieldName,
FIsAnaUrun.FieldName,
FAnaUrunID.FieldName,
FReferansAnaUrunID.FieldName,
FTransferHesapKodu.FieldName,
FKdvTransferHesapKodu.FieldName,
FVergiKodu.FieldName,
FVergiMuafiyetKodu.FieldName,
FDigerVergiKodu.FieldName,
FGtipNo.FieldName
]);
NewParamForQuery(QueryOfUpdate, FHeaderID);
NewParamForQuery(QueryOfUpdate, FSiparisDetayID);
NewParamForQuery(QueryOfUpdate, FIrsaliyeDetayID);
NewParamForQuery(QueryOfUpdate, FFaturaDetayID);
NewParamForQuery(QueryOfUpdate, FStokKodu);
NewParamForQuery(QueryOfUpdate, FStokAciklama);
NewParamForQuery(QueryOfUpdate, FAciklama);
NewParamForQuery(QueryOfUpdate, FReferans);
NewParamForQuery(QueryOfUpdate, FMiktar);
NewParamForQuery(QueryOfUpdate, FOlcuBirimi);
NewParamForQuery(QueryOfUpdate, FIskontoOrani);
NewParamForQuery(QueryOfUpdate, FFiyat);
NewParamForQuery(QueryOfUpdate, FNetFiyat);
NewParamForQuery(QueryOfUpdate, FTutar);
NewParamForQuery(QueryOfUpdate, FIskontoTutar);
NewParamForQuery(QueryOfUpdate, FNetTutar);
NewParamForQuery(QueryOfUpdate, FKdvOrani);
NewParamForQuery(QueryOfUpdate, FKdvTutar);
NewParamForQuery(QueryOfUpdate, FToplamTutar);
NewParamForQuery(QueryOfUpdate, FVadeGun);
NewParamForQuery(QueryOfUpdate, FIsAnaUrun);
NewParamForQuery(QueryOfUpdate, FAnaUrunID);
NewParamForQuery(QueryOfUpdate, FReferansAnaUrunID);
NewParamForQuery(QueryOfUpdate, FTransferHesapKodu);
NewParamForQuery(QueryOfUpdate, FKdvTransferHesapKodu);
NewParamForQuery(QueryOfUpdate, FVergiKodu);
NewParamForQuery(QueryOfUpdate, FVergiMuafiyetKodu);
NewParamForQuery(QueryOfUpdate, FDigerVergiKodu);
NewParamForQuery(QueryOfUpdate, FGtipNo);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TSatisTeklifDetay.Clone():TTable;
begin
Result := TSatisTeklifDetay.Create(Database);
Self.Id.Clone(TSatisTeklifDetay(Result).Id);
FHeaderID.Clone(TSatisTeklifDetay(Result).FHeaderID);
FSiparisDetayID.Clone(TSatisTeklifDetay(Result).FSiparisDetayID);
FIrsaliyeDetayID.Clone(TSatisTeklifDetay(Result).FIrsaliyeDetayID);
FFaturaDetayID.Clone(TSatisTeklifDetay(Result).FFaturaDetayID);
FStokKodu.Clone(TSatisTeklifDetay(Result).FStokKodu);
FStokAciklama.Clone(TSatisTeklifDetay(Result).FStokAciklama);
FAciklama.Clone(TSatisTeklifDetay(Result).FAciklama);
FReferans.Clone(TSatisTeklifDetay(Result).FReferans);
FMiktar.Clone(TSatisTeklifDetay(Result).FMiktar);
FOlcuBirimi.Clone(TSatisTeklifDetay(Result).FOlcuBirimi);
FIskontoOrani.Clone(TSatisTeklifDetay(Result).FIskontoOrani);
FFiyat.Clone(TSatisTeklifDetay(Result).FFiyat);
FNetFiyat.Clone(TSatisTeklifDetay(Result).FNetFiyat);
FTutar.Clone(TSatisTeklifDetay(Result).FTutar);
FIskontoTutar.Clone(TSatisTeklifDetay(Result).FIskontoTutar);
FNetTutar.Clone(TSatisTeklifDetay(Result).FNetTutar);
FKdvOrani.Clone(TSatisTeklifDetay(Result).FKdvOrani);
FKdvTutar.Clone(TSatisTeklifDetay(Result).FKdvTutar);
FToplamTutar.Clone(TSatisTeklifDetay(Result).FToplamTutar);
FVadeGun.Clone(TSatisTeklifDetay(Result).FVadeGun);
FIsAnaUrun.Clone(TSatisTeklifDetay(Result).FIsAnaUrun);
FAnaUrunID.Clone(TSatisTeklifDetay(Result).FAnaUrunID);
FReferansAnaUrunID.Clone(TSatisTeklifDetay(Result).FReferansAnaUrunID);
FTransferHesapKodu.Clone(TSatisTeklifDetay(Result).FTransferHesapKodu);
FKdvTransferHesapKodu.Clone(TSatisTeklifDetay(Result).FKdvTransferHesapKodu);
FVergiKodu.Clone(TSatisTeklifDetay(Result).FVergiKodu);
FVergiMuafiyetKodu.Clone(TSatisTeklifDetay(Result).FVergiMuafiyetKodu);
FDigerVergiKodu.Clone(TSatisTeklifDetay(Result).FDigerVergiKodu);
FGtipNo.Clone(TSatisTeklifDetay(Result).FGtipNo);
end;
end.
|
unit mml_var;
{-------------------------------------------------------------------------------
ソフト:テキスト音楽「サクラ」
作 者:クジラ飛行机 https://sakuramml.com
説 明:サクラの基本型タイプを宣言しているユニット
(設計的にはどうかなぁ・・・、コンパイル速度を下げている原因かも。要調査)
履 歴:
2002/06/03 15:13 雛型作成
-------------------------------------------------------------------------------}
interface
uses
{$ifdef Win32}
Windows,
{$endif}
SysUtils,
Classes,
hashUnit,
mml_const,
mml_error;
type
{$ifdef Win32}
{$else}
PBOOL = ^Boolean;
{$endif}
PMmlOnProgress = ^TMmlOnProgress;
TMmlOnProgress = procedure (NowLine, LineCount: Integer; msg: PChar; StopCompile: PBOOL); stdcall;
TIntArray = array of Integer;
//----------------------------------------------------------------------------
//基本型(数値、文字、配列)
TMVarCustom = class
function clone: TMVarCustom; virtual; abstract;
procedure Assign(c: TMVarCustom); virtual;
function IntValue: Integer; virtual;
function StrValue: string; virtual;
end;
//4ビット整数
TMInt = class(TMVarCustom)
public
Flag: Char; // % など、数値の前に付くMML特有のフラグを保持する
value: Integer;
function clone: TMVarCustom; override;
procedure Assign(c: TMVarCustom); override;
function IntValue: Integer; override;
function StrValue: string; override;
end;
//文字列型
TMStr = class(TMVarCustom)
public
value: string;
function clone: TMVarCustom; override;
procedure Assign(c: TMVarCustom); override;
function IntValue: Integer; override;
function StrValue: string; override;
function LoadFromFile(const fname: string): Integer;
end;
//配列方:整数と文字列の混同が可能
TArrayOfByte = array of Byte;
TMArray = class(TMVarCustom)
private
list: TList;
function getValue(Index: Integer): TMVarCustom;
procedure setValue( Index: Integer; v: TMVarCustom );
function getInt(Index: Integer): Integer;
procedure setInt(Index: Integer; v: Integer);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function Add( v: TMVarCustom ): Integer;
procedure Delete( Index: Integer);
function AddInt( v: Integer): Integer;
property Items[Index: Integer]: TMVarCustom read getValue write setValue;
property IntItems[ Index: Integer]: Integer read getInt write setint;
function AddArray(v: TMArray): Integer;
function Count: Integer;
function clone: TMVarCustom; override;
procedure Assign(c: TMVarCustom); override;
procedure AssignToArrayOfByte(var ary: TArrayOfByte);
function StrValue: string; override;
procedure Insert(Index: Integer; value: TMVarCustom);
procedure SortStr;
procedure SortNum;
end;
//----------------------------------------------------------------------------
//実行ソース制御
TSrcPos = class
src: string; //一時的なソース記憶領域
public
ptr: PChar; //実行中のポインタをさす
lineNo: Integer;
fileNo: Integer;
cmd: string; //実行中のコマンド名
procedure Assign(v: TSrcPos);
procedure SetTempSource(s: string);
end;
//----------------------------------------------------------------------------
//システム関数
TMFuncObj = function (var sp: TSrcPos): TMVarCustom of Object;//基本型
TMFunc = class(TMVarCustom)
public
funcPtr: TMFuncObj;
function Execute( var sp: TSrcPos ): TMVarCustom;
function clone: TMVarCustom; override;
end;
TArrayStr = array of string;
TMUserFunc = class(TMVarCustom)
public
ArgType: string;
ArgName: TArrayStr;
ArgInit: TMArray;
Src: TSrcPos;
constructor Create;
destructor Destroy; override;
function clone: TMVarCustom; override;
end;
//----------------------------------------------------------------------------
//変数管理
TMNodeType = (ntInt, ntStr, ntArray, ntSysFunc, ntUserFunc);
TMHashNode = class(THashNode)
public
DefinePos: TSrcPos;//宣言された場所を示す
nodeType: TMNodeType;
value: TMVarCustom;
tag: Integer;
constructor Create(key: string);
destructor Destroy; override;
function Count: Integer;
end;
TMVarHash = class(THash)
protected
function GetValue(key: string): TMHashNode;
public
Parent: TMVarHash;
property Items[key: string]: TMHashNode read GetValue;
function ExistsLocalKey(key: string): Boolean;//ローカルエリアに同名のキーがないかチェック
end;
//----------------------------------------------------------------------------
//スクリプト階層クラス
TMStructType = (stNormal, stFunction, stFor, stLoop, stWhile, stIf, stSwitch);
TMStruct = class
public
Parent: TMStruct;
StructType: TMStructType;
PosFrom,
PosTo: TSrcPos;//While For などで実行範囲を示す(Create で生成)
PosElse: TSrcPos;//IF の FALSE などで実行範囲を示す(If の時だけ生成される)
LoopIndex: Integer;
LoopCount: Integer;
Jouken, siki1, siki2: string;
varHash: TMVarHash ; //その階層の、Commandsを覚えておく
constructor Create(parent: TMStruct; tp: TMStructType);
destructor Destroy; override;
end;
var
OnProgress: TMmlOnProgress; //--- PROGRESS
implementation
{ TMVarHash }
function TMVarHash.ExistsLocalKey(key: string): Boolean;
begin
if nil = TMHashNode( Self.Find( key ) ) then
Result := False
else
Result := True;
end;
function TMVarHash.GetValue(key: string): TMHashNode;
begin
Result := TMHashNode( Self.Find( key ) );
if Result=nil then
begin
//再起的に親を調べる
if Self.Parent = nil then Exit;
Result := Self.Parent.GetValue( key );
end;
end;
{ TSrcPos }
procedure TSrcPos.Assign(v: TSrcPos);
begin
ptr := v.ptr;
lineNo := v.lineNo;
fileNo := v.fileNo;
src := v.src;
cmd := v.cmd ;
end;
procedure TSrcPos.SetTempSource(s: string);
begin
src := s;
ptr := PChar(src);
end;
{ TMArray }
function TMArray.Add(v: TMVarCustom): Integer;
begin
Result := list.Add(v);
end;
function TMArray.AddArray(v: TMArray): Integer;
var
i,c: Integer;
vc: TMVarCustom;
begin
c := Count;
Result := c + v.Count;
list.Count := Result;
for i:=0 to v.Count -1 do
begin
vc := v.Items[i];
if vc<>nil then
Items[c + i] := vc.clone
else
Items[c + i] := nil;
end;
end;
function TMArray.AddInt(v: Integer): Integer;
var
i: TMInt;
begin
i := TMInt.Create ;
i.value := v;
Result := Add(i);
end;
procedure TMArray.Assign(c: TMVarCustom);
begin
inherited;
Self.Clear ;
Self.AddArray(c as TMArray);
end;
procedure TMArray.AssignToArrayOfByte(var ary: TArrayOfByte);
var
i: Integer;
begin
if Count=0 then
begin
ary := nil; Exit;
end;
SetLength(ary, Count);
for i:=0 to Count-1 do
begin
ary[i] := Byte( IntItems[ i ] );
end;
end;
procedure TMArray.Clear;
var
i: Integer;
v: TMVarCustom ;
begin
for i:=0 to list.Count -1 do
begin
v := list.Items[i];
if v<> nil then v.Free ;
end;
list.Clear ;
end;
function TMArray.clone: TMVarCustom;
begin
Result := TMArray.Create ;
TMArray(Result).Assign(Self);
end;
function TMArray.Count: Integer;
begin
Result := list.Count ;
end;
constructor TMArray.Create;
begin
list := TList.Create ;
end;
procedure TMArray.Delete(Index: Integer);
begin
list.Delete(Index);
end;
destructor TMArray.Destroy;
begin
Clear;
list.Free ;
inherited;
end;
function TMArray.getInt(Index: Integer): Integer;
var v: TMVarCustom;
begin
Result := 0;
v := Items[Index];
if v<>nil then
if v.ClassType = TMInt then
begin
Result := (v as TMInt).value ;
end;
end;
function TMArray.getValue(Index: Integer): TMVarCustom;
begin
if ( Index < 0) or ( Index >= list.Count ) then
begin
Result := nil;
end else
Result := list.Items[Index];
end;
procedure TMArray.Insert(Index: Integer; value: TMVarCustom);
begin
list.Insert(Index, value);
end;
procedure TMArray.setInt(Index, v: Integer);
var vc: TMVarCustom;
begin
vc := Items[Index];
if vc<>nil then vc.Free ;
vc := TMInt.Create ;
TMInt(vc).value := v;
Items[Index] := vc;
end;
procedure TMArray.setValue(Index: Integer; v: TMVarCustom);
begin
if Index >= list.Count then
begin
list.Count := Index+1;
end;
list.Items[ Index ] := v;
end;
function sort_num(Item1, Item2: Pointer): Integer;
var
i1, i2: TMVarCustom;
begin
i1 := TMVarCustom(Item1);
i2 := TMVarCustom(Item2);
Result := i1.IntValue - i2.IntValue ;
end;
function sort_str(Item1, Item2: Pointer): Integer;
var
i1, i2: TMVarCustom;
begin
i1 := TMVarCustom(Item1);
i2 := TMVarCustom(Item2);
Result := AnsiCompareStr(i1.StrValue, i2.StrValue) ;
end;
procedure TMArray.SortNum;
begin
list.Sort(sort_num);
end;
procedure TMArray.SortStr;
begin
list.Sort(sort_str);
end;
function TMArray.StrValue: string;
var
i: Integer;
o: TMVarCustom ;
begin
Result := '';
for i:=0 to Count-1 do
begin
o := Items[i];
if o <> nil then
Result := Result + o.StrValue ;
if (i <> Count-1) then
Result := Result + ', ';
end;
end;
{ TMFunc }
function TMFunc.clone: TMVarCustom;
begin
Result := TMFunc.Create ;
TMFunc(Result).funcPtr := Self.funcPtr ;
end;
function TMFunc.Execute(var sp: TSrcPos): TMVarCustom;
begin
Result := funcPtr(sp);
end;
{ TMInt }
procedure TMInt.Assign(c: TMVarCustom);
begin
inherited;
value := TMInt(c).value;
Flag := TMInt(c).Flag;
end;
function TMInt.clone: TMVarCustom;
begin
Result := TMInt.Create ;
TMInt(Result).Assign(Self);
end;
function TMInt.IntValue: Integer;
begin
Result := value;
end;
function TMInt.StrValue: string;
begin
Result := IntToStr(value);
end;
{ TMStr }
procedure TMStr.Assign(c: TMVarCustom);
begin
inherited;
value := TMStr(c).value;
end;
function TMStr.clone: TMVarCustom;
begin
Result := TMStr.Create ;
TMStr(Result).value := value;
end;
function TMStr.IntValue: Integer;
begin
Result := StrToIntDef(value, 0);
end;
function TMStr.LoadFromFile(const fname: string): Integer;
var
s: TStringList;
begin
s := TStringList.Create ;
try
try
s.LoadFromFile(fname);
value := s.Text ;
Result := s.Count ;
except
Result := -1;
end;
finally
s.Free ;
end;
end;
function TMStr.StrValue: string;
begin
Result := value;
end;
{ TMVarCustom }
procedure TMVarCustom.Assign(c: TMVarCustom);
begin
if c.ClassType <> ClassType then raise EInvalidOperation.Create('Assignできません。');
end;
function TMVarCustom.IntValue: Integer;
begin
Result := 0;
end;
function TMVarCustom.StrValue: string;
begin
Result := '';
end;
{ TMUserFunc }
function TMUserFunc.clone: TMVarCustom;
begin
Result := TMUserFunc.Create ;
TMUserFunc(Result).Src := Src ;
TMUserFunc(Result).ArgType := ArgType ;
if ArgInit<> nil then
TMUserFunc(Result).ArgInit := ArgInit.clone as TMArray
else
TMUserFunc(Result).ArgInit := nil;
if ArgName <> nil then
TMUserFUnc(Result).ArgName := Copy(ArgName,0, Length(ArgName));
end;
constructor TMUserFunc.Create;
begin
ArgName := nil;
ArgInit := TMArray.Create ;
Src := TSrcPos.Create ;
end;
destructor TMUserFunc.Destroy;
begin
if ArgInit <> nil then ArgInit.Free;
Src.Free ;
inherited;
end;
{ TMStruct }
constructor TMStruct.Create(parent: TMStruct; tp: TMStructType);
begin
StructType := tp;
//階層構造を記憶するために必要な位置クラス生成
PosFrom := TSrcPos.Create ;
PosTo := TSrcPos.Create ;
if tp = stIf then
begin
PosElse := TSrcPos.Create ;
end;
//変数を管理するハッシュを生成
varHash := TMVarHash.Create ;
//親と子を結びつける
Self.Parent := parent; //Self親
if parent<>nil then
begin
varHash.Parent := parent.varHash ;//変数管理用の親
end;
//ループ回数記憶用
LoopCount := 0;
LoopIndex := -1;
end;
destructor TMStruct.Destroy;
begin
//varHashは、破棄したら、Commandsの値を付け替える必要がある
varHash.Free ;
PosFrom.Free ;
PosTo.Free ;
if StructType = stIf then
begin
PosElse.Free ;
end;
inherited;
end;
{ TMHashNode }
function TMHashNode.Count: Integer;
var
cnt: Integer;
p: THashNode;
begin
cnt := 0;
p := Self;
while p <> nil do
begin
Inc(cnt);
p := p.LinkNext;
end;
Result := cnt;
end;
constructor TMHashNode.Create(key: string);
begin
inherited Create(key);
DefinePos := TSrcPos.Create ;
value := nil;
end;
destructor TMHashNode.Destroy;
begin
DefinePos.Free ;
if value <> nil then value.Free ;
inherited;
end;
end.
|
unit ImprimirRelatorioFormUn;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, osCustomEditFrm, Menus, ImgList, DB, ActnList, osActionList, SQLMainData,
Buttons, ExtCtrls, osUtils, DBClient, osClientDataset, StdCtrls, Mask,
wwdbedit, Wwdotdot, Wwdbcomb, osComboFilter, osSQLQuery, ppReport,
ppComm, ppRelatv, ppProd, ppClass, osCustomSearchFrm, ppMemo, TypInfo,
printers, ppTypes, ppDB, ppParameter, System.Actions;
type
TImprimirRelatorioForm = class(TosCustomEditForm)
osClientDataset1: TosClientDataset;
Report: TppReport;
FilterDataSet: TosClientDataset;
ComboFilter: TosComboFilter;
procedure ReportPreviewFormCreate(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
protected
procedure ImprimirRelatorioComFiltro(idRelatorio: integer);
function findComponentUserName(name: String): TComponent;
procedure ImprimirTemplate(templateName: string);
procedure afterLoadStream; virtual;
function findPipeline(name: string): TppDataPipeline;
public
function Edit(const KeyFields: string; const KeyValues: Variant): boolean; override;
end;
var
ImprimirRelatorioForm: TImprimirRelatorioForm;
implementation
uses osReportUtils, acCustomSQLMainDataUn, osFrm, acCustomParametroSistemaDataUn,
acCustomReportUn, ReportUn, ParametroSistemaDataUn, StatusUnit;
{$R *.dfm}
{ TImprimirRelatorioForm }
function TImprimirRelatorioForm.Edit(const KeyFields: string;
const KeyValues: Variant): boolean;
begin
ImprimirRelatorioComFiltro(KeyValues);
result := true;
end;
procedure TImprimirRelatorioForm.ImprimirRelatorioComFiltro(idRelatorio: integer);
var
stream: TMemoryStream;
qry: TosSQLQuery;
updateContadorImpressao : TosSQLQuery;
templateName, FilterName: string;
srchForm: TCustomSearchForm;
config: TConfigImpressao;
extensao: string;
FTextFileName: string;
where, order: string;
begin
config.orientation := -1;
config.larguraPapel := -1;
config.alturaPapel := -1;
config.margemSuperior := -1;
config.margemInferior := -1;
config.margemEsquerda := -1;
config.margemDireita := -1;
config.tipoSaida := 'T';
FTextFileName := '';
//buscar informações no catálogo de relatórios
qry := acCustomSQLMainData.GetQuery;
try
qry.sql.Text := 'SELECT ' +
' R.Titulo, '+
' RB.Name as TemplateName, '+
' F.Name as NomeFiltro, ' +
' R.ClasseImpressora, ' +
' R.MargemSuperior, ' +
' R.MargemInferior, ' +
' R.MargemEsquerda, ' +
' R.MargemDireita, ' +
' R.AlturaPapel, ' +
' R.LarguraPapel, ' +
' R.Titulo, ' +
' R.Orientation, R.tipoSaida ' +
' FROM Relatorio R ' +
' LEFT JOIN XFilterDef F ' +
' ON F.IDXFilterDef=R.IDXFilterDef ' +
' JOIN RB_ITEM RB' +
' ON RB.ITEM_ID = R.ITEM_ID ' +
' WHERE IdRelatorio=' + IntToStr(idRelatorio);
qry.Open;
templateName := qry.FieldByName('TemplateName').AsString;
FilterName := qry.FieldByName('NomeFiltro').AsString;
config.nomeImpressora := acCustomParametroSistemaData.getNomeImpressoraClasse(qry.FieldByName('ClasseImpressora').AsString);
if not qry.fieldByName('orientation').IsNull then
config.orientation := qry.fieldByName('orientation').AsInteger;
if not qry.fieldByName('larguraPapel').IsNull then
config.larguraPapel := qry.fieldByName('larguraPapel').AsInteger;
if not qry.fieldByName('alturaPapel').IsNull then
config.alturaPapel := qry.fieldByName('alturaPapel').AsInteger;
if not qry.fieldByName('margemSuperior').IsNull then
config.margemSuperior := qry.fieldByName('margemSuperior').AsInteger;
if not qry.fieldByName('margemInferior').IsNull then
config.margemInferior := qry.fieldByName('margemInferior').AsInteger;
if not qry.fieldByName('margemEsquerda').IsNull then
config.margemEsquerda := qry.fieldByName('margemEsquerda').AsInteger;
if not qry.fieldByName('margemDireita').IsNull then
config.margemDireita := qry.fieldByName('margemDireita').AsInteger;
if not qry.fieldByName('tipoSaida').IsNull then
config.tipoSaida := qry.fieldByName('tipoSaida').AsString;
config.NomeRelatorio := TemplateName;
stream := TMemoryStream.Create;
getTemplateByName(TemplateName, stream);
if FilterName <> '' then
begin
ComboFilter.ClearViews;
ComboFilter.FilterDefName := FilterName;
ComboFilter.GetViews();
srchForm := TCustomSearchForm.Create(application);
with srchForm do
begin
FilterDefName := filterName;
srchForm.DataProvider := acCustomSQLMainData.prvFilter;
Execute('',3,toRetornarQuery);
where := GetExpressions;
order := getOrder;
if ConsultaCombo.GetExprList(ConsultaCombo.Items.IndexOf(ConsultaCombo.Text)).Text <> '' then
begin
if where = '' then
where := ConsultaCombo.GetExprList(ConsultaCombo.Items.IndexOf(ConsultaCombo.Text)).Text
else
where := where + ' AND ' +
ConsultaCombo.GetExprList(ConsultaCombo.Items.IndexOf(ConsultaCombo.Text)).Text;
end;
replaceReportSQLAddParam(report, stream, sqlResult.Text, Trim(where), Trim(order));
free;
end;
end
else
Report.Template.LoadFromStream(stream);
report.Units := utMillimeters;
if config.nomeImpressora<>'' then
report.PrinterSetup.PrinterName :=
config.nomeImpressora;
if config.orientation = 1 then
report.PrinterSetup.Orientation := poPortrait;
if config.orientation = 2 then
report.PrinterSetup.Orientation := poLandscape;
if config.alturaPapel <> -1 then
Report.PrinterSetup.PaperHeight := config.alturaPapel;
if config.larguraPapel <> -1 then
Report.PrinterSetup.PaperWidth := config.larguraPapel;
if config.margemInferior <> -1 then
Report.PrinterSetup.MarginBottom := config.margemInferior;
if config.margemEsquerda <> -1 then
Report.PrinterSetup.MarginLeft := config.margemEsquerda;
if config.margemDireita <> -1 then
Report.PrinterSetup.MarginRight := config.margemDireita;
if config.margemSuperior <> -1 then
Report.PrinterSetup.MarginTop := config.margemSuperior;
if config.tipoSaida <> TSTela then
begin
if config.tipoSaida = TSPDF then extensao := 'pdf';
if config.tipoSaida = TSTexto then extensao := 'txt';
if FTextFileName = '' then
if not PromptForFileName(FTextFileName, '*.' + extensao, extensao,
'', '', true) then
exit;
report.AllowPrintToFile := True;
report.TextFileName := FTextFileName;
report.ShowPrintDialog := false;
if config.tipoSaida = TSPDF then
report.DeviceType := 'PDF';
if config.tipoSaida = TSTexto then
report.DeviceType := 'TextFile';
end;
updateContadorImpressao := MainData.GetQuery;
try
updateContadorImpressao.SQL.Text := 'UPDATE rb_item '+
' SET FREQUENCIAUSO = FREQUENCIAUSO+1, '+
' DATAULTIMAIMPRESSAO = '
+ QuotedStr(FormatDateTime('dd.mm.yyyy', MainData.GetServerDatetime)) +
' WHERE ITEM_ID = ' + IntToStr(getTemplateIDByName(TemplateName));
updateContadorImpressao.ExecSQL;
finally
acCustomSQLMainData.FreeQuery(updateContadorImpressao);
end;
TParametroSistemaData.RegistrarUsoRecurso(Config.NomeRelatorio, rrRelatorio);
report.Print;
finally
acCustomSQLMainData.FreeQuery(qry);
end;
end;
procedure TImprimirRelatorioForm.ImprimirTemplate(templateName: string);
var
stream: TMemoryStream;
begin
//buscar informações no catálogo de relatórios
stream := TMemoryStream.Create;
getTemplateByName(TemplateName, stream);
Report.Template.LoadFromStream(stream);
afterLoadStream;
report.Print;
end;
function TImprimirRelatorioForm.findPipeline(name: string): TppDataPipeline;
var
i,j: integer;
begin
result := nil;
for i := 1 to ComponentCount-1 do
begin
if (Components[i] is TdaDataView) then
begin
for j := 0 to TdaDataView(Components[i]).DataPipelineCount-1 do
if upperCase(name)=UpperCase(TdaDataView(Components[i]).DataPipelines[j].UserName) then
result := TdaDataView(Components[i]).DataPipelines[j];
end;
end;
end;
procedure TImprimirRelatorioForm.ReportPreviewFormCreate(Sender: TObject);
begin
inherited;
report.PreviewFormSettings.ZoomSetting := zs100Percent;
report.PreviewFormSettings.WindowState := wsMaximized;
end;
function TImprimirRelatorioForm.findComponentUserName(name: String): TComponent;
var
i: integer;
PropInfo: PPropInfo;
begin
result := nil;
for i := 0 to ComponentCount-1 do
begin
PropInfo := GetPropInfo(components[i], 'userName');
if Assigned(propInfo) then
if UpperCase(GetStrProp(Components[i], 'userName')) = UpperCase(name)then
result := Components[i];
end;
end;
procedure TImprimirRelatorioForm.FormCreate(Sender: TObject);
begin
inherited;
Operacoes := Operacoes-[oInserir,oExcluir,oVisualizar];
filterDataSet.dataProvider := acCustomSQLMainData.prvFilter;
end;
procedure TImprimirRelatorioForm.afterLoadStream;
begin
//
end;
initialization
OSRegisterClass(TImprimirRelatorioForm);
end.
|
unit DelphiXMLDataBindingGenerator;
interface
uses
System.Classes,
System.Generics.Collections,
Xml.XMLSchema,
DelphiXMLDataBindingResources,
XMLDataBindingGenerator,
XMLDataBindingHelpers;
type
TGetFileNameEvent = procedure(Sender: TObject; const SchemaName: String; var Path, FileName: String) of object;
TXMLSchemaList = TList<TXMLDataBindingSchema>;
TDelphiXMLDataBindingGenerator = class(TXMLDataBindingGenerator)
private
FProcessedItems: TList<TXMLDataBindingInterface>;
FUnitNames: TDictionary<TXMLDataBindingSchema, String>;
FHasChecksEmpty: Boolean;
FOnGetFileName: TGetFileNameEvent;
FHasGenerateGetOptionalOrDefault: Boolean;
protected
procedure GenerateDataBinding; override;
procedure GenerateOutputFile(ASchemaList: TXMLSchemaList; const ASourceFileName, AUnitName: String);
function GenerateUsesClause(ASchemaList: TXMLSchemaList): String;
function DelphiSafeName(const AName: String): String;
function TranslateItemName(AItem: TXMLDataBindingItem): String; override;
procedure PostProcessItem(ASchema: TXMLDataBindingSchema; AItem: TXMLDataBindingItem); override;
procedure ResolvePropertyNameConflicts(AItem: TXMLDataBindingInterface);
function DoGetFileName(const ASchemaName: String): String;
function GetDataTypeMapping(ADataType: IXMLTypeDef; out ATypeMapping: TTypeMapping): Boolean;
function GetDataTypeName(AProperty: TXMLDataBindingProperty; AInterfaceName: Boolean): String;
function TranslateDataType(ADataType: IXMLTypeDef): String;
function CreateNewGUID: String;
procedure WriteUnitHeader(AWriter: TNamedFormatWriter; const ASourceFileName, AFileName: String);
procedure WriteSection(AWriter: TNamedFormatWriter; ASection: TDelphiXMLSection; ASchemaList: TXMLSchemaList);
procedure WriteDocumentFunctions(AWriter: TNamedFormatWriter; ASection: TDelphiXMLSection; ASchemaList: TXMLSchemaList);
procedure WriteEnumerationConversions(AWriter: TNamedFormatWriter; ASection: TDelphiXMLSection; ASchemaList: TXMLSchemaList);
procedure WriteImplementationUses(AWriter: TNamedFormatWriter; ASchemaList: TXMLSchemaList);
procedure WriteDocumentation(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingItem);
procedure WriteAfterConstruction(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection);
function WriteInlineCollectionFields(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface): Boolean;
procedure WriteSchemaItem(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingItem; ASection: TDelphiXMLSection);
procedure WriteSchemaInterface(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection);
procedure WriteSchemaInterfaceProperties(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection);
function WriteSchemaInterfaceCollectionProperties(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection): Boolean;
function WriteSchemaInterfaceProperty(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; AProperty: TXMLDataBindingProperty; ASection: TDelphiXMLSection; AMember: TDelphiXMLMember; ANewLine: Boolean): Boolean;
procedure WriteSchemaEnumeration(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingEnumeration; ASection: TDelphiXMLSection);
procedure WriteSchemaEnumerationArray(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingEnumeration);
procedure WriteValidate(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection);
procedure WriteValidateImplementation(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; AStrict: Boolean);
procedure WriteEnumeratorMethod(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection);
procedure WriteEnumerator(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection);
function GetDelphiNodeType(AProperty: TXMLDataBindingProperty): TDelphiNodeType;
function GetDelphiElementType(ANodeType: TDelphiNodeType): TDelphiElementType;
function DataTypeConversion(const ADestination, ASource: String; ADataType: IXMLTypeDef; AAccessor: TDelphiAccessor; ANodeType: TDelphiNodeType; const ATargetNamespace: string; const ALinesBefore: String = ''): String;
function XMLToNativeDataType(const ADestination, ASource: String; ADataType: IXMLTypeDef; ANodeType: TDelphiNodeType; const ATargetNamespace: string; const ALinesBefore: String = ''): String;
function NativeDataTypeToXML(const ADestination, ASource: String; ADataType: IXMLTypeDef; ANodeType: TDelphiNodeType; const ATargetNamespace: string; const ALinesBefore: String = ''): String;
property ProcessedItems: TList<TXMLDataBindingInterface> read FProcessedItems;
property UnitNames: TDictionary<TXMLDataBindingSchema, String> read FUnitNames;
public
property HasChecksEmpty: Boolean read FHasChecksEmpty write FHasChecksEmpty;
property HasGenerateGetOptionalOrDefault: Boolean read FHasGenerateGetOptionalOrDefault write FHasGenerateGetOptionalOrDefault;
property OnGetFileName: TGetFileNameEvent read FOnGetFileName write FOnGetFileName;
end;
implementation
uses
StrUtils,
SysUtils,
X2UtNamedFormat;
const
VariantText = 'Variant';
{ TDelphiXMLDataBindingGenerator }
procedure TDelphiXMLDataBindingGenerator.GenerateDataBinding;
var
schemaList: TXMLSchemaList;
schemaIndex: Integer;
schema: TXMLDataBindingSchema;
unitName: String;
begin
schemaList := TXMLSchemaList.Create;
try
case OutputType of
otSingle:
begin
for schemaIndex := 0 to Pred(SchemaCount) do
schemaList.Add(Schemas[schemaIndex]);
unitName := DoGetFileName(Schemas[0].SchemaName);
GenerateOutputFile(schemaList, SourceFileName, unitName);
end;
otMultiple:
begin
FUnitNames := TDictionary<TXMLDataBindingSchema, String>.Create;
try
for schemaIndex := 0 to Pred(SchemaCount) do
begin
schema := Schemas[schemaIndex];
FUnitNames.Add(schema, DoGetFileName(schema.SchemaName));
end;
for schemaIndex := 0 to Pred(SchemaCount) do
begin
schema := Schemas[schemaIndex];
schemaList.Clear;
schemaList.Add(schema);
unitName := FUnitNames[schema];
GenerateOutputFile(schemaList, schema.SourceFileName, unitName);
end;
finally
FreeAndNil(FUnitNames);
end;
end;
end;
finally
FreeAndNil(schemaList);
end;
end;
procedure TDelphiXMLDataBindingGenerator.GenerateOutputFile(ASchemaList: TXMLSchemaList; const ASourceFileName, AUnitName: String);
var
unitWriter: TNamedFormatWriter;
usesClause: String;
begin
usesClause := '';
if OutputType = otMultiple then
usesClause := GenerateUsesClause(ASchemaList);
unitWriter := TNamedFormatWriter.Create(AUnitName, False, TEncoding.ANSI);
try
WriteUnitHeader(unitWriter, ASourceFileName, AUnitName);
unitWriter.WriteNamedFmt(UnitInterface,
['UsesClause', usesClause]);
WriteSection(unitWriter, dxsForward, ASchemaList);
FProcessedItems := TList<TXMLDataBindingInterface>.Create;
try
FProcessedItems.Clear;
WriteSection(unitWriter, dxsInterface, ASchemaList);
FProcessedItems.Clear;
WriteSection(unitWriter, dxsClass, ASchemaList);
finally
FreeAndNil(FProcessedItems);
end;
WriteDocumentFunctions(unitWriter, dxsInterface, ASchemaList);
WriteEnumerationConversions(unitWriter, dxsInterface, ASchemaList);
unitWriter.Write(UnitImplementation);
WriteImplementationUses(unitWriter, ASchemaList);
WriteDocumentFunctions(unitWriter, dxsImplementation, ASchemaList);
WriteEnumerationConversions(unitWriter, dxsImplementation, ASchemaList);
WriteSection(unitWriter, dxsImplementation, ASchemaList);
unitWriter.Write(unitFooter);
finally
FreeAndNil(unitWriter);
end;
end;
function TDelphiXMLDataBindingGenerator.GenerateUsesClause(ASchemaList: TXMLSchemaList): String;
var
includedSchemas: TList<TXMLDataBindingSchema>;
procedure AddSchema(ASchema: TXMLDataBindingSchema);
begin
if Assigned(ASchema) and
(not includedSchemas.Contains(ASchema)) and
(not ASchemaList.Contains(ASchema)) then
includedSchemas.Add(ASchema);
end;
var
schemaIndex: Integer;
schema: TXMLDataBindingSchema;
itemIndex: Integer;
interfaceItem: TXMLDataBindingInterface;
propertyIndex: Integer;
propertyItem: TXMLDataBindingProperty;
begin
Result := '';
includedSchemas := TList<TXMLDataBindingSchema>.Create;
try
{ Determine which items are used }
for schemaIndex := 0 to Pred(ASchemaList.Count) do
begin
schema := ASchemaList[schemaIndex];
for itemIndex := 0 to Pred(schema.ItemCount) do
begin
if schema.Items[itemIndex].ItemType = itInterface then
begin
interfaceItem := TXMLDataBindingInterface(schema.Items[itemIndex]);
if Assigned(interfaceItem.CollectionItem) then
AddSchema(interfaceItem.CollectionItem.Schema);
for propertyIndex := 0 to Pred(interfaceItem.PropertyCount) do
begin
propertyItem := interfaceItem.Properties[propertyIndex];
if propertyItem.PropertyType = ptItem then
AddSchema(TXMLDataBindingItemProperty(propertyItem).Item.Schema);
end;
end;
end;
end;
{ Build uses clause }
if includedSchemas.Count > 0 then
begin
for schema in includedSchemas do
Result := Result + ' ' + ChangeFileExt(ExtractFileName(FUnitNames[schema]), '') + ',' + CrLf;
Result := Result + CrLf;
end;
finally
FreeAndNil(includedSchemas);
end;
end;
function TDelphiXMLDataBindingGenerator.GetDataTypeMapping(ADataType: IXMLTypeDef; out ATypeMapping: TTypeMapping): Boolean;
var
mappingIndex: Integer;
dataTypeName: String;
begin
Assert(not ADataType.IsComplex, 'Complex DataTypes not supported');
Assert(ADataType.Enumerations.Count = 0, 'Enumerations not supported');
Result := False;
if (ADataType.NamespaceURI = SXMLSchemaURI_1999) or
(ADataType.NamespaceURI = SXMLSchemaURI_2000_10) or
(ADataType.NamespaceURI = SXMLSchemaURI_2001) then
begin
dataTypeName := ADataType.Name;
for mappingIndex := Low(SimpleTypeMapping) to High(SimpleTypeMapping) do
if SimpleTypeMapping[mappingIndex].SchemaName = dataTypeName then
begin
ATypeMapping := SimpleTypeMapping[mappingIndex];
Result := True;
Break;
end;
end;
end;
function TDelphiXMLDataBindingGenerator.GetDataTypeName(AProperty: TXMLDataBindingProperty; AInterfaceName: Boolean): String;
var
item: TXMLDataBindingItem;
begin
case AProperty.PropertyType of
ptSimple:
if AProperty.IsRepeating then
begin
if AInterfaceName then
Result := ItemInterface
else
Result := ItemClass;
end else
Result := TranslateDataType(TXMLDataBindingSimpleProperty(AProperty).DataType);
ptItem:
begin
item := TXMLDataBindingItemProperty(AProperty).Item;
if (item.ItemType = itEnumeration) or (not AInterfaceName) then
Result := PrefixClass
else
Result := PrefixInterface;
Result := Result + item.TranslatedName;
end;
end;
end;
function TDelphiXMLDataBindingGenerator.TranslateDataType(ADataType: IXMLTypeDef): String;
var
typeMapping: TTypeMapping;
begin
Result := VariantText;
if GetDataTypeMapping(ADataType, typeMapping) then
Result := typeMapping.DelphiName;
end;
function TDelphiXMLDataBindingGenerator.DelphiSafeName(const AName: String): String;
var
charIndex: Integer;
wordIndex: Integer;
begin
Result := AName;
{ Remove unsafe characters }
for charIndex := Length(Result) downto 1 do
begin
if not CharInSet(Result[charIndex], SafeChars) then
Delete(Result, charIndex, 1);
end;
if Length(Result) > 0 then
begin
{ Number as the first character is not allowed }
if CharInSet(Result[1], ['0'..'9']) then
Result := '_' + Result;
{ Check for reserved words }
for wordIndex := Low(ReservedWords) to High(ReservedWords) do
begin
if SameText(Result, ReservedWords[wordIndex]) then
begin
Result := '_' + Result;
Break;
end;
end;
end;
end;
function TDelphiXMLDataBindingGenerator.TranslateItemName(AItem: TXMLDataBindingItem): String;
begin
Result := DelphiSafeName(inherited TranslateItemName(AItem));
case AItem.ItemType of
itEnumerationMember:
Result := DelphiSafeName(TXMLDataBindingEnumerationMember(AItem).Enumeration.TranslatedName) + '_' + Result;
end;
end;
procedure TDelphiXMLDataBindingGenerator.PostProcessItem(ASchema: TXMLDataBindingSchema; AItem: TXMLDataBindingItem);
begin
inherited PostProcessItem(ASchema, AItem);
if AItem.ItemType = itInterface then
begin
{ Resolve conflicts in case only for properties }
ResolvePropertyNameConflicts(TXMLDataBindingInterface(AItem));
end;
end;
procedure TDelphiXMLDataBindingGenerator.ResolvePropertyNameConflicts(AItem: TXMLDataBindingInterface);
var
propertyNames: TStringList;
propertyItem: TXMLDataBindingProperty;
propertyIndex: Integer;
baseName: String;
counter: Integer;
begin
propertyNames := TStringList.Create;
try
propertyNames.CaseSensitive := False;
for propertyIndex := 0 to Pred(AItem.PropertyCount) do
begin
propertyItem := AItem.Properties[propertyIndex];
baseName := propertyItem.TranslatedName;
counter := 1;
while propertyNames.IndexOf(propertyItem.TranslatedName) > -1 do
begin
{ Unfortunately, the context is exactly the same, this is the best we can do }
Inc(counter);
propertyItem.TranslatedName := baseName + IntToStr(counter);
end;
propertyNames.Add(propertyItem.TranslatedName);
end;
finally
FreeAndNil(propertyNames);
end;
end;
procedure TDelphiXMLDataBindingGenerator.WriteUnitHeader(AWriter: TNamedFormatWriter; const ASourceFileName, AFileName: String);
begin
AWriter.WriteNamedFmt(UnitHeader,
['SourceFileName', ASourceFileName,
'UnitName', ChangeFileExt(ExtractFileName(AFileName), ''),
'DateTime', DateTimeToStr(Now)]);
end;
procedure TDelphiXMLDataBindingGenerator.WriteSection(AWriter: TNamedFormatWriter; ASection: TDelphiXMLSection; ASchemaList: TXMLSchemaList);
var
schemaIndex: Integer;
schema: TXMLDataBindingSchema;
itemIndex: Integer;
begin
for schemaIndex := 0 to Pred(ASchemaList.Count) do
begin
schema := ASchemaList[schemaIndex];
AWriter.WriteLineNamedFmt(SectionComments[ASection],
['SchemaName', schema.SchemaName]);
for itemIndex := 0 to Pred(schema.ItemCount) do
WriteSchemaItem(AWriter, schema.Items[itemIndex], ASection);
AWriter.WriteLine;
end;
end;
procedure TDelphiXMLDataBindingGenerator.WriteDocumentFunctions(AWriter: TNamedFormatWriter; ASection: TDelphiXMLSection; ASchemaList: TXMLSchemaList);
var
schemaIndex: Integer;
schema: TXMLDataBindingSchema;
itemIndex: Integer;
item: TXMLDataBindingItem;
interfaceItem: TXMLDataBindingInterface;
hasItem: Boolean;
nameSpace: String;
begin
hasItem := False;
nameSpace := '';
for schemaIndex := 0 to Pred(ASchemaList.Count) do
begin
schema := ASchemaList[schemaIndex];
for itemIndex := 0 to Pred(schema.ItemCount) do
begin
item := schema.Items[itemIndex];
if item.ItemType = itInterface then
begin
interfaceItem := TXMLDataBindingInterface(item);
if item.DocumentElement then
begin
if not hasItem then
begin
if ASection = dxsInterface then
AWriter.Write(' ');
AWriter.WriteLine('{ Document functions }');
hasItem := True;
end;
if Length(schema.TargetNamespace) > 0 then
nameSpace := schema.TargetNamespace;
with TNamedFormatStringList.Create do
try
case ASection of
dxsInterface: Add(DocumentFunctionsInterface);
dxsImplementation: Add(DocumentFunctionsImplementation);
end;
AWriter.Write(Format(['SourceName', interfaceItem.Name,
'Name', interfaceItem.TranslatedName]));
finally
Free;
end;
AWriter.WriteLine;
end;
end;
end;
end;
if (ASection = dxsInterface) and hasItem then
begin
AWriter.WriteLine('const');
AWriter.WriteLine(' TargetNamespace = ''%s'';', [nameSpace]);
AWriter.WriteLine;
AWriter.WriteLine;
end;
end;
procedure TDelphiXMLDataBindingGenerator.WriteEnumerationConversions(AWriter: TNamedFormatWriter; ASection: TDelphiXMLSection; ASchemaList: TXMLSchemaList);
var
enumerations: TList<TXMLDataBindingItem>;
schemaIndex: Integer;
schema: TXMLDataBindingSchema;
itemIndex: Integer;
item: TXMLDataBindingItem;
enumerationItem: TXMLDataBindingEnumeration;
sourceCode: TNamedFormatStringList;
indent: String;
begin
if not (ASection in [dxsInterface, dxsImplementation]) then
Exit;
enumerations := TList<TXMLDataBindingItem>.Create;
try
for schemaIndex := 0 to Pred(ASchemaList.Count) do
begin
schema := ASchemaList[schemaIndex];
for itemIndex := 0 to Pred(schema.ItemCount) do
begin
item := schema.Items[itemIndex];
if item.ItemType = itEnumeration then
enumerations.Add(item);
end;
end;
if enumerations.Count > 0 then
begin
if ASection = dxsInterface then
begin
{ Enumeration value arrays }
AWriter.WriteLine('const');
for itemIndex := 0 to Pred(enumerations.Count) do
WriteSchemaEnumerationArray(AWriter, TXMLDataBindingEnumeration(enumerations[itemIndex]));
end;
{ Conversion helpers }
if ASection = dxsInterface then
AWriter.Write(' ');
AWriter.WriteLine('{ Enumeration conversion helpers }');
for itemIndex := Pred(enumerations.Count) downto 0 do
begin
enumerationItem := TXMLDataBindingEnumeration(enumerations[itemIndex]);
indent := '';
if ASection = dxsInterface then
indent := ' ';
sourceCode := TNamedFormatStringList.Create;
try
sourceCode.Add(indent + 'function StringTo%<ItemName>:s(const AValue: WideString): %<DataType>:s;');
if ASection = dxsImplementation then
begin
sourceCode.Add('var');
sourceCode.Add(' enumValue: %<DataType>:s;');
sourceCode.AddLn;
sourceCode.Add('begin');
sourceCode.Add(' Result := %<DataType>:s(-1);');
sourceCode.Add(' for enumValue := Low(%<DataType>:s) to High(%<DataType>:s) do');
sourceCode.Add(' if %<ItemName>:sValues[enumValue] = AValue then');
sourceCode.Add(' begin');
sourceCode.Add(' Result := enumValue;');
sourceCode.Add(' break;');
sourceCode.Add(' end;');
sourceCode.Add('end;');
sourceCode.AddLn;
end;
AWriter.Write(sourceCode.Format(['ItemName', enumerationItem.TranslatedName,
'DataType', PrefixClass + enumerationItem.TranslatedName]));
finally
FreeAndNil(sourceCode);
end;
end;
AWriter.WriteLine;
end;
finally
FreeAndNil(enumerations);
end;
end;
procedure TDelphiXMLDataBindingGenerator.WriteImplementationUses(AWriter: TNamedFormatWriter; ASchemaList: TXMLSchemaList);
begin
{ In ye olde days this is where we checked if XMLDataBindingUtils was required. With the
introduction of the IXSDValidate, this is practically always the case. }
AWriter.WriteLine('uses');
AWriter.WriteLine(' Variants;');
AWriter.WriteLine;
end;
procedure TDelphiXMLDataBindingGenerator.WriteDocumentation(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingItem);
var
documentation: String;
lineIndex: Integer;
lines: TStringList;
begin
if not AItem.HasDocumentation then
exit;
lines := TStringList.Create;
try
documentation := AItem.Documentation;
{ Replace dangerous characters }
documentation := StringReplace(documentation, '{', '(', [rfReplaceAll]);
documentation := StringReplace(documentation, '}', ')', [rfReplaceAll]);
lines.Text := WrapText(documentation, 76);
AWriter.WriteLine(' /// <summary>');
for lineIndex := 0 to Pred(lines.Count) do
AWriter.WriteLine(' /// ' + lines[lineIndex]);
AWriter.WriteLine(' /// </summary>');
finally
FreeAndNil(lines);
end;
end;
procedure TDelphiXMLDataBindingGenerator.WriteSchemaItem(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingItem; ASection: TDelphiXMLSection);
begin
case AItem.ItemType of
itInterface: WriteSchemaInterface(AWriter, TXMLDataBindingInterface(AItem), ASection);
itEnumeration: WriteSchemaEnumeration(AWriter, TXMLDataBindingEnumeration(AItem), ASection);
end;
end;
procedure TDelphiXMLDataBindingGenerator.WriteSchemaInterface(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection);
var
parent: String;
begin
if ASection in [dxsInterface, dxsClass] then
begin
{ Ensure the base item is completely defined first, Delphi doesn't allow
inheritance with just a forward declaration. }
if ProcessedItems.Contains(AItem) then
exit;
if Assigned(AItem.BaseItem) then
WriteSchemaInterface(AWriter, AItem.BaseItem, ASection);
ProcessedItems.Add(AItem);
end;
case ASection of
dxsForward:
AWriter.WriteLineNamedFmt(InterfaceItemForward,
['Name', AItem.TranslatedName]);
dxsInterface:
begin
if Assigned(AItem.BaseItem) then
parent := PrefixInterface + AItem.BaseItem.TranslatedName
else if AItem.IsCollection then
begin
parent := CollectionInterface;
WriteEnumerator(AWriter, AItem, ASection);
end else
parent := ItemInterface;
WriteDocumentation(AWriter, AItem);
AWriter.WriteLineNamedFmt(InterfaceItemInterface,
['Name', AItem.TranslatedName,
'ParentName', parent]);
AWriter.WriteLine(' ' + CreateNewGUID);
WriteSchemaInterfaceProperties(AWriter, AItem, ASection);
AWriter.WriteLine(' end;');
AWriter.WriteLine;
end;
dxsClass:
begin
if Assigned(AItem.BaseItem) then
parent := PrefixClass + AItem.BaseItem.TranslatedName
else if AItem.IsCollection then
begin
parent := CollectionClass;
WriteEnumerator(AWriter, AItem, ASection);
end else
parent := ItemClass;
if AItem.CanValidate then
parent := parent + ', ' + XSDValidateInterface;
AWriter.WriteLineNamedFmt(InterfaceItemClass,
['Name', AItem.TranslatedName,
'ParentName', parent]);
WriteSchemaInterfaceProperties(AWriter, AItem, ASection);
AWriter.WriteLine(' end;');
AWriter.WriteLine;
end;
dxsImplementation:
begin
WriteEnumerator(AWriter, AItem, ASection);
WriteSchemaInterfaceProperties(AWriter, AItem, ASection);
end;
end;
end;
procedure TDelphiXMLDataBindingGenerator.WriteAfterConstruction(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection);
var
hasPrototype: Boolean;
procedure WritePrototype;
begin
if not hasPrototype then
begin
case ASection of
dxsClass:
begin
AWriter.WriteLine(' public');
AWriter.WriteLine(' procedure AfterConstruction; override;');
end;
dxsImplementation:
begin
AWriter.WriteLine('procedure TXML%s.AfterConstruction;', [AItem.TranslatedName]);
AWriter.WriteLine('begin');
end;
end;
hasPrototype := True;
end;
end;
var
itemProperty: TXMLDataBindingItemProperty;
propertyIndex: Integer;
propertyItem: TXMLDataBindingProperty;
begin
if not (ASection in [dxsClass, dxsImplementation]) then
Exit;
if (ASection = dxsClass) and
(not AItem.IsCollection) then
WriteInlineCollectionFields(AWriter, AItem);
hasPrototype := False;
for propertyIndex := 0 to Pred(AItem.PropertyCount) do
begin
propertyItem := AItem.Properties[propertyIndex];
if (not AItem.IsCollection) and Assigned(propertyItem.Collection) then
begin
WritePrototype;
{ Inline collection }
if ASection = dxsImplementation then
begin
if propertyItem.PropertyType = ptItem then
begin
if propertyItem.HasTargetNamespace then
AWriter.WriteLineNamedFmt(' RegisterChildNode(''%<ItemSourceName>:s'', %<ItemClass>:s, ''%<Namespace>:s'');',
['ItemSourceName', propertyItem.Name,
'ItemClass', GetDataTypeName(propertyItem, False),
'Namespace', propertyItem.TargetNamespace])
else
AWriter.WriteLineNamedFmt(' RegisterChildNode(''%<ItemSourceName>:s'', %<ItemClass>:s);',
['ItemSourceName', propertyItem.Name,
'ItemClass', GetDataTypeName(propertyItem, False)]);
end;
AWriter.WriteLineNamedFmt(' %<FieldName>:s := CreateCollection(%<CollectionClass>:s, %<ItemInterface>:s, ''%<ItemSourceName>:s'', ''%<Namespace>:s'') as %<CollectionInterface>:s;',
['FieldName', PrefixField + propertyItem.TranslatedName,
'CollectionClass', PrefixClass + propertyItem.Collection.TranslatedName,
'CollectionInterface', PrefixInterface + propertyItem.Collection.TranslatedName,
'ItemInterface', GetDataTypeName(propertyItem, True),
'ItemSourceName', propertyItem.Name,
'Namespace', propertyItem.TargetNamespace]);
end;
end;
if propertyItem.PropertyType = ptItem then
begin
itemProperty := TXMLDataBindingItemProperty(propertyItem);
if (not AItem.IsCollection) or
(propertyItem <> AItem.CollectionItem) then
begin
{ Item property }
if Assigned(itemProperty.Item) and
(itemProperty.Item.ItemType = itInterface) then
begin
case ASection of
dxsClass:
WritePrototype;
dxsImplementation:
begin
WritePrototype;
if propertyItem.HasTargetNamespace then
AWriter.WriteLineNamedFmt(' RegisterChildNode(''%<SourceName>:s'', TXML%<Name>:s, ''%<Namespace>:s'');',
['SourceName', propertyItem.Name,
'Name', itemProperty.Item.TranslatedName,
'Namespace', propertyItem.TargetNamespace])
else
AWriter.WriteLineNamedFmt(' RegisterChildNode(''%<SourceName>:s'', TXML%<Name>:s);',
['SourceName', propertyItem.Name,
'Name', itemProperty.Item.TranslatedName]);
end;
end;
end;
end;
end;
end;
if AItem.IsCollection then
begin
WritePrototype;
if ASection = dxsImplementation then
begin
WritePrototype;
if AItem.CollectionItem.HasTargetNamespace then
AWriter.WriteLineNamedFmt(' RegisterChildNode(''%<SourceName>:s'', %<DataClass>:s, ''%<Namespace>:s'');',
['SourceName', AItem.CollectionItem.Name,
'DataClass', GetDataTypeName(AItem.CollectionItem, False),
'Namespace', AItem.CollectionItem.TargetNamespace])
else
AWriter.WriteLineNamedFmt(' RegisterChildNode(''%<SourceName>:s'', %<DataClass>:s);',
['SourceName', AItem.CollectionItem.Name,
'DataClass', GetDataTypeName(AItem.CollectionItem, False)]);
AWriter.WriteLine;
AWriter.WriteLine(' ItemTag := ''%s'';', [AItem.CollectionItem.Name]);
AWriter.WriteLine(' ItemInterface := %s;', [GetDataTypeName(AItem.CollectionItem, True)]);
AWriter.WriteLine;
end;
end;
if hasPrototype and (ASection = dxsImplementation) then
begin
AWriter.WriteLine(' inherited;');
if AItem.IsCollection and (AItem.TargetNamespace <> AItem.CollectionItem.TargetNamespace) then
begin
AWriter.WriteLine;
AWriter.WriteLine(' ItemNS := ''%s'';', [AItem.CollectionItem.TargetNamespace]);
end;
AWriter.WriteLine('end;');
AWriter.WriteLine;
end;
end;
function TDelphiXMLDataBindingGenerator.WriteInlineCollectionFields(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface): Boolean;
var
propertyIndex: Integer;
collectionProperty: TXMLDataBindingProperty;
begin
Result := False;
for propertyIndex := 0 to Pred(AItem.PropertyCount) do
if AItem.Properties[propertyIndex].IsRepeating then
begin
collectionProperty := AItem.Properties[propertyIndex];
if Assigned(collectionProperty.Collection) then
begin
if not Result then
begin
AWriter.WriteLine(' private');
Result := True;
end;
AWriter.WriteLineNamedFmt(' %<PropertyName>:s: %<DataInterface>:s;',
['PropertyName', PrefixField + collectionProperty.TranslatedName,
'DataInterface', PrefixInterface + collectionProperty.Collection.TranslatedName]);
end;
end;
end;
procedure TDelphiXMLDataBindingGenerator.WriteSchemaInterfaceProperties(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection);
var
propertyIndex: Integer;
itemProperty: TXMLDataBindingProperty;
hasMembers: Boolean;
firstMember: Boolean;
member: TDelphiXMLMember;
begin
if ASection = dxsForward then
Exit;
if ASection in [dxsClass, dxsImplementation] then
WriteAfterConstruction(AWriter, AItem, ASection);
if ASection = dxsClass then
AWriter.WriteLine(' protected');
WriteValidate(AWriter, AItem, ASection);
WriteEnumeratorMethod(AWriter, AItem, ASection);
hasMembers := WriteSchemaInterfaceCollectionProperties(AWriter, AItem, ASection);
for member := Low(TDelphiXMLMember) to High(TDelphiXMLMember) do
begin
firstMember := True;
for propertyIndex := 0 to Pred(AItem.PropertyCount) do
begin
itemProperty := AItem.Properties[propertyIndex];
if WriteSchemaInterfaceProperty(AWriter, AItem, itemProperty, ASection, member,
hasMembers and firstMember and (ASection in [dxsInterface, dxsClass])) then
begin
firstMember := False;
hasMembers := True;
end;
end;
end;
end;
function TDelphiXMLDataBindingGenerator.WriteSchemaInterfaceCollectionProperties(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection): Boolean;
var
dataIntfName: String;
dataTypeName: String;
dataClassName: String;
collectionItem: TXMLDataBindingItem;
sourceCode: TNamedFormatStringList;
typeDef: IXMLTypeDef;
typeMapping: TTypeMapping;
begin
Result := False;
if not AItem.IsCollection then
Exit;
case AItem.CollectionItem.PropertyType of
ptSimple:
begin
dataTypeName := TranslateDataType(TXMLDataBindingSimpleProperty(AItem.CollectionItem).DataType);
dataClassName := ItemClass;
dataIntfName := ItemInterface;
end;
ptItem:
begin
collectionItem := TXMLDataBindingItemProperty(AItem.CollectionItem).Item;
if collectionItem.ItemType = itEnumeration then
begin
// #ToDo1 (MvR) 17-3-2008: DataType and conversions for enumerations
dataTypeName := PrefixInterface + collectionItem.TranslatedName;
dataClassName := PrefixClass + collectionItem.TranslatedName;
dataIntfName := dataTypeName;
end else
begin
dataTypeName := PrefixInterface + collectionItem.TranslatedName;
dataClassName := PrefixClass + collectionItem.TranslatedName;
dataIntfName := dataTypeName;
end;
end;
end;
sourceCode := TNamedFormatStringList.Create;
try
case ASection of
dxsInterface,
dxsClass:
begin
sourceCode.Add(' function Get_%<ItemName>:s(Index: Integer): %<DataType>:s;');
case AItem.CollectionItem.PropertyType of
ptSimple:
begin
sourceCode.Add(' function Add(%<ItemName>:s: %<DataType>:s): %<DataInterface>:s;');
sourceCode.Add(' function Insert(Index: Integer; %<ItemName>:s: %<DataType>:s): %<DataInterface>:s;');
end;
ptItem:
begin
sourceCode.Add(' function Add: %<DataType>:s;');
sourceCode.Add(' function Insert(Index: Integer): %<DataType>:s;');
end;
end;
end;
dxsImplementation:
begin
case AItem.CollectionItem.PropertyType of
ptSimple:
begin
typeDef := TXMLDataBindingSimpleProperty(AItem.CollectionItem).DataType;
sourceCode.Add('function TXML%<Name>:s.Get_%<ItemName>:s(Index: Integer): %<DataType>:s;');
if GetDataTypeMapping(typeDef, typeMapping) and (typeMapping.Conversion = tcString) then
sourceCode.Add(XMLToNativeDataType('Result', 'List[Index].Text', typeDef, dntCustom, AItem.CollectionItem.TargetNamespace))
else
sourceCode.Add(XMLToNativeDataType('Result', 'List[Index].NodeValue', typeDef, dntCustom, AItem.CollectionItem.TargetNamespace));
sourceCode.AddLn;
sourceCode.Add('function TXML%<Name>:s.Add(%<ItemName>:s: %<DataType>:s): %<DataInterface>:s;');
sourceCode.Add(NativeDataTypeToXML('Result.NodeValue', '%<ItemName>:s', typeDef, dntCustom, '',
' Result := AddItem(-1);'));
sourceCode.AddLn;
sourceCode.Add('function TXML%<Name>:s.Insert(Index: Integer; %<ItemName>:s: %<DataType>:s): %<DataInterface>:s;');
sourceCode.Add(NativeDataTypeToXML('Result.NodeValue', '%<ItemName>:s', typeDef, dntCustom, '',
' Result := AddItem(Index);'));
sourceCode.AddLn;
end;
ptItem:
begin
sourceCode.Add('function TXML%<Name>:s.Get_%<ItemName>:s(Index: Integer): %<DataType>:s;');
sourceCode.Add('begin');
sourceCode.Add(' Result := (List[Index] as %<DataType>:s);');
sourceCode.Add('end;');
sourceCode.AddLn;
sourceCode.Add('function TXML%<Name>:s.Add: %<DataType>:s;');
sourceCode.Add('begin');
sourceCode.Add(' Result := (AddItem(-1) as %<DataType>:s);');
sourceCode.Add('end;');
sourceCode.AddLn;
sourceCode.Add('function TXML%<Name>:s.Insert(Index: Integer): %<DataType>:s;');
sourceCode.Add('begin');
sourceCode.Add(' Result := (AddItem(Index) as %<DataType>:s);');
sourceCode.Add('end;');
sourceCode.AddLn;
end;
end;
end;
end;
if ASection = dxsInterface then
begin
sourceCode.AddLn;
sourceCode.Add(' property %<ItemName>:s[Index: Integer]: %<DataType>:s read Get_%<ItemName>:s; default;');
end;
Result := (sourceCode.Count > 0);
if Result then
AWriter.Write(sourceCode.Format(['Name', AItem.TranslatedName,
'ItemName', AItem.CollectionItem.TranslatedName,
'ItemSourceName', AItem.CollectionItem.Name,
'DataType', dataTypeName,
'DataClass', dataClassName,
'DataInterface', dataIntfName]));
finally
FreeAndNil(sourceCode);
end;
end;
function TDelphiXMLDataBindingGenerator.WriteSchemaInterfaceProperty(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; AProperty: TXMLDataBindingProperty; ASection: TDelphiXMLSection; AMember: TDelphiXMLMember; ANewLine: Boolean): Boolean;
procedure WriteNewLine;
begin
if ANewLine then
AWriter.WriteLine;
end;
function IsReadOnly(AProperty: TXMLDataBindingProperty): Boolean;
var
typeMapping: TTypeMapping;
begin
if Assigned(AProperty.Collection) then
exit(True);
Result := AProperty.IsReadOnly;
if (not Result) and (AProperty.PropertyType = ptSimple) then
begin
if GetDataTypeMapping(TXMLDataBindingSimpleProperty(AProperty).DataType, typeMapping) then
Result := (typeMapping.Conversion = tcNode);
end;
end;
var
sourceCode: TNamedFormatStringList;
writeOptional: Boolean;
writeNil: Boolean;
writeTextProp: Boolean;
propertyItem: TXMLDataBindingItem;
dataTypeName: String;
value: String;
propertyItemName: String;
fieldName: String;
writeStream: Boolean;
typeMapping: TTypeMapping;
nodeType: TDelphiNodeType;
begin
Result := False;
if AProperty = AItem.CollectionItem then
Exit;
{ If the property has a collection, it's Count property will be enough
to check if an item is present, no need to write a HasX method. }
writeOptional := False;
writeNil := AProperty.IsNillable;
if AMember in [dxmPropertyGet, dxmPropertyDeclaration] then
writeOptional := not Assigned(AProperty.Collection) and
AProperty.IsOptional;
writeStream := False;
if (AMember = dxmPropertyMethods) and (AProperty.PropertyType = ptSimple) then
begin
if GetDataTypeMapping(TXMLDataBindingSimpleProperty(AProperty).DataType, typeMapping) then
writeStream := (typeMapping.Conversion = tcBase64);
end;
dataTypeName := '';
propertyItem := nil;
fieldName := '';
{ Get data type }
writeTextProp := False;
if Assigned(AProperty.Collection) then
begin
dataTypeName := PrefixInterface + AProperty.Collection.TranslatedName;
fieldName := PrefixField + AProperty.TranslatedName;
end else
begin
case AProperty.PropertyType of
ptSimple:
dataTypeName := TranslateDataType(TXMLDataBindingSimpleProperty(AProperty).DataType);
ptItem:
begin
propertyItem := TXMLDataBindingItemProperty(AProperty).Item;
if Assigned(propertyItem) then
begin
if propertyItem.ItemType = itEnumeration then
begin
dataTypeName := PrefixClass;
writeTextProp := True;
end else
dataTypeName := PrefixInterface;
dataTypeName := dataTypeName + propertyItem.TranslatedName;
end;
end;
end;
end;
if Length(dataTypeName) = 0 then
Exit;
sourceCode := TNamedFormatStringList.Create;
try
case ASection of
dxsInterface,
dxsClass:
begin
{ Interface declaration }
case AMember of
dxmPropertyGet:
begin
WriteNewLine;
if writeOptional then
begin
sourceCode.Add(PropertyIntfMethodGetOptional);
if HasGenerateGetOptionalOrDefault and (AProperty.PropertyType = ptSimple) and (dataTypeName <> VariantText) then
sourceCode.Add(PropertyIntfMethodGetOptionalOrDefault);
end;
if writeNil then
sourceCode.Add(PropertyIntfMethodGetNil);
if writeTextProp then
sourceCode.Add(PropertyIntfMethodGetText);
sourceCode.Add(PropertyIntfMethodGet);
end;
dxmPropertySet:
if not IsReadOnly(AProperty) then
begin
WriteNewLine;
if writeNil then
sourceCode.Add(PropertyIntfMethodSetNil);
if writeTextProp then
sourceCode.Add(PropertyIntfMethodSetText);
sourceCode.Add(PropertyIntfMethodSet);
end;
dxmPropertyMethods:
if writeStream then
begin
sourceCode.Add(PropertyIntfMethodLoadFromStream);
sourceCode.Add(PropertyIntfMethodLoadFromFile);
sourceCode.Add(PropertyIntfMethodSaveToStream);
sourceCode.Add(PropertyIntfMethodSaveToFile);
end;
dxmPropertyDeclaration:
if ASection = dxsInterface then
begin
WriteNewLine;
if writeOptional then
sourceCode.Add(PropertyInterfaceOptional);
if IsReadOnly(AProperty) then
begin
if writeNil then
sourceCode.Add(PropertyInterfaceNilReadOnly);
if writeTextProp then
sourceCode.Add(PropertyInterfaceTextReadOnly);
sourceCode.Add(PropertyInterfaceReadOnly);
end else
begin
if writeNil then
sourceCode.Add(PropertyInterfaceNil);
if writeTextProp then
sourceCode.Add(PropertyInterfaceText);
sourceCode.Add(PropertyInterface);
end;
end;
end;
end;
dxsImplementation:
begin
{ Implementation }
case AMember of
dxmPropertyGet:
begin
nodeType := GetDelphiNodeType(AProperty);
WriteNewLine;
if writeOptional then
begin
if HasChecksEmpty and (AProperty.PropertyType = ptSimple) and (not Assigned(AProperty.Collection)) then
begin
if AProperty.IsAttribute then
sourceCode.Add(PropertyImplMethodGetOptionalAttrEmpty)
else
sourceCode.Add(PropertyImplMethodGetOptionalEmpty[GetDelphiElementType(nodeType)]);
end else
begin
if AProperty.IsAttribute then
sourceCode.Add(PropertyImplMethodGetOptionalAttr)
else
sourceCode.Add(PropertyImplMethodGetOptional[GetDelphiElementType(nodeType)]);
end;
if HasGenerateGetOptionalOrDefault and (AProperty.PropertyType = ptSimple) and (dataTypeName <> VariantText) then
sourceCode.Add(PropertyImplMethodGetOptionalOrDefault);
end;
if writeNil then
sourceCode.Add(PropertyImplMethodGetNil[GetDelphiElementType(nodeType)]);
if writeTextProp then
if AProperty.IsAttribute then
sourceCode.Add(PropertyImplMethodGetTextAttr)
else
sourceCode.Add(PropertyImplMethodGetText[GetDelphiElementType(nodeType)]);
sourceCode.Add('function TXML%<Name>:s.Get%<PropertyName>:s: %<DataType>:s;');
case AProperty.PropertyType of
ptSimple:
if Assigned(AProperty.Collection) then
begin
sourceCode.Add('begin');
sourceCode.Add(' Result := %<FieldName>:s;');
sourceCode.Add('end;');
end else
sourceCode.Add(XMLToNativeDataType('Result',
'%<PropertySourceName>:s',
TXMLDataBindingSimpleProperty(AProperty).DataType,
nodeType,
AProperty.TargetNamespace));
ptItem:
begin
if Assigned(AProperty.Collection) then
begin
sourceCode.Add('begin');
sourceCode.Add(' Result := %<FieldName>:s;');
sourceCode.Add('end;');
end else
begin
if Assigned(propertyItem) then
begin
case propertyItem.ItemType of
itInterface:
begin
sourceCode.Add('begin');
if AProperty.HasTargetNamespace then
sourceCode.Add(' Result := (ChildNodesNS[''%<PropertySourceName>:s'', ''%<Namespace>:s''] as IXML%<PropertyItemName>:s);')
else
sourceCode.Add(' Result := (ChildNodes[''%<PropertySourceName>:s''] as IXML%<PropertyItemName>:s);');
sourceCode.Add('end;');
end;
itEnumeration:
begin
sourceCode.Add('begin');
sourceCode.Add(' Result := StringTo%<PropertyItemName>:s(Get%<PropertyName>:sText);');
sourceCode.Add('end;');
end;
end;
end;
end;
end;
end;
sourceCode.AddLn;
end;
dxmPropertySet:
if not IsReadOnly(AProperty) then
begin
nodeType := GetDelphiNodeType(AProperty);
WriteNewLine;
if writeNil then
sourceCode.Add(PropertyImplMethodSetNil[GetDelphiElementType(nodeType)]);
if writeTextProp then
if AProperty.IsAttribute then
sourceCode.Add(PropertyImplMethodSetTextAttr)
else
sourceCode.Add(PropertyImplMethodSetText[GetDelphiElementType(nodeType)]);
sourceCode.Add('procedure TXML%<Name>:s.Set%<PropertyName>:s(const Value: %<DataType>:s);');
value := '%<PropertySourceName>:s';
if Assigned(propertyItem) and (propertyItem.ItemType = itEnumeration) then
begin
sourceCode.Add(NativeDataTypeToXML(value, '%<PropertyItemName>:sValues[Value]', nil,
nodeType,
AProperty.TargetNamespace));
end else
begin
if AProperty.PropertyType <> ptSimple then
raise Exception.Create('Setter must be a simple type');
sourceCode.Add(NativeDataTypeToXML(value, 'Value',
TXMLDataBindingSimpleProperty(AProperty).DataType,
nodeType,
AProperty.TargetNamespace));
end;
sourceCode.AddLn;
end;
dxmPropertyMethods:
if writeStream then
begin
nodeType := GetDelphiElementType(GetDelphiNodeType(AProperty));
sourceCode.Add(PropertyImplMethodLoadFromStream[nodeType]);
sourceCode.Add(PropertyImplMethodLoadFromFile[nodeType]);
sourceCode.Add(PropertyImplMethodSaveToStream[nodeType]);
sourceCode.Add(PropertyImplMethodSaveToFile[nodeType]);
end;
end;
end;
end;
propertyItemName := '';
if Assigned(propertyItem) then
propertyItemName := propertyItem.TranslatedName;
Result := (sourceCode.Count > 0);
if Result then
AWriter.Write(sourceCode.Format(['Name', AItem.TranslatedName,
'PropertySourceName', AProperty.Name,
'PropertyName', AProperty.TranslatedName,
'PropertyItemName', propertyItemName,
'DataType', dataTypeName,
'FieldName', fieldName,
'Namespace', AProperty.TargetNamespace]));
finally
FreeAndNil(sourceCode);
end;
end;
procedure TDelphiXMLDataBindingGenerator.WriteSchemaEnumeration(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingEnumeration; ASection: TDelphiXMLSection);
var
memberIndex: Integer;
enumStart: String;
lineIndent: String;
begin
if (ASection <> dxsForward) or (AItem.MemberCount = 0) then
exit;
enumStart := NamedFormat(' TXML%<Name>:s = (',
['Name', AItem.TranslatedName]);
AWriter.Write(enumStart);
lineIndent := StringOfChar(' ', Length(enumStart));
for memberIndex := 0 to Pred(AItem.MemberCount) do
begin
if memberIndex > 0 then
AWriter.Write(lineIndent);
AWriter.Write(AItem.Members[memberIndex].TranslatedName);
if memberIndex < Pred(AItem.MemberCount) then
AWriter.WriteLine(',')
else
AWriter.WriteLine(');');
end;
end;
procedure TDelphiXMLDataBindingGenerator.WriteSchemaEnumerationArray(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingEnumeration);
var
memberIndex: Integer;
enumStart: String;
lineIndent: String;
begin
if (AItem.MemberCount = 0) then
exit;
enumStart := NamedFormat(' %<Name>:sValues: ', ['Name', AItem.TranslatedName]);
AWriter.WriteLine(enumStart + NamedFormat('array[TXML%<Name>:s] of WideString =',
['Name', AItem.TranslatedName]));
lineIndent := StringOfChar(' ', Length(enumStart));
AWriter.WriteLine(lineIndent + '(');
for memberIndex := 0 to Pred(AItem.MemberCount) do
begin
AWriter.Write(NamedFormat('%<Indent>:s ''%<Name>:s''',
['Indent', lineIndent,
'Name', AItem.Members[memberIndex].Name]));
if memberIndex < Pred(AItem.MemberCount) then
AWriter.WriteLine(',')
else
AWriter.WriteLine;
end;
AWriter.WriteLine(lineIndent + ');');
AWriter.WriteLine;
end;
procedure TDelphiXMLDataBindingGenerator.WriteValidate(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection);
begin
if AItem.DocumentElement then
begin
case ASection of
dxsInterface,
dxsClass:
AWriter.WriteLine(XSDValidateDocumentMethodInterface);
dxsImplementation:
AWriter.WriteLineNamedFmt(XSDValidateDocumentMethodImplementation,
['Name', AItem.TranslatedName]);
end;
end;
if AItem.CanValidate then
begin
case ASection of
dxsInterface,
dxsClass:
begin
AWriter.WriteLine(XSDValidateMethodInterface);
AWriter.WriteLine('');
end;
dxsImplementation:
begin
WriteValidateImplementation(AWriter, AItem, False);
WriteValidateImplementation(AWriter, AItem, True);
end;
end;
end;
end;
procedure TDelphiXMLDataBindingGenerator.WriteValidateImplementation(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; AStrict: Boolean);
procedure AddArrayElement(var AOutput: string; var ACount: Integer; const AValue: string);
begin
AOutput := AOutput + ', ';
{ Prevent "Line too long" on large elements }
if (ACount > 0) and (ACount mod 5 = 0) then
AOutput := AOutput + XSDValidateMethodImplementationArrayBreak;
AOutput := AOutput + AValue;
Inc(ACount);
end;
var
propertyIndex: Integer;
propertyItem: TXMLDataBindingProperty;
elementSortCount: Integer;
elementSortOrder: string;
elementRequired: string;
elementNamespaceRequired: string;
elementRequiredCount: Integer;
elementNamespaceRequiredCount: Integer;
attributeRequired: string;
attributeRequiredCount: Integer;
begin
AWriter.WriteLineNamedFmt(IfThen(AStrict, XSDValidateStrictMethodImplementationBegin, XSDValidateMethodImplementationBegin),
['Name', AItem.TranslatedName]);
elementSortCount := 0;
elementSortOrder := '';
elementRequiredCount := 0;
elementRequired := '';
attributeRequiredCount := 0;
attributeRequired := '';
for propertyIndex := 0 to Pred(AItem.PropertyCount) do
begin
propertyItem := AItem.Properties[propertyIndex];
if propertyItem.IsAttribute then
begin
if not propertyItem.IsOptional then
AddArrayElement(attributeRequired, attributeRequiredCount, QuotedStr(propertyItem.Name));
end else if not propertyItem.IsNodeValue then
begin
AddArrayElement(elementSortOrder, elementSortCount, QuotedStr(propertyItem.Name));
if (not propertyItem.IsOptional) and (not propertyItem.IsRepeating) then
begin
case propertyItem.PropertyType of
ptSimple:
begin
AddArrayElement(elementRequired, elementRequiredCount, QuotedStr(propertyItem.Name));
AddArrayElement(elementNamespaceRequired, elementNamespaceRequiredCount, QuotedStr(propertyItem.TargetNamespace));
end;
ptItem:
{ For Item properties, we call our getter property. This ensures the child element exists,
but also that it is created using our binding implementation. Otherwise there will be no
IXSDValidate interface to call on the newly created node. }
AWriter.WriteLineNamedFmt(XSDValidateMethodImplementationComplex,
['Name', propertyItem.TranslatedName]);
end;
end;
end;
end;
if elementRequiredCount > 0 then
begin
Delete(elementRequired, 1, 2);
Delete(elementNamespaceRequired, 1, 2);
AWriter.WriteLineNamedFmt(IfThen(AStrict, XSDValidateStrictMethodImplementationRequired, XSDValidateMethodImplementationRequired),
['RequiredElements', elementRequired,
'RequiredElementNamespaces', elementNamespaceRequired]);
end;
if attributeRequiredCount > 0 then
begin
Delete(attributeRequired, 1, 2);
AWriter.WriteLineNamedFmt(IfThen(AStrict, XSDValidateStrictMethodImplementationAttrib, XSDValidateMethodImplementationAttrib),
['RequiredAttributes', attributeRequired]);
end;
if elementSortCount > 1 then
begin
Delete(elementSortOrder, 1, 2);
AWriter.WriteLineNamedFmt(XSDValidateMethodImplementationSort,
['SortOrder', elementSortOrder]);
end;
AWriter.WriteLine(IfThen(AStrict, XSDValidateStrictMethodImplementationEnd, XSDValidateMethodImplementationEnd));
end;
procedure TDelphiXMLDataBindingGenerator.WriteEnumeratorMethod(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection);
begin
if not AItem.IsCollection then
Exit;
case ASection of
dxsInterface,
dxsClass:
begin
AWriter.WriteLineNamedFmt(EnumeratorMethodInterface,
['Name', AItem.TranslatedName]);
AWriter.WriteLine('');
end;
dxsImplementation:
begin
AWriter.WriteLineNamedFmt(EnumeratorMethodImplementation,
['Name', AItem.TranslatedName]);
end;
end;
end;
procedure TDelphiXMLDataBindingGenerator.WriteEnumerator(AWriter: TNamedFormatWriter; AItem: TXMLDataBindingInterface; ASection: TDelphiXMLSection);
begin
if not AItem.IsCollection then
Exit;
case ASection of
dxsInterface:
begin
AWriter.WriteLineNamedFmt(EnumeratorInterface,
['Name', AItem.TranslatedName,
'DataType', GetDataTypeName(AItem.CollectionItem, True),
'GUID', CreateNewGUID]);
AWriter.WriteLine('');
end;
dxsClass:
begin
AWriter.WriteLineNamedFmt(EnumeratorClass,
['Name', AItem.TranslatedName,
'DataType', GetDataTypeName(AItem.CollectionItem, True)]);
AWriter.WriteLine('');
end;
dxsImplementation:
begin
AWriter.WriteLineNamedFmt(EnumeratorImplementation,
['Name', AItem.TranslatedName,
'DataType', GetDataTypeName(AItem.CollectionItem, True)]);
end;
end;
end;
function TDelphiXMLDataBindingGenerator.GetDelphiNodeType(AProperty: TXMLDataBindingProperty): TDelphiNodeType;
begin
if AProperty.IsAttribute then
Result := dntAttribute
else if AProperty.IsNodeValue then
Result := dntNodeValue
else if AProperty.HasTargetNamespace then
Result := dntElementNS
else
Result := dntElement;
end;
function TDelphiXMLDataBindingGenerator.GetDelphiElementType(ANodeType: TDelphiNodeType): TDelphiElementType;
begin
if ANodeType = dntElementNS then
Result := dntElementNS
else
Result := dntElement;
end;
function TDelphiXMLDataBindingGenerator.DataTypeConversion(const ADestination, ASource: String; ADataType: IXMLTypeDef;
AAccessor: TDelphiAccessor; ANodeType: TDelphiNodeType;
const ATargetNamespace: string; const ALinesBefore: String = ''): String;
var
typeMapping: TTypeMapping;
conversion: String;
begin
with TNamedFormatStringList.Create do
try
if not (Assigned(ADataType) and GetDataTypeMapping(ADataType, typeMapping)) then
typeMapping.Conversion := tcNone;
Add('begin');
if Length(ALinesBefore) > 0 then
Add(ALinesBefore);
conversion := TypeConversion[AAccessor, ANodeType, typeMapping.Conversion];
if Length(conversion) = 0 then
conversion := TypeConversionNone[AAccessor, ANodeType];
Add(conversion);
Add('end;');
// #ToDo1 -oMvR: 6-4-2012: Namespace
Result := Trim(Format(['Destination', ADestination,
'Source', ASource,
'Namespace', ATargetNamespace]));
finally
Free;
end;
end;
function TDelphiXMLDataBindingGenerator.XMLToNativeDataType(const ADestination, ASource: String; ADataType: IXMLTypeDef;
ANodeType: TDelphiNodeType; const ATargetNamespace: string;
const ALinesBefore: String): String;
begin
Result := DataTypeConversion(ADestination, ASource, ADataType, daGet, ANodeType, ATargetNamespace, ALinesBefore);
end;
function TDelphiXMLDataBindingGenerator.NativeDataTypeToXML(const ADestination, ASource: String; ADataType: IXMLTypeDef;
ANodeType: TDelphiNodeType; const ATargetNamespace: string;
const ALinesBefore: String): String;
begin
Result := DataTypeConversion(ADestination, ASource, ADataType, daSet, ANodeType, ATargetNamespace, ALinesBefore);
end;
function TDelphiXMLDataBindingGenerator.CreateNewGUID: String;
var
guid: TGUID;
begin
Result := '{ GUID generation failed }';
if CreateGUID(guid) = S_OK then
Result := '[''' + GUIDToString(guid) + ''']';
end;
function TDelphiXMLDataBindingGenerator.DoGetFileName(const ASchemaName: String): String;
var
path: String;
fileName: String;
begin
Result := OutputPath;
if OutputType = otMultiple then
begin
path := IncludeTrailingPathDelimiter(Result);
fileName := ASchemaName.Replace('-', '_');
fileName := fileName + '.pas';
if Assigned(FOnGetFileName) then
FOnGetFileName(Self, ASchemaName, path, fileName);
Result := IncludeTrailingPathDelimiter(path) + fileName;
end;
end;
end.
|
unit usvcMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, SvcMgr, Dialogs,
ncSources, ncSockets, Registry, DB, ADODB, ncCommandHandlers, ncDBSrv, ActiveX;
type
TsvcOnLogMessage = procedure(Sender: TObject; aMessage: string; aError: Boolean = False) of object;
// Name property is the name we are going to use to uniquelly identify our service
TNetcomDataServer = class(TService)
srvController: TncServerSource;
DBServer: TncDBServer;
ADOConnection: TADOConnection;
procedure ServiceCreate(Sender: TObject);
procedure ServiceDestroy(Sender: TObject);
procedure ServiceStart(Sender: TService; var Started: Boolean);
procedure ServiceStop(Sender: TService; var Stopped: Boolean);
procedure ServiceShutdown(Sender: TService);
private
FOnLogMessage: TsvcOnLogMessage;
function GetServicePort: Integer;
procedure SetServicePort(const Value: Integer);
function GetDBConnectionString: string;
procedure SetDBConnectionString(const Value: string);
procedure StopAndShutdown;
function GetCacheResponses: Boolean;
procedure SetCacheResponses(const Value: Boolean);
public
Settings: TRegistry;
procedure Log(aStr: string; aError: Boolean = False);
function GetServiceController: TServiceController; override;
property OnLogMessage: TsvcOnLogMessage read FOnLogMessage write FOnLogMessage;
property ServicePort: Integer read GetServicePort write SetServicePort;
property DBConnectionString: string read GetDBConnectionString write SetDBConnectionString;
property CacheResponses: Boolean read GetCacheResponses write SetCacheResponses;
end;
var
Service: TNetcomDataServer;
implementation
uses uscvServiceCommands;
{$R *.DFM}
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
Service.Controller(CtrlCode);
end;
function TNetcomDataServer.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TNetcomDataServer.ServiceCreate(Sender: TObject);
begin
FOnLogMessage := nil;
Settings := TRegistry.Create(KEY_READ or KEY_WRITE);
Settings.LazyWrite := False;
Settings.RootKey := HKEY_CURRENT_USER;
if not Settings.OpenKey('\HKEY_CURRENT_USER\Software\' + Name, True) then
Log('Cannot open settings key: \HKEY_CURRENT_USER\Software\' + Name);
end;
procedure TNetcomDataServer.ServiceDestroy(Sender: TObject);
begin
Settings.CloseKey;
Settings.Free;
end;
procedure TNetcomDataServer.Log(aStr: string; aError: Boolean = False);
var
ErrType: DWord;
begin
if Assigned(FOnLogMessage) then
// Call custom handler
FOnLogMessage(Self, aStr, aError)
else
begin
// Write to windows log system
if aError then
ErrType := EVENTLOG_AUDIT_FAILURE
else
ErrType := EVENTLOG_AUDIT_SUCCESS;
Self.LogMessage(aStr, ErrType);
end;
end;
procedure TNetcomDataServer.ServiceStart(Sender: TService; var Started: Boolean);
begin
try
CoInitialize(nil);
// Put critical startup code here
srvController.Port := ServicePort;
ADOConnection.ConnectionString := DBConnectionString;
DBServer.CacheResponses := CacheResponses;
ADOConnection.Connected := True;
srvController.Active := True;
Log('"' + DisplayName + '" (' + Name + ') service started successfully, on port: ' + IntTostr(srvController.Port));
except
on E: Exception do
begin
Log('"' + DisplayName + '" (' + Name + ') service failed to start. ' + E.Message, True);
Started := False;
end;
end;
end;
procedure TNetcomDataServer.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
StopAndShutdown;
Log('"' + DisplayName + '" service stopped successfully');
end;
procedure TNetcomDataServer.ServiceShutdown(Sender: TService);
begin
StopAndShutdown;
Log('"' + DisplayName + '" service stopped successfully');
end;
procedure TNetcomDataServer.StopAndShutdown;
begin
srvController.Active := False;
ADOConnection.Connected := False;
CoUninitialize;
end;
function TNetcomDataServer.GetServicePort: Integer;
begin
try
if not Settings.ValueExists('ServicePort') then
Abort;
Result := Settings.ReadInteger('ServicePort');
except
Result := srvController.Port;
end;
end;
procedure TNetcomDataServer.SetServicePort(const Value: Integer);
begin
Settings.WriteInteger('ServicePort', Value);
end;
function TNetcomDataServer.GetDBConnectionString: string;
begin
try
if not Settings.ValueExists('DBConnection') then
Abort;
Result := Settings.ReadString('DBConnection');
except
Result := ADOConnection.ConnectionString;
end;
end;
procedure TNetcomDataServer.SetDBConnectionString(const Value: string);
begin
Settings.WriteString('DBConnection', Value);
end;
function TNetcomDataServer.GetCacheResponses: Boolean;
begin
try
if not Settings.ValueExists('CacheResponses') then
Abort;
Result := Settings.ReadBool('CacheResponses');
except
Result := DBServer.CacheResponses;
end;
end;
procedure TNetcomDataServer.SetCacheResponses(const Value: Boolean);
begin
Settings.WriteBool('CacheResponses', Value);
end;
end.
|
unit PluginManager;
interface
uses
{$IFDEF DELPHIXE3_LVL}
Winapi.Windows,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.ExtCtrls,
{$ELSE}
Windows,
SysUtils,
Classes,
Graphics,
ExtCtrls,
Dialogs,
{$ENDIF }
Helpers,
Forms,
uObjects,
uConstsProg;
type
EPluginManagerError = class(Exception);
EPluginLoadError = class(EPluginManagerError);
EDuplicatePluginError = class(EPluginLoadError);
EPluginsLoadError = class(EPluginLoadError)
private
FItems: TStrings;
public
constructor Create(const AText: String; const AFailedPlugins: TStrings);
destructor Destroy; override;
property FailedPluginFileNames: TStrings read FItems;
end;
IPlugin = interface
// protected
function GetIndex: Integer;
function GetHandle: HMODULE;
function GetIcon: TIcon;
procedure DestroyIcon;
function GetFileName: String;
function GetID: TGUID;
function GetName: String;
function GetVersion: String;
function GetAuthorName: String;
function GetEmailAuthor: String;
function GetSiteAuthor: String;
function GetIndexIcon: Integer;
procedure SetIndexIcon(i: Integer);
function GetUpdatedIcons: Boolean;
procedure SetUpdatedIcons(Value: Boolean);
function GetUpdatedActive: Boolean;
procedure SetUpdatedActive(Value: Boolean);
function GetUpdatedPremium: Boolean;
procedure SetUpdatedPremium(Value: Boolean);
function GetOptionsIndexIcon: Integer;
procedure SetOptionsIndexIcon(Value: Integer);
function GetGetedGraphRating: Boolean;
procedure SetGetedGraphRating(Value: Boolean);
function GetImageGraphRating: TImage;
procedure SetImageGraphRating(Value: TImage);
function GetPanelStatistic: TPanel;
procedure SetPanelStatistic(Value: TPanel);
function GetPanelInfoRank: TPanel;
procedure SetPanelInfoRank(Value: TPanel);
function GetGlobalRank: String;
procedure SetGlobalRank(Value: String);
function GetPictureRatings: TMemoryStream;
procedure SetPictureRatings(Value: TMemoryStream);
function GetTaskIndexIcon: Integer;
procedure SetTaskIndexIcon(Value: Integer);
function GetItemIndex: Integer;
procedure SetItemIndex(Value: Integer);
function GetSalePremIndexIcon: Integer;
procedure SetSalePremIndexIcon(Value: Integer);
function GetMask: String;
function GetDescription: String;
function GetFilterIndex: Integer;
procedure SetFilterIndex(const AValue: Integer);
// public
property Index: Integer read GetIndex;
property Handle: HMODULE read GetHandle;
property FileName: String read GetFileName;
property ID: TGUID read GetID;
property Name: String read GetName;
property Version: String read GetVersion;
property AuthorName: String read GetAuthorName;
property EmailAuthor: String read GetEmailAuthor;
property SiteAuthor: String read GetSiteAuthor;
property Icon: TIcon read GetIcon;
property IndexIcon: Integer read GetIndexIcon write SetIndexIcon;
property UpdatedIcons: Boolean read GetUpdatedIcons write SetUpdatedIcons;
property UpdatedActive: Boolean read GetUpdatedActive
write SetUpdatedActive;
property UpdatedPremium: Boolean read GetUpdatedPremium
write SetUpdatedPremium;
property OptionsIndexIcon: Integer read GetOptionsIndexIcon
write SetOptionsIndexIcon;
property GetedGraphRating: Boolean read GetGetedGraphRating
write SetGetedGraphRating;
property ImageGraphRating: TImage read GetImageGraphRating
write SetImageGraphRating;
property PanelStatistic: TPanel read GetPanelStatistic
write SetPanelStatistic;
property PanelInfoRank: TPanel read GetPanelInfoRank write SetPanelInfoRank;
property GlobalRank: string read GetGlobalRank write SetGlobalRank;
property PictureRatings: TMemoryStream read GetPictureRatings
write SetPictureRatings;
property TaskIndexIcon: Integer read GetTaskIndexIcon
write SetTaskIndexIcon;
property ItemIndex: Integer read GetItemIndex write SetItemIndex;
property SalePremIndexIcon: Integer read GetSalePremIndexIcon
write SetSalePremIndexIcon;
property Mask: String read GetMask;
property Description: String read GetDescription;
property FilterIndex: Integer read GetFilterIndex write SetFilterIndex;
end;
IServiceProvider = interface
function CreateInterface(const APlugin: IPlugin; const AIID: TGUID;
out Intf): Boolean;
end;
IProvider = interface(IServiceProvider)
procedure Delete;
end;
IPluginManager = interface
// protected
function GetItem(const AIndex: Integer): IPlugin;
function GetCount: Integer;
// public
function LoadPlugin(const AFileName: String): IPlugin;
procedure UnloadPlugin(const AIndex: Integer);
procedure LoadPlugins(const AFolder: String; const AFileExt: String = '');
procedure Ban(const AFileName: String);
procedure Unban(const AFileName: String);
procedure SaveSettings(const ARegPath: String);
procedure LoadSettings(const ARegPath: String);
property Items[const AIndex: Integer]: IPlugin read GetItem; default;
property Count: Integer read GetCount;
function IndexOf(const AID: TGUID): Integer;
procedure DoLoaded;
procedure UnloadAll;
procedure ProvidersListCreate;
procedure SetVersion(const AVersion: Integer);
procedure RegisterServiceProvider(const AProvider: IServiceProvider);
end;
TBasicProvider = class(TCheckedInterfacedObject, IUnknown, IServiceProvider,
IProvider)
private
FManager: IPluginManager;
FPlugin: PluginManager.IPlugin;
protected
// IUnknown
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
// IServiceProvider
function CreateInterface(const APlugin: IPlugin; const AIID: TGUID;
out Intf): Boolean; virtual;
// IProvider
procedure Delete;
public
constructor Create(const AManager: IPluginManager;
const APlugin: PluginManager.IPlugin);
property Manager: IPluginManager read FManager;
property Plugin: PluginManager.IPlugin read FPlugin;
end;
function Plugins: IPluginManager;
implementation
uses
{$IFDEF DELPHIXE3_LVL}
System.Win.Registry,
{$ELSE}
Registry,
{$ENDIF }
uProcedures,
PluginAPI;
resourcestring
rsPluginsLoadError = 'One or more plugins has failed to load:' +
sLineBreak + '%s';
rsDuplicatePlugin = 'Plugin is already loaded.' + sLineBreak +
'ID: %s; Name: %s;' + sLineBreak + 'File name 1: %s' + sLineBreak +
'File name 2: %s';
type
IProviderManager = interface
['{799F9F9F-9030-43B1-B184-0950962B09A5}']
procedure RegisterProvider(const AProvider: IProvider);
end;
// TPlugin = class;
TPluginManager = class(TCheckedInterfacedObject, IUnknown, IPluginManager)
private
FItems: array of IPlugin;
FCount: Integer;
FBanned: TStringList;
FVersion: Integer;
FProviders: TInterfaceList;
protected
function CreateInterface(const APlugin: PluginManager.IPlugin;
const AIID: TGUID; out Intf): Boolean;
// PluginManager.IPluginManager
function GetItem(const AIndex: Integer): PluginManager.IPlugin;
function GetCount: Integer;
function CanLoad(const AFileName: String): Boolean;
procedure SetVersion(const AVersion: Integer);
procedure RegisterServiceProvider(const AProvider: IServiceProvider);
// ICore
function GetVersion: Integer;
public
constructor Create;
destructor Destroy; override;
property Count: Integer read GetCount;
property Items[const AIndex: Integer]: PluginManager.IPlugin
read GetItem; default;
// PluginManager.IPluginManager
function LoadPlugin(const AFileName: String): IPlugin;
procedure UnloadPlugin(const AIndex: Integer);
procedure LoadPlugins(const AFolder, AFileExt: String);
function IndexOf(const APlugin: IPlugin): Integer; overload;
function IndexOf(const AID: TGUID): Integer; overload;
procedure Ban(const AFileName: String);
procedure Unban(const AFileName: String);
procedure SaveSettings(const ARegPath: String);
procedure LoadSettings(const ARegPath: String);
procedure UnloadAll;
procedure DoLoaded;
procedure ProvidersListCreate;
end;
TPlugin = class(TCheckedInterfacedObject, IUnknown, IPlugin, IProviderManager,
IDestroyNotify, IPlugins, ICore)
private
FManager: TPluginManager;
FFileName: String;
FHandle: HMODULE;
FIconPlugin: TIcon;
FIndexIcon: Integer;
FUpdatedIcons: Boolean;
FUpdatedActive: Boolean;
FUpdatedPremium: Boolean;
FOptionsIndexIcon: Integer;
FGetedGraphRating: Boolean;
FImageGraphRating: TImage;
FPanelStatistic: TPanel;
FPanelInfoRank: TPanel;
FGlobalRank: String;
FPictureRatings: TMemoryStream;
FTaskIndexIcon: Integer;
FItemIndex: Integer;
FSalePremIndexIcon: Integer;
FInit: TInitPluginFunc;
FDone: TDonePluginFunc;
FFilterIndex: Integer;
FPlugin: PluginAPI.IPlugin;
FID: TGUID;
FName: String;
FVersion: String;
FAuthorName: String;
FEmailAuthor: String;
FSiteAuthor: String;
FPluginType: Integer;
FInfoRetrieved: Boolean;
FMask: String;
FDescription: String;
FProviders: array of IProvider;
procedure GetInfo;
procedure ReleasePlugin;
procedure ReleaseProviders;
protected
function CreateInterface(const AIID: TGUID; out Intf): Boolean;
// IUnknown
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
// IPlugin
function GetFileName: String;
function GetID: TGUID;
function GetName: String;
function GetVersion: String;
function GetAuthorName: String;
function GetEmailAuthor: String;
function GetSiteAuthor: String;
function GetIndex: Integer;
function GetHandle: HMODULE;
function GetIcon: TIcon;
procedure DestroyIcon;
function GetIndexIcon: Integer;
procedure SetIndexIcon(i: Integer);
function GetUpdatedIcons: Boolean;
procedure SetUpdatedIcons(Value: Boolean);
function GetUpdatedActive: Boolean;
procedure SetUpdatedActive(Value: Boolean);
function GetUpdatedPremium: Boolean;
procedure SetUpdatedPremium(Value: Boolean);
function GetOptionsIndexIcon: Integer;
procedure SetOptionsIndexIcon(Value: Integer);
function GetGetedGraphRating: Boolean;
procedure SetGetedGraphRating(Value: Boolean);
function GetImageGraphRating: TImage;
procedure SetImageGraphRating(Value: TImage);
function GetPanelStatistic: TPanel;
procedure SetPanelStatistic(Value: TPanel);
function GetPanelInfoRank: TPanel;
procedure SetPanelInfoRank(Value: TPanel);
function GetGlobalRank: String;
procedure SetGlobalRank(Value: String);
function GetPictureRatings: TMemoryStream;
procedure SetPictureRatings(Value: TMemoryStream);
function GetTaskIndexIcon: Integer;
procedure SetTaskIndexIcon(Value: Integer);
function GetItemIndex: Integer;
procedure SetItemIndex(Value: Integer);
function GetSalePremIndexIcon: Integer;
procedure SetSalePremIndexIcon(Value: Integer);
function GetMask: String;
function GetDescription: String;
function GetFilterIndex: Integer;
procedure SetFilterIndex(const AValue: Integer);
// ICore
function GetCoreVersion: Integer; safecall;
function ICore.GetVersion = GetCoreVersion;
// IPlugins
function GetCount: Integer; safecall;
function GetPlugin(const AIndex: Integer): PluginAPI.IPlugin; safecall;
// IProviderManager
procedure RegisterProvider(const AProvider: IProvider);
// IDestroyNotify
procedure Delete; safecall;
public
constructor Create(const APluginManger: TPluginManager;
const AFileName: String); virtual;
destructor Destroy; override;
end;
{ TPluginManager }
constructor TPluginManager.Create;
begin
OutputDebugString('TPluginManager.Create');
SetName('TPluginManager');
inherited Create;
FBanned := TStringList.Create;
FProviders := TInterfaceList.Create;
SetVersion(1);
end;
destructor TPluginManager.Destroy;
begin
OutputDebugString('TPluginManager.Destroy');
UnloadAll;
FreeAndNil(FProviders);
FreeAndNil(FBanned);
inherited;
end;
procedure TPluginManager.DoLoaded;
var
X: Integer;
LoadNotify: ILoadNotify;
begin
for X := 0 to GetCount - 1 do
if Supports(Plugins[X], ILoadNotify, LoadNotify) then
LoadNotify.Loaded;
end;
function TPluginManager.LoadPlugin(const AFileName: String): IPlugin;
begin
if CanLoad(AFileName) then
begin
Result := nil;
Exit;
end;
// Загружаем плагин
try
Result := TPlugin.Create(Self, AFileName);
except
on E: Exception do
raise EPluginLoadError.Create
(Format('[%s] %s', [E.ClassName, E.Message]));
end;
// Заносим в список
if Length(FItems) <= FCount then // "Capacity"
SetLength(FItems, Length(FItems) + 64);
FItems[FCount] := Result;
Inc(FCount);
end;
procedure TPluginManager.LoadPlugins(const AFolder, AFileExt: String);
var
Path: String;
sr: TSearchRec;
Failures: TStringList;
FailedPlugins: TStringList;
function PluginOK(const APluginName, AFileExt: String): Boolean;
begin
Result := (AFileExt = '');
if Result then
Exit;
Result := SameFileName(ExtractFileExt(APluginName), AFileExt);
end;
begin
Path := IncludeTrailingPathDelimiter(AFolder);
Sleep(100);
Failures := TStringList.Create;
FailedPlugins := TStringList.Create;
try
if FindFirst(Path + '*.*', 0, sr) = 0 then
try
repeat
if ((sr.Attr and faDirectory) = 0) and PluginOK(sr.Name, AFileExt)
then
begin
try
LoadPlugin(Path + sr.Name);
except
on E: Exception do
begin
FailedPlugins.Add(sr.Name);
Failures.Add(Format('%s: %s', [sr.Name, E.Message]));
end;
end;
end;
Application.ProcessMessages;
until FindNext(sr) <> 0;
finally
FindClose(sr);
end;
if Failures.Count > 0 then
raise EPluginsLoadError.Create(Format(rsPluginsLoadError, [Failures.Text]
), FailedPlugins);
finally
FreeAndNil(FailedPlugins);
FreeAndNil(Failures);
end;
end;
procedure TPluginManager.ProvidersListCreate;
begin
if not Assigned(FProviders) then
FProviders := TInterfaceList.Create;
end;
procedure TPluginManager.UnloadAll;
procedure NotifyRelease;
var
X: Integer;
Notify: IDestroyNotify;
begin
for X := FCount - 1 downto 0 do // for X := 0 to FCount - 1 do
begin
if Supports(FItems[X], IDestroyNotify, Notify) then
Notify.Delete;
end;
end;
begin
NotifyRelease;
FCount := 0;
Finalize(FItems);
FreeAndNil(FProviders);
end;
procedure TPluginManager.UnloadPlugin(const AIndex: Integer);
var
X: Integer;
Notify: IDestroyNotify;
begin
FItems[AIndex] := nil;
// Сдвинуть плагины в списке, чтобы закрыть "дырку"
for X := AIndex to FCount - 1 do
FItems[X] := FItems[X + 1];
// Не забыть учесть последний
FItems[FCount - 1] := nil;
Dec(FCount);
end;
function TPluginManager.IndexOf(const APlugin: IPlugin): Integer;
begin
Result := IndexOf(APlugin.ID);
end;
function TPluginManager.IndexOf(const AID: TGUID): Integer;
var
X: Integer;
ID: TGUID;
begin
Result := -1;
for X := 0 to FCount - 1 do
begin
ID := FItems[X].ID;
if CompareMem(@ID, @AID, SizeOf(TGUID)) then
begin
Result := X;
Break;
end;
end;
end;
procedure TPluginManager.Ban(const AFileName: String);
begin
Unban(AFileName);
FBanned.Add(AFileName);
end;
procedure TPluginManager.Unban(const AFileName: String);
var
X: Integer;
begin
for X := 0 to FBanned.Count - 1 do
if SameFileName(FBanned[X], AFileName) then
begin
FBanned.Delete(X);
Break;
end;
end;
function TPluginManager.CanLoad(const AFileName: String): Boolean;
var
X: Integer;
begin
// Не грузить отключенные
for X := 0 to FBanned.Count - 1 do
if SameFileName(FBanned[X], AFileName) then
begin
Result := true;
Exit;
end;
// Не грузить уже загруженные
for X := 0 to FCount - 1 do
if SameFileName(FItems[X].FileName, AFileName) then
begin
Result := true;
Exit;
end;
Result := False;
end;
const
SRegDisabledPlugins = 'Disabled plugins';
SRegPluginX = 'Plugin%d';
procedure TPluginManager.SaveSettings(const ARegPath: String);
var
Reg: TRegIniFile;
Path: String;
X: Integer;
begin
Reg := TRegIniFile.Create(ARegPath, KEY_ALL_ACCESS);
try
// Удаляем старые
Reg.EraseSection(SRegDisabledPlugins);
Path := ARegPath + '\' + SRegDisabledPlugins;
if not Reg.OpenKey(Path, true) then
Exit;
// Сохраняем новые
for X := 0 to FBanned.Count - 1 do
Reg.WriteString(Path, Format(SRegPluginX, [X]), FBanned[X]);
finally
FreeAndNil(Reg);
end;
end;
procedure TPluginManager.SetVersion(const AVersion: Integer);
begin
FVersion := AVersion;
end;
procedure TPluginManager.LoadSettings(const ARegPath: String);
var
Reg: TRegIniFile;
Path: String;
X: Integer;
begin
Reg := TRegIniFile.Create(ARegPath, KEY_READ);
try
FBanned.BeginUpdate;
try
FBanned.Clear;
// Читаем
Path := ARegPath + '\' + SRegDisabledPlugins;
if not Reg.OpenKey(Path, true) then
Exit;
Reg.ReadSectionValues(Path, FBanned);
// Убираем "Plugin5=" из строк
for X := 0 to FBanned.Count - 1 do
FBanned[X] := FBanned.ValueFromIndex[X];
finally
FBanned.EndUpdate;
end;
finally
FreeAndNil(Reg);
end;
end;
function TPluginManager.CreateInterface(const APlugin: PluginManager.IPlugin;
const AIID: TGUID; out Intf): Boolean;
var
Provider: IServiceProvider;
X: Integer;
begin
Pointer(Intf) := nil;
Result := False;
for X := 0 to FProviders.Count - 1 do
begin
Provider := IServiceProvider(FProviders[X]);
if Provider.CreateInterface(APlugin, AIID, Intf) then
begin
Result := true;
Exit;
end;
end;
end;
procedure TPluginManager.RegisterServiceProvider(const AProvider
: IServiceProvider);
begin
FProviders.Add(AProvider);
end;
function TPluginManager.GetCount: Integer;
begin
Result := FCount;
end;
function TPluginManager.GetItem(const AIndex: Integer): PluginManager.IPlugin;
begin
Result := FItems[AIndex];
end;
function TPluginManager.GetVersion: Integer;
begin
Result := FVersion;
end;
{ TBasicProvider }
constructor TBasicProvider.Create(const AManager: IPluginManager;
const APlugin: PluginManager.IPlugin);
var
Manager: IProviderManager;
begin
inherited Create;
FManager := AManager;
FPlugin := APlugin;
if Supports(APlugin, IProviderManager, Manager) then
Manager.RegisterProvider(Self);
SetName(Format('TBasicProvider(%s): %s', [ExtractFileName(APlugin.FileName),
ClassName]));
end;
function TBasicProvider.CreateInterface(const APlugin: IPlugin;
const AIID: TGUID; out Intf): Boolean;
begin
Result := Succeeded(inherited QueryInterface(AIID, Intf));
end;
function TBasicProvider.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
Result := inherited QueryInterface(IID, Obj);
if Failed(Result) then
Result := FPlugin.QueryInterface(IID, Obj);
end;
procedure TBasicProvider.Delete;
begin
FPlugin := nil;
FManager := nil;
end;
{ TPlugin }
constructor TPlugin.Create(const APluginManger: TPluginManager;
const AFileName: String);
function SafeLoadLibrary(const FileName: string; ErrorMode: UINT): HMODULE;
const
LOAD_WITH_ALTERED_SEARCH_PATH = $008;
var
OldMode: UINT;
FPUControlWord: Word;
begin
OldMode := SetErrorMode(ErrorMode);
try
{$IFNDEF CPUX64}
asm
FNSTCW FPUControlWord
end;
try
{$ENDIF}
Result := LoadLibraryEx(PChar(FileName), 0,
LOAD_WITH_ALTERED_SEARCH_PATH);
{$IFNDEF CPUX64}
finally
asm
FNCLEX
FLDCW FPUControlWord
end;
end;
{$ENDIF}
finally
SetErrorMode(OldMode);
end;
end;
var
Ind: Integer;
begin
OutputDebugString(PChar('TPlugin.Create: ' + ExtractFileName(AFileName)));
SetName(Format('TPlugin(%s)', [ExtractFileName(AFileName)]));
inherited Create;
FManager := APluginManger;
FFileName := AFileName;
FFilterIndex := -1;
FHandle := SafeLoadLibrary(AFileName, SEM_NOOPENFILEERRORBOX or
SEM_FAILCRITICALERRORS);
Win32Check(FHandle <> 0);
FDone := GetProcAddress(FHandle, SPluginDoneFuncName);
FInit := GetProcAddress(FHandle, SPluginInitFuncName);
Win32Check(Assigned(FInit));
FPlugin := FInit(Self);
Win32Check(Assigned(FPlugin));
Ind := FManager.IndexOf(FPlugin.ID);
if Ind >= 0 then
raise EDuplicatePluginError.CreateFmt(rsDuplicatePlugin,
[GUIDToString(FPlugin.ID), FPlugin.Name, FManager[Ind].FileName,
AFileName]);
FID := FPlugin.ID;
FName := FPlugin.Name;
FVersion := FPlugin.Version;
FAuthorName := FPlugin.AuthorName;
FEmailAuthor := FPlugin.EmailAuthor;
FSiteAuthor := FPlugin.SiteAuthor;
FPluginType := FPlugin.PluginType;
// FServiceName := FServicePlugin.ServiceName;
// FServices := FServicePlugin.Services;
SetName(Format('TPlugin(%s): %s', [ExtractFileName(AFileName),
GUIDToString(FID)]));
end;
destructor TPlugin.Destroy;
begin
OutputDebugString(PChar('TPlugin.Destroy: ' + ExtractFileName(FFileName)));
Delete;
if Assigned(FDone) then
FDone;
if FHandle <> 0 then
begin
FreeLibrary(FHandle);
FHandle := 0;
end;
inherited;
end;
procedure TPlugin.Delete;
begin
ReleaseProviders;
ReleasePlugin;
end;
procedure TPlugin.ReleaseProviders;
var
X: Integer;
begin
for X := High(FProviders) downto 0 do
FProviders[X].Delete;
Finalize(FProviders);
end;
procedure TPlugin.ReleasePlugin;
var
Notify: IDestroyNotify;
begin
if Supports(FPlugin, IDestroyNotify, Notify) then
Notify.Delete;
FPlugin := nil;
end;
function TPlugin.CreateInterface(const AIID: TGUID; out Intf): Boolean;
var
X: Integer;
begin
Pointer(Intf) := nil;
Result := False;
for X := 0 to High(FProviders) do
begin
Result := FProviders[X].CreateInterface(Self, AIID, Intf);
if Result then
Break;
end;
end;
function TPlugin.GetFileName: String;
begin
Result := FFileName;
end;
function TPlugin.GetID: TGUID;
begin
Result := FID;
end;
function TPlugin.GetName: String;
begin
Result := FName;
end;
function TPlugin.GetVersion: String;
begin
Result := FVersion;
end;
function TPlugin.GetAuthorName: String;
begin
Result := FAuthorName;
end;
function TPlugin.GetEmailAuthor: String;
begin
Result := FEmailAuthor;
end;
function TPlugin.GetSiteAuthor: String;
begin
Result := FSiteAuthor;
end;
function TPlugin.GetIndexIcon: Integer;
begin
Result := FIndexIcon;
end;
procedure TPlugin.SetIndexIcon(i: Integer);
begin
FIndexIcon := i;
end;
function TPlugin.GetUpdatedIcons: Boolean;
begin
Result := FUpdatedIcons;
end;
procedure TPlugin.SetUpdatedIcons(Value: Boolean);
begin
FUpdatedIcons := Value;
end;
function TPlugin.GetUpdatedActive: Boolean;
begin
Result := FUpdatedActive;
end;
procedure TPlugin.SetUpdatedActive(Value: Boolean);
begin
FUpdatedActive := Value;
end;
function TPlugin.GetUpdatedPremium: Boolean;
begin
Result := FUpdatedPremium;
end;
procedure TPlugin.SetUpdatedPremium(Value: Boolean);
begin
FUpdatedPremium := Value;
end;
function TPlugin.GetOptionsIndexIcon: Integer;
begin
Result := FOptionsIndexIcon;
end;
procedure TPlugin.SetOptionsIndexIcon(Value: Integer);
begin
FOptionsIndexIcon := Value;
end;
function TPlugin.GetGetedGraphRating: Boolean;
begin
Result := FGetedGraphRating;
end;
procedure TPlugin.SetGetedGraphRating(Value: Boolean);
begin
FGetedGraphRating := Value;
end;
function TPlugin.GetImageGraphRating: TImage;
begin
Result := FImageGraphRating;
end;
procedure TPlugin.SetImageGraphRating(Value: TImage);
begin
FImageGraphRating := Value;
end;
function TPlugin.GetPanelStatistic: TPanel;
begin
Result := FPanelStatistic;
end;
procedure TPlugin.SetPanelStatistic(Value: TPanel);
begin
FPanelStatistic := Value;
end;
function TPlugin.GetPanelInfoRank: TPanel;
begin
Result := FPanelInfoRank;
end;
procedure TPlugin.SetPanelInfoRank(Value: TPanel);
begin
FPanelInfoRank := Value;
end;
function TPlugin.GetGlobalRank: String;
begin
Result := FGlobalRank;
end;
procedure TPlugin.SetGlobalRank(Value: String);
begin
FGlobalRank := Value;
end;
function TPlugin.GetPictureRatings: TMemoryStream;
begin
Result := FPictureRatings;
end;
procedure TPlugin.SetPictureRatings(Value: TMemoryStream);
begin
FPictureRatings := Value;
end;
function TPlugin.GetTaskIndexIcon: Integer;
begin
Result := FTaskIndexIcon;
end;
procedure TPlugin.SetTaskIndexIcon(Value: Integer);
begin
FTaskIndexIcon := Value;
end;
function TPlugin.GetItemIndex: Integer;
begin
Result := FItemIndex;
end;
procedure TPlugin.SetItemIndex(Value: Integer);
begin
FItemIndex := Value;
end;
function TPlugin.GetSalePremIndexIcon: Integer;
begin
Result := FSalePremIndexIcon;
end;
procedure TPlugin.SetSalePremIndexIcon(Value: Integer);
begin
FSalePremIndexIcon := Value;
end;
function TPlugin.GetHandle: HMODULE;
begin
Result := FHandle;
end;
function TPlugin.GetIcon: TIcon;
begin
FIconPlugin := TIcon.Create;
try
FIconPlugin.LoadFromResourceName(FHandle, 'Icon_1');
Result := FIconPlugin;
except
end;
end;
procedure TPlugin.DestroyIcon;
begin
try
if Assigned(FIconPlugin { <> nil } ) then
FIconPlugin.Free;
except
end;
end;
function TPlugin.GetIndex: Integer;
begin
Result := FManager.IndexOf(Self);
end;
procedure TPlugin.GetInfo;
var
Plugin: IExportImportPluginInfo;
begin
if FInfoRetrieved then
Exit;
if Supports(FPlugin, IExportImportPluginInfo, Plugin) then
begin
FMask := Plugin.Mask;
FDescription := Plugin.Description;
end
else
begin
FMask := '';
FDescription := '';
end;
FInfoRetrieved := true;
end;
function TPlugin.GetMask: String;
begin
GetInfo;
Result := FMask;
end;
function TPlugin.GetDescription: String;
begin
GetInfo;
Result := FDescription;
end;
function TPlugin.GetFilterIndex: Integer;
begin
Result := FFilterIndex;
end;
procedure TPlugin.SetFilterIndex(const AValue: Integer);
begin
FFilterIndex := AValue;
end;
function TPlugin._AddRef: Integer;
begin
Result := inherited _AddRef;
end;
function TPlugin._Release: Integer;
begin
Result := inherited _Release;
end;
function TPlugin.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
// Оболочка TPlugin
Result := inherited QueryInterface(IID, Obj);
// Сам плагин
if Failed(Result) and Assigned(FPlugin) then
Result := FPlugin.QueryInterface(IID, Obj);
// Уже созданные провайдеры
if Failed(Result) then
begin
if CreateInterface(IID, Obj) then
Result := S_OK;
end;
// Потенциальные провайдеры (создаются)
if Failed(Result) then
begin
if FManager.CreateInterface(Self, IID, Obj) then
Result := S_OK;
end;
end;
procedure TPlugin.RegisterProvider(const AProvider: IProvider);
begin
SetLength(FProviders, Length(FProviders) + 1);
FProviders[High(FProviders)] := AProvider;
end;
function TPlugin.GetCoreVersion: Integer;
begin
Result := FManager.GetVersion;
end;
function TPlugin.GetCount: Integer;
begin
Result := FManager.Count;
end;
function TPlugin.GetPlugin(const AIndex: Integer): PluginAPI.IPlugin;
begin
Supports(FManager[AIndex], PluginAPI.IPlugin, Result);
end;
{ EPluginsLoadError }
constructor EPluginsLoadError.Create(const AText: String;
const AFailedPlugins: TStrings);
begin
inherited Create(AText);
FItems := TStringList.Create;
FItems.Assign(AFailedPlugins);
end;
destructor EPluginsLoadError.Destroy;
begin
FreeAndNil(FItems);
inherited;
end;
// ________________________________________________________________
var
FPluginManager: IPluginManager;
function Plugins: IPluginManager;
begin
Result := FPluginManager;
end;
initialization
FPluginManager := TPluginManager.Create;
finalization
if Assigned(FPluginManager) then
FPluginManager.UnloadAll;
FPluginManager := nil;
end. |
{-----------------------------------------------------------------------------
Unit Name: uhGetVer
Author: n0mad
Version: 1.1.6.75
Creation: 15.10.2002
Purpose: Getting versions of modules
History:
-----------------------------------------------------------------------------}
unit uhGetver;
interface
{$I bugger.inc}
uses
Bugger, StrConsts, Windows, SysUtils;
function GetModuleVersionInfoStr(const ModuleName: string): string;
function GetModuleVersionInfo(const ModuleName: string; var ProductName, ProductVersion,
FileVersion: string): string;
implementation
const
UnitName: string = 'uhGetver';
Translation_Block: string = '\VarFileInfo\Translation';
Lang_Specific_Block: string = '\StringFileInfo\';
Default_Lang: string = '040904E4';
// English 1252 - '040904E4';
// Russian 1251 - '041904E3';
Default_Error_String: string = '<Error>';
function GetModuleVersionInfoStr(const ModuleName: string): string;
var
vProductName, vProductVersion, vFileVersion: string;
begin
Result := GetModuleVersionInfo(ModuleName, vProductName, vProductVersion, vFileVersion);
end;
function GetModuleVersionInfo(const ModuleName: string; var ProductName, ProductVersion,
FileVersion: string): string;
const
ProcName: string = 'GetModuleVersionInfo';
procedure GetVersionStringDef(var sBuffer: string; const sVersionBuffer,
sPath, sDefault: string);
var
lplpBuffer: Pointer;
puLen: Cardinal;
begin
sBuffer := sDefault;
if (length(sVersionBuffer) > 0) and (length(sPath) > 0) then
if VerQueryValue(@sVersionBuffer[1], PChar(sPath), lplpBuffer, puLen) then
if (lplpBuffer <> nil) and (puLen > 0) then
begin
SetLength(sBuffer, puLen);
StrCopy(@sBuffer[1], lplpBuffer);
SetLength(sBuffer, puLen - 1);
end;
end;
var
s, VersionInfo_Buf, ProductName_Buf, ProductVersion_Buf, LegalCopyright_Buf,
FileDescription_Buf, CompanyName_Buf, FileVersion_Buf, Version_Block: string;
VerInfoBlockSize, SubBlockSize: dword;
dwHandle: Cardinal;
wLang, wCharset: word;
Point1, Point2: Pointer;
begin
DEBUGMessEnh(1, UnitName, ProcName, '->');
// --------------------------------------------------------------------------
s := '';
ProductName_Buf := 'N/A';
ProductVersion_Buf := 'N/A';
LegalCopyright_Buf := 'N/A';
FileDescription_Buf := 'N/A';
CompanyName_Buf := 'N/A';
FileVersion_Buf := 'N/A';
VerInfoBlockSize := GetFileVersionInfoSize(PChar(ModuleName), dwHandle);
if VerInfoBlockSize > 0 then
begin
SetLength(VersionInfo_Buf, VerInfoBlockSize + 1);
Point1 := @VersionInfo_Buf[1];
if GetFileVersionInfo(PChar(ModuleName), dwHandle, VerInfoBlockSize, Point1) then
begin
if VerQueryValue(Point1, '\', Point2, SubBlockSize) then
with TVSFixedFileInfo(Point2^) do
begin
FileVersion_Buf := IntToStr(HiWord(dwFileVersionMS))
+ '.' + IntToStr(LoWord(dwFileVersionMS))
+ '.' + IntToStr(HiWord(dwFileVersionLS))
+ '.' + IntToStr(LoWord(dwFileVersionLS));
end;
if VerQueryValue(Point1, PChar(Translation_Block), Point2, SubBlockSize) then
begin
wLang := word(Point2^);
Point2 := Pointer(dword(Point2) + 2);
wCharset := word(Point2^);
Version_Block := Lang_Specific_Block + IntToHex(wLang, 4) + IntToHex(wCharset, 4);
end
else
Version_Block := Lang_Specific_Block + Default_Lang;
GetVersionStringDef(ProductName_Buf, VersionInfo_Buf, Version_Block +
'\\ProductName', Default_Error_String);
GetVersionStringDef(ProductVersion_Buf, VersionInfo_Buf, Version_Block +
'\\ProductVersion', Default_Error_String);
GetVersionStringDef(LegalCopyright_Buf, VersionInfo_Buf, Version_Block +
'\\LegalCopyright', Default_Error_String);
GetVersionStringDef(FileDescription_Buf, VersionInfo_Buf, Version_Block +
'\\FileDescription', Default_Error_String);
GetVersionStringDef(CompanyName_Buf, VersionInfo_Buf, Version_Block +
'\\CompanyName', Default_Error_String);
GetVersionStringDef(FileVersion_Buf, VersionInfo_Buf, Version_Block +
'\\FileVersion', Default_Error_String);
end;
end;
ProductName := ProductName_Buf;
ProductVersion := ProductVersion_Buf;
FileVersion := FileVersion_Buf;
Result :=
'Product Name : "' + ProductName_Buf + '"'
+ c_CRLF
+ 'Product Version : [' + ProductVersion_Buf + ']'
+ c_CRLF
+ 'Legal Copyright : "' + LegalCopyright_Buf + '"'
+ c_CRLF
+ 'File Description : "' + FileDescription_Buf + '"'
+ c_CRLF
+ 'Company Name : "' + CompanyName_Buf + '"'
+ c_CRLF
+ 'File Version : [' + FileVersion_Buf + ']';
DEBUGMessEnh(0, UnitName, ProcName, 'Module Path : "' + ExpandFileName(ModuleName) + '"');
DEBUGMessEnh(0, UnitName, ProcName, 'Product Name : "' + ProductName_Buf + '"');
DEBUGMessEnh(0, UnitName, ProcName, 'Product Version : [' + ProductVersion_Buf + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'Legal Copyright : "' + LegalCopyright_Buf + '"');
DEBUGMessEnh(0, UnitName, ProcName, 'File Description : "' + FileDescription_Buf + '"');
DEBUGMessEnh(0, UnitName, ProcName, 'Company Name : "' + CompanyName_Buf + '"');
DEBUGMessEnh(0, UnitName, ProcName, 'File Version : [' + FileVersion_Buf + ']');
// --------------------------------------------------------------------------
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
end;
{$IFDEF DEBUG_Module_Start_Finish}
initialization
DEBUGMess(0, UnitName + '.Init');
{$ENDIF}
{$IFDEF DEBUG_Module_Start_Finish}
finalization
DEBUGMess(0, UnitName + '.Final');
{$ENDIF}
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{ *************************************************************************** }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
unit SockConst;
interface
resourcestring
sUnknownCommand = 'Unknown command';
sNoHost = 'No host';
sSocketReadError = 'Socket read error';
sCouldNotOpenRegKey = 'Unable to not open registry key: %s';
sInvalidAction = 'Invalid Action %d';
sInterpretDataException = 'Exception in InterpretData: %s';
sInvalidDataPacket = 'Invalid data packet';
sBadVariantType = 'Bad variant type %x';
{$IFDEF MSWINDOWS}
sErrorExec = 'Can''t execute %s %d';
sFailedTimeZoneInfo = 'Failed attempting to retrieve time zone information.';
{$ENDIF}
{$IFDEF LINUX}
sErrorExecTimeout = 'Timeout occurred waiting for %s to execute';
sErrorExecFail = 'Unable to execute %s';
sErrorExecUnexpected = 'Unexpected error occurred executing %s';
{$ENDIF}
sSocketRequestError = 'SocketRequest error in WebAppDbg: ';
implementation
end.
|
unit int_32_2;
interface
implementation
var G1, G2: Int32;
G3: Int8;
procedure Test;
begin
G1 := 0;
G2 := 128;
G3 := G1 - G2;
end;
initialization
Test();
finalization
Assert(G3 = -128);
end. |
{
Ultibo Configure RTL Tool.
Copyright (C) 2022 - SoftOz Pty Ltd.
Arch
====
<All>
Boards
======
<All>
Licence
=======
LGPLv2.1 with static linking exception (See COPYING.modifiedLGPL.txt)
Credits
=======
Information for this unit was obtained from:
References
==========
Configure RTL
=============
The Configure RTL tool is used by the Ultibo core installer to update the configuration
files used by FPC to determine unit locations etc and the environment options file for
Lazarus.
The tool only runs once at the end of the install and is not required again, the
files updated are:
FP.CFG
FPC.CFG
RPI.CFG
RPI2.CFG
RPI3.CFG
RPI4.CFG
QEMUVPB.CFG
environmentoptions.xml
lazarus.cfg
BuildRTL.ini
QEMULauncher.ini
}
unit Main;
{$MODE Delphi}
interface
uses
{$IFDEF WINDOWS}
Windows,
{$ENDIF}
LCLIntf,
LCLType,
LMessages,
SysUtils,
Classes,
IniFiles;
{==============================================================================}
const
LineEnd = Chr(13) + Chr(10); {CR LF}
{==============================================================================}
function GetTempDirectoryString:String;
function AddTrailingSlash(const FilePath:String):String;
function StripTrailingSlash(const FilePath:String):String;
function EditConfiguration(const AName,APath,ASearch,AReplace:String):Boolean;
function CreateOptions(const AName,AInstallPath,ACompilerPath,ALazarusVersion,ALazarusVersionNo:String):Boolean;
function CreateConfig(const AName,AInstallPath,AProfilePath:String):Boolean;
function CreateBuildRTL(const AName,AInstallPath,ACompilerVersion:String):Boolean;
function CreateQEMULauncher(const AName,AInstallPath:String):Boolean;
{==============================================================================}
{==============================================================================}
implementation
{==============================================================================}
function GetTempDirectoryString:String;
var
szTempPath:array[0..(MAX_PATH - 1)] of char;
begin
{}
Result:='';
{$IFDEF WINDOWS}
szTempPath:='';
if GetTempPath(MAX_PATH,szTempPath) > 0 then
begin
Result:=szTempPath;
end;
{$ENDIF}
{$IFDEF LINUX}
//To Do
{$ENDIF}
end;
{==============================================================================}
function AddTrailingSlash(const FilePath:String):String;
var
SlashChar:Char;
WorkBuffer:String;
begin
{}
{$IFDEF WINDOWS}
SlashChar:='\';
{$ENDIF}
{$IFDEF LINUX}
SlashChar:='/';
{$ENDIF}
WorkBuffer:=Trim(FilePath);
Result:=WorkBuffer;
if Length(WorkBuffer) > 0 then
begin
if WorkBuffer[Length(WorkBuffer)] <> SlashChar then
begin
Result:=WorkBuffer + SlashChar;
end;
end;
end;
{==============================================================================}
function StripTrailingSlash(const FilePath:String):String;
var
SlashChar:Char;
WorkBuffer:String;
begin
{}
{$IFDEF WINDOWS}
SlashChar:='\';
{$ENDIF}
{$IFDEF LINUX}
SlashChar:='/';
{$ENDIF}
WorkBuffer:=Trim(FilePath);
Result:=WorkBuffer;
if Length(WorkBuffer) > 0 then
begin
if WorkBuffer[Length(WorkBuffer)] = SlashChar then
begin
Delete(WorkBuffer,Length(WorkBuffer),1);
Result:=WorkBuffer;
end;
end;
end;
{==============================================================================}
function EditConfiguration(const AName,APath,ASearch,AReplace:String):Boolean;
var
PosIdx:Integer;
WorkBuffer:String;
LeftBuffer:String;
RightBuffer:String;
FileStream:TFileStream;
begin
{}
Result:=False;
try
if Length(AName) = 0 then Exit;
if Length(APath) = 0 then Exit;
if Length(ASearch) = 0 then Exit;
{Check File}
if not FileExists(APath + AName) then Exit;
{Open File}
FileStream:=TFileStream.Create(APath + AName,fmOpenReadWrite);
try
{Get Size}
SetLength(WorkBuffer,FileStream.Size);
{Read File}
FileStream.ReadBuffer(PChar(WorkBuffer)^,Length(WorkBuffer));
{Find}
PosIdx:=Pos(ASearch,WorkBuffer);
while PosIdx <> 0 do
begin
LeftBuffer:=Copy(WorkBuffer,1,PosIdx - 1);
RightBuffer:=Copy(WorkBuffer,PosIdx + Length(ASearch),Length(WorkBuffer));
WorkBuffer:=LeftBuffer + AReplace + RightBuffer;
PosIdx:=Pos(ASearch,WorkBuffer);
end;
{Set Size}
FileStream.Size:=Length(WorkBuffer);
{Write File}
FileStream.Position:=0;
FileStream.WriteBuffer(PChar(WorkBuffer)^,Length(WorkBuffer));
Result:=True;
finally
FileStream.Free;
end;
except
{}
end;
end;
{==============================================================================}
function CreateOptions(const AName,AInstallPath,ACompilerPath,ALazarusVersion,ALazarusVersionNo:String):Boolean;
var
WorkBuffer:String;
FileStream:TFileStream;
begin
{}
Result:=False;
try
if Length(AName) = 0 then Exit;
if Length(AInstallPath) = 0 then Exit;
if Length(ACompilerPath) = 0 then Exit;
if Length(ALazarusVersion) = 0 then Exit;
if Length(ALazarusVersionNo) = 0 then Exit;
{Check File}
if FileExists(AInstallPath + AName) then
begin
{Check Backup}
if FileExists(AInstallPath + AName + '.bak') then
begin
{Delete Backup}
DeleteFile(AInstallPath + AName + '.bak')
end;
{Backup File}
if not RenameFile(AInstallPath + AName,AInstallPath + AName + '.bak') then Exit;
{Check File}
if FileExists(AInstallPath + AName) then Exit;
end;
{Create File}
FileStream:=TFileStream.Create(AInstallPath + AName,fmCreate);
try
{Create Content}
WorkBuffer:='';
{$IFDEF WINDOWS}
WorkBuffer:=WorkBuffer + '<?xml version="1.0"?>' + LineEnd;
WorkBuffer:=WorkBuffer + '<CONFIG>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <EnvironmentOptions>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <Version Value="' + ALazarusVersionNo + '" Lazarus="' + ALazarusVersion + '"/>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <LazarusDirectory Value="' + StripTrailingSlash(AInstallPath) + '">' + LineEnd;
WorkBuffer:=WorkBuffer + ' </LazarusDirectory>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <CompilerFilename Value="' + StripTrailingSlash(ACompilerPath) + '\bin\i386-win32\fpc.exe">' + LineEnd;
WorkBuffer:=WorkBuffer + ' </CompilerFilename>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <FPCSourceDirectory Value="$(LazarusDir)fpc\$(FPCVer)\source">' + LineEnd;
WorkBuffer:=WorkBuffer + ' </FPCSourceDirectory>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <MakeFilename Value="' + StripTrailingSlash(ACompilerPath) + '\bin\i386-win32\make.exe">' + LineEnd;
WorkBuffer:=WorkBuffer + ' </MakeFilename>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <TestBuildDirectory Value="' + AddTrailingSlash(GetTempDirectoryString) + '">' + LineEnd;
WorkBuffer:=WorkBuffer + ' </TestBuildDirectory>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <Debugger Class="TGDBMIDebugger"/>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <DebuggerFilename Value="' + StripTrailingSlash(ACompilerPath) + '\bin\i386-win32\gdb.exe">' + LineEnd;
WorkBuffer:=WorkBuffer + ' </DebuggerFilename>' + LineEnd;
WorkBuffer:=WorkBuffer + ' </EnvironmentOptions>' + LineEnd;
WorkBuffer:=WorkBuffer + '</CONFIG>' + LineEnd;
{$ENDIF}
{$IFDEF LINUX}
WorkBuffer:=WorkBuffer + '<?xml version="1.0" encoding="UTF-8"?>' + LineEnd;
WorkBuffer:=WorkBuffer + '<CONFIG>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <EnvironmentOptions>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <Version Value="' + ALazarusVersionNo + '" Lazarus="' + ALazarusVersion + '"/>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <LazarusDirectory Value="' + StripTrailingSlash(AInstallPath) + '">' + LineEnd;
WorkBuffer:=WorkBuffer + ' </LazarusDirectory>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <CompilerFilename Value="' + StripTrailingSlash(ACompilerPath) + '/bin/fpc">' + LineEnd;
WorkBuffer:=WorkBuffer + ' </CompilerFilename>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <FPCSourceDirectory Value="' + StripTrailingSlash(ACompilerPath) + '/source">' + LineEnd;
WorkBuffer:=WorkBuffer + ' </FPCSourceDirectory>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <MakeFilename Value="make">' + LineEnd;
WorkBuffer:=WorkBuffer + ' </MakeFilename>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <TestBuildDirectory Value="~/tmp/">' + LineEnd;
WorkBuffer:=WorkBuffer + ' </TestBuildDirectory>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <Debugger Class="TGDBMIDebugger"/>' + LineEnd;
WorkBuffer:=WorkBuffer + ' <DebuggerFilename Value="gdb">' + LineEnd;
WorkBuffer:=WorkBuffer + ' </DebuggerFilename>' + LineEnd;
WorkBuffer:=WorkBuffer + ' </EnvironmentOptions>' + LineEnd;
WorkBuffer:=WorkBuffer + '</CONFIG>' + LineEnd;
{$ENDIF}
{Set Size}
FileStream.Size:=Length(WorkBuffer);
{Write File}
FileStream.Position:=0;
FileStream.WriteBuffer(PChar(WorkBuffer)^,Length(WorkBuffer));
Result:=True;
finally
FileStream.Free;
end;
except
{}
end;
end;
{==============================================================================}
function CreateConfig(const AName,AInstallPath,AProfilePath:String):Boolean;
var
WorkBuffer:String;
FileStream:TFileStream;
begin
{}
Result:=False;
try
if Length(AName) = 0 then Exit;
if Length(AInstallPath) = 0 then Exit;
{if Length(AProfilePath) = 0 then Exit;} {Optional}
{Check File}
if FileExists(AInstallPath + AName) then Exit;
{Create File}
FileStream:=TFileStream.Create(AInstallPath + AName,fmCreate);
try
{Create Content}
WorkBuffer:='';
WorkBuffer:=WorkBuffer + '#--disabledocking' + LineEnd;
if Length(AProfilePath) <> 0 then
begin
WorkBuffer:=WorkBuffer + '--pcp=' + AProfilePath + LineEnd;
end;
{Set Size}
FileStream.Size:=Length(WorkBuffer);
{Write File}
FileStream.Position:=0;
FileStream.WriteBuffer(PChar(WorkBuffer)^,Length(WorkBuffer));
Result:=True;
finally
FileStream.Free;
end;
except
{}
end;
end;
{==============================================================================}
function CreateBuildRTL(const AName,AInstallPath,ACompilerVersion:String):Boolean;
var
WorkBuffer:String;
IniFile:TIniFile;
FileStream:TFileStream;
begin
{}
Result:=False;
try
if Length(AName) = 0 then Exit;
if Length(AInstallPath) = 0 then Exit;
if Length(ACompilerVersion) = 0 then Exit;
{Check File}
if FileExists(AInstallPath + AName) then
begin
IniFile:=TIniFile.Create(AInstallPath + AName);
try
{Check Compiler Version}
if IniFile.ReadString('BuildRTL','CompilerVersion','') = ACompilerVersion then Exit;
{Update Compiler Version}
IniFile.WriteString('BuildRTL','CompilerVersion',ACompilerVersion);
{$IFDEF WINDOWS}
IniFile.WriteString('BuildRTL','CompilerPath',AInstallPath + 'fpc\' + ACompilerVersion);
IniFile.WriteString('BuildRTL','SourcePath',AInstallPath + 'fpc\' + ACompilerVersion + '\source');
{$ENDIF}
Result:=True;
Exit;
finally
IniFile.Free;
end;
end;
{Create File}
FileStream:=TFileStream.Create(AInstallPath + AName,fmCreate);
try
{Create Content}
WorkBuffer:='';
WorkBuffer:=WorkBuffer + '[BuildRTL]' + LineEnd;
WorkBuffer:=WorkBuffer + 'CompilerVersion=' + ACompilerVersion + LineEnd;
{$IFDEF WINDOWS}
WorkBuffer:=WorkBuffer + 'CompilerPath=' + AInstallPath + 'fpc\' + ACompilerVersion + LineEnd;
WorkBuffer:=WorkBuffer + 'SourcePath=' + AInstallPath + 'fpc\' + ACompilerVersion + '\source' + LineEnd;
{$ENDIF}
{$IFDEF LINUX}
WorkBuffer:=WorkBuffer + 'CompilerPath=' + AInstallPath + 'fpc' + LineEnd;
WorkBuffer:=WorkBuffer + 'SourcePath=' + AInstallPath + 'fpc' + '/source' + LineEnd;
{$ENDIF}
{Set Size}
FileStream.Size:=Length(WorkBuffer);
{Write File}
FileStream.Position:=0;
FileStream.WriteBuffer(PChar(WorkBuffer)^,Length(WorkBuffer));
Result:=True;
finally
FileStream.Free;
end;
except
{}
end;
end;
{==============================================================================}
function CreateQEMULauncher(const AName,AInstallPath:String):Boolean;
var
WorkBuffer:String;
FileStream:TFileStream;
begin
{}
Result:=False;
try
if Length(AName) = 0 then Exit;
if Length(AInstallPath) = 0 then Exit;
{Check File}
if FileExists(AInstallPath + AName) then Exit;
{Create File}
FileStream:=TFileStream.Create(AInstallPath + AName,fmCreate);
try
{Create Content}
WorkBuffer:='';
WorkBuffer:=WorkBuffer + '[QEMULauncher]' + LineEnd;
{Set Size}
FileStream.Size:=Length(WorkBuffer);
{Write File}
FileStream.Position:=0;
FileStream.WriteBuffer(PChar(WorkBuffer)^,Length(WorkBuffer));
Result:=True;
finally
FileStream.Free;
end;
except
{}
end;
end;
{==============================================================================}
{==============================================================================}
end.
|
unit ServData;
{ This Datamodule is the CoClass for the IEmpServer interface. It was
created using the File | New | Remote Data Module menu option }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComServ, ComObj, VCLCom, StdVcl, DataBkr, Provider, BdeProv, Db, DBTables,
Serv_TLB;
type
TEmpServer = class(TDataModule, IEmpServer)
EmpQuery: TQuery;
procedure EmpQueryAfterOpen(DataSet: TDataSet);
procedure EmpServerCreate(Sender: TObject);
procedure EmpServerDestroy(Sender: TObject);
protected
function Get_EmpQuery: IProvider; safecall;
end;
var
EmpServer: TEmpServer;
implementation
{$R *.DFM}
uses ServMain;
{ This method was generated using the "export from datamodule" option on the
local menu of any TQuery, Table, or TProvider component. It returns the
IProvider interface used by the client. }
function TEmpServer.Get_EmpQuery: IProvider;
begin
Result := EmpQuery.Provider;
end;
{ This rest of this code just demonstrates how you might monitor client
activity from the server. None of this is required to develop an
application server. }
procedure TEmpServer.EmpQueryAfterOpen(DataSet: TDataSet);
begin
{ Update the query counter }
MainForm.IncQueryCount;
end;
procedure TEmpServer.EmpServerCreate(Sender: TObject);
begin
{ Update the client counter }
MainForm.UpdateClientCount(1);
end;
procedure TEmpServer.EmpServerDestroy(Sender: TObject);
begin
{ Update the client counter }
MainForm.UpdateClientCount(-1);
end;
initialization
{ This creates the class factory for us. This code is generated automatically }
TComponentFactory.Create(ComServer, TEmpServer, Class_EmpServer,
ciMultiInstance);
end.
|
unit DtmfDecoder;
interface
uses
System.SysUtils,
System.Rtti,
System.Generics.Collections,
System.Math;
type
TDtmfToneTable = class(TDictionary<TPair<Double,Double>, Char>)
public const
kLowFreqs : array[0..3] of Double = (697, 770, 852, 941);
kHighFreqs : array[0..3] of Double = (1209, 1336,1477,1633);
kDtmfCodes : array[0..3] of array[0..3] of Char = (('1','2','3','A'), ('4','5','6','B'), ('7','8','9','C'), ('*','0','#','D'));
public
constructor Create(); overload;
procedure Init();
function Get(LowFreq: Double; HighFreq: Double): Char;
end;
TWindowFunction = (
Blackman,
BlackmanNuttall,
BlackmanHarris,
Hamming,
FlatTop
);
TWindowFunctionTable = record
private
FType : TWindowFunction;
FTable : TArray<Double>;
public
constructor Create(AWindowFunction: TWindowFunction; ANumberOfSamples: Longint);
property _Type: TWindowFunction read FType;
property Table: TArray<Double> read FTable;
end;
TDtmfDecoder<T> = class
type
TOnDtmfCode = reference to procedure(Sender: TObject; DtmfCode: Char; Duration: Integer);
private
FBitsPerSample : Integer;
FSampleRate : Double;
FSamplesPerMilliseconds : Integer;
FWindowFrames : TArray<SmallInt>;
FWindowFunctionTable : TWindowFunctionTable;
FLastDtmfTone : Char;
FToneSamples : Integer;
FTimestamp : Int64;
FOverlapFramesCount : Integer;
FWindowOverlapMilliseconds : Integer;
FWindowDurationMilliseconds : Integer;
FNumberOfSamples : Integer;
FThresold : Double;
FMinToneSamples : Integer;
FDtmfToneTable : TDtmfToneTable;
FOnDtmfCode : TOnDtmfCode;
function goertzelFunction(aFreq: Double; aSampleRate: Double; const aSamples: TArray<Double>; aNumberOfSamples: Longint): Double;
function getExistsFrequency(const aSamples: TArray<Double>; aNumberOfSamples: Longint; aSampleRate: Double; const aFreqs: array of Double; AThresold : Double = -59.0): Double;
// property WindowFunction
procedure SetWindowFunction(AWindowFunction: TWindowFunction);
function GetWindowFunction(): TWindowFunction;
public
constructor Create(ASampleRate: Cardinal); overload;
destructor Destroy; override;
class function DetectDTMF(const AData: TArray<T>; ASampleRate: Cardinal): TArray<Char>;
function Analyze(ASamples: TArray<T>; AOffset: Integer; ANumberOfSamples: Longint): TArray<Char>; overload;
property OnDtmfCode: TOnDtmfCode read FOnDtmfCode write FOnDtmfCode;
property WindowFunction: TWindowFunction read GetWindowFunction write SetWindowFunction;
property Thresold: Double read FThresold write FThresold;
end;
implementation
//
constructor TWindowFunctionTable.Create(AWindowFunction: TWindowFunction; ANumberOfSamples: Longint);
var
i : Integer;
lArcSin : Double;
begin
if ((FType = AWindowFunction) and (Length(FTable) = ANumberOfSamples)) then
exit;
FType := AWindowFunction;
SetLength(FTable, ANumberOfSamples);
case AWindowFunction of
Blackman:
begin
for i := 0 to ANumberOfSamples - 1 do
FTable[i] := (0.42 - 0.5 * cos(2.0 * System.Pi * i / (ANumberOfSamples - 1)) + 0.08 * cos(4.0 * System.Pi * i / (ANumberOfSamples - 1))) {/ (System.Math.Power(2, FBitsPerSample * 8 - 1) - 1)};
end;
BlackmanNuttall:
begin
for i := 0 to ANumberOfSamples - 1 do
begin
lArcSin := 2.0 * System.Pi * i / (ANumberOfSamples - 1);
FTable[i] := 0.3635819 - 0.4891775 * cos(lArcSin) + 0.1365995 * cos(2 * lArcSin) - 0.00106411 * cos(3 * lArcSin){ / (System.Math.Power(2, FBitsPerSample * 8 - 1) - 1)};
end;
end;
BlackmanHarris:
begin
for i := 0 to ANumberOfSamples - 1 do
begin
lArcSin := 2.0 * System.Pi * i / (ANumberOfSamples - 1);
FTable[i] := 0.35875 - 0.48829 * cos(lArcSin) + 0.14128 * cos(2 * lArcSin) - 0.01168 * cos(3 * lArcSin){ / (System.Math.Power(2, FBitsPerSample * 8 - 1) - 1)};
end;
end;
Hamming:
begin
for i := 0 to ANumberOfSamples - 1 do
FTable[i] := 0.53836 - 0.46164 * cos(2.0 * System.Pi * i / (ANumberOfSamples - 1)) {/ (System.Math.Power(2, FBitsPerSample * 8 - 1) - 1)};
end;
FlatTop:
begin
for i := 0 to ANumberOfSamples - 1 do
begin
lArcSin := 2.0 * System.Pi * i / (ANumberOfSamples - 1);
FTable[i] := 1 - 1.93 * cos(lArcSin) + 1.29 * cos(2 * lArcSin) - 0.388 * cos(3 * lArcSin) * 0.028 * cos(4 * lArcSin){ / (System.Math.Power(2, FBitsPerSample * 8 - 1) - 1)};
end;
end;
end;
end;
//
constructor TDtmfToneTable.Create();
begin
inherited Create;
Init();
end;
function TDtmfToneTable.Get(LowFreq: Double; HighFreq: Double): Char;
begin
if Self.ContainsKey(TPair<Double, Double>.Create(LowFreq, HighFreq)) then
result := Self.Items[TPair<Double, Double>.Create(LowFreq, HighFreq)]
else result := #0;
end;
procedure TDtmfToneTable.Init();
var
I, K : integer;
begin
inherited Create;
Self.Clear;
for I := 0 to Length(kLowFreqs) - 1 do
begin
for K := 0 to Length(kHighFreqs) - 1 do
begin
Self.Add(TPair<Double, Double>.Create(kLowFreqs[i], kHighFreqs[k]), kDtmfCodes[i][k]);
end;
end;
end;
//
constructor TDtmfDecoder<T>.Create(ASampleRate: Cardinal);
begin
inherited Create;
FThresold := 55.0;
FTimestamp := 0;
FToneSamples := 0;
FBitsPerSample := SizeOf(T);
FSampleRate := aSampleRate;
FSamplesPerMilliseconds := Round(Self.FSampleRate / 1000);
FWindowDurationMilliseconds := 50;
FWindowOverlapMilliseconds := 10;
if FWindowOverlapMilliseconds > FWindowDurationMilliseconds then
FWindowOverlapMilliseconds := FWindowDurationMilliseconds;
FNumberOfSamples := (FSamplesPerMilliseconds * FWindowDurationMilliseconds);
FOverlapFramesCount := FSamplesPerMilliseconds * FWindowOverlapMilliseconds;
// minimal tone time
FMinToneSamples := FSamplesPerMilliseconds * 50;
SetWindowFunction(TWindowFunction.Blackman);
FDtmfToneTable := TDtmfToneTable.Create;
end;
destructor TDtmfDecoder<T>.Destroy;
begin
FreeAndNil(FDtmfToneTable);
inherited Destroy;
end;
procedure TDtmfDecoder<T>.SetWindowFunction(AWindowFunction: TWindowFunction);
begin
Self.FWindowFunctionTable := TWindowFunctionTable.Create(AWindowFunction, Self.FNumberOfSamples);
end;
function TDtmfDecoder<T>.GetWindowFunction(): TWindowFunction;
begin
result := Self.FWindowFunctionTable._Type;
end;
function TDtmfDecoder<T>.Analyze(ASamples: TArray<T>; AOffset: Integer; ANumberOfSamples: Longint): TArray<Char>;
var
i : Integer;
lOffset : Integer;
lWindowFramesOffset : Integer;
lNumberOfSamples : Integer;
lLen : Integer;
LResultedFrames : TArray<Double>;
lLowFreq : Double;
lHighFreq : Double;
begin
SetLength(result, 0);
lOffset := AOffset;
lNumberOfSamples := ANumberOfSamples;
while lNumberOfSamples > 0 do
begin
lLen := Min(ANumberOfSamples, FNumberOfSamples - Length(FWindowFrames));
lWindowFramesOffset := Length(FWindowFrames);
SetLength(FWindowFrames, lWindowFramesOffset + lLen);
Move(ASamples[lOffset], FWindowFrames[lWindowFramesOffset], lLen * FBitsPerSample);
lOffset := lOffset + lLen;
lNumberOfSamples := lNumberOfSamples - lLen;
if Length(FWindowFrames) >= FNumberOfSamples then
begin
SetLength(LResultedFrames, FNumberOfSamples);
for I := 0 to FNumberOfSamples - 1 do
lResultedFrames[i] := FWindowFunctionTable.Table[i] * FWindowFrames[i];
lLowFreq := getExistsFrequency(lResultedFrames, FNumberOfSamples, FSampleRate, TDtmfToneTable.kLowFreqs, FThresold);
lHighFreq := getExistsFrequency(lResultedFrames, FNumberOfSamples, FSampleRate, TDtmfToneTable.kHighFreqs, FThresold);
FToneSamples := FToneSamples + FOverlapFramesCount;
if (FDtmfToneTable.Get(lLowFreq, lHighFreq) <> FLastDtmfTone) then
begin
if (FLastDtmfTone <> #0) then
begin
if FToneSamples >= Self.FMinToneSamples then
begin
if assigned(Self.FOnDtmfCode) then
Self.FOnDtmfCode(Self, FLastDtmfTone, Round(FToneSamples / FSamplesPerMilliseconds));
SetLength(result, Length(result)+1);
result[High(result)] := FLastDtmfTone;
end;
end;
FToneSamples := 0;
FLastDtmfTone := FDtmfToneTable.Get(lLowFreq, lHighFreq);
end;
Delete(FWindowFrames, 0, FOverlapFramesCount);
end;
FTimestamp := FTimestamp + lLen;
end;
end;
function TDtmfDecoder<T>.goertzelFunction(aFreq: Double; aSampleRate: Double; const aSamples: TArray<Double>; aNumberOfSamples: Longint): Double;
var
i : integer;
lScalingFactor: Double;
k : Double;
lOmega : Double;
lCosine : Double;
lSine : Double;
lQ0 : Double;
lQ1 : Double;
lQ2 : Double;
lCoeff : Double;
lReal : Double;
lImag : Double;
begin
lScalingFactor := Length(aSamples) / 2;
k := 0.5 + ((Length(aSamples) * aFreq) / aSampleRate);
lOmega := (2.0 * System.Pi * k) / Length(aSamples);
lSine := sin(lOmega);
lCosine := cos(lOmega);
lCoeff := 2.0 * lCosine;
lQ0 := 0;
lQ1 := 0;
lQ2 := 0;
for i := 0 to Length(aSamples) - 1 do
begin
lQ0:= lCoeff * lQ1 - lQ2 + aSamples[i];
lQ2:= lQ1;
lQ1:= lQ0;
end;
lReal := (lQ1 - lQ2 * lCosine) / lScalingFactor;
lImag := (lQ2 * lSine) / lScalingFactor;
result := System.sqrt(lReal*lReal + lImag*lImag);
end;
function TDtmfDecoder<T>.getExistsFrequency(const aSamples: TArray<Double>; aNumberOfSamples: Longint; aSampleRate: Double; const aFreqs: array of Double; AThresold : Double = -59.0): Double;
var
lMax : Double;
lFreq : Double;
lMag : Double;
begin
lMax := AThresold;
result := 0;
try
for lFreq in aFreqs do
begin
lMag := 20 * log10(goertzelFunction(lFreq, aSampleRate, aSamples, aNumberOfSamples));
if lMag > lMax then
begin
lMax := lMag;
result := lFreq;
end;
end;
except end;
end;
class function TDtmfDecoder<T>.DetectDTMF(const AData: TArray<T>; ASampleRate: Cardinal): TArray<Char>;
var
lDtmfDecoder : TDtmfDecoder<T>;
lDtmfTones : TArray<Char>;
begin
lDtmfDecoder := TDtmfDecoder<T>.Create(ASampleRate);
try
result := lDtmfDecoder.Analyze(AData, 0, Length(AData));
finally
FreeAndNil(lDtmfDecoder);
end;
end;
end.
|
unit NewUser;
{$mode objfpc}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, ExtDlgs;
type
TRegFunc = procedure (Nick, FirstName, LastName, Email, Password, ImgPath :string);
type
{ TNewUserForm }
TNewUserForm = class(TForm)
Bevel1 :TBevel;
Bevel2 :TBevel;
OpenDialog: TOpenPictureDialog;
SelAvaBtn :TButton;
CancelBtn :TButton;
EditEmailPWD: TLabeledEdit;
Image :TImage;
SaveBtn :TButton;
CanfcelBtn :TButton;
CheckBox :TCheckBox;
EditEmail :TLabeledEdit;
EditNickName :TLabeledEdit;
procedure SelAvaBtnClick(Sender: TObject);
procedure CancelBtnClick(Sender: TObject);
procedure CheckBoxChange (Sender :TObject);
procedure SaveBtnClick (Sender :TObject);
private
{ private declarations }
procedure StoreValues;
public
{ public declarations }
NickName, Email, Password, PathToAvatar: String;
procedure SetCaptionsWithUsers();
procedure SetCaptionsWithContacts();
end;
var
NewUserForm :TNewUserForm;
implementation
{$R *.lfm}
{ TNewUserForm }
procedure TNewUserForm.CheckBoxChange (Sender :TObject);
begin
if not CheckBox.Checked then
EditEmailPWD.PasswordChar := '*'
else
EditEmailPWD.PasswordChar := #0;
end;
procedure TNewUserForm.CancelBtnClick(Sender: TObject);
begin
CancelBtn.ModalResult:= mrCancel;
end;
procedure TNewUserForm.SelAvaBtnClick(Sender: TObject);
begin
if OpenDialog.Execute then
begin
PathToAvatar:= OpenDialog.FileName;
Image.Picture.LoadFromFile(PathToAvatar);
end;
end;
procedure TNewUserForm.SaveBtnClick (Sender :TObject);
begin
StoreValues;
SaveBtn.ModalResult:= mrOk;
end;
procedure TNewUserForm.StoreValues;
begin
NickName:= trim(EditNickName.Text);
Email:= trim(EditEmail.Text);
Password:= trim(EditEmailPWD.Text);
end;
procedure TNewUserForm.SetCaptionsWithUsers;
begin
Caption:= 'Создание нового пользователя';
EditNickName.EditLabel.Caption:= 'Ваше имя или псевдоним: ';
EditEmail.EditLabel.Caption:= 'Ваш адрес EMail:';
EditEmailPWD.Visible:= True;
CheckBox.Visible:= True;
end;
procedure TNewUserForm.SetCaptionsWithContacts;
begin
Caption:= 'Добавление нового собеседника';
EditNickName.EditLabel.Caption:= 'Псевдоним: ';
EditEmail.EditLabel.Caption:= 'EMail:';
EditEmailPWD.Visible:= False;
CheckBox.Visible:= False;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ Streamed Connection classes }
{ }
{ Copyright (c) 1997,99 Inprise Corporation }
{ }
{*******************************************************}
unit SConnect;
{$R-}
interface
uses
VarUtils, Variants, Windows, Messages, Classes, SysUtils, MConnect,
ScktComp, WinSock, WinInet, ComObj;
type
{$HPPEMIT '#pragma link "wininet.lib"'}
{ IDataBlock }
IDataBlock = interface(IUnknown)
['{CA6564C2-4683-11D1-88D4-00A0248E5091}']
function GetBytesReserved: Integer; stdcall;
function GetMemory: Pointer; stdcall;
function GetSize: Integer; stdcall;
procedure SetSize(Value: Integer); stdcall;
function GetStream: TStream; stdcall;
function GetSignature: Integer; stdcall;
procedure SetSignature(Value: Integer); stdcall;
procedure Clear; stdcall;
function Write(const Buffer; Count: Integer): Integer; stdcall;
function Read(var Buffer; Count: Integer): Integer; stdcall;
procedure IgnoreStream; stdcall;
function InitData(Data: Pointer; DataLen: Integer; CheckLen: Boolean): Integer; stdcall;
property BytesReserved: Integer read GetBytesReserved;
property Memory: Pointer read GetMemory;
property Signature: Integer read GetSignature write SetSignature;
property Size: Integer read GetSize write SetSize;
property Stream: TStream read GetStream;
end;
{ ISendDataBlock }
ISendDataBlock = interface
['{87AD1043-470E-11D1-88D5-00A0248E5091}']
function Send(const Data: IDataBlock; WaitForResult: Boolean): IDataBlock; stdcall;
end;
{ ITransport }
ITransport = interface(IUnknown)
['{CA6564C1-4683-11D1-88D4-00A0248E5091}']
function GetWaitEvent: THandle; stdcall;
function GetConnected: Boolean; stdcall;
procedure SetConnected(Value: Boolean); stdcall;
function Receive(WaitForInput: Boolean; Context: Integer): IDataBlock; stdcall;
function Send(const Data: IDataBlock): Integer; stdcall;
property Connected: Boolean read GetConnected write SetConnected;
end;
{ IDataIntercept }
IDataIntercept = interface
['{B249776B-E429-11D1-AAA4-00C04FA35CFA}']
procedure DataIn(const Data: IDataBlock); stdcall;
procedure DataOut(const Data: IDataBlock); stdcall;
end;
{ TDataBlock }
TDataBlock = class(TInterfacedObject, IDataBlock)
private
FStream: TMemoryStream;
FReadPos: Integer;
FWritePos: Integer;
FIgnoreStream: Boolean;
protected
{ IDataBlock }
function GetBytesReserved: Integer; stdcall;
function GetMemory: Pointer; stdcall;
function GetSize: Integer; stdcall;
procedure SetSize(Value: Integer); stdcall;
function GetStream: TStream; stdcall;
function GetSignature: Integer; stdcall;
procedure SetSignature(Value: Integer); stdcall;
procedure Clear; stdcall;
function Write(const Buffer; Count: Integer): Integer; stdcall;
function Read(var Buffer; Count: Integer): Integer; stdcall;
procedure IgnoreStream; stdcall;
function InitData(Data: Pointer; DataLen: Integer; CheckLen: Boolean): Integer; stdcall;
property BytesReserved: Integer read GetBytesReserved;
property Memory: Pointer read GetMemory;
property Signature: Integer read GetSignature write SetSignature;
property Size: Integer read GetSize write SetSize;
property Stream: TStream read GetStream;
public
constructor Create;
destructor Destroy; override;
end;
{ TDataBlockInterpreter }
const
{ Action Signatures }
CallSig = $DA00; // Call signature
ResultSig = $DB00; // Result signature
asError = $01; // Specify an exception was raised
asInvoke = $02; // Specify a call to Invoke
asGetID = $03; // Specify a call to GetIdsOfNames
asCreateObject = $04; // Specify a com object to create
asFreeObject = $05; // Specify a dispatch to free
asGetServers = $10; // Get classname list
asGetGUID = $11; // Get GUID for ClassName
asGetAppServers = $12; // Get AppServer classname list
asSoapCommand = $14; // Soap command
asMask = $FF; // Mask for action
type
PIntArray = ^TIntArray;
TIntArray = array[0..0] of Integer;
PVariantArray = ^TVariantArray;
TVariantArray = array[0..0] of OleVariant;
TVarFlag = (vfByRef, vfVariant);
TVarFlags = set of TVarFlag;
EInterpreterError = class(Exception);
TDataDispatch = class;
TCustomDataBlockInterpreter = class
protected
procedure AddDispatch(Value: TDataDispatch); virtual; abstract;
procedure RemoveDispatch(Value: TDataDispatch); virtual; abstract;
{ Sending Calls }
procedure CallFreeObject(DispatchIndex: Integer); virtual; abstract;
function CallGetIDsOfNames(DispatchIndex: Integer; const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; virtual; stdcall; abstract;
function CallInvoke(DispatchIndex, DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; virtual; stdcall; abstract;
function CallGetServerList: OleVariant; virtual; abstract;
{ Receiving Calls }
function InternalCreateObject(const ClassID: TGUID): OleVariant; virtual; abstract;
function CreateObject(const Name: string): OleVariant; virtual; abstract;
function StoreObject(const Value: OleVariant): Integer; virtual; abstract;
function LockObject(ID: Integer): IDispatch; virtual; abstract;
procedure UnlockObject(ID: Integer; const Disp: IDispatch); virtual; abstract;
procedure ReleaseObject(ID: Integer); virtual; abstract;
function CanCreateObject(const ClassID: TGUID): Boolean; virtual; abstract;
function CallCreateObject(Name: string): OleVariant; virtual; abstract;
public
procedure InterpretData(const Data: IDataBlock); virtual; abstract;
end;
{ TBinary... }
TDataBlockInterpreter = class(TCustomDataBlockInterpreter)
private
FDispatchList: TList;
FDispList: OleVariant;
FSendDataBlock: ISendDataBlock;
FCheckRegValue: string;
function GetVariantPointer(const Value: OleVariant): Pointer;
procedure CopyDataByRef(const Source: TVarData; var Dest: TVarData);
function ReadArray(VType: Integer; const Data: IDataBlock): OleVariant;
procedure WriteArray(const Value: OleVariant; const Data: IDataBlock);
function ReadVariant(out Flags: TVarFlags; const Data: IDataBlock): OleVariant;
procedure WriteVariant(const Value: OleVariant; const Data: IDataBlock);
procedure DoException(const Data: IDataBlock);
protected
procedure AddDispatch(Value: TDataDispatch); override;
procedure RemoveDispatch(Value: TDataDispatch); override;
function InternalCreateObject(const ClassID: TGUID): OleVariant; override;
function CreateObject(const Name: string): OleVariant; override;
function StoreObject(const Value: OleVariant): Integer; override;
function LockObject(ID: Integer): IDispatch; override;
procedure UnlockObject(ID: Integer; const Disp: IDispatch); override;
procedure ReleaseObject(ID: Integer); override;
function CanCreateObject(const ClassID: TGUID): Boolean; override;
{Sending Calls}
procedure CallFreeObject(DispatchIndex: Integer); override;
function CallGetIDsOfNames(DispatchIndex: Integer; const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; override;
function CallInvoke(DispatchIndex, DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; override;
function CallGetServerList: OleVariant; override;
{Receiving Calls}
procedure DoCreateObject(const Data: IDataBlock);
procedure DoFreeObject(const Data: IDataBlock);
procedure DoGetIDsOfNames(const Data: IDataBlock);
procedure DoInvoke(const Data: IDataBlock);
function DoCustomAction(Action: Integer; const Data: IDataBlock): Boolean; virtual;
procedure DoGetAppServerList(const Data: IDataBlock);
procedure DoGetServerList(const Data: IDataBlock);
public
constructor Create(SendDataBlock: ISendDataBlock; CheckRegValue: string);
destructor Destroy; override;
function CallCreateObject(Name: string): OleVariant; override;
procedure InterpretData(const Data: IDataBlock); override;
end;
{ TDataDispatch }
TDataDispatch = class(TInterfacedObject, IDispatch)
private
FDispatchIndex: Integer;
FInterpreter: TCustomDataBlockInterpreter;
protected
property DispatchIndex: Integer read FDispatchIndex;
{ IDispatch }
function GetTypeInfoCount(out Count: Integer): HResult; stdcall;
function GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall;
function GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall;
function Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall;
public
constructor Create(Interpreter: TCustomDataBlockInterpreter; DispatchIndex: Integer);
destructor Destroy; override;
end;
{ TTransportThread }
const
THREAD_SENDSTREAM = WM_USER + 1;
THREAD_RECEIVEDSTREAM = THREAD_SENDSTREAM + 1;
THREAD_EXCEPTION = THREAD_RECEIVEDSTREAM + 1;
THREAD_SENDNOTIFY = THREAD_EXCEPTION + 1;
THREAD_REPLACETRANSPORT = THREAD_SENDNOTIFY + 1;
type
TTransportThread = class(TThread)
private
FParentHandle: THandle;
FSemaphore: THandle;
FTransport: ITransport;
public
constructor Create(AHandle: THandle; Transport: ITransport); virtual;
destructor Destroy; override;
property Semaphore: THandle read FSemaphore;
procedure Execute; override;
end;
{ TStreamedConnection }
TStreamedConnection = class(TDispatchConnection, ISendDataBlock)
private
FRefCount: Integer;
FHandle: THandle;
FTransport: TTransportThread;
FTransIntf: ITransport;
FInterpreter: TCustomDataBlockInterpreter;
FSupportCallbacks: Boolean;
FInterceptGUID: TGUID;
FInterceptName: string;
function GetHandle: THandle;
procedure TransportTerminated(Sender: TObject);
procedure SetSupportCallbacks(Value: Boolean);
procedure SetInterceptName(const Value: string);
function GetInterceptGUID: string;
procedure SetInterceptGUID(const Value: string);
protected
{ IUnknown }
function QueryInterface(const IID: TGUID; out Obj): HResult; reintroduce; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
{ ISendDataBlock }
function Send(const Data: IDataBlock; WaitForResult: Boolean): IDataBlock; stdcall;
procedure InternalOpen; virtual;
procedure InternalClose; virtual;
procedure ThreadReceivedStream(var Message: TMessage); message THREAD_RECEIVEDSTREAM;
procedure ThreadException(var Message: TMessage); message THREAD_EXCEPTION;
procedure WndProc(var Message: TMessage);
function CreateTransport: ITransport; virtual;
procedure DoConnect; override;
procedure DoDisconnect; override;
procedure DoError(E: Exception); virtual;
function GetInterpreter: TCustomDataBlockInterpreter; virtual;
property Interpreter: TCustomDataBlockInterpreter read GetInterpreter;
property Handle: THandle read GetHandle;
property SupportCallbacks: Boolean read FSupportCallbacks write SetSupportCallbacks default True;
property InterceptGUID: string read GetInterceptGUID write SetInterceptGUID;
property InterceptName: string read FInterceptName write SetInterceptName;
public
function GetInterceptorList: OleVariant; virtual;
function GetServerList: OleVariant; override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
{ TSocketTransport }
ESocketConnectionError = class(Exception);
TSocketTransport = class(TInterfacedObject, ITransport)
private
FEvent: THandle;
FAddress: string;
FHost: string;
FPort: Integer;
FClientSocket: TClientSocket;
FSocket: TCustomWinSocket;
FInterceptGUID: string;
FInterceptor: IDataIntercept;
FCreateAttempted: Boolean;
function CheckInterceptor: Boolean;
procedure InterceptIncoming(const Data: IDataBlock);
procedure InterceptOutgoing(const Data: IDataBlock);
protected
{ ITransport }
function GetWaitEvent: THandle; stdcall;
function GetConnected: Boolean; stdcall;
procedure SetConnected(Value: Boolean); stdcall;
function Receive(WaitForInput: Boolean; Context: Integer): IDataBlock; stdcall;
function Send(const Data: IDataBlock): Integer; stdcall;
public
constructor Create;
destructor Destroy; override;
property Host: string read FHost write FHost;
property Address: string read FAddress write FAddress;
property Port: Integer read FPort write FPort;
property Socket: TCustomWinSocket read FSocket write FSocket;
property InterceptGUID: string read FInterceptGUID write FInterceptGUID;
end;
{ TSocketConnection }
TSocketConnection = class(TStreamedConnection)
private
FAddress: string;
FHost: string;
FPort: Integer;
procedure SetAddress(Value: string);
procedure SetHost(Value: string);
function IsHostStored: Boolean;
function IsAddressStored: Boolean;
protected
function CreateTransport: ITransport; override;
procedure DoConnect; override;
public
constructor Create(AOwner: TComponent); override;
published
property Address: string read FAddress write SetAddress stored IsAddressStored;
property Host: string read FHost write SetHost stored IsHostStored;
property InterceptGUID;
property InterceptName;
property Port: Integer read FPort write FPort default 211;
property SupportCallbacks;
property ObjectBroker;
end;
{ TWebConnection }
TWebConnection = class(TStreamedConnection, ITransport)
private
FAgent: string;
FUserName: string;
FPassword: string;
FURL: string;
FURLHost: string;
FURLSite: string;
FURLPort: Integer;
FURLScheme: Integer;
FProxy: string;
FProxyByPass: string;
FInetRoot: HINTERNET;
FInetConnect: HINTERNET;
FInterpreter: TCustomDataBlockInterpreter;
procedure Check(Error: Boolean);
function IsURLStored: Boolean;
procedure SetURL(const Value: string);
protected
{ ITransport }
function GetInterpreter: TCustomDataBlockInterpreter; override;
function GetWaitEvent: THandle; stdcall;
function Transport_GetConnected: Boolean; stdcall;
function ITransport.GetConnected = Transport_GetConnected;
procedure Transport_SetConnected(Value: Boolean); stdcall;
procedure ITransport.SetConnected = Transport_SetConnected;
function Receive(WaitForInput: Boolean; Context: Integer): IDataBlock; stdcall;
function Send(const Data: IDataBlock): Integer; stdcall;
protected
function CreateTransport: ITransport; override;
procedure DoConnect; override;
property SupportCallbacks default False;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Agent: string read FAgent write FAgent;
property UserName: string read FUserName write FUserName;
property Password: string read FPassword write FPassword;
property URL: string read FURL write SetURL stored IsURLStored;
property Proxy: string read FProxy write FProxy;
property ProxyByPass: string read FProxyByPass write FProxyByPass;
property ObjectBroker;
end;
{ TPacketInterceptFactory }
TPacketInterceptFactory = class(TComObjectFactory)
public
procedure UpdateRegistry(Register: Boolean); override;
end;
{$EXTERNALSYM TPacketInterceptFactory}
{ Utility functions }
function LoadWinSock2: Boolean;
procedure GetPacketInterceptorList(List: TStringList);
var
WSACreateEvent: function: THandle stdcall;
WSAResetEvent: function(hEvent: THandle): Boolean stdcall;
WSACloseEvent: function(hEvent: THandle): Boolean stdcall;
WSAEventSelect: function(s: TSocket; hEventObject: THandle; lNetworkEvents: Integer): Integer stdcall;
implementation
uses
ActiveX, MidConst, RTLConsts;
var
hWinSock2: THandle;
{ Utility functions }
procedure CheckSignature(Sig: Integer);
begin
if (Sig and $FF00 <> CallSig) and
(Sig and $FF00 <> ResultSig) then
raise Exception.CreateRes(@SInvalidDataPacket);
end;
function LoadWinSock2: Boolean;
const
DLLName = 'ws2_32.dll';
begin
Result := hWinSock2 > 0;
if Result then Exit;
hWinSock2 := LoadLibrary(PChar(DLLName));
Result := hWinSock2 > 0;
if Result then
begin
WSACreateEvent := GetProcAddress(hWinSock2, 'WSACreateEvent');
WSAResetEvent := GetProcAddress(hWinSock2, 'WSAResetEvent');
WSACloseEvent := GetProcAddress(hWinSock2, 'WSACloseEvent');
WSAEventSelect := GetProcAddress(hWinSock2, 'WSAEventSelect');
end;
end;
procedure GetPacketInterceptorList(List: TStringList);
var
EnumGUID: IEnumGUID;
Fetched: Cardinal;
Guid: TGUID;
Rslt: HResult;
CatInfo: ICatInformation;
I: Integer;
ClassIDKey: HKey;
S: string;
Buffer: array[0..255] of Char;
begin
List.Clear;
Rslt := CoCreateInstance(CLSID_StdComponentCategoryMgr, nil,
CLSCTX_INPROC_SERVER, ICatInformation, CatInfo);
if Succeeded(Rslt) then
begin
OleCheck(CatInfo.EnumClassesOfCategories(1, @CATID_MIDASInterceptor, 0, nil, EnumGUID));
while EnumGUID.Next(1, Guid, Fetched) = S_OK do
List.Add(ClassIDToProgID(Guid));
end else
begin
if RegOpenKey(HKEY_CLASSES_ROOT, 'CLSID', ClassIDKey) <> 0 then
try
I := 0;
while RegEnumKey(ClassIDKey, I, Buffer, SizeOf(Buffer)) = 0 do
begin
S := Format(SCatImplKey,[Buffer, GUIDToString(CATID_MIDASInterceptor)]);
List.Add(ClassIDToProgID(StringToGUID(Buffer)));
Inc(I);
end;
finally
RegCloseKey(ClassIDKey);
end;
end;
end;
procedure FreeWinSock2;
begin
if hWinSock2 > 0 then
begin
WSACreateEvent := nil;
WSAResetEvent := nil;
WSACloseEvent := nil;
WSAEventSelect := nil;
FreeLibrary(hWinSock2);
end;
hWinSock2 := 0;
end;
procedure GetDataBrokerList(List: TStringList; const RegCheck: string);
function OpenRegKey(Key: HKey; const SubKey: string): HKey;
begin
if Windows.RegOpenKey(Key, PChar(SubKey), Result) <> 0 then Result := 0;
end;
function EnumRegKey(Key: HKey; Index: Integer; var Value: string): Boolean;
var
Buffer: array[0..255] of Char;
begin
Result := False;
if Windows.RegEnumKey(Key, Index, Buffer, SizeOf(Buffer)) = 0 then
begin
Value := Buffer;
Result := True;
end;
end;
function QueryRegKey(Key: HKey; const SubKey: string;
var Value: string): Boolean;
var
BufSize: Longint;
Buffer: array[0..255] of Char;
begin
Result := False;
BufSize := SizeOf(Buffer);
if Windows.RegQueryValue(Key, PChar(SubKey), Buffer, BufSize) = 0 then
begin
Value := Buffer;
Result := True;
end;
end;
procedure CloseRegKey(Key: HKey);
begin
RegCloseKey(Key);
end;
var
I: Integer;
ClassIDKey: HKey;
ClassID, S: string;
begin
List.Clear;
ClassIDKey := OpenRegKey(HKEY_CLASSES_ROOT, 'CLSID');
if ClassIDKey <> 0 then
try
I := 0;
while EnumRegKey(ClassIDKey, I, ClassID) do
begin
if RegCheck <> '' then
begin
QueryRegKey(ClassIDKey, ClassID + '\' + RegCheck, S);
if S <> SFlagOn then continue;
end;
if not QueryRegKey(ClassIDKey, ClassID + '\Control', S) and
QueryRegKey(ClassIDKey, ClassID + '\ProgID', S) and
QueryRegKey(ClassIDKey, ClassID + '\TypeLib', S) and
QueryRegKey(ClassIDKey, ClassID + '\Version', S) and
QueryRegKey(ClassIDKey, ClassID + '\Borland DataBroker', S) then
List.Add(ClassIDToProgID(StringToGUID(ClassID)));
Inc(I);
end;
finally
CloseRegKey(ClassIDKey);
end;
end;
{ TDataBlock }
constructor TDataBlock.Create;
begin
inherited Create;
FIgnoreStream := False;
FStream := TMemoryStream.Create;
Clear;
end;
destructor TDataBlock.Destroy;
begin
if not FIgnoreStream then
FStream.Free;
inherited Destroy;
end;
{ TDataBlock.IDataBlock }
function TDataBlock.GetBytesReserved: Integer;
begin
Result := SizeOf(Integer) * 2;
end;
function TDataBlock.GetMemory: Pointer;
var
DataSize: Integer;
begin
FStream.Position := 4;
DataSize := FStream.Size - BytesReserved;
FStream.Write(DataSize, SizeOf(DataSize));
Result := FStream.Memory;
end;
function TDataBlock.GetSize: Integer;
begin
Result := FStream.Size - BytesReserved;
end;
procedure TDataBlock.SetSize(Value: Integer);
begin
FStream.Size := Value + BytesReserved;
end;
function TDataBlock.GetStream: TStream;
var
DataSize: Integer;
begin
FStream.Position := 4;
DataSize := FStream.Size - BytesReserved;
FStream.Write(DataSize, SizeOf(DataSize));
FStream.Position := 0;
Result := FStream;
end;
function TDataBlock.GetSignature: Integer;
begin
FStream.Position := 0;
FStream.Read(Result, SizeOf(Result));
end;
procedure TDataBlock.SetSignature(Value: Integer);
begin
FStream.Position := 0;
FStream.Write(Value, SizeOf(Value));
end;
procedure TDataBlock.Clear;
begin
FStream.Size := BytesReserved;
FReadPos := BytesReserved;
FWritePos := BytesReserved;
end;
function TDataBlock.Write(const Buffer; Count: Integer): Integer;
begin
FStream.Position := FWritePos;
Result := FStream.Write(Buffer, Count);
FWritePos := FStream.Position;
end;
function TDataBlock.Read(var Buffer; Count: Integer): Integer;
begin
FStream.Position := FReadPos;
Result := FStream.Read(Buffer, Count);
FReadPos := FStream.Position;
end;
procedure TDataBlock.IgnoreStream;
begin
FIgnoreStream := True;
end;
function TDataBlock.InitData(Data: Pointer; DataLen: Integer; CheckLen: Boolean): Integer; stdcall;
var
Sig: Integer;
P: Pointer;
begin
P := Data;
if DataLen < MINDATAPACKETSIZE then
raise Exception.CreateRes(@SInvalidDataPacket);
Sig := Integer(P^);
P := Pointer(Integer(Data) + SizeOf(Sig));
CheckSignature(Sig);
Signature := Sig;
Result := Integer(P^);
P := Pointer(Integer(P) + SizeOf(Result));
if CheckLen then
begin
if (Result <> DataLen - MINDATAPACKETSIZE) then
raise Exception.CreateRes(@SInvalidDataPacket);
Size := Result;
if Result > 0 then
Write(P^, Result);
end else
begin
Size := DataLen - MINDATAPACKETSIZE;
if Size > 0 then
Write(P^, Size);
end;
end;
{ TDataBlockInterpreter }
const
EasyArrayTypes = [varSmallInt, varInteger, varSingle, varDouble, varCurrency,
varDate, varBoolean, varShortInt, varByte, varWord, varLongWord];
VariantSize: array[0..varLongWord] of Word = (0, 0, SizeOf(SmallInt), SizeOf(Integer),
SizeOf(Single), SizeOf(Double), SizeOf(Currency), SizeOf(TDateTime), 0, 0,
SizeOf(Integer), SizeOf(WordBool), 0, 0, 0, 0, SizeOf(ShortInt), SizeOf(Byte),
SizeOf(Word), SizeOf(LongWord));
constructor TDataBlockInterpreter.Create(SendDataBlock: ISendDataBlock; CheckRegValue: string);
begin
inherited Create;
FSendDataBlock := SendDataBlock;
FDispatchList := TList.Create;
FCheckRegValue := CheckRegValue;
end;
destructor TDataBlockInterpreter.Destroy;
var
i: Integer;
begin
for i := FDispatchList.Count - 1 downto 0 do
TDataDispatch(FDispatchList[i]).FInterpreter := nil;
FDispatchList.Free;
FSendDataBlock := nil;
inherited Destroy;
end;
procedure TDataBlockInterpreter.AddDispatch(Value: TDataDispatch);
begin
if FDispatchList.IndexOf(Value) = -1 then
FDispatchList.Add(Value);
end;
procedure TDataBlockInterpreter.RemoveDispatch(Value: TDataDispatch);
begin
FDispatchList.Remove(Value);
end;
{ Variant conversion methods }
function TDataBlockInterpreter.GetVariantPointer(const Value: OleVariant): Pointer;
begin
case VarType(Value) of
varEmpty, varNull: Result := nil;
varDispatch: Result := TVarData(Value).VDispatch;
varVariant: Result := @Value;
varUnknown: Result := TVarData(Value).VUnknown;
else
Result := @TVarData(Value).VPointer;
end;
end;
procedure TDataBlockInterpreter.CopyDataByRef(const Source: TVarData; var Dest: TVarData);
var
VType: Integer;
begin
VType := Source.VType;
if Source.VType and varArray = varArray then
begin
VarClear(OleVariant(Dest));
SafeArrayCheck(SafeArrayCopy(PSafeArray(Source.VArray), PSafeArray(Dest.VArray)));
end else
case Source.VType and varTypeMask of
varEmpty, varNull: ;
varOleStr:
begin
if (Dest.VType and varTypeMask) <> varOleStr then
Dest.VOleStr := SysAllocString(Source.VOleStr)
else if (Dest.VType and varByRef) = varByRef then
SysReallocString(PBStr(Dest.VOleStr)^,Source.VOleStr)
else
SysReallocString(Dest.VOleStr,Source.VOleStr);
end;
varDispatch: Dest.VDispatch := Source.VDispatch;
varVariant: CopyDataByRef(PVarData(Source.VPointer)^, Dest);
varUnknown: Dest.VUnknown := Source.VUnknown;
else
if Dest.VType = 0 then
OleVariant(Dest) := OleVariant(Source)
else if Dest.VType and varByRef = varByRef then
begin
VType := VType or varByRef;
Move(Source.VPointer, Dest.VPointer^, VariantSize[Source.VType and varTypeMask]);
end
else
Move(Source.VPointer, Dest.VPointer, VariantSize[Source.VType and varTypeMask]);
end;
Dest.VType := VType;
end;
function TDataBlockInterpreter.ReadArray(VType: Integer;
const Data: IDataBlock): OleVariant;
var
Flags: TVarFlags;
LoDim, HiDim, Indices, Bounds: PIntArray;
DimCount, VSize, i: Integer;
{P: Pointer;}
V: OleVariant;
LSafeArray: PSafeArray;
P: Pointer;
begin
VarClear(Result);
Data.Read(DimCount, SizeOf(DimCount));
VSize := DimCount * SizeOf(Integer);
GetMem(LoDim, VSize);
try
GetMem(HiDim, VSize);
try
Data.Read(LoDim^, VSize);
Data.Read(HiDim^, VSize);
GetMem(Bounds, VSize * 2);
try
for i := 0 to DimCount - 1 do
begin
Bounds[i * 2] := LoDim[i];
Bounds[i * 2 + 1] := HiDim[i];
end;
Result := VarArrayCreate(Slice(Bounds^,DimCount * 2), VType and varTypeMask);
finally
FreeMem(Bounds);
end;
if VType and varTypeMask in EasyArrayTypes then
begin
Data.Read(VSize, SizeOf(VSize));
P := VarArrayLock(Result);
try
Data.Read(P^, VSize);
finally
VarArrayUnlock(Result);
end;
end else
begin
LSafeArray := PSafeArray(TVarData(Result).VArray);
GetMem(Indices, VSize);
try
FillChar(Indices^, VSize, 0);
for I := 0 to DimCount - 1 do
Indices[I] := LoDim[I];
while True do
begin
V := ReadVariant(Flags, Data);
if VType and varTypeMask = varVariant then
SafeArrayCheck(SafeArrayPutElement(LSafeArray, Indices^, V))
else
SafeArrayCheck(SafeArrayPutElement(LSafeArray, Indices^, TVarData(V).VPointer^));
Inc(Indices[DimCount - 1]);
if Indices[DimCount - 1] > HiDim[DimCount - 1] then
for i := DimCount - 1 downto 0 do
if Indices[i] > HiDim[i] then
begin
if i = 0 then Exit;
Inc(Indices[i - 1]);
Indices[i] := LoDim[i];
end;
end;
finally
FreeMem(Indices);
end;
end;
finally
FreeMem(HiDim);
end;
finally
FreeMem(LoDim);
end;
end;
procedure TDataBlockInterpreter.WriteArray(const Value: OleVariant;
const Data: IDataBlock);
var
LVarData: TVarData;
VType: Integer;
VSize, i, DimCount, ElemSize: Integer;
LSafeArray: PSafeArray;
LoDim, HiDim, Indices: PIntArray;
V: OleVariant;
P: Pointer;
begin
LVarData := FindVarData(Value)^;
VType := LVarData.VType;
LSafeArray := PSafeArray(LVarData.VPointer);
Data.Write(VType, SizeOf(Integer));
DimCount := VarArrayDimCount(Value);
Data.Write(DimCount, SizeOf(DimCount));
VSize := SizeOf(Integer) * DimCount;
GetMem(LoDim, VSize);
try
GetMem(HiDim, VSize);
try
for i := 1 to DimCount do
begin
LoDim[i - 1] := VarArrayLowBound(Value, i);
HiDim[i - 1] := VarArrayHighBound(Value, i);
end;
Data.Write(LoDim^,VSize);
Data.Write(HiDim^,VSize);
if VType and varTypeMask in EasyArrayTypes then
begin
ElemSize := SafeArrayGetElemSize(LSafeArray);
VSize := 1;
for i := 0 to DimCount - 1 do
VSize := (HiDim[i] - LoDim[i] + 1) * VSize;
VSize := VSize * ElemSize;
P := VarArrayLock(Value);
try
Data.Write(VSize, SizeOf(VSize));
Data.Write(P^,VSize);
finally
VarArrayUnlock(Value);
end;
end else
begin
GetMem(Indices, VSize);
try
for I := 0 to DimCount - 1 do
Indices[I] := LoDim[I];
while True do
begin
if VType and varTypeMask <> varVariant then
begin
SafeArrayCheck(SafeArrayGetElement(LSafeArray, Indices^, TVarData(V).VPointer));
TVarData(V).VType := VType and varTypeMask;
end else
SafeArrayCheck(SafeArrayGetElement(LSafeArray, Indices^, V));
WriteVariant(V, Data);
Inc(Indices[DimCount - 1]);
if Indices[DimCount - 1] > HiDim[DimCount - 1] then
for i := DimCount - 1 downto 0 do
if Indices[i] > HiDim[i] then
begin
if i = 0 then Exit;
Inc(Indices[i - 1]);
Indices[i] := LoDim[i];
end;
end;
finally
FreeMem(Indices);
end;
end;
finally
FreeMem(HiDim);
end;
finally
FreeMem(LoDim);
end;
end;
function TDataBlockInterpreter.ReadVariant(out Flags: TVarFlags;
const Data: IDataBlock): OleVariant;
var
I, VType: Integer;
W: WideString;
TmpFlags: TVarFlags;
begin
VarClear(Result);
Flags := [];
Data.Read(VType, SizeOf(VType));
if VType and varByRef = varByRef then
Include(Flags, vfByRef);
if VType = varByRef then
begin
Include(Flags, vfVariant);
Result := ReadVariant(TmpFlags, Data);
Exit;
end;
if vfByRef in Flags then
VType := VType xor varByRef;
if (VType and varArray) = varArray then
Result := ReadArray(VType, Data) else
case VType and varTypeMask of
varEmpty: VarClear(Result);
varNull: Result := NULL;
varOleStr:
begin
Data.Read(I, SizeOf(Integer));
SetLength(W, I);
Data.Read(W[1], I * 2);
Result := W;
end;
varDispatch:
begin
Data.Read(I, SizeOf(Integer));
Result := TDataDispatch.Create(Self, I) as IDispatch;
end;
varUnknown:
raise EInterpreterError.CreateResFmt(@SBadVariantType,[IntToHex(VType,4)]);
else
TVarData(Result).VType := VType;
Data.Read(TVarData(Result).VPointer, VariantSize[VType and varTypeMask]);
end;
end;
function TDataBlockInterpreter.CanCreateObject(const ClassID: TGUID): Boolean;
begin
Result := (FCheckRegValue = '') or
(GetRegStringValue(SClsid + GuidToString(ClassID), FCheckRegValue) = SFlagOn);
end;
function TDataBlockInterpreter.InternalCreateObject(const ClassID: TGUID): OleVariant;
var
Unk: IUnknown;
begin
OleCheck(CoCreateInstance(ClassID, nil, CLSCTX_INPROC_SERVER or
CLSCTX_LOCAL_SERVER or CLSCTX_REMOTE_SERVER, IUnknown, Unk));
Result := Unk as IDispatch;
end;
function TDataBlockInterpreter.CreateObject(const Name: string): OleVariant;
var
ClassID: TGUID;
begin
if (Name[1] = '{') and (Name[Length(Name)] = '}') then
ClassID := StringToGUID(Name) else
ClassID := ProgIDToClassID(Name);
if CanCreateObject(ClassID) then
Result := InternalCreateObject(ClassID) else
raise Exception.CreateResFmt(@SObjectNotAvailable, [GuidToString(ClassID)]);
end;
function TDataBlockInterpreter.StoreObject(const Value: OleVariant): Integer;
begin
if not VarIsArray(FDispList) then
FDispList := VarArrayCreate([0,10], varVariant);
Result := 0;
while Result <= VarArrayHighBound(FDispList, 1) do
if VarIsClear(FDispList[Result]) then break else Inc(Result);
if Result > VarArrayHighBound(FDispList, 1) then
VarArrayRedim(FDispList, Result + 10);
FDispList[Result] := Value;
end;
function TDataBlockInterpreter.LockObject(ID: Integer): IDispatch;
begin
Result := FDispList[ID];
end;
procedure TDataBlockInterpreter.UnlockObject(ID: Integer; const Disp: IDispatch);
begin
end;
procedure TDataBlockInterpreter.ReleaseObject(ID: Integer);
begin
if (ID >= 0) and (VarIsArray(FDispList)) and
(ID < VarArrayHighBound(FDispList, 1)) then
FDispList[ID] := UNASSIGNED;
end;
procedure TDataBlockInterpreter.WriteVariant(const Value: OleVariant;
const Data: IDataBlock);
var
I, VType: Integer;
W: WideString;
begin
VType := VarType(Value);
if VType and varArray <> 0 then
WriteArray(Value, Data)
else
case (VType and varTypeMask) of
varEmpty, varNull:
Data.Write(VType, SizeOf(Integer));
varOleStr:
begin
W := WideString(Value);
I := Length(W);
Data.Write(VType, SizeOf(Integer));
Data.Write(I,SizeOf(Integer));
Data.Write(W[1], I * 2);
end;
varDispatch:
begin
if VType and varByRef = varByRef then
raise EInterpreterError.CreateResFmt(@SBadVariantType,[IntToHex(VType,4)]);
I := StoreObject(Value);
Data.Write(VType, SizeOf(Integer));
Data.Write(I, SizeOf(Integer));
end;
varVariant:
begin
if VType and varByRef <> varByRef then
raise EInterpreterError.CreateResFmt(@SBadVariantType,[IntToHex(VType,4)]);
I := varByRef;
Data.Write(I, SizeOf(Integer));
WriteVariant(Variant(TVarData(Value).VPointer^), Data);
end;
varUnknown:
raise EInterpreterError.CreateResFmt(@SBadVariantType,[IntToHex(VType,4)]);
else
Data.Write(VType, SizeOf(Integer));
if VType and varByRef = varByRef then
Data.Write(TVarData(Value).VPointer^, VariantSize[VType and varTypeMask])
else
Data.Write(TVarData(Value).VPointer, VariantSize[VType and varTypeMask]);
end;
end;
{ Sending Calls }
function TDataBlockInterpreter.CallGetServerList: OleVariant;
var
Flags: TVarFlags;
Data: IDataBlock;
begin
Data := TDataBlock.Create as IDataBlock;
Data.Signature := CallSig or asGetAppServers;
Data := FSendDataBlock.Send(Data, True);
Result := ReadVariant(Flags, Data);
end;
function TDataBlockInterpreter.CallCreateObject(Name: string): OleVariant;
var
Flags: TVarFlags;
Data: IDataBlock;
begin
Data := TDataBlock.Create as IDataBlock;
WriteVariant(Name, Data);
Data.Signature := CallSig or asCreateObject;
Data := FSendDataBlock.Send(Data, True);
Result := ReadVariant(Flags, Data);
end;
procedure TDataBlockInterpreter.CallFreeObject(DispatchIndex: Integer);
var
Data: IDataBlock;
begin
Data := TDataBlock.Create as IDataBlock;
WriteVariant(DispatchIndex, Data);
Data.Signature := CallSig or asFreeObject;
FSendDataBlock.Send(Data, False);
end;
function TDataBlockInterpreter.CallGetIDsOfNames(DispatchIndex: Integer;
const IID: TGUID; Names: Pointer; NameCount, LocaleID: Integer;
DispIDs: Pointer): HResult; stdcall;
var
Flags: TVarFlags;
Data: IDataBlock;
begin
if NameCount <> 1 then
Result := E_NOTIMPL else
begin
Data := TDataBlock.Create as IDataBlock;
WriteVariant(DispatchIndex, Data);
WriteVariant(WideString(POleStrList(Names)^[0]), Data);
Data.Signature := CallSig or asGetID;
Data := FSendDataBlock.Send(Data, True);
Result := ReadVariant(Flags, Data);
if Result = S_OK then
PDispIdList(DispIDs)^[0] := ReadVariant(Flags, Data);
end;
end;
function TDataBlockInterpreter.CallInvoke(DispatchIndex, DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall;
var
VarFlags: TVarFlags;
PDest: PVarData;
i: Integer;
Data: IDataBlock;
begin
Data := TDataBlock.Create as IDataBlock;
WriteVariant(DispatchIndex, Data);
WriteVariant(DispID, Data);
WriteVariant(Flags, Data);
WriteVariant(VarResult <> nil, Data);
WriteVariant(PDispParams(@Params).cArgs, Data);
WriteVariant(PDispParams(@Params).cNamedArgs, Data);
for i := 0 to PDispParams(@Params).cNamedArgs - 1 do
WriteVariant(PDispParams(@Params).rgdispidNamedArgs[i], Data);
for i := 0 to PDispParams(@Params).cArgs - 1 do
WriteVariant(OleVariant(PDispParams(@Params).rgvarg^[i]), Data);
Data.Signature := CallSig or asInvoke;
Data := FSendDataBlock.Send(Data, True);
Result := ReadVariant(VarFlags, Data);
if (Result = DISP_E_EXCEPTION) then
begin
PExcepInfo(ExcepInfo).scode := ReadVariant(VarFlags, Data);
PExcepInfo(ExcepInfo).bstrDescription := ReadVariant(VarFlags, Data);
end;
for i := 0 to PDispParams(@Params).cArgs - 1 do
with PDispParams(@Params)^ do
if rgvarg^[i].vt and varByRef = varByRef then
begin
if rgvarg^[i].vt = (varByRef or varVariant) then
PDest := @TVarData(TVarData(rgvarg^[i]).VPointer^)
else
PDest := @TVarData(rgvarg^[i]);
CopyDataByRef(TVarData(ReadVariant(VarFlags, Data)), PDest^);
end;
if VarResult <> nil then
PVariant(VarResult)^ := ReadVariant(VarFlags, Data);
end;
{ Receiving Calls }
procedure TDataBlockInterpreter.InterpretData(const Data: IDataBlock);
var
Action: Integer;
begin
Action := Data.Signature;
if (Action and asMask) = asError then DoException(Data);
try
case (Action and asMask) of
asInvoke: DoInvoke(Data);
asGetID: DoGetIDsOfNames(Data);
asCreateObject: DoCreateObject(Data);
asFreeObject: DoFreeObject(Data);
asGetServers: DoGetServerList(Data);
asGetAppServers: DoGetAppServerList(Data);
else
if not DoCustomAction(Action and asMask, Data) then
raise EInterpreterError.CreateResFmt(@SInvalidAction, [Action and asMask]);
end;
except
on E: Exception do
begin
Data.Clear;
WriteVariant(E.Message, Data);
Data.Signature := ResultSig or asError;
FSendDataBlock.Send(Data, False);
end;
end;
end;
procedure TDataBlockInterpreter.DoException(const Data: IDataBlock);
var
VarFlags: TVarFlags;
begin
raise Exception.Create(ReadVariant(VarFlags, Data));
end;
procedure TDataBlockInterpreter.DoGetAppServerList(const Data: IDataBlock);
var
VList: OleVariant;
List: TStringList;
i: Integer;
begin
Data.Clear;
List := TStringList.Create;
try
GetMIDASAppServerList(List, FCheckRegValue);
if List.Count > 0 then
begin
VList := VarArrayCreate([0, List.Count - 1], varOleStr);
for i := 0 to List.Count - 1 do
VList[i] := List[i];
end else
VList := NULL;
finally
List.Free;
end;
WriteVariant(VList, Data);
Data.Signature := ResultSig or asGetAppServers;
FSendDataBlock.Send(Data, False);
end;
procedure TDataBlockInterpreter.DoGetServerList(const Data: IDataBlock);
var
VList: OleVariant;
List: TStringList;
i: Integer;
begin
Data.Clear;
List := TStringList.Create;
try
GetDataBrokerList(List, FCheckRegValue);
if List.Count > 0 then
begin
VList := VarArrayCreate([0, List.Count - 1], varOleStr);
for i := 0 to List.Count - 1 do
VList[i] := List[i];
end else
VList := NULL;
finally
List.Free;
end;
WriteVariant(VList, Data);
Data.Signature := ResultSig or asGetServers;
FSendDataBlock.Send(Data, False);
end;
procedure TDataBlockInterpreter.DoCreateObject(const Data: IDataBlock);
var
V: OleVariant;
VarFlags: TVarFlags;
I: Integer;
begin
V := CreateObject(ReadVariant(VarFlags, Data));
Data.Clear;
I := TVarData(V).VType;
if (I and varTypeMask) = varInteger then
begin
I := varDispatch;
Data.Write(I, SizeOf(Integer));
I := V;
Data.Write(I, SizeOf(Integer));
end else
WriteVariant(V, Data);
Data.Signature := ResultSig or asCreateObject;
FSendDataBlock.Send(Data, False);
end;
procedure TDataBlockInterpreter.DoFreeObject(const Data: IDataBlock);
var
VarFlags: TVarFlags;
begin
try
ReleaseObject(ReadVariant(VarFlags, Data));
except
{ Don't return any exceptions }
end;
end;
procedure TDataBlockInterpreter.DoGetIDsOfNames(const Data: IDataBlock);
var
ObjID, RetVal, DispID: Integer;
Disp: IDispatch;
W: WideString;
VarFlags: TVarFlags;
begin
ObjID := ReadVariant(VarFlags, Data);
Disp := LockObject(ObjID);
try
W := ReadVariant(VarFlags, Data);
Data.Clear;
RetVal := Disp.GetIDsOfNames(GUID_NULL, @W, 1, 0, @DispID);
finally
UnlockObject(ObjID, Disp);
end;
WriteVariant(RetVal, Data);
if RetVal = S_OK then
WriteVariant(DispID, Data);
Data.Signature := ResultSig or asGetID;
FSendDataBlock.Send(Data, False);
end;
procedure TDataBlockInterpreter.DoInvoke(const Data: IDataBlock);
var
ExcepInfo: TExcepInfo;
DispParams: TDispParams;
ObjID, DispID, Flags, i: Integer;
RetVal: HRESULT;
ExpectResult: Boolean;
VarFlags: TVarFlags;
Disp: IDispatch;
VarList: PVariantArray;
V: OleVariant;
begin
VarList := nil;
FillChar(ExcepInfo, SizeOf(ExcepInfo), 0);
FillChar(DispParams, SizeOf(DispParams), 0);
ObjID := ReadVariant(VarFlags, Data);
Disp := LockObject(ObjID);
try
DispID := ReadVariant(VarFlags, Data);
Flags := ReadVariant(VarFlags, Data);
ExpectResult := ReadVariant(VarFlags, Data);
DispParams.cArgs := ReadVariant(VarFlags, Data);
DispParams.cNamedArgs := ReadVariant(VarFlags, Data);
try
DispParams.rgdispidNamedArgs := nil;
if DispParams.cNamedArgs > 0 then
begin
GetMem(DispParams.rgdispidNamedArgs, DispParams.cNamedArgs * SizeOf(Integer));
for i := 0 to DispParams.cNamedArgs - 1 do
DispParams.rgdispidNamedArgs[i] := ReadVariant(VarFlags, Data);
end;
if DispParams.cArgs > 0 then
begin
GetMem(DispParams.rgvarg, DispParams.cArgs * SizeOf(TVariantArg));
GetMem(VarList, DispParams.cArgs * SizeOf(OleVariant));
Initialize(VarList^, DispParams.cArgs);
for i := 0 to DispParams.cArgs - 1 do
begin
VarList[i] := ReadVariant(VarFlags, Data);
if vfByRef in VarFlags then
begin
if vfVariant in VarFlags then
begin
DispParams.rgvarg[i].vt := varVariant or varByRef;
TVarData(DispParams.rgvarg[i]).VPointer := @VarList[i];
end else
begin
DispParams.rgvarg[i].vt := VarType(VarList[i]) or varByRef;
TVarData(DispParams.rgvarg[i]).VPointer := GetVariantPointer(VarList[i]);
end;
end else
DispParams.rgvarg[i] := TVariantArg(VarList[i]);
end;
end;
Data.Clear;
RetVal := Disp.Invoke(DispID, GUID_NULL, 0, Flags, DispParams, @V, @ExcepInfo, nil);
WriteVariant(RetVal, Data);
if RetVal = DISP_E_EXCEPTION then
begin
WriteVariant(ExcepInfo.scode, Data);
WriteVariant(ExcepInfo.bstrDescription, Data);
end;
if DispParams.rgvarg <> nil then
begin
for i := 0 to DispParams.cArgs - 1 do
if DispParams.rgvarg[i].vt and varByRef = varByRef then
WriteVariant(OleVariant(DispParams.rgvarg[i]), Data);
end;
if ExpectResult then WriteVariant(V, Data);
Data.Signature := ResultSig or asInvoke;
FSendDataBlock.Send(Data, False);
finally
if DispParams.rgdispidNamedArgs <> nil then
FreeMem(DispParams.rgdispidNamedArgs);
if VarList <> nil then
begin
Finalize(VarList^, DispParams.cArgs);
FreeMem(VarList);
end;
if DispParams.rgvarg <> nil then
FreeMem(DispParams.rgvarg);
end;
finally
UnlockObject(ObjID, Disp);
end;
end;
function TDataBlockInterpreter.DoCustomAction(Action: Integer;
const Data: IDataBlock): Boolean;
begin
Result := False;
end;
{ TDataDispatch }
constructor TDataDispatch.Create(Interpreter: TCustomDataBlockInterpreter; DispatchIndex: Integer);
begin
inherited Create;
FDispatchIndex := DispatchIndex;
FInterpreter := Interpreter;
Interpreter.AddDispatch(Self);
end;
destructor TDataDispatch.Destroy;
begin
if Assigned(FInterpreter) then
begin
FInterpreter.CallFreeObject(FDispatchIndex);
FInterpreter.RemoveDispatch(Self);
end;
inherited Destroy;
end;
{ TDataDispatch.IDispatch }
function TDataDispatch.GetTypeInfoCount(out Count: Integer): HResult; stdcall;
begin
Count := 0;
Result := S_OK;
end;
function TDataDispatch.GetTypeInfo(Index, LocaleID: Integer; out TypeInfo): HResult; stdcall;
begin
Result := E_NOTIMPL;
end;
function TDataDispatch.GetIDsOfNames(const IID: TGUID; Names: Pointer;
NameCount, LocaleID: Integer; DispIDs: Pointer): HResult; stdcall;
begin
Result := FInterpreter.CallGetIDsOfNames(FDispatchIndex, IID, Names, NameCount,
LocaleID, DispIDs);
end;
function TDataDispatch.Invoke(DispID: Integer; const IID: TGUID; LocaleID: Integer;
Flags: Word; var Params; VarResult, ExcepInfo, ArgErr: Pointer): HResult; stdcall;
begin
Result := FInterpreter.CallInvoke(FDispatchIndex, DispID, IID, LocaleID, Flags,
Params, VarResult, ExcepInfo, ArgErr);
end;
{ TTransportThread }
constructor TTransportThread.Create(AHandle: THandle; Transport: ITransport);
begin
FParentHandle := AHandle;
FTransport := Transport;
FreeOnTerminate := True;
FSemaphore := CreateSemaphore(nil, 0, 1, nil);
inherited Create(False);
end;
destructor TTransportThread.Destroy;
begin
CloseHandle(FSemaphore);
inherited Destroy;
end;
procedure TTransportThread.Execute;
procedure SynchronizeException;
var
SendException: TObject;
begin
SendException := AcquireExceptionObject;
if Assigned(FTransport) and (SendException is ESocketConnectionError) then
FTransport.Connected := False;
PostMessage(FParentHandle, THREAD_EXCEPTION, 0, Integer(Pointer(SendException)));
end;
var
msg: TMsg;
Data: IDataBlock;
Event: THandle;
Context: Integer;
begin
CoInitialize(nil);
try
PeekMessage(msg, 0, WM_USER, WM_USER, PM_NOREMOVE);
ReleaseSemaphore(FSemaphore, 1, nil);
try
FTransport.Connected := True;
try
Event := FTransport.GetWaitEvent;
while not Terminated and FTransport.Connected do
try
case MsgWaitForMultipleObjects(1, Event, False, INFINITE, QS_ALLINPUT) of
WAIT_OBJECT_0:
begin
WSAResetEvent(Event);
Data := FTransport.Receive(False, 0);
if Assigned(Data) then
begin
Data._AddRef;
PostMessage(FParentHandle, THREAD_RECEIVEDSTREAM, 0, Integer(Pointer(Data)));
Data := nil;
end;
end;
WAIT_OBJECT_0 + 1:
begin
while PeekMessage(msg, 0, 0, 0, PM_REMOVE) do
begin
if (msg.hwnd = 0) then
case msg.message of
THREAD_SENDSTREAM:
begin
Data := IDataBlock(msg.lParam);
Data._Release;
Context := FTransport.Send(Data);
if msg.wParam = 1 then
begin
Data := FTransport.Receive(True, Context);
Data._AddRef;
PostMessage(FParentHandle, THREAD_RECEIVEDSTREAM, 0, Integer(Pointer(Data)));
Data := nil;
end else
PostMessage(FParentHandle, THREAD_SENDNOTIFY, 0, 0);
end;
THREAD_REPLACETRANSPORT:
begin
FTransport := ITransport(msg.lParam);
FTransport._Release;
end;
else
DispatchMessage(msg);
end
else
DispatchMessage(msg);
end;
end;
end;
except
SynchronizeException;
end;
finally
Data := nil;
FTransport.Connected := False;
end;
except
SynchronizeException;
end;
finally
FTransport := nil;
CoUninitialize();
end;
end;
{ TStreamedConnection }
constructor TStreamedConnection.Create(AOwner: TComponent);
var
Obj: ISendDataBlock;
begin
inherited Create(AOwner);
GetInterface(ISendDataBlock, Obj);
// FInterpreter := TDataBlockInterpreter.Create(Self, SSockets);
FSupportCallbacks := True;
end;
destructor TStreamedConnection.Destroy;
begin
SetConnected(False);
FInterpreter.Free;
if FHandle <> 0 then DeallocateHWnd(FHandle);
if Assigned(FTransport) then FTransport.OnTerminate := nil;
FTransIntf := nil;
inherited Destroy;
end;
function TStreamedConnection.GetInterceptGUID: string;
begin
if (FInterceptGUID.D1 <> 0) or (FInterceptGUID.D2 <> 0) or (FInterceptGUID.D3 <> 0) then
Result := GUIDToString(FInterceptGUID) else
Result := '';
end;
procedure TStreamedConnection.SetInterceptGUID(const Value: string);
var
InterceptName: PWideChar;
begin
if not (csLoading in ComponentState) then
SetConnected(False);
if Value = '' then
FillChar(FInterceptGUID, SizeOf(FInterceptGUID), 0)
else
begin
FInterceptGUID := StringToGUID(Value);
if ProgIDFromCLSID(FInterceptGUID, InterceptName) = 0 then
begin
FInterceptName := InterceptName;
CoTaskMemFree(InterceptName);
end;
end;
end;
procedure TStreamedConnection.SetInterceptName(const Value: string);
begin
if Value <> FInterceptName then
begin
if not (csLoading in ComponentState) then
begin
SetConnected(False);
if CLSIDFromProgID(PWideChar(WideString(Value)), FInterceptGUID) <> 0 then
FillChar(FInterceptGUID, SizeOf(FInterceptGUID), 0);
end;
FInterceptName := Value;
end;
end;
procedure TStreamedConnection.SetSupportCallbacks(Value: Boolean);
begin
if Connected then Connected := False;
FSupportCallbacks := Value;
end;
procedure TStreamedConnection.InternalOpen;
begin
if FSupportCallbacks then
begin
FTransport := TTransportThread.Create(Handle, CreateTransport);
FTransport.OnTerminate := TransportTerminated;
WaitForSingleObject(FTransport.Semaphore, INFINITE);
end else
begin
FTransIntf := CreateTransport;
FTransIntf.SetConnected(True);
end;
end;
procedure TStreamedConnection.InternalClose;
begin
if Assigned(FTransport) then
begin
FTransport.OnTerminate := nil;
FTransport.Terminate;
PostThreadMessage(FTransport.ThreadID, WM_USER, 0, 0);
if Assigned(FTransport.FTransport) then
WaitForSingleObject(FTransport.Handle, 180000);
FTransport := nil;
end else
if Assigned(FTransIntf) then
begin
FTransIntf.Connected := False;
FTransIntf := nil;
end;
end;
function TStreamedConnection.GetServerList: OleVariant;
var
DidConnect: Boolean;
begin
DidConnect := not Connected;
if DidConnect then InternalOpen;
try
Result := Interpreter.CallGetServerList;
finally
if DidConnect then InternalClose;
end;
end;
function TStreamedConnection.GetInterceptorList: OleVariant;
var
List: TStringList;
i: Integer;
begin
Result := NULL;
List := TStringList.Create;
try
GetPacketInterceptorList(List);
if List.Count > 0 then
begin
Result := VarArrayCreate([0, List.Count - 1], varOleStr);
for i := 0 to List.Count - 1 do
Result[i] := List[i];
end;
finally
List.Free;
end;
end;
function TStreamedConnection.GetHandle: THandle;
begin
if FHandle = 0 then
FHandle := AllocateHwnd(WndProc);
Result := FHandle;
end;
procedure TStreamedConnection.WndProc(var Message: TMessage);
begin
try
Dispatch(Message);
except
if Assigned(ApplicationHandleException) then
ApplicationHandleException(Self);
end;
end;
procedure TStreamedConnection.ThreadReceivedStream(var Message: TMessage);
var
Data: IDataBlock;
begin
Data := IDataBlock(Message.lParam);
Data._Release;
Interpreter.InterpretData(Data);
end;
procedure TStreamedConnection.ThreadException(var Message: TMessage);
begin
DoError(Exception(Message.lParam));
end;
procedure TStreamedConnection.DoError(E: Exception);
begin
raise E;
end;
procedure TStreamedConnection.TransportTerminated(Sender: TObject);
begin
FTransport := nil;
SetConnected(False);
end;
procedure TStreamedConnection.DoConnect;
var
TempStr: string;
begin
try
if ServerGUID <> '' then
TempStr := ServerGUID else
TempStr := ServerName;
if TempStr = '' then
raise Exception.CreateResFmt(@SServerNameBlank, [Name]);
InternalOpen;
SetAppServer(Interpreter.CallCreateObject(TempStr));
except
InternalClose;
raise;
end;
end;
procedure TStreamedConnection.DoDisconnect;
begin
inherited DoDisconnect;
InternalClose;
end;
function TStreamedConnection.CreateTransport: ITransport;
begin
Result := nil;
end;
function TStreamedConnection.GetInterpreter: TCustomDataBlockInterpreter;
begin
if not Assigned(FInterpreter) then
FInterpreter := TDataBlockInterpreter.Create(Self, SSockets);
Result := FInterpreter;
end;
{ TStreamedConnection.IUnknown }
function TStreamedConnection.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then Result := 0 else Result := E_NOINTERFACE;
end;
function TStreamedConnection._AddRef: Integer;
begin
Inc(FRefCount);
Result := FRefCount;
end;
function TStreamedConnection._Release: Integer;
begin
Dec(FRefCount);
Result := FRefCount;
end;
{ TStreamedConnection.ISendDataBlock }
function TStreamedConnection.Send(const Data: IDataBlock; WaitForResult: Boolean): IDataBlock;
var
Msg: TMsg;
Context: Integer;
begin
if FSupportCallbacks then
begin
if not Assigned(FTransport) then Exit;
Data._AddRef;
PostThreadMessage(FTransport.ThreadID, THREAD_SENDSTREAM, Ord(WaitForResult),
Integer(Pointer(Data)));
if WaitForResult then
while True do
begin
if GetMessage(Msg, FHandle, THREAD_RECEIVEDSTREAM, THREAD_EXCEPTION) then
begin
if Msg.message = THREAD_RECEIVEDSTREAM then
begin
Result := IDataBlock(Msg.lParam);
Result._Release;
if (Result.Signature and ResultSig) = ResultSig then
break else
Interpreter.InterpretData(Result);
end
else if Msg.Message <> WM_NULL then
DoError(Exception(Msg.lParam))
else
raise Exception.CreateRes(@SReturnError);
end else
raise Exception.CreateRes(@SReturnError);
end
else
GetMessage(Msg, FHandle, THREAD_SENDNOTIFY, THREAD_SENDNOTIFY);
end else
begin
if not Assigned(FTransIntf) then Exit;
Context := FTransIntf.Send(Data);
Result := FTransIntf.Receive(WaitForResult, Context);
end;
if Assigned(Result) and ((Result.Signature and asMask) = asError) then
Interpreter.InterpretData(Result);
end;
{ TSocketTransport }
constructor TSocketTransport.Create;
begin
inherited Create;
FInterceptor := nil;
FEvent := 0;
end;
destructor TSocketTransport.Destroy;
begin
FInterceptor := nil;
SetConnected(False);
inherited Destroy;
end;
function TSocketTransport.GetWaitEvent: THandle;
begin
FEvent := WSACreateEvent;
WSAEventSelect(FSocket.SocketHandle, FEvent, FD_READ or FD_CLOSE);
Result := FEvent;
end;
function TSocketTransport.GetConnected: Boolean;
begin
Result := (FSocket <> nil) and (FSocket.Connected);
end;
procedure TSocketTransport.SetConnected(Value: Boolean);
begin
if GetConnected = Value then Exit;
if Value then
begin
if (FAddress = '') and (FHost = '') then
raise ESocketConnectionError.CreateRes(@SNoAddress);
FClientSocket := TClientSocket.Create(nil);
FClientSocket.ClientType := ctBlocking;
FSocket := FClientSocket.Socket;
FClientSocket.Port := FPort;
if FAddress <> '' then
FClientSocket.Address := FAddress else
FClientSocket.Host := FHost;
FClientSocket.Open;
end else
begin
if FSocket <> nil then FSocket.Close;
FSocket := nil;
FreeAndNil(FClientSocket);
if FEvent <> 0 then WSACloseEvent(FEvent);
FEvent := 0;
end;
end;
function TSocketTransport.Receive(WaitForInput: Boolean; Context: Integer): IDataBlock;
var
RetLen, Sig, StreamLen: Integer;
P: Pointer;
FDSet: TFDSet;
TimeVal: PTimeVal;
RetVal: Integer;
begin
Result := nil;
TimeVal := nil;
FD_ZERO(FDSet);
FD_SET(FSocket.SocketHandle, FDSet);
if not WaitForInput then
begin
New(TimeVal);
TimeVal.tv_sec := 0;
TimeVal.tv_usec := 1;
end;
RetVal := select(0, @FDSet, nil, nil, TimeVal);
if Assigned(TimeVal) then
FreeMem(TimeVal);
if RetVal = SOCKET_ERROR then
raise ESocketConnectionError.Create(SysErrorMessage(WSAGetLastError));
if (RetVal = 0) then Exit;
RetLen := FSocket.ReceiveBuf(Sig, SizeOf(Sig));
if RetLen <> SizeOf(Sig) then
raise ESocketConnectionError.CreateRes(@SSocketReadError);
CheckSignature(Sig);
RetLen := FSocket.ReceiveBuf(StreamLen, SizeOf(StreamLen));
if RetLen = 0 then
raise ESocketConnectionError.CreateRes(@SSocketReadError);
if RetLen <> SizeOf(StreamLen) then
raise ESocketConnectionError.CreateRes(@SSocketReadError);
Result := TDataBlock.Create as IDataBlock;
Result.Size := StreamLen;
Result.Signature := Sig;
P := Result.Memory;
Inc(Integer(P), Result.BytesReserved);
while StreamLen > 0 do
begin
RetLen := FSocket.ReceiveBuf(P^, StreamLen);
if RetLen = 0 then
raise ESocketConnectionError.CreateRes(@SSocketReadError);
if RetLen > 0 then
begin
Dec(StreamLen, RetLen);
Inc(Integer(P), RetLen);
end;
end;
if StreamLen <> 0 then
raise ESocketConnectionError.CreateRes(@SInvalidDataPacket);
InterceptIncoming(Result);
end;
function TSocketTransport.Send(const Data: IDataBlock): Integer;
var
P: Pointer;
begin
Result := 0;
InterceptOutgoing(Data);
P := Data.Memory;
FSocket.SendBuf(P^, Data.Size + Data.BytesReserved);
end;
function TSocketTransport.CheckInterceptor: Boolean;
var
GUID: TGUID;
begin
if not Assigned(FInterceptor) and (FInterceptGUID <> '') then
if not FCreateAttempted then
try
FCreateAttempted := True;
Guid := StringToGuid(FInterceptGUID);
FInterceptor := CreateComObject(Guid) as IDataIntercept;
except
{ raise no exception if the creating failed }
end;
Result := Assigned(FInterceptor);
end;
procedure TSocketTransport.InterceptIncoming(const Data: IDataBlock);
begin
if CheckInterceptor then
FInterceptor.DataIn(Data);
end;
procedure TSocketTransport.InterceptOutgoing(const Data: IDataBlock);
begin
if CheckInterceptor then
FInterceptor.DataOut(Data);
end;
{ TSocketConnection }
constructor TSocketConnection.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPort := 211;
end;
function TSocketConnection.IsAddressStored: Boolean;
begin
Result := (ObjectBroker = nil) and (Address <> '');
end;
procedure TSocketConnection.SetAddress(Value: string);
begin
if Value <> '' then
FHost := '';
FAddress := Value;
end;
function TSocketConnection.IsHostStored: Boolean;
begin
Result := (ObjectBroker = nil) and (Host <> '');
end;
procedure TSocketConnection.SetHost(Value: string);
begin
if Value <> '' then
FAddress := '';
FHost := Value;
end;
function TSocketConnection.CreateTransport: ITransport;
var
SocketTransport: TSocketTransport;
begin
if SupportCallbacks then
if not LoadWinSock2 then raise Exception.CreateRes(@SNoWinSock2);
if (FAddress = '') and (FHost = '') then
raise ESocketConnectionError.CreateRes(@SNoAddress);
SocketTransport := TSocketTransport.Create;
SocketTransport.Host := FHost;
SocketTransport.Address := FAddress;
SocketTransport.Port := FPort;
SocketTransport.InterceptGUID := InterceptGUID;
Result := SocketTransport as ITransport;
end;
procedure TSocketConnection.DoConnect;
var
Comp: string;
p, i: Integer;
begin
if (ObjectBroker <> nil) then
begin
repeat
if FAddress <> '' then
Comp := FAddress else
if FHost <> '' then
Comp := FHost else
if ServerGUID <> '' then
Comp := ObjectBroker.GetComputerForGUID(GetServerCLSID) else
Comp := ObjectBroker.GetComputerForProgID(ServerName);
try
p := ObjectBroker.GetPortForComputer(Comp);
if p > 0 then
FPort := p;
p := 0;
for i := 1 to Length(Comp) do
if (Comp[i] in ['0'..'9', '.']) then
Inc(p, Ord(Comp[i] = '.')) else
break;
if p <> 3 then
Host := Comp else
Address := Comp;
inherited DoConnect;
ObjectBroker.SetConnectStatus(Comp, True);
except
ObjectBroker.SetConnectStatus(Comp, False);
FAddress := '';
FHost := '';
end;
until Connected;
end else
inherited DoConnect;
end;
{ TWebConnection }
constructor TWebConnection.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FInterpreter := TDataBlockInterpreter.Create(Self, SWeb);
SupportCallbacks := False;
FInetRoot := nil;
FInetConnect := nil;
FAgent := 'DataSnap';
URL := SDefaultURL;
end;
destructor TWebConnection.Destroy;
begin
SetConnected(False);
FInterpreter.Free;
inherited Destroy;
end;
function TWebConnection.GetInterpreter: TCustomDataBlockInterpreter;
begin
if not Assigned(FInterpreter) then
FInterpreter := TDataBlockInterpreter.Create(Self, SWeb);
Result := FInterpreter;
end;
procedure TWebConnection.SetURL(const Value: string);
var
URLComp: TURLComponents;
P: PChar;
begin
SetConnected(False);
if FURL = Value then Exit;
if Value <> '' then
begin
FillChar(URLComp, SizeOf(URLComp), 0);
URLComp.dwStructSize := SizeOf(URLComp);
URLComp.dwSchemeLength := 1;
URLComp.dwHostNameLength := 1;
URLComp.dwURLPathLength := 1;
P := PChar(Value);
InternetCrackUrl(P, 0, 0, URLComp);
if not (URLComp.nScheme in [INTERNET_SCHEME_HTTP, INTERNET_SCHEME_HTTPS]) then
raise Exception.CreateRes(@SInvalidURL);
FURLScheme := URLComp.nScheme;
FURLPort := URLComp.nPort;
FURLHost := Copy(Value, URLComp.lpszHostName - P + 1, URLComp.dwHostNameLength);
FURLSite := Copy(Value, URLComp.lpszUrlPath - P + 1, URLComp.dwUrlPathLength);
end else
begin
FURLPort := 0;
FURLHost := '';
FURLSite := '';
FURLScheme := 0;
end;
FURL := Value;
end;
function TWebConnection.CreateTransport: ITransport;
begin
if FURLHost = '' then
raise Exception.CreateRes(@SURLRequired);
Result := Self;
end;
function TWebConnection.IsURLStored: Boolean;
begin
Result := (ObjectBroker = nil) and (URL <> '');
end;
procedure TWebConnection.Check(Error: Boolean);
var
ErrCode: Integer;
S: string;
begin
ErrCode := GetLastError;
if Error and (ErrCode <> 0) then
begin
SetLength(S, 256);
FormatMessage(FORMAT_MESSAGE_FROM_HMODULE, Pointer(GetModuleHandle('wininet.dll')),
ErrCode, 0, PChar(S), Length(S), nil);
SetLength(S, StrLen(PChar(S)));
while (Length(S) > 0) and (S[Length(S)] in [#10, #13]) do
SetLength(S, Length(S) - 1);
raise Exception.Create(S);
end;
end;
function TWebConnection.GetWaitEvent: THandle;
begin
Result := 0;
end;
function TWebConnection.Transport_GetConnected: Boolean;
begin
Result := Assigned(FinetConnect);
end;
procedure TWebConnection.Transport_SetConnected(Value: Boolean);
var
AccessType: Integer;
begin
if Value and not GetConnected then
begin
if Length(FProxy) > 0 then
AccessType := INTERNET_OPEN_TYPE_PROXY else
AccessType := INTERNET_OPEN_TYPE_PRECONFIG;
FInetRoot := InternetOpen(PChar(Agent), AccessType, PChar(FProxy), PChar(FProxyByPass), 0);
if InternetAttemptConnect(0) <> ERROR_SUCCESS then SysUtils.Abort;
Check(not Assigned(FInetRoot));
try
FInetConnect := InternetConnect(FInetRoot, PChar(FURLHost), FURLPort, PChar(FUserName),
PChar(FPassword), INTERNET_SERVICE_HTTP, 0, Cardinal(Self));
Check(not Assigned(FInetConnect));
except
InternetCloseHandle(FInetRoot);
end;
end else
if not Value then
begin
if Assigned(FInetConnect) then
InternetCloseHandle(FInetConnect);
FInetConnect := nil;
if Assigned(FInetRoot) then
InternetCloseHandle(FInetRoot);
FInetRoot := nil;
end;
end;
function TWebConnection.Receive(WaitForInput: Boolean; Context: Integer): IDataBlock;
const
MaxStatusText: Integer = 4096;
var
Size, Downloaded, Status, Len, Index, Position: DWord;
Data: array of byte;
S: string;
begin
Len := SizeOf(Status);
Index := 0;
if HttpQueryInfo(Pointer(Context), HTTP_QUERY_STATUS_CODE or HTTP_QUERY_FLAG_NUMBER,
@Status, Len, Index) and (Status >= 300) then
begin
Index := 0;
Size := MaxStatusText;
SetLength(S, Size);
if HttpQueryInfo(Pointer(Context), HTTP_QUERY_STATUS_TEXT, @S[1], Size, Index) then
begin
SetLength(S, Size);
raise Exception.CreateFmt('%s (%d)', [S, Status]);
end;
end;
Len := 0;
Position := 0;
repeat
Check(not InternetQueryDataAvailable(Pointer(Context), Size, 0, 0));
if Size > 0 then
begin
SetLength(Data, Position + Size);
Check(not InternetReadFile(Pointer(Context), @Data[Position], Size, Downloaded));
if Assigned(Result) then
Result.Write(Data[0], Downloaded)
else
begin
Inc(Position, Downloaded);
if (Position >= MINDATAPACKETSIZE) then
begin
Result := TDataBlock.Create;
Len := Result.InitData(@Data[0], Position, False);
Position := 0;
end
else
Continue;
end;
end;
until Size = 0;
if ((Position > 0) and (Position < MINDATAPACKETSIZE)) or
(Assigned(Result) and (Len <> DWord(Result.Size))) then
raise Exception.CreateRes(@SInvalidDataPacket);
end;
function TWebConnection.Send(const Data: IDataBlock): Integer;
var
Request: HINTERNET;
RetVal, Flags: DWord;
P: Pointer;
AcceptTypes: array of PChar;
begin
SetLength(AcceptTypes, 2);
AcceptTypes[0] := PChar('application/octet-stream');
AcceptTypes[1] := nil;
Flags := INTERNET_FLAG_KEEP_CONNECTION or INTERNET_FLAG_NO_CACHE_WRITE;
if FURLScheme = INTERNET_SCHEME_HTTPS then
Flags := Flags or INTERNET_FLAG_SECURE;
Request := HttpOpenRequest(FInetConnect, 'POST', PChar(FURLSite), nil,
nil, Pointer(AcceptTypes), Flags, Integer(Self));
Check(not Assigned(Request));
while True do
begin
Check(not HttpSendRequest(Request, nil, 0, Data.Memory, Data.Size + Data.BytesReserved));
RetVal := InternetErrorDlg(GetDesktopWindow(), Request, GetLastError,
FLAGS_ERROR_UI_FILTER_FOR_ERRORS or FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS or
FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, P);
case RetVal of
ERROR_SUCCESS: break;
ERROR_CANCELLED: SysUtils.Abort;
ERROR_INTERNET_FORCE_RETRY: {Retry the operation};
end;
end;
Result := Integer(Request)
end;
procedure TWebConnection.DoConnect;
begin
if (ObjectBroker <> nil) then
begin
repeat
if URL = '' then
if ServerGUID <> '' then
URL := ObjectBroker.GetComputerForGUID(GetServerCLSID) else
URL := ObjectBroker.GetComputerForProgID(ServerName);
try
inherited DoConnect;
ObjectBroker.SetConnectStatus(URL, True);
except
ObjectBroker.SetConnectStatus(URL, False);
URL := '';
end;
until Connected;
end else
inherited DoConnect;
end;
{ TPacketInterceptFactory }
procedure TPacketInterceptFactory.UpdateRegistry(Register: Boolean);
var
CatReg: ICatRegister;
Rslt: HResult;
CatInfo: TCATEGORYINFO;
Description: string;
begin
inherited UpdateRegistry(Register);
Rslt := CoCreateInstance(CLSID_StdComponentCategoryMgr, nil,
CLSCTX_INPROC_SERVER, ICatRegister, CatReg);
if Succeeded(Rslt) then
begin
if Register then
begin
CatInfo.catid := CATID_MIDASInterceptor;
CatInfo.lcid := $0409;
StringToWideChar(MIDASInterceptor_CatDesc, CatInfo.szDescription,
Length(MIDASInterceptor_CatDesc) + 1);
OleCheck(CatReg.RegisterCategories(1, @CatInfo));
OleCheck(CatReg.RegisterClassImplCategories(ClassID, 1, @CATID_MIDASInterceptor));
end else
begin
OleCheck(CatReg.UnRegisterClassImplCategories(ClassID, 1, @CATID_MIDASInterceptor));
DeleteRegKey(Format(SClsid + SCatImplBaseKey, [GUIDToString(ClassID)]));
end;
end else
begin
if Register then
begin
CreateRegKey('Component Categories\' + GUIDToString(CATID_MIDASInterceptor), '409', MIDASInterceptor_CatDesc);
CreateRegKey(Format(SClsid + SCatImplKey, [GUIDToString(ClassID), GUIDToString(CATID_MIDASInterceptor)]), '', '');
end else
begin
DeleteRegKey(Format(SClsid + SCatImplKey, [GUIDToString(ClassID), GUIDToString(CATID_MIDASAppServer)]));
DeleteRegKey(Format(SClsid + SCatImplBaseKey, [GUIDToString(ClassID)]));
end;
end;
if Register then
begin
Description := GetRegStringValue(SClsid + GUIDToString(ClassID), '');
CreateRegKey('AppID\' + GUIDToString(ClassID), '', Description);
CreateRegKey(SClsid + GUIDToString(ClassID), 'AppID', GUIDToString(ClassID));
end else
DeleteRegKey('AppID\' + GUIDToString(ClassID));
end;
initialization
finalization
FreeWinSock2;
end.
|
unit uImagePicker;
interface
uses
{$IF CompilerVersion > 22}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,Forms, Dialogs, ComCtrls,
{$IFEND}
CNClrLib.Control.EnumTypes, CNClrLib.Control.EventArgs, CNClrLib.Control.Base,
CNClrLib.Component.OpenFileDialog, CNClrLib.Control.PictureBox,
CNClrLib.Control.ButtonBase, CNClrLib.Control.Button, Vcl.ExtDlgs;
type
TfrmClrImageEditor = class(TForm)
CnPictureBoxImage: TCnPictureBox;
CnButtonLoad: TCnButton;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
CnButtonClear: TCnButton;
CnButtonExit: TCnButton;
OpenPictureDialog1: TOpenPictureDialog;
procedure CnButtonLoadClick(Sender: TObject; E: _EventArgs);
procedure CnButtonExitClick(Sender: TObject; E: _EventArgs);
procedure CnButtonClearClick(Sender: TObject; E: _EventArgs);
procedure FormShow(Sender: TObject);
private
procedure SetButtonEnabled;
end;
var
frmClrImageEditor: TfrmClrImageEditor;
implementation
uses CNClrLib.Drawing;
{$R *.dfm}
procedure TfrmClrImageEditor.CnButtonExitClick(Sender: TObject;
E: _EventArgs);
begin
Close;
end;
procedure TfrmClrImageEditor.CnButtonClearClick(Sender: TObject; E: _EventArgs);
begin
CnPictureBoxImage.Image := nil;
SetButtonEnabled;
end;
procedure TfrmClrImageEditor.CnButtonLoadClick(Sender: TObject; E: _EventArgs);
begin
if OpenPictureDialog1.Execute(Handle) then
CnPictureBoxImage.Image.LoadFromFile(OpenPictureDialog1.FileName);
SetButtonEnabled
end;
procedure TfrmClrImageEditor.FormShow(Sender: TObject);
begin
SetButtonEnabled;
end;
procedure TfrmClrImageEditor.SetButtonEnabled;
begin
CnButtonClear.Enabled := not CnPictureBoxImage.Image.IsEmpty;
end;
end.
|
unit rhlMurmur2;
interface
uses
rhlCore;
type
{ TrhlMurmur2 }
TrhlMurmur2 = class(TrhlHashWithKey)
private
const
CKEY: DWord = $C58F1A7B;
M: DWord = $5BD1E995;
R: Integer = 24;
var
m_key,
m_working_key,
m_h: DWord;
protected
procedure UpdateBytes(const ABuffer; ASize: LongWord); override;
function GetKey: TBytes; override;
procedure SetKey(AValue: TBytes); override;
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlMurmur2 }
procedure TrhlMurmur2.UpdateBytes(const ABuffer; ASize: LongWord);
var
a_data: array[0..0] of Byte absolute ABuffer;
ci: Integer;
k: DWord;
begin
if (ASize = 0) then
Exit;
m_h := m_working_key xor ASize;
ci := 0;
while (ASize >= 4) do
begin
k := a_data[ci+0] or (a_data[ci+1] shl 8) or (a_data[ci+2] shl 16) or (a_data[ci+3] shl 24);
k := k * M;
k := k xor (k shr R);
k := k * M;
m_h := m_h * M;
m_h := m_h xor k;
Inc(ci, 4);
Dec(ASize, 4);
end;
case ASize of
3: m_h := m_h xor (a_data[ci+0] or a_data[ci+1] shl 8) xor (a_data[ci+2] shl 16);
2: m_h := m_h xor (a_data[ci+0] or a_data[ci+1] shl 8);
1: m_h := m_h xor (a_data[ci]);
end;
if ASize >= 1 then
m_h := m_h * M;
m_h := m_h xor (m_h shr 13);
m_h := m_h * M;
m_h := m_h xor (m_h shr 15);
end;
function TrhlMurmur2.GetKey: TBytes;
begin
SetLength(Result, SizeOf(DWord));
Move(m_key, Result[0], SizeOf(DWord));
end;
procedure TrhlMurmur2.SetKey(AValue: TBytes);
begin
if Length(AValue) = SizeOf(m_key) then
Move(AValue[0], m_key, SizeOf(m_key));
end;
constructor TrhlMurmur2.Create;
begin
HashSize := 4;
BlockSize := 4;
m_key := CKEY;
end;
procedure TrhlMurmur2.Init;
begin
inherited Init;
m_working_key := m_key;
end;
procedure TrhlMurmur2.Final(var ADigest);
begin
Move(m_h, ADigest, 4);
end;
end.
|
(**
This module contains code for added and removing about box entries in the IDE.
@Author David Hoyle
@Version 1.0
@Date 03 Jan 2018
**)
Unit ITHelper.AboutBox;
Interface
Function AddAboutBoxEntry : Integer;
Procedure RemoveAboutBoxEntry(Const iAboutBoxIndex : Integer);
Implementation
Uses
ToolsAPI,
SysUtils,
Windows,
Forms,
ITHelper.ResourceStrings,
ITHelper.Constants,
ITHelper.CommonFunctions;
(**
This method installs the about box entry in the IDE.
@precon None.
@postcon The about box entry is installed and the return value is the index with whch to remove it
later.
@return an Integer
**)
Function AddAboutBoxEntry : Integer;
Const
strITHelperSplashScreen48x48 = 'ITHelperSplashScreen48x48';
strSKUBuild = 'SKU Build %d.%d.%d.%d';
ResourceString
strPluginDescription = 'An IDE expert to allow the configuration of pre and post compilation ' +
'processes and automatically ZIP the successfully compiled project for release.';
Var
bmSplashScreen : HBITMAP;
iMajor, iMinor, iBugFix, iBuild : Integer;
ABS : IOTAAboutBoxServices;
strModuleName: String;
iSize: Cardinal;
Begin
Result := -1;
SetLength(strModuleName, MAX_PATH);
iSize := GetModuleFileName(hInstance, PChar(strModuleName), MAX_PATH);
SetLength(strModuleName, iSize);
BuildNumber(strModuleName, iMajor, iMinor, iBugFix, iBuild);
bmSplashScreen := LoadBitmap(hInstance, strITHelperSplashScreen48x48);
If Supports(BorlandIDEServices, IOTAAboutBoxServices, ABS) Then
Begin
Result := (BorlandIDEServices As IOTAAboutBoxServices).AddPluginInfo(
Format(strSplashScreenName, [iMajor, iMinor, Copy(strRevisions, iBugFix + 1, 1),
Application.Title]),
strPluginDescription,
bmSplashScreen,
{$IFDEF DEBUG} True {$ELSE} False {$ENDIF},
Format(strSplashScreenBuild, [iMajor, iMinor, iBugfix, iBuild]),
Format(strSKUBuild, [iMajor, iMinor, iBugfix, iBuild]));
End;
End;
(**
This method removes the about box entry from the IDE with the given index.
@precon Must be a valid index for an about box entry.
@postcon The about box entry is removed.
@param iAboutBoxIndex as an Integer as a constant
**)
Procedure RemoveAboutBoxEntry(Const iAboutBoxIndex : Integer);
Begin
If iAboutBoxIndex > -1 Then
(BorlandIDEServices As IOTAAboutBoxServices).RemovePluginInfo(iAboutBoxIndex);
End;
End.
|
unit rhlSHA0;
interface
uses
rhlCore;
type
{ TrhlSHA0 }
TrhlSHA0 = class(TrhlHash)
private
FStates: array[0..4] of DWord;
protected
type TBF = array[0..79] of DWord;
procedure Expand(var W: TBF); virtual;
procedure UpdateBlock(const AData); override;
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlSHA0 }
procedure TrhlSHA0.Expand(var W: TBF);
var
j: DWord;
begin
for j := 16 to 79 do
W[j] := ((W[j - 3] xor W[j - 8]) xor W[j - 14]) xor W[j - $10];
end;
procedure TrhlSHA0.UpdateBlock(const AData);
const
G: array[1..4] of LongWord = ($5A827999, $6ED9EBA1, $8F1BBCDC, $CA62C1D6);
var
A, B, C, D, E: DWord;
W: array[0..79] of DWord;
begin
FillChar({%H-}W[0], SizeOf(W), 0);
ConvertBytesToDWordsSwapOrder(AData, 64, W);
Expand(W);
A:= FStates[0];
B:= FStates[1];
C:= FStates[2];
D:= FStates[3];
E:= FStates[4];
Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + G[1] + W[ 0]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + G[1] + W[ 1]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + G[1] + W[ 2]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + G[1] + W[ 3]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + G[1] + W[ 4]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + G[1] + W[ 5]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + G[1] + W[ 6]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + G[1] + W[ 7]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + G[1] + W[ 8]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + G[1] + W[ 9]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + G[1] + W[10]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + G[1] + W[11]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + G[1] + W[12]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + G[1] + W[13]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + G[1] + W[14]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + (D xor (B and (C xor D))) + G[1] + W[15]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + (C xor (A and (B xor C))) + G[1] + W[16]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + (B xor (E and (A xor B))) + G[1] + W[17]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + (A xor (D and (E xor A))) + G[1] + W[18]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + (E xor (C and (D xor E))) + G[1] + W[19]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + G[2] + W[20]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + G[2] + W[21]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + G[2] + W[22]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + G[2] + W[23]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + G[2] + W[24]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + G[2] + W[25]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + G[2] + W[26]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + G[2] + W[27]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + G[2] + W[28]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + G[2] + W[29]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + G[2] + W[30]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + G[2] + W[31]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + G[2] + W[32]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + G[2] + W[33]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + G[2] + W[34]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + G[2] + W[35]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + G[2] + W[36]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + G[2] + W[37]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + G[2] + W[38]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + G[2] + W[39]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + G[3] + W[40]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + G[3] + W[41]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + G[3] + W[42]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + G[3] + W[43]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + G[3] + W[44]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + G[3] + W[45]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + G[3] + W[46]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + G[3] + W[47]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + G[3] + W[48]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + G[3] + W[49]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + G[3] + W[50]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + G[3] + W[51]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + G[3] + W[52]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + G[3] + W[53]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + G[3] + W[54]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + ((B and C) or (D and (B or C))) + G[3] + W[55]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + ((A and B) or (C and (A or B))) + G[3] + W[56]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + ((E and A) or (B and (E or A))) + G[3] + W[57]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + ((D and E) or (A and (D or E))) + G[3] + W[58]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + ((C and D) or (E and (C or D))) + G[3] + W[59]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + G[4] + W[60]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + G[4] + W[61]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + G[4] + W[62]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + G[4] + W[63]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + G[4] + W[64]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + G[4] + W[65]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + G[4] + W[66]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + G[4] + W[67]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + G[4] + W[68]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + G[4] + W[69]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + G[4] + W[70]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + G[4] + W[71]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + G[4] + W[72]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + G[4] + W[73]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + G[4] + W[74]); C:= (C shl 30) or (C shr 2);
Inc(E,((A shl 5) or (A shr 27)) + (B xor C xor D) + G[4] + W[75]); B:= (B shl 30) or (B shr 2);
Inc(D,((E shl 5) or (E shr 27)) + (A xor B xor C) + G[4] + W[76]); A:= (A shl 30) or (A shr 2);
Inc(C,((D shl 5) or (D shr 27)) + (E xor A xor B) + G[4] + W[77]); E:= (E shl 30) or (E shr 2);
Inc(B,((C shl 5) or (C shr 27)) + (D xor E xor A) + G[4] + W[78]); D:= (D shl 30) or (D shr 2);
Inc(A,((B shl 5) or (B shr 27)) + (C xor D xor E) + G[4] + W[79]); C:= (C shl 30) or (C shr 2);
Inc(FStates[0], A);
Inc(FStates[1], B);
Inc(FStates[2], C);
Inc(FStates[3], D);
Inc(FStates[4], E);
end;
constructor TrhlSHA0.Create;
begin
HashSize := 20;
BlockSize := 64;
end;
procedure TrhlSHA0.Init;
begin
inherited Init;
FStates[0] := $67452301;
FStates[1] := $EFCDAB89;
FStates[2] := $98BADCFE;
FStates[3] := $10325476;
FStates[4] := $C3D2E1F0;
end;
procedure TrhlSHA0.Final(var ADigest);
var
bits: QWord;
pad: TBytes;
padIndex: DWord;
begin
bits := QWord(FProcessedBytes) * 8;
if FBuffer.Pos < 56 then
padIndex := 56 - FBuffer.Pos
else
padIndex := 120 - FBuffer.Pos;
SetLength(pad, padIndex + 8);
FillChar(pad[0], Length(pad), 0);
pad[0] := $80;
bits := SwapEndian(bits);
Move(bits, pad[padIndex], SizeOf(bits));
Inc(padIndex, 8);
UpdateBytes(pad[0], padIndex);
ConvertDWordsToBytesSwapOrder(FStates, Length(FStates), ADigest)
end;
end.
|
(**
This module contains a Delphi IDE Wizard which implements support for running
external tools before and after the compilation of the current project.
@Version 1.0
@Date 05 Jan 2018
@Author David Hoyle
**)
Unit ITHelper.Wizard;
Interface
Uses
ToolsAPI,
Menus,
ITHelper.Interfaces;
{$INCLUDE 'CompilerDefinitions.inc'}
Type
(** An enumerate to define which dialogue should be displayed. **)
TSetting = (seProject, seBefore, seAfter, seZip);
(** This class implements the IDE Wizard which provides the IDE interface
to the package. **)
TITHWizard = Class(TNotifierObject, IOTAWizard)
Strict Private
FAboutBoxIndex : Integer;
FGlobalOps : IITHGlobalOptions;
FTestingHelperMenu : TMenuItem;
FProjectMgrMenuIndex : Integer;
FProjectMgrMenuNotifier : IOTAProjectMenuItemCreatorNotifier;
FIDENotifierIndex : Integer;
//FHTMLHelpCookie : THandle;
Strict Protected
// IOTAWizard
Procedure Execute;
Function GetIDString: String;
Function GetName: String;
Function GetState: TWizardState;
// General Methods
Procedure CreateMenus;
Procedure ProjectOptions(Const Project: IOTAProject);
Procedure BeforeCompilation(Const Project: IOTAProject);
Procedure AfterCompilation(Const Project: IOTAProject);
Procedure ZIPOptions(Const Project: IOTAProject);
// Event Handler
Procedure BeforeCompilationClick(Sender: TObject);
Procedure AfterCompilationClick(Sender: TObject);
Procedure ToggleEnabled(Sender: TObject);
Procedure FontDialogueClick(Sender: TObject);
Procedure ZIPDialogueClick(Sender: TObject);
Procedure ZIPDialogueUpdate(Sender: TObject);
Procedure GlobalOptionDialogueClick(Sender: TObject);
Procedure ProjectOptionsClick(Sender: TObject);
Procedure ProjectOptionsUpdate(Sender: TObject);
Procedure UpdateEnabled(Sender: TObject);
Procedure BeforeCompilationUpdate(Sender: TObject);
Procedure AfterCompilationUpdate(Sender: TObject);
Procedure HelpClick(Sender : TObject);
Public
Constructor Create;
Destructor Destroy; Override;
Procedure ConfigureOptions(Const Project: IOTAProject; Const Setting: TSetting);
End;
Implementation
Uses
Windows,
SysUtils,
Dialogs,
Graphics,
Forms,
StrUtils,
Variants,
ActnList,
ITHelper.EnabledOptions,
ITHelper.ProcessingForm,
ITHelper.ExternalProcessInfo,
ITHelper.ProjectManagerMenuInterface,
ITHelper.FontDialogue,
ITHelper.ZIPDialogue,
ITHelper.GlobalOptionsDialogue,
ITHelper.ProjectOptionsDialogue,
ITHelper.SplashScreen,
ITHelper.AboutBox,
ITHelper.IDENotifierInterface,
ITHelper.Types,
ITHelper.ConfigurationForm,
ITHelper.TestingHelperUtils,
ITHelper.GlobalOptions;
Const
(** A constant to define the failed state of a wizard / notifier interface. **)
iWizardFailState = -1;
(**
This method displays the After Compilation options dialogue for configuring tools to be run after a
successful compilation.
@precon Project must be a valid instance.
@postcon Displays the After Compilation options dialogue for configuring tools to be run after a
successful compilation.
@param Project as an IOTAProject as a constant
**)
Procedure TITHWizard.AfterCompilation(Const Project: IOTAProject);
Begin
If TfrmITHConfigureDlg.Execute(Project, FGlobalOps, dtAfter) Then
FGlobalOps.Save;
End;
(**
This is an on click event handler for the After Compilation action.
@precon None.
@postcon Invokes the After Compilation dialogue.
@param Sender as a TObject
**)
Procedure TITHWizard.AfterCompilationClick(Sender: TObject);
Begin
If ActiveProject <> Nil Then
AfterCompilation(ActiveProject);
End;
(**
This is an on update event handler for the After Compilation action.
@precon None.
@postcon Enables or disables the action based on the availability of a project.
@param Sender as a TObject
**)
Procedure TITHWizard.AfterCompilationUpdate(Sender: TObject);
ResourceString
strAfterCompilationOptionsFor = 'After Compilation Options for %s';
strAfterCompilationOptionsNoActiveProject = 'After Compilation Options: No Active Project!';
Var
strProject: String;
P : IOTAProject;
A : TAction;
Begin
If Sender Is TAction Then
Begin
A := Sender As TAction;
P := ActiveProject;
If P <> Nil Then
Begin
A.Enabled := True;
strProject := GetProjectName(P);
A.Caption := Format(strAfterCompilationOptionsFor, [strProject])
End
Else
Begin
A.Caption := strAfterCompilationOptionsNoActiveProject;
A.Enabled := False;
End;
End;
End;
(**
This method displays the Before Compilation options dialogue for configuring tools to be run before a
successful compilation.
@precon Project must be a valid instance.
@postcon Displays the Before Compilation options dialogue for configuring tools to be run before a
successful compilation.
@param Project as an IOTAProject as a constant
**)
Procedure TITHWizard.BeforeCompilation(Const Project: IOTAProject);
Begin
If TfrmITHConfigureDlg.Execute(Project, FGlobalOps, dtBefore) Then
FGlobalOps.Save;
End;
(**
This is an on click event handler for the Before Compilation action.
@precon None.
@postcon Displays the before compilation dialogue.
@param Sender as a TObject
**)
Procedure TITHWizard.BeforeCompilationClick(Sender: TObject);
Begin
If ActiveProject <> Nil Then
BeforeCompilation(ActiveProject);
End;
(**
This is an on update event handler for the Before Compilation action.
@precon None.
@postcon Enables or disables the action based on the availability of a project.
@param Sender as a TObject
**)
Procedure TITHWizard.BeforeCompilationUpdate(Sender: TObject);
ResourceString
strBeforeCompilationOptionsFor = 'Before Compilation Options for %s';
strBeforeCompilationOptionsNoActiveProject = 'Before Compilation Options: No Active Project!';
Var
P : IOTAProject;
strProject: String;
A : TAction;
Begin
If Sender Is TAction Then
Begin
A := Sender As TAction;
P := ActiveProject;
If P <> Nil Then
Begin
A.Enabled := True;
strProject := GetProjectName(P);
A.Caption := Format(strBeforeCompilationOptionsFor, [strProject])
End
Else
Begin
A.Caption := strBeforeCompilationOptionsNoActiveProject;
A.Enabled := False;
End;
End;
End;
(**
This method displays the options dialogue for the given project.
@precon None.
@postcon Displays the options dialogue for the given project.
@param Project as an IOTAProject as a constant
@param Setting as a TSetting as a constant
**)
Procedure TITHWizard.ConfigureOptions(Const Project: IOTAProject; Const Setting: TSetting);
Begin
If Project <> Nil Then
Case Setting Of
seProject: ProjectOptions(Project);
seBefore: BeforeCompilation(Project);
seAfter: AfterCompilation(Project);
seZip: ZIPOptions(Project);
End;
End;
(**
This is the constructor method for the TTestingHelperWizard class.
@precon None.
@postcon Initialises the wizard and creates a menu item.
**)
Constructor TITHWizard.Create;
Var
PM : IOTAProjectManager;
Begin
Inherited Create;
FIDENotifierIndex := iWizardFailState;
InstallSplashScreen;
FAboutBoxIndex := AddAboutBoxEntry;
FProjectMgrMenuNotifier := TITHProjectManagerMenu.Create(Self);
If Supports(BorlandIDEServices, IOTAProjectManager, PM) Then
{$IFNDEF D2010}
FProjectMgrMenu := PM.AddMenuCreatorNotifier(FProjectMgrMenuNotifier);
{$ELSE}
FProjectMgrMenuIndex := PM.AddMenuItemCreatorNotifier(FProjectMgrMenuNotifier);
{$ENDIF}
CreateMenus;
FGlobalOps := TITHGlobalOptions.Create;
FIDENotifierIndex := (BorlandIDEServices As IOTAServices).AddNotifier(
TITHelperIDENotifier.Create(FGlobalOps));
//FHTMLHelpCookie := HTMLHelp(Application.Handle, Nil, HH_INITIALIZE, 0);
End;
(**
This method creates the Integrated Testing Helper IDE menus.
@precon None.
@postcon The menus are created.
@nocheck HardCodedString
**)
Procedure TITHWizard.CreateMenus;
Begin
FTestingHelperMenu := CreateMenuItem('ITHTestingHelper', '&Testing Helper', 'Tools', Nil, Nil, True, False, '');
CreateMenuItem('ITHEnabled', 'Oops...', 'ITHTestingHelper', ToggleEnabled, UpdateEnabled, False, True, 'Ctrl+Shift+Alt+F9', clFuchsia);
CreateMenuItem('ITHSeparator1', '', 'ITHTestingHelper', Nil, Nil, False, True, '');
CreateMenuItem('ITHGlobalOptions', '&Global Options...', 'ITHTestingHelper', GlobalOptionDialogueClick, Nil, False, True, '', clFuchsia);
CreateMenuItem('ITHProjectOptions', '&Project Options...', 'ITHTestingHelper', ProjectOptionsClick, ProjectOptionsUpdate, False, True, '', clFuchsia);
CreateMenuItem('ITHBeforeCompilation', '&Before Compilation Tools...', 'ITHTestingHelper', BeforeCompilationClick, BeforeCompilationUpdate, False, True, '', clFuchsia);
CreateMenuItem('ITHAfterCompilation', '&After Compilation Tools...', 'ITHTestingHelper', AfterCompilationClick, AfterCompilationUpdate, False, True, '', clFuchsia);
CreateMenuItem('ITHZIPDlg', '&ZIP Options...', 'ITHTestingHelper', ZIPDialogueClick, ZIPDialogueUpdate, False, True, '', clFuchsia);
CreateMenuItem('ITHFontDlg', 'Message &Fonts...', 'ITHTestingHelper', FontDialogueClick, Nil, False, True, '', clOlive);
CreateMenuItem('ITHSeparator2', '', 'ITHTestingHelper', Nil, Nil, False, True, '');
CreateMenuItem('ITHHelp', '&Help...', 'ITHTestingHelper', HelpClick, Nil, False, True, '');
End;
(**
This is the destructor method for the TTestingHelperWizard class.
@precon None.
@postcon Removes the meun item from the IDE.
**)
Destructor TITHWizard.Destroy;
Var
PM : IOTAProjectManager;
Begin
HTMLHelp(0, Nil, HH_CLOSE_ALL, 0);
//HTMLHelp(Application.Handle, Nil, HH_UNINITIALIZE, FHTMLHelpCookie);
If FIDENotifierIndex > iWizardFailState Then
(BorlandIDEServices As IOTAServices).RemoveNotifier(FIDENotifierIndex);
{$IFNDEF D2005}
FMenuTimer.Free;
{$ENDIF}
FTestingHelperMenu.Free;
{$IFNDEF DXE20}
//: @bug This has been removed from Delphi XE2 as it generates an Access Violation as
//: the IDE closes down.
ClearMessages([cmCompiler, cmGroup]);
{$ENDIF}
FGlobalOps := Nil;
If FProjectMgrMenuIndex > -1 Then
If Supports(BorlandIDEServices, IOTAPRojectManager, PM) Then
{$IFNDEF D2010}
PM.RemoveMenuCreatorNotifier(FProjectMgrMenuIndex);
{$ELSE}
PM.RemoveMenuItemCreatorNotifier(FProjectMgrMenuIndex);
{$ENDIF}
RemoveAboutBoxEntry(FAboutBoxIndex);
Inherited Destroy;
End;
(**
This method is a null implementation of the Wizards Execute interface.
@precon None.
@postcon None.
@nocheck EmptyMethod
**)
Procedure TITHWizard.Execute;
Begin //FI:W519
End;
(**
This is an on click event handler for the Font Dialogue menu item.
@precon None.
@postcon Displays the message fonts dialogue.
@param Sender as a TObject
**)
Procedure TITHWizard.FontDialogueClick(Sender: TObject);
Begin
TfrmITHFontDialogue.Execute(FGlobalOps);
End;
(**
This method is an implementation of the Wizards GetIDString interface.
@precon None.
@postcon Returns the IDE Wizard`s ID String.
@return a String
**)
Function TITHWizard.GetIDString: String;
Const
strIDString = 'Seasons.Fall.Music.Integrated.Testing.Helper';
Begin
Result := strIDString;
End;
(**
This method is an implementation of the Wizards GetName interface.
@precon None.
@postcon Returns the IDE Wizard`s Name.
@return a string
**)
Function TITHWizard.GetName: String;
ResourceString
strName = 'Integrated Testing Helper - Support for running external tools before and after ' +
'compilations.';
Begin
Result := strName;
End;
(**
This method is an implementation of the Wizards GetState interface.
@precon None.
@postcon Returns the IDE Wizard`s State.
@return a TWizardState
**)
Function TITHWizard.GetState: TWizardState;
Begin
Result := [wsEnabled];
End;
(**
This is an on click event handler for the Global Options dialogue action.
@precon None.
@postcon Displazs the Global Options dialogue.
@param Sender as a TObject
**)
Procedure TITHWizard.GlobalOptionDialogueClick(Sender: TObject);
Begin
TfrmITHGlobalOptionsDialogue.Execute(FGlobalOps);
End;
(**
This is an on click event handler for the Help action.
@precon None.
@postcon Displays the HTML Help for the add-in.
@param Sender as a TObject
**)
Procedure TITHWizard.HelpClick(Sender: TObject);
Const
strHelpStartPage = 'Welcome';
Begin
HTMLHelp(0, PChar(ITHHTMLHelpFile(strHelpStartPage)), HH_DISPLAY_TOC, 0);
End;
(**
This method displays the Project Options dialogue.
@precon Project must be a valid instance.
@postcon Displays the Project Options dialogue.
@param Project as an IOTAProject as a constant
**)
Procedure TITHWizard.ProjectOptions(Const Project: IOTAProject);
Begin
TfrmITHProjectOptionsDialogue.Execute(FGlobalOps, Project);
End;
(**
This is an on click event handler for the Project Options action.
@precon None.
@postcon Dispays the projects options dialogue.
@param Sender as a TObject
**)
Procedure TITHWizard.ProjectOptionsClick(Sender: TObject);
Begin
If ActiveProject <> Nil Then
ProjectOptions(ActiveProject);
End;
(**
This is an on update event handler for the Project Options action.
@precon None.
@postcon Updates the project options action caption based on the avtive project.
@param Sender as a TObject
**)
Procedure TITHWizard.ProjectOptionsUpdate(Sender: TObject);
ResourceString
strProjectOptionsFor = 'Project Options for %s';
strProjectOptionsNoActiveProject = 'Project Options: No Active Project!';
Var
P : IOTAProject;
strProject: String;
A : TAction;
Begin
If Sender Is TAction Then
Begin
A := Sender As TAction;
P := ActiveProject;
If P <> Nil Then
Begin
A.Enabled := True;
strProject := GetProjectName(P);
A.Caption := Format(strProjectOptionsFor, [strProject])
End
Else
Begin
A.Caption := strProjectOptionsNoActiveProject;
A.Enabled := False;
End;
End;
End;
(**
This is an on click event handler for the Enable Menu item.
@precon None.
@postcon Enables / Disable the ITHelper for the current project.
@param Sender as a TObject
**)
Procedure TITHWizard.ToggleEnabled(Sender: TObject);
ResourceString
strThereNotActiveProjectToEnabledOrDisable = 'There is not active project to enabled or disable.';
Var
strProjectGroup: String;
PG : IOTAProjectGroup;
Ops : TITHEnabledOptions;
Begin
PG := ProjectGroup;
If PG <> Nil Then
Begin
Ops := FGlobalOps.ProjectGroupOps;
If TfrmITHEnabledOptions.Execute(strProjectGroup, Ops) Then
FGlobalOps.ProjectGroupOps := Ops;
End
Else
ShowMessage(strThereNotActiveProjectToEnabledOrDisable);
End;
(**
This method is an on update event handler for the Enabled action.
@precon None.
@postcon Enables or disables the action based on the availability of a project.
@param Sender as a TObject
**)
Procedure TITHWizard.UpdateEnabled(Sender: TObject);
ResourceString
strITHelperFor = 'ITHelper for %s';
strNotAvailable = 'Not Available';
Var
strProjectGroup: String;
PG : IOTAProjectGroup;
A : TAction;
Begin
If Sender Is TAction Then
Begin
A := Sender As TAction;
PG := ProjectGroup;
If PG <> Nil Then
Begin
A.Enabled := True;
strProjectGroup := ExtractFileName(PG.FileName);
A.Caption := Format(strITHelperFor, [strProjectGroup]);
End
Else
Begin
A.Caption := strNotAvailable;
A.Enabled := False;
End;
End;
End;
(**
This is an on click event handler for the ZIP Dialogue action.
@precon None.
@postcon Displays thezipping options dialogue.
@param Sender as a TObject
**)
Procedure TITHWizard.ZIPDialogueClick(Sender: TObject);
Begin
If ActiveProject <> Nil Then
ZIPOptions(ActiveProject);
End;
(**
This is an on update event handler for the ZIP Dialogue action.
@precon None.
@postcon Updates the actions cption.
@param Sender as a TObject
**)
Procedure TITHWizard.ZIPDialogueUpdate(Sender: TObject);
ResourceString
strZIPOptionsFor = 'ZIP Options for %s';
strZIPOptionsNoActiveProject = 'ZIP Options: No Active Project!';
Var
P : IOTAProject;
strProject: String;
A : TAction;
Begin
If Sender Is TAction Then
Begin
A := Sender As TAction;
P := ActiveProject;
If P <> Nil Then
Begin
A.Enabled := True;
strProject := GetProjectName(P);
A.Caption := Format(strZIPOptionsFor, [strProject])
End
Else
Begin
A.Caption := strZIPOptionsNoActiveProject;
A.Enabled := False;
End;
End;
End;
(**
This method displays the ZIP Options dialogue for configuring the zipping of the project after a
successful compilation.
@precon Project must be a valid instance.
@postcon Displays the ZIP Options dialogue for configuring the zipping of the project after a
successful compilation.
@param Project as an IOTAProject as a constant
**)
Procedure TITHWizard.ZIPOptions(Const Project: IOTAProject);
Begin
TfrmITHZIPDialogue.Execute(Project, FGlobalOps);
End;
End.
|
unit dlg_StreetRange;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ToolWin, ComCtrls;
type
TStreetRangeDialog = class(TForm)
MainToolBar: TToolBar;
SaveAndExitButton: TSpeedButton;
CancelButton: TSpeedButton;
StartingRangeGroupBox: TGroupBox;
edt_StartingStreetNumber: TEdit;
Label1: TLabel;
Label2: TLabel;
edt_StartingStreet: TEdit;
EndingStreetGroupBox: TGroupBox;
Label3: TLabel;
Label4: TLabel;
edt_EndingStreetNumber: TEdit;
edt_EndingStreet: TEdit;
procedure SaveAndExitButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
StartingStreetNumber,
StartingStreet,
EndingStreetNumber,
EndingStreet : String;
Procedure Load(_StartingStreetNumber : String;
_StartingStreet : String;
_EndingStreetNumber : String;
_EndingStreet : String);
Procedure Save;
end;
var
StreetRangeDialog: TStreetRangeDialog;
implementation
{$R *.DFM}
uses Utilitys, GlblCnst;
{===============================================================}
Procedure TStreetRangeDialog.FormKeyPress( Sender: TObject;
var Key: Char);
begin
If _Compare(Key, #13, coEqual)
then
begin
Key := #0;
Perform(WM_NEXTDLGCTL, 0, 0);
end;
end; {FormKeyPress}
{===============================================================}
Procedure TStreetRangeDialog.Load(_StartingStreetNumber : String;
_StartingStreet : String;
_EndingStreetNumber : String;
_EndingStreet : String);
begin
edt_StartingStreetNumber.Text := _StartingStreetNumber;
edt_StartingStreet.Text := _StartingStreet;
edt_EndingStreetNumber.Text := _EndingStreetNumber;
edt_EndingStreet.Text := _EndingStreet;
end; {Load}
{===============================================================}
Procedure TStreetRangeDialog.Save;
begin
StartingStreetNumber := edt_StartingStreetNumber.Text;
StartingStreet := edt_StartingStreet.Text;
EndingStreetNumber := edt_EndingStreetNumber.Text;
EndingStreet := edt_EndingStreet.Text;
end; {Save}
{===============================================================}
Procedure TStreetRangeDialog.SaveAndExitButtonClick(Sender: TObject);
begin
Save;
ModalResult := mrOK;
end; {SaveAndExitButtonClick}
{===============================================================}
Procedure TStreetRangeDialog.CancelButtonClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
end.
|
{Test cases for XSalsa20 stream cipher, (c) 2009 W.Ehrhardt}
program T_S20_ST;
{$i std.inc}
{$ifdef APPCONS}
{$apptype console}
{$endif}
{$ifndef FPC}
{$N+}
{$endif}
uses
{$ifdef WINCRT}
WinCRT,
{$endif}
salsa20,mem_util;
type
trec = record
key: string[64];
IV : string[48];
pt : string[240];
ct : string[240];
end;
{Test case from Wei Dai's Crypto++ 5.60}
const
test: array[1..10] of trec = (
(key:'3154d3f5bb56b00b34a255425057e99ed9effd1cb0168d16157fd769ddc665ba';
IV :'f7f9f18f9648f6dc06ac643ea77f1493a9fea3390a98bb0c';
pt :'80a488703cf316be904ac8394437ea02ae2c027b7880ebec58416429ea060db543839d781d82a0fa209077e4b1';
ct :'a07abc8ef3641cf33179296ca401bb291a9547d3e6d1b0886ac31d26d2f3281a6a568cc042593132a3cc1082be'),
(key:'7066fe1125429407b653fd090262bed2a3f7f3be2fa8f160f3344f327b1e53da';
IV :'beec3787c335739fa5d7ad15b85b7e3e7c9438367434872a';
pt :'9dad7f5ca1';
ct :'014a1f27cc'),
(key:'81426f03ae1578d8ec1407827db18640d9d90d2bb773971f4ef14f859bc19e06';
IV :'479961f75954ed4f8024108cdb149ca3fd53e6a239a01e86';
pt :'9cd08cf58e13e94e02c9a40269875392251353223f5329412e2a5e34328ea18c414d4c730b4e1c0bc140953f4ecf4ffc8aec963e59305d4d';
ct :'db3ea5b5fdc9671ec56b3f1cecbb2a552b0ea4ce9be508863f3dfb3238d4fb91b896727357fe454a08114200ea7226787fd2ab154d53eac8'),
(key:'ad1a5c47688874e6663a0f3fa16fa7efb7ecadc175c468e5432914bdb480ffc6';
IV :'e489eed440f1aae1fac8fb7a9825635454f8f8f1f52e2fcc';
pt :'aa6c1e53580f03a9abb73bfdadedfecada4c6b0ebe020ef10db745e54ba861caf65f0e40dfc520203bb54d29e0a8f78f16b3f1aa525d6bfa'+
'33c54726e59988cfbec78056';
ct :'02fe84ce81e178e7aabdd3ba925a766c3c24756eefae33942af75e8b464556b5997e616f3f2dfc7fce91848afd79912d9fb55201b5813a5a'+
'074d2c0d4292c1fd441807c5'),
(key:'053a02bedd6368c1fb8afc7a1b199f7f7ea2220c9a4b642a6850091c9d20ab9c';
IV :'c713eea5c26dad75ad3f52451e003a9cb0d649f917c89dde';
pt :'8f0a8a164760426567e388840276de3f95cb5e3fadc6ed3f3e4fe8bc169d9388804dcb94b6587dbb66cb0bd5f87b8e98b52af37ba290629b'+
'858e0e2aa7378047a26602';
ct :'516710e59843e6fbd4f25d0d8ca0ec0d47d39d125e9dad987e0518d49107014cb0ae405e30c2eb3794750bca142ce95e290cf95abe15e822'+
'823e2e7d3ab21bc8fbd445'),
(key:'b3c260036b79cd3345e04cbee474dfea3a7c773db2ccb29d4c36a1b8c8b252e7';
IV :'1277840fe82046c024e6f4f53b4ff761c7c9bd1fea6c855a';
pt :'6a6dac1bc93b9b5c0dde0d1e6a534914dc2a6d51e6f8af3e9d42b88bedc2173782a2314b33f795cc2e4536829871d77186168f5461d18130'+
'581664586256';
ct :'ff5e71022c6522998a2d10843fda170796a70d186e5fca2afcf529c6d075c5212c793fb322c1675d0bd3cc6b18f2715678812e81a8727a2d'+
'6ac1158eacf6'),
(key:'ea060c72f6e0080fd4a9a2131c9d684902415cab34fce4e52d62273e3c385f37';
IV :'5826043957a27509423fdd82f34935928a4b23a84ede72c8';
pt :'20ae58dbf5c20225c35518711a86a19a61d5ba47ab17e8c5fa9658333d40ed31bffb79cde927c36baf61ed8df37acac330f64471bd91d90b'+
'fafa72dc8cdb6ed95ec6610cd6e8f2859255216a3eb4b573410d5644a40e4f0fa785d556304489c0023a1991eb0d01b5';
ct :'6025c4d5bcc769cc3e67b88340b4101690eb283654c761f8a0af360926313129f16d1c9358ecbaf66acd85787c7c1f52a953bc05e91d43bf'+
'3d94d341bffc5913435fb3a8e6264ccd1c355472929a140fe30a22689b055082c70395e0b070a3f0967ab36848cdf3d9'),
(key:'0f2850f98634181f49e53bf49d2f822fbf75e5f77c6cd7487541c514a4101ce7';
IV :'d6defb4e74c327d89123bdc1d1c6d2fce6b745079bc2c9ef';
pt :'a064bd9bdab0ee26530c2d26be556cd67295180bca445dfc87954bc51b28a21b606a229cf5a41fa104c51c3f32003a65064ff73e66691e4d'+
'2b1a22d236232be18677d54aba7ad49edcc9284897a7f88945513460166e5dfd7650959c05328abc0a7e95c352dbc227ca17';
ct :'51de41664070aec657612a57641c0c83ae14f5b3b25b25d916e0cdfae1c1bd21f7b47d9ab02b6841e115394cad58a568c1d7c2559a1d3fcd'+
'9cb4b25529d26e475ae313e6487538d16376a6b24e5cf27d2dbf4c83bd18996594f60549f34a8683b04d05198893a816adbb'),
(key:'5cf680e8a11eb005d03fdc3d4ec0e129e6aceb47262dee6c452a5b8b0ef1b450';
IV :'6a6920ddba39b5a2640976ca10c97bf308a8cdd70ea98260';
pt :'1f322b31f5f577a596b0fbe567864c7ce2973b41f924205defe08e2866b7fb5c1814d664d33957614e91668bb15d9848ffb93dc08c1f74c5'+
'f5e1f88148d1a1a7ad47395b75834de4988adfbf7e58a38157544c2be5b913152c1d00';
ct :'64d6c9ca4db201d95afc0dce28f6e47d51c2856ccbbc8f4c2e2bd2d834aca165dedd117b0be9a7dcd21eb22b508f4ecd0236075b064a0ced'+
'23e324b18b2bf2cda1c4416f78c740e51ce687cd37842be368fc4e6ba7cb312d89ea7a'),
(key:'0f2850f98634181f49e53bf49d2f822fbf75e5f77c6cd7487541c514a4101ce7';
IV :'d6defb4e74c327d89123bdc1d1c6d2fce6b745079bc2c9ef';
pt :'a064bd9bdab0ee26530c2d26be556cd67295180bca445dfc87954bc51b28a21b606a229cf5a41fa104c51c3f32003a65064ff73e66691e4d'+
'2b1a22d236232be18677d54aba7ad49edcc9284897a7f88945513460166e5dfd7650959c05328abc0a7e95c352dbc227ca17';
ct :'51de41664070aec657612a57641c0c83ae14f5b3b25b25d916e0cdfae1c1bd21f7b47d9ab02b6841e115394cad58a568c1d7c2559a1d3fcd'+
'9cb4b25529d26e475ae313e6487538d16376a6b24e5cf27d2dbf4c83bd18996594f60549f34a8683b04d05198893a816adbb')
);
var
ptb, ctb, tmp: array[0..123] of byte;
k256: array[0..31] of byte;
n192: array[0..23] of byte;
ctx: salsa_ctx;
i: integer;
sl, mlen: word;
begin
writeln('Test cases for XSalsa20 stream cipher (c) 2009 W.Ehrhardt');
writeln('XSalsa20 selftest: ', xsalsa_selftest);
for i:=1 to 10 do begin
with test[i] do begin
write('Test',i:3, ' - ');
Hex2Mem(key, @k256, sizeof(k256), sl);
if sl<>sizeof(k256) then begin
writeln('Invalid key size or conversion error');
halt;
end;
Hex2Mem(IV, @n192, sizeof(n192), sl);
if sl<>sizeof(n192) then begin
writeln('Invalid IV size or conversion error');
halt;
end;
Hex2Mem(pt, @ptb, sizeof(ptb) , sl);
Hex2Mem(ct, @ctb, sizeof(ctb) , mlen);
if mlen<>sl then begin
writeln('different sizes of plaintext and ciphertext or conversion error');
halt;
end;
xsalsa_setup(ctx, @k256, @n192);
xsalsa_encrypt_bytes(ctx, @ptb, @tmp, mlen);
write('EncBuf:', compmem(@ctb, @tmp, mlen):5);
xsalsa_setup(ctx, @k256, @n192);
xsalsa_decrypt_bytes(ctx, @ctb, @tmp, mlen);
write(', DecBuf:', compmem(@ptb, @tmp, mlen):5);
xsalsa_encrypt_packet(@k256, @n192, @ptb, @tmp, mlen);
write(', EncPack:', compmem(@ctb, @tmp, mlen):5);
xsalsa_decrypt_packet(@k256, @n192, @ctb, @tmp, mlen);
write(', DecPack:', compmem(@ptb, @tmp, mlen):5);
writeln;
end;
end;
end.
|
_______________________________________________________________
FRAKFFC.PAS Accompanies "Mimicking Mountains," by Tom Jeffery,
BYTE, December 1987, page 337
______________________________________________________________
program fractal_ffc;
const
size = 64; {Maximum index of array}
var
row, col, n, step, st : longint;
srf : array[0..size, 0..size] of longint; {The surface file}
ans : string[10];
srfile : file of longint;
H : real; {Roughness factor}
stepfactor : real;
function gauss : real;
{Returns a gaussian variable with mean = 0, variance = 1}
{Polar method due to Knuth, vol. 2, pp. 104, 113 }
{but found in "Smalltalk-80, Language and Implementation",}
{Goldberg and Robinson, p. 437.}
var
i : integer;
sum, v1, v2, s : real;
begin
sum := 0;
repeat
v1 := (random / maxint);
v2 := (random / maxint);
s := sqr(v1) + sqr(v2);
until s < 1;
s := sqrt(-2 * ln(s) / s) * v1;
gauss := s;
end;
procedure hordetail (row : longint);
{Calculates new points for one row}
var
disp, i, col : longint;
begin
col := 0;
while col < size do
begin
disp := Round(100 * (gauss * stepfactor)); {Random displacement}
srf[row, col + step] :=
(srf[row, col] + srf[row, col + 2 * step]) div 2; {Midpoint}
srf[row, col + step] := srf[row, col + step] + disp;{New point}
col := col + 2 * step;
end;
end;
procedure verdetail (col : longint);
{Calculates new points for one column}
var
disp, i, row : longint;
begin
row := 0;
while row < size do
begin
disp := Round(100 * (gauss * stepfactor)); {Random displacement}
srf[row + step, col] :=
(srf[row, col] + srf[row + 2 * step, col]) div 2; {Midpoint}
srf[row + step, col] := srf[row + step, col] + disp; {New point}
row := row + 2 * step;
end;
end;
procedure centdetail (row : longint);
{Calculates new points for centers of all cells in a row}
var
disp, i, col : longint;
begin
col := step;
while col < size do
begin
disp := Round(100 * (gauss * stepfactor)); {Random displacement}
srf[row, col] :=
(srf[row, col - step] + srf[row, col + step]
+ srf[row - step, col]
+ srf[row + step, col]) div 4; {Center Point}
srf[row, col] := srf[row, col] + disp; {New point}
col := col + 2 * step;
end;
end;
procedure detail;
{Calculates new points at current step size}
var
i, row, col : longint;
begin
row := 0;
col := 0;
while row <= size do
begin
hordetail(row);
row := row + 2 * step;
end;
while col <= size do
begin
verdetail(col);
col := col + 2 * step;
end;
row := step;
while row <= size - step do
begin
centdetail(row);
row := row + 2 * step;
end;
end;
procedure newsurface;
var
row, col : longint;
begin
step := size;
stepfactor := exp(2 * H * ln(step));
srf[0, 0] := Round(100 * (gauss * stepfactor));
srf[0, size] := Round(100 * (gauss * stepfactor));
srf[size, 0] := Round(100 * (gauss * stepfactor));
srf[size, size] := Round(100 * (gauss * stepfactor));
repeat
step := step div 2; {Go to smaller scale}
write('step = ');
writeln(step);
stepfactor := exp(2 * H * ln(step)); {Factor proportional to step size}
detail; {Calculate all new points at current step size}
until step = 1;
end;
begin
showtext;
write('H = ?');{Set roughness}
readln(H);
open(srfile, NewfileName('Surface File'));
st := tickcount;
randseed := st; {Randomize}
newsurface; {Calculate surface}
for row := 0 to size do
for col := 0 to size do
write(srfile, srf[row, col]); {Store surface in file}
close(srfile);
st := (tickcount - st) div 3600;
write(st);
writeln(' minutes');
end.
|
unit UnFechamentoContaController;
interface
uses Classes,
{ Fluente }
UnModelo, UnFechamentoDeContaModelo, UnAplicacao;
type
TFechamentoContaController = class
private
FFechamentoContaModelo: TFechamentoDeContaModelo;
public
function ExibirPagamentos(Sender: TObject): TFechamentoContaController;
function Modelo(const Modelo: TModelo): TFechamentoContaController;
function LancarDinheiro(Sender: TObject;
const AposRegistrarLancamento: TNotifyEvent): TFechamentoContaController;
function LancarCredito(Sender: TObject;
const AposRegistrarLancamento: TNotifyEvent): TFechamentoContaController;
function LancarDebito(Sender: TObject;
const AposRegistrarLancamento: TNotifyEvent): TFechamentoContaController;
function Preparar: TFechamentoContaController;
end;
implementation
uses SysUtils, Controls, Dialogs, DB,
{ Fluente }
UnLancarDinheiroView, UnLancarDebitoView, UnLancarCreditoView,
UnPagamentosView;
{ TFechamentoContaController }
function TFechamentoContaController.ExibirPagamentos(
Sender: TObject): TFechamentoContaController;
var
_valor: Real;
_dataSet: TDataSet;
_pagamentos: TPagamentosView;
begin
Result := Self;
end;
function TFechamentoContaController.LancarCredito(Sender: TObject;
const AposRegistrarLancamento: TNotifyEvent): TFechamentoContaController;
var
_lancarCreditoView: TLancarCreditoView;
begin
_lancarCreditoView := TLancarCreditoView.Create(nil)
.Modelo(Self.FFechamentoContaModelo)
.Preparar;
try
if (_lancarCreditoView.ShowModal = mrOk) and
Assigned(AposRegistrarLancamento) then
begin
AposRegistrarLancamento(Self);
end;
finally
_lancarCreditoView.Descarregar;
FreeAndNil(_lancarCreditoView);
end;
Result := Self;
end;
function TFechamentoContaController.LancarDebito(Sender: TObject;
const AposRegistrarLancamento: TNotifyEvent): TFechamentoContaController;
var
_lancarDebito: TLancarDebitoView;
begin
_lancarDebito := TLancarDebitoView.Create(nil)
.Modelo(Self.FFechamentoContaModelo)
.Preparar;
try
if (_lancarDebito.ShowModal = mrOk) and
Assigned(AposRegistrarLancamento) then
begin
AposRegistrarLancamento(Self);
end;
finally
_lancarDebito.Descarregar;
FreeAndNil(_lancarDebito);
end;
Result := Self;
end;
function TFechamentoContaController.LancarDinheiro(Sender: TObject;
const AposRegistrarLancamento: TNotifyEvent): TFechamentoContaController;
var
_valor: Real;
_dataSet: TDataSet;
_lancarDinheiroView: ITela;
begin
_dataSet := Self.FFechamentoContaModelo.DataSet;
if _dataSet.FieldByName('SALDO_TOTAL').AsString = '' then
_valor := 0
else
_valor := StrToFloat(_dataSet.FieldByName('SALDO_TOTAL').AsString);
Self.FFechamentoContaModelo.Parametros.GravarParametro('total', FloatToStr(_valor));
_lancarDinheiroView := TLancarDinheiroView.Create(nil)
.Modelo(Self.FFechamentoContaModelo)
.Preparar;
try
if (_lancarDinheiroView.ExibirTela = mrOk) and
Assigned(AposRegistrarLancamento) then
begin
AposRegistrarLancamento(Self);
end;
finally
_lancarDinheiroView.Descarregar;
FreeAndNil(_lancarDinheiroView);
end;
Result := Self;
end;
function TFechamentoContaController.Modelo(
const Modelo: TModelo): TFechamentoContaController;
begin
Self.FFechamentoContaModelo := (Modelo as TFechamentoDeContaModelo);
Result := Self;
end;
function TFechamentoContaController.Preparar: TFechamentoContaController;
begin
Result := Self;
end;
end.
|
unit BodyVariationJedecQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, 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, Vcl.StdCtrls, DSWrap;
type
TBodyVariationJedecW = class(TDSWrap)
private
FIDBodyVariation: TFieldWrap;
FIDJEDEC: TFieldWrap;
FID: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
property IDBodyVariation: TFieldWrap read FIDBodyVariation;
property IDJEDEC: TFieldWrap read FIDJEDEC;
property ID: TFieldWrap read FID;
end;
TQueryBodyVariationJedec = class(TQueryBase)
private
FW: TBodyVariationJedecW;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
function SearchByIDJEDEC(AIDBodyVariation, AIDJEDEC: Integer;
TestResult: Integer = -1): Integer;
function SearchByIDBodyVariation(AIDBodyVariation: Integer): Integer;
procedure UpdateJEDEC(AIDBodyVariation: Integer;
AJedecIDArr: TArray<Integer>);
property W: TBodyVariationJedecW read FW;
{ Public declarations }
end;
implementation
uses
StrHelper, System.Generics.Collections;
{$R *.dfm}
constructor TQueryBodyVariationJedec.Create(AOwner: TComponent);
begin
inherited;
FW := TBodyVariationJedecW.Create(FDQuery);
end;
function TQueryBodyVariationJedec.SearchByIDJEDEC(AIDBodyVariation,
AIDJEDEC: Integer; TestResult: Integer = -1): Integer;
begin
Assert(AIDBodyVariation > 0);
Assert(AIDJEDEC > 0);
// Ищем
Result := SearchEx([TParamRec.Create(W.IDBodyVariation.FullName,
AIDBodyVariation), TParamRec.Create(W.IDJEDEC.FullName, AIDJEDEC)],
TestResult);
end;
function TQueryBodyVariationJedec.SearchByIDBodyVariation(AIDBodyVariation
: Integer): Integer;
begin
Assert(AIDBodyVariation > 0);
// Ищем
Result := SearchEx([TParamRec.Create(W.IDBodyVariation.FullName,
AIDBodyVariation)]);
end;
procedure TQueryBodyVariationJedec.UpdateJEDEC(AIDBodyVariation: Integer;
AJedecIDArr: TArray<Integer>);
var
i: Integer;
begin
SearchByIDBodyVariation(AIDBodyVariation);
// Сначала удалим всё лишнее
W.DeleteAll;
{
TArray.Sort<Integer>(AJedecIDArr);
FDQuery.First;
while not FDQuery.Eof do
begin
// Если в массиве такого кода нет - нужно удалить его из БД
if not TArray.BinarySearch(AJedecIDArr, W.IDJEDEC.F.AsInteger, i) then
FDQuery.Delete
else
FDQuery.Next;
end;
}
// Теперь добавим недостающее
for i := Low(AJedecIDArr) to High(AJedecIDArr) do
begin
if not W.IDJEDEC.Locate(AJedecIDArr[i], []) then
begin
W.TryAppend;
W.IDBodyVariation.F.AsInteger := AIDBodyVariation;
W.IDJEDEC.F.AsInteger := AJedecIDArr[i];
W.TryPost;
end;
end;
end;
constructor TBodyVariationJedecW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FIDBodyVariation := TFieldWrap.Create(Self, 'IDBodyVariation');
FIDJEDEC := TFieldWrap.Create(Self, 'IDJEDEC');
end;
end.
|
{**************************************************************************}
{ }
{ This file is release under dual licenses, MPL 2.0 and LGPL. }
{ }
{ This Source Code Form is subject to the terms of the Mozilla Public }
{ License, v. 2.0. If a copy of the MPL was not distributed with this }
{ file, You can obtain one at http://mozilla.org/MPL/2.0/. }
{ }
{ This program is free software: you can redistribute it and/or modify }
{ it under the terms of the GNU Lesser General Public License as }
{ published by the Free Software Foundation, either version 3 of the }
{ License, or (at your option) any later version. }
{ Yu can obtain a copy of the LGPL at http://www.gnu.org/licenses/ }
{ }
{ 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. }
{ }
{ Original Copyright: Christian Budde }
{ }
{ Roughly based on LLVM-Pascal API unit llvmAPI.pas }
{ -> http://code.google.com/p/llvm-pascal }
{ }
{**************************************************************************}
unit dwsLLVM;
interface
uses
Windows, SysUtils;
const
CLLVMLibraryMajorVersion = 3;
CLLVMLibraryMinorVersion = 4;
CLLVMLibraryPrefix = 'LLVM';
CLLVMLibraryExtension = '.dll';
{$IFDEF CPUX86}
CLLVMLibraryPlatform = 'x86';
{$ENDIF}
{$IFDEF CPUX64}
CLLVMLibraryPlatform = 'x64';
{$ENDIF}
CLTO_API_VERSION = 4;
type
{ The top-level container for all LLVM global data. See the LLVMContext class. }
TLLVMOpaqueContext = packed record
end;
PLLVMContext = ^TLLVMOpaqueContext;
{ The top-level container for all other LLVM Intermediate Representation
(IR) objects. }
TLLVMOpaqueModule = packed record
end;
PLLVMModule = ^TLLVMOpaqueModule;
{ Each value in the LLVM IR has a type, an PLLVMType. }
TLLVMOpaqueType = packed record
end;
PLLVMType = ^TLLVMOpaqueType;
TLLVMTypePtrArray = array [0 .. 0] of PLLVMType;
PLLVMTypePtrArray = ^TLLVMTypePtrArray;
{ Represents an individual value in LLVM IR. }
TLLVMOpaqueValue = packed record
end;
PLLVMValue = ^TLLVMOpaqueValue;
TLLVMValuePtrArray = array [0 .. 0] of PLLVMValue;
PLLVMValuePtrArray = ^TLLVMValuePtrArray;
{ Represents a basic block of instructions in LLVM IR. }
TLLVMOpaqueBasicBlock = packed record
end;
PLLVMBasicBlock = ^TLLVMOpaqueBasicBlock;
TLLVMBasicBlockPtrArray = array [0 .. 0] of PLLVMBasicBlock;
PLLVMBasicBlockPtrArray = ^TLLVMBasicBlockPtrArray;
{ Represents an LLVM basic block builder. }
TLLVMOpaqueBuilder = packed record
end;
PLLVMBuilder = ^TLLVMOpaqueBuilder;
{ Interface used to provide a module to JIT or interpreter.
This is now just a synonym for llvm::Module, but we have to keep using the
different type to keep binary compatibility. }
TLLVMOpaqueModuleProvider = packed record
end;
PLLVMModuleProvider = ^TLLVMOpaqueModuleProvider;
{ Used to provide a module to JIT or interpreter. }
TLLVMOpaqueMemoryBuffer = packed record
end;
PLLVMMemoryBuffer = ^TLLVMOpaqueMemoryBuffer;
TLLVMOpaquePassManager = packed record
end;
PLLVMPassManager = ^TLLVMOpaquePassManager;
TLLVMOpaquePassRegistry = packed record
end;
PLLVMPassRegistry = ^TLLVMOpaquePassRegistry;
{ Used to get the users and usees of a Value. }
TLLVMOpaqueUse = packed record
end;
PLLVMUse = ^TLLVMOpaqueUse;
TLLVMOpaqueTargetData = packed record
end;
PLLVMTargetData = ^TLLVMOpaqueTargetData;
TLLVMOpaqueTargetLibraryInfotData = packed record
end;
PLLVMTargetLibraryInfo = ^TLLVMOpaqueTargetLibraryInfotData;
TLLVMOpaqueTargetMachine = packed record
end;
PLLVMTargetMachine = ^TLLVMOpaqueTargetMachine;
TLLVMOpaqueTarget = packed record
end;
PLLVMTarget = ^TLLVMOpaqueTarget;
TLLVMStructLayout = packed record
end;
PLLVMStructLayout = ^TLLVMStructLayout;
TLLVMOpaqueObjectFile = packed record
end;
PLLVMObjectFile = ^TLLVMOpaqueObjectFile;
TLLVMOpaqueSectionIterator = packed record
end;
PLLVMSectionIterator = ^TLLVMOpaqueSectionIterator;
TLLVMOpaqueSymbolIterator = packed record
end;
PLLVMSymbolIterator = ^TLLVMOpaqueSymbolIterator;
TLLVMOpaqueRelocationIterator = packed record
end;
PLLVMRelocationIterator = ^TLLVMOpaqueRelocationIterator;
TLLVMOpaqueGenericValue = packed record
end;
PLLVMGenericValue = ^TLLVMOpaqueGenericValue;
TLLVMOpaqueExecutionEngine = packed record
end;
PLLVMExecutionEngine = ^TLLVMOpaqueExecutionEngine;
TLLVMOpaquePassManagerBuilder = packed record
end;
PLLVMPassManagerBuilder = ^TLLVMOpaquePassManagerBuilder;
TLTOModule = packed record
end;
PLTOModule = ^TLTOModule;
TLTOCodeGenerator = packed record
end;
PLTOCodeGenerator = ^TLTOCodeGenerator;
{$Z4}
TLLVMAttribute = (
LLVMZExtAttribute = 1 shl 0,
LLVMSExtAttribute = 1 shl 1,
LLVMNoReturnAttribute = 1 shl 2,
LLVMInRegAttribute = 1 shl 3,
LLVMStructRetAttribute = 1 shl 4,
LLVMNoUnwindAttribute = 1 shl 5,
LLVMNoAliasAttribute = 1 shl 6,
LLVMByValAttribute = 1 shl 7,
LLVMNestAttribute = 1 shl 8,
LLVMReadNoneAttribute = 1 shl 9,
LLVMReadOnlyAttribute = 1 shl 10,
LLVMNoInlineAttribute = 1 shl 11,
LLVMAlwaysInlineAttribute = 1 shl 12,
LLVMOptimizeForSizeAttribute = 1 shl 13,
LLVMStackProtectAttribute = 1 shl 14,
LLVMStackProtectReqAttribute = 1 shl 15,
LLVMAlignment = 31 shl 16,
LLVMNoCaptureAttribute = 1 shl 21,
LLVMNoRedZoneAttribute = 1 shl 22,
LLVMNoImplicitFloatAttribute = 1 shl 23,
LLVMNakedAttribute = 1 shl 24,
LLVMInlineHintAttribute = 1 shl 25,
LLVMStackAlignment = 7 shl 26,
LLVMReturnsTwice = 1 shl 29,
LLVMUWTable = 1 shl 30,
LLVMNonLazyBind = 1 shl 31
);
TLLVMOpcode = (
// Terminator Instructions
LLVMRet = 1,
LLVMBr = 2,
LLVMSwitch = 3,
LLVMIndirectBr = 4,
LLVMInvoke = 5,
LLVMUnreachable = 7,
// Standard Binary Operators
LLVMAdd = 8,
LLVMFAdd = 9,
LLVMSub = 10,
LLVMFSub = 11,
LLVMMul = 12,
LLVMFMul = 13,
LLVMUDiv = 14,
LLVMSDiv = 15,
LLVMFDiv = 16,
LLVMURem = 17,
LLVMSRem = 18,
LLVMFRem = 19,
// Logical Operators
LLVMShl = 20,
LLVMLShr = 21,
LLVMAShr = 22,
LLVMAnd = 23,
LLVMOr = 24,
LLVMXor = 25,
// Memory Operators
LLVMAlloca = 26,
LLVMLoad = 27,
LLVMStore = 28,
LLVMGetElementPtr = 29,
// Cast Operators
LLVMTrunc = 30,
LLVMZExt = 31,
LLVMSExt = 32,
LLVMFPToUI = 33,
LLVMFPToSI = 34,
LLVMUIToFP = 35,
LLVMSIToFP = 36,
LLVMFPTrunc = 37,
LLVMFPExt = 38,
LLVMPtrToInt = 39,
LLVMIntToPtr = 40,
LLVMBitCast = 41,
// Other Operators
LLVMICmp = 42,
LLVMFCmp = 43,
LLVMPHI = 44,
LLVMCall = 45,
LLVMSelect = 46,
LLVMUserOp1 = 47,
LLVMUserOp2 = 48,
LLVMVAArg = 49,
LLVMExtractElement = 50,
LLVMInsertElement = 51,
LLVMShuffleVector = 52,
LLVMExtractValue = 53,
LLVMInsertValue = 54,
// Atomic operators
LLVMFence = 55,
LLVMAtomicCmpXchg = 56,
LLVMAtomicRMW = 57,
// Exception Handling Operators
LLVMResume = 58,
LLVMLandingPad = 59
);
TLLVMTypeKind = (
LLVMVoidTypeKind, // type with no size
LLVMHalfTypeKind, // 16 bit floating point type
LLVMFloatTypeKind, // 32 bit floating point type
LLVMDoubleTypeKind, // 64 bit floating point type
LLVMX86_FP80TypeKind, // 80 bit floating point type (X87)
LLVMFP128TypeKind, // 128 bit floating point type (112-bit mantissa)
LLVMPPC_FP128TypeKind, // 128 bit floating point type (two 64-bits)
LLVMLabelTypeKind, // Labels
LLVMIntegerTypeKind, // Arbitrary bit width integers
LLVMFunctionTypeKind, // Functions
LLVMStructTypeKind, // Structures
LLVMArrayTypeKind, // Arrays
LLVMPointerTypeKind, // Pointers
LLVMVectorTypeKind, // SIMD 'packed' format, or other vector type
LLVMMetadataTypeKind, // Metadata
LLVMX86_MMXTypeKind // X86 MMX
);
TLLVMLinkage = (
LLVMExternalLinkage, // Externally visible function
LLVMAvailableExternallyLinkage,
LLVMLinkOnceAnyLinkage, // Keep one copy of function when linking (inline)
LLVMLinkOnceODRLinkage, // Same, but only replaced by something equivalent.
LLVMLinkOnceODRAutoHideLinkage, // Like LinkOnceODR, but possibly hidden.
LLVMWeakAnyLinkage, // Keep one copy of function when linking (weak)
LLVMWeakODRLinkage, // Same, but only replaced by something equivalent.
LLVMAppendingLinkage, // Special purpose, only applies to global arrays
LLVMInternalLinkage, // Rename collisions when linking (static functions)
LLVMPrivateLinkage, // Like Internal, but omit from symbol table
LLVMDLLImportLinkage, // Function to be imported from DLL
LLVMDLLExportLinkage, // Function to be accessible from DLL
LLVMExternalWeakLinkage,// ExternalWeak linkage description
LLVMGhostLinkage, // Obsolete
LLVMCommonLinkage, // Tentative definitions
LLVMLinkerPrivateLinkage, // Like Private, but linker removes.
LLVMLinkerPrivateWeakLinkage // Like LinkerPrivate, but is weak.
);
TLLVMVisibility = (
LLVMDefaultVisibility, // The GV is visible
LLVMHiddenVisibility, // The GV is hidden
LLVMProtectedVisibility // The GV is protected
);
TLLVMCallConv = (
LLVMCCallConv = 0,
LLVMFastCallConv = 8,
LLVMColdCallConv = 9,
LLVMX86StdcallCallConv = 64,
LLVMX86FastcallCallConv = 65
);
TLLVMIntPredicate = (
LLVMIntEQ = 32, // equal
LLVMIntNE, // not equal
LLVMIntUGT, // unsigned greater than
LLVMIntUGE, // unsigned greater or equal
LLVMIntULT, // unsigned less than
LLVMIntULE, // unsigned less or equal
LLVMIntSGT, // signed greater than
LLVMIntSGE, // signed greater or equal
LLVMIntSLT, // signed less than
LLVMIntSLE // signed less or equal
);
TLLVMRealPredicate = (
LLVMRealPredicateFalse, // Always false (always folded)
LLVMRealOEQ, // True if ordered and equal
LLVMRealOGT, // True if ordered and greater than
LLVMRealOGE, // True if ordered and greater than or equal
LLVMRealOLT, // True if ordered and less than
LLVMRealOLE, // True if ordered and less than or equal
LLVMRealONE, // True if ordered and operands are unequal
LLVMRealORD, // True if ordered (no nans)
LLVMRealUNO, // True if unordered: isnan(X) | isnan(Y)
LLVMRealUEQ, // True if unordered or equal
LLVMRealUGT, // True if unordered or greater than
LLVMRealUGE, // True if unordered, greater than, or equal
LLVMRealULT, // True if unordered or less than
LLVMRealULE, // True if unordered, less than, or equal
LLVMRealUNE, // True if unordered or not equal
LLVMRealPredicateTrue // Always true (always folded)
);
TLLVMCodeGenOptLevel = (
LLVMCodeGenLevelNone,
LLVMCodeGenLevelLess,
LLVMCodeGenLevelDefault,
LLVMCodeGenLevelAggressive
);
TLLVMRelocMode = (
LLVMRelocDefault,
LLVMRelocStatic,
LLVMRelocPIC,
LLVMRelocDynamicNoPic
);
TLLVMCodeModel = (
LLVMCodeModelDefault,
LLVMCodeModelJITDefault,
LLVMCodeModelSmall,
LLVMCodeModelKernel,
LLVMCodeModelMedium,
LLVMCodeModelLarge
);
TLLVMCodeGenFileType = (
LLVMAssemblyFile,
LLVMObjectFile
);
TLLVMLandingPadClauseTy = (
LLVMLandingPadCatch, // A catch clause
LLVMLandingPadFilter // A filter clause
);
TLLVMVerifierFailureAction = (
LLVMAbortProcessAction, // verifier will print to stderr and abort
LLVMPrintMessageAction, // verifier will print to stderr and return 1
LLVMReturnStatusAction // verifier will just return 1
);
TLLVMByteOrdering = (
LLVMBigEndian,
LLVMLittleEndian
);
TLTOSymbolAttributes = (
LTO_SYMBOL_ALIGNMENT_MASK = $0000001F, (* log2 of alignment *)
LTO_SYMBOL_PERMISSIONS_MASK = $000000E0,
LTO_SYMBOL_PERMISSIONS_CODE = $000000A0,
LTO_SYMBOL_PERMISSIONS_DATA = $000000C0,
LTO_SYMBOL_PERMISSIONS_RODATA = $00000080,
LTO_SYMBOL_DEFINITION_MASK = $00000700,
LTO_SYMBOL_DEFINITION_REGULAR = $00000100,
LTO_SYMBOL_DEFINITION_TENTATIVE = $00000200,
LTO_SYMBOL_DEFINITION_WEAK = $00000300,
LTO_SYMBOL_DEFINITION_UNDEFINED = $00000400,
LTO_SYMBOL_DEFINITION_WEAKUNDEF = $00000500,
LTO_SYMBOL_SCOPE_MASK = $00003800,
LTO_SYMBOL_SCOPE_INTERNAL = $00000800,
LTO_SYMBOL_SCOPE_HIDDEN = $00001000,
LTO_SYMBOL_SCOPE_PROTECTED = $00002000,
LTO_SYMBOL_SCOPE_DEFAULT = $00001800,
LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN = $00002800
);
TLTODebugModel = (
LTO_DEBUG_MODEL_NONE = 0,
LTO_DEBUG_MODEL_DWARF = 1
);
TLTOCodegenModel = (
LTO_CODEGEN_PIC_MODEL_STATIC = 0,
LTO_CODEGEN_PIC_MODEL_DYNAMIC = 1,
LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC = 2
);
TLLVMDisassemblerVariantKind = (
dvkNone = 0,
dvkArmHi16 = 1,
dvkArmLo16 = 2
);
TLLVMDisassemblerReferenceTypeIn = (
drtiOutNone = 0,
drtiBranch = 1,
drtiPCrelLoad = 2
);
TLLVMDisassemblerReferenceTypeOut = (
drtoSymbolStub = 1,
drtoLitPoolSymAddr = 2,
drtoLitPoolCstrAddr = 3
);
TLLVMDisassemblerOption = (
doUseMarkup = 1
);
TLLVMDisassemblerOptions = set of TLLVMDisassemblerOption;
PLLVMDisasmContext = Pointer;
TLLVMOpInfoCallback = function (DisInfo: Pointer; PC: UInt64; Offset: UInt64; Size: UInt64; TagType: Integer; TagBuf: Pointer): Integer; cdecl;
TLLVMOpInfoSymbol1 = packed record
Present: UInt64; // 1 if this symbol is present
Name: PAnsiChar; // symbol name if not NULL
Value: UInt64; // symbol value if name is NULL
end;
TLLVMOpInfo1 = packed record
AddSymbol: TLLVMOpInfoSymbol1;
SubtractSymbol: TLLVMOpInfoSymbol1;
Value: UInt64;
VariantKind: UInt64;
end;
TLLVMSymbolLookupCallback = function(DisInfo: Pointer; ReferenceValue: Cardinal; ReferenceType: PCardinal; ReferencePC: Cardinal; var ReferenceName: PAnsiChar): PAnsiChar; cdecl;
var
LLVMInitializeCore: procedure(R: PLLVMPassRegistry); cdecl;
{ Error handling }
LLVMDisposeMessage: procedure(&Message: PAnsiChar); cdecl;
{ Create a new context.
Every call to this function should be paired with a call to
LLVMContextDispose or the context will leak memory. }
LLVMContextCreate: function: PLLVMContext; cdecl;
{ Obtain the global context instance. }
LLVMGetGlobalContext: function: PLLVMContext; cdecl;
{ Destroy a context instance.
This should be called for every call to LLVMContextCreate or memory
will be leaked. }
LLVMContextDispose: procedure(C: PLLVMContext); cdecl;
LLVMGetMDKindIDInContext: function(C: PLLVMContext; const Name: PAnsiChar; SLen: Cardinal): Cardinal; cdecl;
LLVMGetMDKindID: function(const Name: PAnsiChar; SLen: Cardinal): Cardinal; cdecl;
{ Create a new, empty module in the global context.
This is equivalent to calling LLVMModuleCreateWithNameInContext with
LLVMGetGlobalContext as the context parameter.
Every invocation should be paired with LLVMDisposeModule or memory
will be leaked. }
LLVMModuleCreateWithName: function(const ModuleID: PAnsiChar): PLLVMModule; cdecl;
{ Create a new, empty module in a specific context.
Every invocation should be paired with LLVMDisposeModule or memory
will be leaked. }
LLVMModuleCreateWithNameInContext: function(const ModuleID: PAnsiChar; C: PLLVMContext): PLLVMModule; cdecl;
{ Destroy a module instance.
This must be called for every created module or memory will be
leaked. }
LLVMDisposeModule: procedure(M: PLLVMModule); cdecl;
{ Obtain the data layout for a module. }
LLVMGetDataLayout: function(M: PLLVMModule): PAnsiChar; cdecl;
{ Set the data layout for a module. }
LLVMSetDataLayout: procedure(M: PLLVMModule; const Triple: PAnsiChar); cdecl;
{ Obtain the target triple for a module. }
LLVMGetTarget: function(M: PLLVMModule): PAnsiChar; cdecl;
{ Set the target triple for a module. }
LLVMSetTarget: procedure(M: PLLVMModule; const Triple: PAnsiChar); cdecl;
{ Dump a representation of a module to stderr. }
LLVMDumpModule: procedure(M: PLLVMModule); cdecl;
{ Print a representation of a module to a file.
The ErrorMessage needs to be disposed with LLVMDisposeMessage.
Returns 0 on success, 1 otherwise. }
LLVMPrintModuleToFile: function(M: PLLVMModule; const Filename: PAnsiChar; var ErrorMessage: PAnsiChar): Boolean; cdecl;
// new in 3.4
LLVMPrintModuleToString: function(M: PLLVMModule): PAnsiChar; cdecl;
{ Set inline assembly for a module. }
LLVMSetModuleInlineAsm: procedure(M: PLLVMModule; const &Asm: PAnsiChar); cdecl;
{ Obtain the context to which this module is associated. }
LLVMGetModuleContext: function(M: PLLVMModule): PLLVMContext; cdecl;
{ Obtain a Type from a module by its registered name. }
LLVMGetTypeByName: function(M: PLLVMModule; const Name: PAnsiChar): PLLVMType; cdecl;
{ Obtain the number of operands for named metadata in a module. }
LLVMGetNamedMetadataNumOperands: function(M: PLLVMModule; const Name: PAnsiChar): Cardinal; cdecl;
{ Obtain the named metadata operands for a module.
The passed PLLVMValue pointer should refer to an array of
PLLVMValue at least LLVMGetNamedMetadataNumOperands long. This
array will be populated with the PLLVMValue instances. Each
instance corresponds to a llvm::MDNode. }
LLVMGetNamedMetadataOperands: procedure(M: PLLVMModule; const Name: PAnsiChar; var Dest: PLLVMValue); cdecl;
{ Add an operand to named metadata. }
LLVMAddNamedMetadataOperand: procedure(M: PLLVMModule; const Name: PAnsiChar; Val: PLLVMValue); cdecl;
{ Add a function to a module under a specified name. }
LLVMAddFunction: function(M: PLLVMModule; const Name: PAnsiChar; FunctionTy: PLLVMType): PLLVMValue; cdecl;
{ Obtain a Function value from a Module by its name.
The returned value corresponds to a llvm::Function value. }
LLVMGetNamedFunction: function(M: PLLVMModule; const Name: PAnsiChar): PLLVMValue; cdecl;
{ Obtain an iterator to the first Function in a Module. }
LLVMGetFirstFunction: function(M: PLLVMModule): PLLVMValue; cdecl;
{ Obtain an iterator to the last Function in a Module. }
LLVMGetLastFunction: function(M: PLLVMModule): PLLVMValue; cdecl;
{ Advance a Function iterator to the next Function.
Returns NULL if the iterator was already at the end and there are no more
functions. }
LLVMGetNextFunction: function(Fn: PLLVMValue): PLLVMValue; cdecl;
{ Decrement a Function iterator to the previous Function.
Returns NULL if the iterator was already at the beginning and there are
no previous functions. }
LLVMGetPreviousFunction: function(Fn: PLLVMValue): PLLVMValue; cdecl;
{ Obtain the enumerated type of a Type instance. }
LLVMGetTypeKind: function(Ty: PLLVMType): TLLVMTypeKind; cdecl;
{ Whether the type has a known size.
Things that don't have a size are abstract types, labels, and void.a }
LLVMTypeIsSized: function(Ty: PLLVMType): Boolean; cdecl;
{ Obtain the context to which this type instance is associated. }
LLVMGetTypeContext: function(Ty: PLLVMType): PLLVMContext; cdecl;
{ Obtain an integer type from a context with specified bit width. }
LLVMInt1TypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
LLVMInt8TypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
LLVMInt16TypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
LLVMInt32TypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
LLVMInt64TypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
LLVMIntTypeInContext: function(C: PLLVMContext; NumBits: Cardinal): PLLVMType; cdecl;
{ Obtain a 16-bit floating point type from a context. }
LLVMHalfTypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
{ Obtain a 32-bit floating point type from a context. }
LLVMFloatTypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
{ Obtain a 64-bit floating point type from a context. }
LLVMDoubleTypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
{ Obtain a 80-bit floating point type (X87) from a context. }
LLVMX86FP80TypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
{ Obtain a 128-bit floating point type (112-bit mantissa) from a
context. }
LLVMFP128TypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
{ Obtain a 128-bit floating point type (two 64-bits) from a context. }
LLVMPPCFP128TypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
{ Obtain an integer type from the global context with a specified bit width. }
LLVMInt1Type: function: PLLVMType; cdecl;
LLVMInt8Type: function: PLLVMType; cdecl;
LLVMInt16Type: function: PLLVMType; cdecl;
LLVMInt32Type: function: PLLVMType; cdecl;
LLVMInt64Type: function: PLLVMType; cdecl;
LLVMIntType: function(NumBits: Cardinal): PLLVMType; cdecl;
LLVMGetIntTypeWidth: function(IntegerTy: PLLVMType): Cardinal; cdecl;
{ Obtain a floating point type from the global context.
These map to the functions in this group of the same name. }
LLVMHalfType: function: PLLVMType; cdecl;
LLVMFloatType: function: PLLVMType; cdecl;
LLVMDoubleType: function: PLLVMType; cdecl;
LLVMX86FP80Type: function: PLLVMType; cdecl;
LLVMFP128Type: function: PLLVMType; cdecl;
LLVMPPCFP128Type: function: PLLVMType; cdecl;
{ Obtain a function type consisting of a specified signature.
The function is defined as a tuple of a return Type, a list of
parameter types, and whether the function is variadic. }
LLVMFunctionType: function(ReturnType: PLLVMType; ParamTypes: PLLVMTypePtrArray; ParamCount: Cardinal; IsVarArg: Boolean): PLLVMType; cdecl;
{ Returns whether a function type is variadic. }
LLVMIsFunctionVarArg: function(FunctionTy: PLLVMType): Boolean; cdecl;
{ Obtain the Type this function Type returns. }
LLVMGetReturnType: function(FunctionTy: PLLVMType): PLLVMType; cdecl;
{ Obtain the number of parameters this function accepts. }
LLVMCountParamTypes: function(FunctionTy: PLLVMType): Cardinal; cdecl;
{ Obtain the types of a function's parameters.
The Dest parameter should point to a pre-allocated array of
PLLVMType at least LLVMCountParamTypes large. On return, the
first LLVMCountParamTypes entries in the array will be populated
with PLLVMType instances.
param FunctionTy The function type to operate on.
param Dest Memory address of an array to be filled with result. }
LLVMGetParamTypes: procedure(FunctionTy: PLLVMType; var Dest: PLLVMType); cdecl;
{ Create a new structure type in a context.
A structure is specified by a list of inner elements/types and
whether these can be packed together. }
LLVMStructTypeInContext: function(C: PLLVMContext; ElementTypes: PLLVMTypePtrArray; ElementCount: Cardinal; &Packed: Boolean): PLLVMType; cdecl;
{ Create a new structure type in the global context. }
LLVMStructType: function(ElementTypes: PLLVMTypePtrArray; ElementCount: Cardinal; &Packed: Boolean): PLLVMType; cdecl;
{ Create an empty structure in a context having a specified name. }
LLVMStructCreateNamed: function(C: PLLVMContext; const Name: PAnsiChar): PLLVMType; cdecl;
{ Obtain the name of a structure. }
LLVMGetStructName: function(Ty: PLLVMType): PAnsiChar; cdecl;
{ Set the contents of a structure type. }
LLVMStructSetBody: procedure(StructTy: PLLVMType; ElementTypes: PLLVMTypePtrArray; ElementCount: Cardinal; &Packed: Boolean); cdecl;
{ Get the number of elements defined inside the structure. }
LLVMCountStructElementTypes: function(StructTy: PLLVMType): Cardinal; cdecl;
{ Get the elements within a structure.
The function is passed the address of a pre-allocated array of
PLLVMType at least LLVMCountStructElementTypes long. After
invocation, this array will be populated with the structure's
elements. The objects in the destination array will have a lifetime
of the structure type itself, which is the lifetime of the context it
is contained in. }
LLVMGetStructElementTypes: procedure(StructTy: PLLVMType; var Dest: PLLVMType); cdecl;
{ Determine whether a structure is packed. }
LLVMIsPackedStruct: function(StructTy: PLLVMType): Boolean; cdecl;
{ Determine whether a structure is opaque. }
LLVMIsOpaqueStruct: function(StructTy: PLLVMType): Boolean; cdecl;
{ Obtain the type of elements within a sequential type.
This works on array, vector, and pointer types. }
LLVMGetElementType: function(Ty: PLLVMType): PLLVMType; cdecl;
{ Create a fixed size array type that refers to a specific type.
The created type will exist in the context that its element type
exists in. }
LLVMArrayType: function(ElementType: PLLVMType; ElementCount: Cardinal): PLLVMType; cdecl;
{ Obtain the length of an array type.
This only works on types that represent arrays. }
LLVMGetArrayLength: function(ArrayTy: PLLVMType): Cardinal; cdecl;
{ Create a pointer type that points to a defined type.
The created type will exist in the context that its pointee type
exists in. }
LLVMPointerType: function(ElementType: PLLVMType; AddressSpace: Cardinal): PLLVMType; cdecl;
{ Obtain the address space of a pointer type.
This only works on types that represent pointers. }
LLVMGetPointerAddressSpace: function(PointerTy: PLLVMType): Cardinal; cdecl;
{ Create a vector type that contains a defined type and has a specific
number of elements.
The created type will exist in the context thats its element type
exists in. }
LLVMVectorType: function(ElementType: PLLVMType; ElementCount: Cardinal): PLLVMType; cdecl;
{ Obtain the number of elements in a vector type.
This only works on types that represent vectors. }
LLVMGetVectorSize: function(VectorTy: PLLVMType): Cardinal; cdecl;
{ Create a void type in a context. }
LLVMVoidTypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
{ Create a label type in a context. }
LLVMLabelTypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
{ Create a X86 MMX type in a context. }
LLVMX86MMXTypeInContext: function(C: PLLVMContext): PLLVMType; cdecl;
{ These are similar to the above functions except they operate on the
global context. }
LLVMVoidType: function: PLLVMType; cdecl;
LLVMLabelType: function: PLLVMType; cdecl;
LLVMX86MMXType: function: PLLVMType; cdecl;
{ Obtain the type of a value. }
LLVMTypeOf: function(Val: PLLVMValue): PLLVMType; cdecl;
{ Obtain the string name of a value. }
LLVMGetValueName: function(Val: PLLVMValue): PAnsiChar; cdecl;
{ Set the string name of a value. }
LLVMSetValueName: procedure(Val: PLLVMValue; const Name: PAnsiChar); cdecl;
{ Dump a representation of a value to stderr. }
LLVMDumpValue: procedure(Val: PLLVMValue); cdecl;
{ Replace all uses of a value with another one. }
LLVMReplaceAllUsesWith: procedure(OldVal: PLLVMValue; NewVal: PLLVMValue); cdecl;
{ Determine whether the specified constant instance is constant. }
LLVMIsConstant: function(Val: PLLVMValue): Boolean; cdecl;
{ Determine whether a value instance is undefined. }
LLVMIsUndef: function(Val: PLLVMValue): Boolean; cdecl;
{ Convert value instances between types.
Internally, a PLLVMValue is "pinned" to a specific type. This series of
functions allows you to cast an instance to a specific type.
If the cast is not valid for the specified type, NULL is returned. }
LLVMIsAArgument: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsABasicBlock: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAInlineAsm: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAMDNode: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAMDString: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAUser: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAConstant: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsABlockAddress: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAConstantAggregateZero: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAConstantArray: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAConstantExpr: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAConstantFP: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAConstantInt: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAConstantPointerNull: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAConstantStruct: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAConstantVector: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAGlobalValue: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAFunction: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAGlobalAlias: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAGlobalVariable: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAUndefValue: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAInstruction: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsABinaryOperator: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsACallInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAIntrinsicInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsADbgInfoIntrinsic: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsADbgDeclareInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAMemIntrinsic: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAMemCpyInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAMemMoveInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAMemSetInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsACmpInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAFCmpInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAICmpInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAExtractElementInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAGetElementPtrInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAInsertElementInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAInsertValueInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsALandingPadInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAPHINode: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsASelectInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAShuffleVectorInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAStoreInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsATerminatorInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsABranchInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAIndirectBrInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAInvokeInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAReturnInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsASwitchInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAUnreachableInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAResumeInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAUnaryInstruction: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAAllocaInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsACastInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsABitCastInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAFPExtInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAFPToSIInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAFPToUIInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAFPTruncInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAIntToPtrInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAPtrToIntInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsASExtInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsASIToFPInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsATruncInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAUIToFPInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAZExtInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAExtractValueInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsALoadInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
LLVMIsAVAArgInst: function(Val: PLLVMValue): PLLVMValue; cdecl;
{ Obtain the first use of a value.
Uses are obtained in an iterator fashion. First, call this function
to obtain a reference to the first use. Then, call LLVMGetNextUse
on that instance and all subsequently obtained instances until
LLVMGetNextUse returns NULL. }
LLVMGetFirstUse: function(Val: PLLVMValue): PLLVMUse; cdecl;
{ Obtain the next use of a value.
This effectively advances the iterator. It returns NULL if you are on
the final use and no more are available. }
LLVMGetNextUse: function(U: PLLVMUse): PLLVMUse; cdecl;
{ Obtain the user value for a user.
The returned value corresponds to a llvm::User type. }
LLVMGetUser: function(U: PLLVMUse): PLLVMValue; cdecl;
{ Obtain the value this use corresponds to. }
LLVMGetUsedValue: function(U: PLLVMUse): PLLVMValue; cdecl;
{ Obtain an operand at a specific index in a llvm::User value. }
LLVMGetOperand: function(Val: PLLVMValue; Index: Cardinal): PLLVMValue; cdecl;
{ Set an operand at a specific index in a llvm::User value. }
LLVMSetOperand: procedure(User: PLLVMValue; Index: Cardinal; Val: PLLVMValue); cdecl;
{ Obtain the number of operands in a llvm::User value. }
LLVMGetNumOperands: function(Val: PLLVMValue): Integer; cdecl;
{ Obtain a constant value referring to the null instance of a type. }
LLVMConstNull: function(Ty: PLLVMType): PLLVMValue; cdecl;
{ Obtain a constant value referring to the instance of a type
consisting of all ones.
This is only valid for integer types. }
LLVMConstAllOnes: function(Ty: PLLVMType): PLLVMValue; cdecl;
{ Obtain a constant value referring to an undefined value of a type. }
LLVMGetUndef: function(Ty: PLLVMType): PLLVMValue; cdecl;
{ Determine whether a value instance is null. }
LLVMIsNull: function(Val: PLLVMValue): Boolean; cdecl;
{ Obtain a constant that is a constant pointer pointing to NULL for a
specified type. }
LLVMConstPointerNull: function(Ty: PLLVMType): PLLVMValue; cdecl;
{ Obtain a constant value for an integer type.
The returned value corresponds to a llvm::ConstantInt.
@param IntTy Integer type to obtain value of.
@param N The value the returned instance should refer to.
@param SignExtend Whether to sign extend the produced value. }
LLVMConstInt: function(IntTy: PLLVMType; N: UInt64; SignExtend: Boolean): PLLVMValue; cdecl;
{ Obtain a constant value for an integer of arbitrary precision. }
LLVMConstIntOfArbitraryPrecision: function(IntTy: PLLVMType; NumWords: Cardinal; Words: PUInt64): PLLVMValue; cdecl;
{ Obtain a constant value for an integer parsed from a string.
A similar API, LLVMConstIntOfStringAndSize is also available. If the
string's length is available, it is preferred to call that function
instead. }
LLVMConstIntOfString: function(IntTy: PLLVMType; const Text: PAnsiChar; Radix: Byte): PLLVMValue; cdecl;
{ Obtain a constant value for an integer parsed from a string with
specified length. }
LLVMConstIntOfStringAndSize: function(IntTy: PLLVMType; const Text: PAnsiChar; SLen: Cardinal; Radix: Byte): PLLVMValue; cdecl;
{ Obtain a constant value referring to a double floating point value. }
LLVMConstReal: function(RealTy: PLLVMType; N: Double): PLLVMValue; cdecl;
{ Obtain a constant for a floating point value parsed from a string.
A similar API, LLVMConstRealOfStringAndSize is also available. It
should be used if the input string's length is known. }
LLVMConstRealOfString: function(RealTy: PLLVMType; const Text: PAnsiChar): PLLVMValue; cdecl;
{ Obtain a constant for a floating point value parsed from a string. }
LLVMConstRealOfStringAndSize: function(RealTy: PLLVMType; const Text: PAnsiChar; SLen: Cardinal): PLLVMValue; cdecl;
{ Obtain the zero extended value for an integer constant value. }
LLVMConstIntGetZExtValue: function(ConstantVal: PLLVMValue): UInt64; cdecl;
{ Obtain the sign extended value for an integer constant value. }
LLVMConstIntGetSExtValue: function(ConstantVal: PLLVMValue): Int64; cdecl;
{ Create a ConstantDataSequential and initialize it with a string. }
LLVMConstStringInContext: function(C: PLLVMContext; const Str: PAnsiChar; Length: Cardinal; DontNullTerminate: Boolean): PLLVMValue; cdecl;
{ Create a ConstantDataSequential with string content in the global context.
This is the same as LLVMConstStringInContext except it operates on the
global context. }
LLVMConstString: function(const Str: PAnsiChar; Length: Cardinal; DontNullTerminate: Boolean): PLLVMValue; cdecl;
{ Create an anonymous ConstantStruct with the specified values. }
LLVMConstStructInContext: function(C: PLLVMContext; ConstantVals: PLLVMValuePtrArray; Count: Cardinal; &Packed: Boolean): PLLVMValue; cdecl;
{ Create a ConstantStruct in the global Context.
This is the same as LLVMConstStructInContext except it operates on the
global Context. }
LLVMConstStruct: function(ConstantVals: PLLVMValuePtrArray; Count: Cardinal; &Packed: Boolean): PLLVMValue; cdecl;
{ Create a ConstantArray from values. }
LLVMConstArray: function(ElementTy: PLLVMType; ConstantVals: PLLVMValuePtrArray; Length: Cardinal): PLLVMValue; cdecl;
{ Create a non-anonymous ConstantStruct from values. }
LLVMConstNamedStruct: function(StructTy: PLLVMType; ConstantVals: PLLVMValuePtrArray; Count: Cardinal): PLLVMValue; cdecl;
{ Create a ConstantVector from values. }
LLVMConstVector: function(ScalarConstantVals: PLLVMValuePtrArray; Size: Cardinal): PLLVMValue; cdecl;
{ Functions below correspond to APIs on llvm::ConstantExpr. }
LLVMGetConstOpcode: function(ConstantVal: PLLVMValue): TLLVMOpcode; cdecl;
LLVMAlignOf: function(Ty: PLLVMType): PLLVMValue; cdecl;
LLVMSizeOf: function(Ty: PLLVMType): PLLVMValue; cdecl;
LLVMConstNeg: function(ConstantVal: PLLVMValue): PLLVMValue; cdecl;
LLVMConstNSWNeg: function(ConstantVal: PLLVMValue): PLLVMValue; cdecl;
LLVMConstNUWNeg: function(ConstantVal: PLLVMValue): PLLVMValue; cdecl;
LLVMConstFNeg: function(ConstantVal: PLLVMValue): PLLVMValue; cdecl;
LLVMConstNot: function(ConstantVal: PLLVMValue): PLLVMValue; cdecl;
LLVMConstAdd: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstNSWAdd: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstNUWAdd: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstFAdd: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstSub: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstNSWSub: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstNUWSub: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstFSub: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstMul: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstNSWMul: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstNUWMul: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstFMul: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstUDiv: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstSDiv: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstExactSDiv: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstFDiv: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstURem: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstSRem: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstFRem: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstAnd: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstOr: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstXor: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstICmp: function(Predicate: TLLVMIntPredicate; LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstFCmp: function(Predicate: TLLVMIntPredicate; LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstShl: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstLShr: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstAShr: function(LHSConstant: PLLVMValue; RHSConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstGEP: function(ConstantVal: PLLVMValue; ConstantIndices: PLLVMValuePtrArray; NumIndices: Cardinal): PLLVMValue; cdecl;
LLVMConstInBoundsGEP: function(ConstantVal: PLLVMValue; ConstantIndices: PLLVMValuePtrArray; NumIndices: Cardinal): PLLVMValue; cdecl;
LLVMConstTrunc: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstSExt: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstZExt: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstFPTrunc: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstFPExt: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstUIToFP: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstSIToFP: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstFPToUI: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstFPToSI: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstPtrToInt: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstIntToPtr: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstBitCast: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstZExtOrBitCast: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstSExtOrBitCast: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstTruncOrBitCast: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstPointerCast: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstIntCast: function(ConstantVal: PLLVMValue; ToType: PLLVMType; isSigned: Boolean): PLLVMValue; cdecl;
LLVMConstFPCast: function(ConstantVal: PLLVMValue; ToType: PLLVMType): PLLVMValue; cdecl;
LLVMConstSelect: function(ConstantCondition: PLLVMValue; ConstantIfTrue: PLLVMValue; ConstantIfFalse: PLLVMValue): PLLVMValue; cdecl;
LLVMConstExtractElement: function(VectorConstant: PLLVMValue; IndexConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstInsertElement: function(VectorConstant: PLLVMValue; ElementValueConstant: PLLVMValue; IndexConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstShuffleVector: function(VectorAConstant: PLLVMValue; VectorBConstant: PLLVMValue; MaskConstant: PLLVMValue): PLLVMValue; cdecl;
LLVMConstExtractValue: function(AggConstant: PLLVMValue; IdxList: PCardinal; NumIdx: Cardinal): PLLVMValue; cdecl;
LLVMConstInsertValue: function(AggConstant: PLLVMValue; ElementValueConstant: PLLVMValue; IdxList: PCardinal; NumIdx: Cardinal): PLLVMValue; cdecl;
LLVMConstInlineAsm: function(Ty: PLLVMType; const AsmString: PAnsiChar; const Constraints: PAnsiChar; HasSideEffects: Boolean; IsAlignStack: Boolean): PLLVMValue; cdecl;
LLVMBlockAddress: function(F: PLLVMValue; BB: PLLVMBasicBlock): PLLVMValue; cdecl;
{ This group contains functions that operate on global values. Functions in
this group relate to functions in the llvm::GlobalValue class tree. }
LLVMGetGlobalParent: function(Global: PLLVMValue): PLLVMModule; cdecl;
LLVMIsDeclaration: function(Global: PLLVMValue): Boolean; cdecl;
LLVMGetLinkage: function(Global: PLLVMValue): TLLVMLinkage; cdecl;
LLVMSetLinkage: procedure(Global: PLLVMValue; Linkage: TLLVMLinkage); cdecl;
LLVMGetSection: function(Global: PLLVMValue): PAnsiChar; cdecl;
LLVMSetSection: procedure(Global: PLLVMValue; const Section: PAnsiChar); cdecl;
LLVMGetVisibility: function(Global: PLLVMValue): TLLVMVisibility; cdecl;
LLVMSetVisibility: procedure(Global: PLLVMValue; Viz: TLLVMVisibility); cdecl;
LLVMGetAlignment: function(Global: PLLVMValue): Cardinal; cdecl;
LLVMSetAlignment: procedure(Global: PLLVMValue; Bytes: Cardinal); cdecl;
{ This group contains functions that operate on global variable values. }
LLVMAddGlobal: function(M: PLLVMModule; Ty: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMAddGlobalInAddressSpace: function(M: PLLVMModule; Ty: PLLVMType; const Name: PAnsiChar; AddressSpace: Cardinal): PLLVMValue; cdecl;
LLVMGetNamedGlobal: function(M: PLLVMModule; Name: PAnsiChar): PLLVMValue; cdecl;
LLVMGetFirstGlobal: function(M: PLLVMModule): PLLVMValue; cdecl;
LLVMGetLastGlobal: function(M: PLLVMModule): PLLVMValue; cdecl;
LLVMGetNextGlobal: function(GlobalVar: PLLVMValue): PLLVMValue; cdecl;
LLVMGetPreviousGlobal: function(GlobalVar: PLLVMValue): PLLVMValue; cdecl;
LLVMDeleteGlobal: procedure(GlobalVar: PLLVMValue); cdecl;
LLVMGetInitializer: function(GlobalVar: PLLVMValue): PLLVMValue; cdecl;
LLVMSetInitializer: procedure(GlobalVar: PLLVMValue; ConstantVal: PLLVMValue); cdecl;
LLVMIsThreadLocal: function(GlobalVar: PLLVMValue): Boolean; cdecl;
LLVMSetThreadLocal: procedure(GlobalVar: PLLVMValue; IsThreadLocal: Boolean); cdecl;
LLVMIsGlobalConstant: function(GlobalVar: PLLVMValue): Boolean; cdecl;
LLVMSetGlobalConstant: procedure(GlobalVar: PLLVMValue; IsConstant: Boolean); cdecl;
{ This group contains function that operate on global alias values. }
LLVMAddAlias: function(M: PLLVMModule; Ty: PLLVMType; Aliasee: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
{ Remove a function from its containing module and deletes it. }
LLVMDeleteFunction: procedure(Fn: PLLVMValue); cdecl;
{ Obtain the ID number from a function instance. }
LLVMGetIntrinsicID: function(Fn: PLLVMValue): Cardinal; cdecl;
{ Obtain the calling function of a function.
The returned value corresponds to the TLLVMCallConv enumeration. }
LLVMGetFunctionCallConv: function(Fn: PLLVMValue): Cardinal; cdecl;
{ Set the calling convention of a function. }
LLVMSetFunctionCallConv: procedure(Fn: PLLVMValue; CC: Cardinal); cdecl;
{ Obtain the name of the garbage collector to use during code
generation. }
LLVMGetGC: function(Fn: PLLVMValue): PAnsiChar; cdecl;
{ Define the garbage collector to use during code generation. }
LLVMSetGC: procedure(Fn: PLLVMValue; const Name: PAnsiChar); cdecl;
{ Add an attribute to a function. }
LLVMAddFunctionAttr: procedure(Fn: PLLVMValue; PA: TLLVMAttribute); cdecl;
{ Obtain an attribute from a function. }
LLVMGetFunctionAttr: function(Fn: PLLVMValue): TLLVMAttribute; cdecl;
{ Remove an attribute from a function. }
LLVMRemoveFunctionAttr: procedure(Fn: PLLVMValue; PA: TLLVMAttribute); cdecl;
{ Obtain the number of parameters in a function. }
LLVMCountParams: function(Fn: PLLVMValue): Cardinal; cdecl;
{ Obtain the parameters in a function.
The takes a pointer to a pre-allocated array of PLLVMValue that is
at least LLVMCountParams long. This array will be filled with
PLLVMValue instances which correspond to the parameters the
function receives. Each PLLVMValue corresponds to a llvm::Argument
instance. }
LLVMGetParams: procedure(Fn: PLLVMValue; Params: PLLVMValuePtrArray); cdecl;
{ Obtain the parameter at the specified index.
Parameters are indexed from 0. }
LLVMGetParam: function(Fn: PLLVMValue; Index: Cardinal): PLLVMValue; cdecl;
{ Obtain the function to which this argument belongs.
Unlike other functions in this group, this one takes a PLLVMValue
that corresponds to a llvm::Attribute.
The returned PLLVMValue is the llvm::Function to which this
argument belongs. }
LLVMGetParamParent: function(Inst: PLLVMValue): PLLVMValue; cdecl;
{ Obtain the first parameter to a function. }
LLVMGetFirstParam: function(Fn: PLLVMValue): PLLVMValue; cdecl;
{ Obtain the last parameter to a function. }
LLVMGetLastParam: function(Fn: PLLVMValue): PLLVMValue; cdecl;
{ Obtain the next parameter to a function.
This takes a PLLVMValue obtained from LLVMGetFirstParam (which is actually
a wrapped iterator) and obtains the next parameter from the underlying
iterator. }
LLVMGetNextParam: function(Arg: PLLVMValue): PLLVMValue; cdecl;
{ Obtain the previous parameter to a function.
This is the opposite of LLVMGetNextParam. }
LLVMGetPreviousParam: function(Arg: PLLVMValue): PLLVMValue; cdecl;
{ Add an attribute to a function argument. }
LLVMAddAttribute: procedure(Arg: PLLVMValue; PA: TLLVMAttribute); cdecl;
{ Remove an attribute from a function argument. }
LLVMRemoveAttribute: procedure(Arg: PLLVMValue; PA: TLLVMAttribute); cdecl;
{ Get an attribute from a function argument. }
LLVMGetAttribute: function(Arg: PLLVMValue): TLLVMAttribute; cdecl;
{ Set the alignment for a function parameter. }
LLVMSetParamAlignment: procedure(Arg: PLLVMValue; align: Cardinal); cdecl;
{ Obtain a MDString value from a context.
The returned instance corresponds to the llvm::MDString class.
The instance is specified by string data of a specified length. The
string content is copied, so the backing memory can be freed after this
function returns. }
LLVMMDStringInContext: function(C: PLLVMContext; const Str: PAnsiChar; SLen: Cardinal): PLLVMValue; cdecl;
{ Obtain a MDString value from the global context. }
LLVMMDString: function(const Str: PAnsiChar; SLen: Cardinal): PLLVMValue; cdecl;
{ Obtain a MDNode value from a context.
The returned value corresponds to the llvm::MDNode class. }
LLVMMDNodeInContext: function(C: PLLVMContext; Vals: PLLVMValuePtrArray; Count: Cardinal): PLLVMValue; cdecl;
{ Obtain a MDNode value from the global context. }
LLVMMDNode: function(Vals: PLLVMValuePtrArray; Count: Cardinal): PLLVMValue; cdecl;
{ Obtain the underlying string from a MDString value.
@param V Instance to obtain string from.
@param Len Memory address which will hold length of returned string.
@return String data in MDString. }
LLVMGetMDString: function(V: PLLVMValue; Len: PCardinal): PAnsiChar; cdecl;
{ Obtain the number of operands from an MDNode value.
@param V MDNode to get number of operands from.
@return Number of operands of the MDNode. }
LLVMGetMDNodeNumOperands: function(V: PLLVMValue): Cardinal; cdecl;
{ Obtain the given MDNode's operands.
The passed PLLVMValue pointer should point to enough memory to hold all of
the operands of the given MDNode (see LLVMGetMDNodeNumOperands) as
LLVMValueRefs. This memory will be populated with the LLVMValueRefs of the
MDNode's operands.
@param V MDNode to get the operands from.
@param Dest Destination array for operands. }
LLVMGetMDNodeOperands: procedure(V: PLLVMValue; var Dest: PLLVMValue); cdecl;
{ Convert a basic block instance to a value type. }
LLVMBasicBlockAsValue: function(BB: PLLVMBasicBlock): PLLVMValue; cdecl;
{ Determine whether a PLLVMValue is itself a basic block. }
LLVMValueIsBasicBlock: function(Val: PLLVMValue): Boolean; cdecl;
{ Convert a PLLVMValue to a PLLVMBasicBlock instance. }
LLVMValueAsBasicBlock: function(Val: PLLVMValue): PLLVMBasicBlock; cdecl;
{ Obtain the function to which a basic block belongs. }
LLVMGetBasicBlockParent: function(BB: PLLVMBasicBlock): PLLVMValue; cdecl;
{ Obtain the terminator instruction for a basic block.
If the basic block does not have a terminator (it is not well-formed if
it doesn't), then NULL is returned.
The returned PLLVMValue corresponds to a llvm::TerminatorInst. }
LLVMGetBasicBlockTerminator: function(BB: PLLVMBasicBlock): PLLVMValue; cdecl;
{ Obtain the number of basic blocks in a function.
@param Fn Function value to operate on. }
LLVMCountBasicBlocks: function(Fn: PLLVMValue): Cardinal; cdecl;
{ Obtain all of the basic blocks in a function.
This operates on a function value. The BasicBlocks parameter is a
pointer to a pre-allocated array of PLLVMBasicBlock of at least
LLVMCountBasicBlocks in length. This array is populated with
PLLVMBasicBlock instances. }
LLVMGetBasicBlocks: procedure(Fn: PLLVMValue; BasicBlocks: PLLVMBasicBlockPtrArray); cdecl;
{ Obtain the first basic block in a function.
The returned basic block can be used as an iterator. You will likely
eventually call into LLVMGetNextBasicBlock with it. }
LLVMGetFirstBasicBlock: function(Fn: PLLVMValue): PLLVMBasicBlock; cdecl;
{ Obtain the last basic block in a function. }
LLVMGetLastBasicBlock: function(Fn: PLLVMValue): PLLVMBasicBlock; cdecl;
{ Advance a basic block iterator. }
LLVMGetNextBasicBlock: function(BB: PLLVMBasicBlock): PLLVMBasicBlock; cdecl;
{ Go backwards in a basic block iterator. }
LLVMGetPreviousBasicBlock: function(BB: PLLVMBasicBlock): PLLVMBasicBlock; cdecl;
{ Obtain the basic block that corresponds to the entry point of a
function. }
LLVMGetEntryBasicBlock: function(Fn: PLLVMValue): PLLVMBasicBlock; cdecl;
{ Append a basic block to the end of a function. }
LLVMAppendBasicBlockInContext: function(C: PLLVMContext; Fn: PLLVMValue; const Name: PAnsiChar): PLLVMBasicBlock; cdecl;
{ Append a basic block to the end of a function using the global
context. }
LLVMAppendBasicBlock: function(Fn: PLLVMValue; const Name: PAnsiChar): PLLVMBasicBlock; cdecl;
{ Insert a basic block in a function before another basic block.
The function to add to is determined by the function of the
passed basic block. }
LLVMInsertBasicBlockInContext: function(C: PLLVMContext; BB: PLLVMBasicBlock; const Name: PAnsiChar): PLLVMBasicBlock; cdecl;
{ Insert a basic block in a function using the global context. }
LLVMInsertBasicBlock: function(InsertBeforeBB: PLLVMBasicBlock; const Name: PAnsiChar): PLLVMBasicBlock; cdecl;
{ Remove a basic block from a function and delete it.
This deletes the basic block from its containing function and deletes
the basic block itself. }
LLVMDeleteBasicBlock: procedure(BB: PLLVMBasicBlock); cdecl;
{ Remove a basic block from a function.
This deletes the basic block from its containing function but keep
the basic block alive. }
LLVMRemoveBasicBlockFromParent: procedure(BB: PLLVMBasicBlock); cdecl;
{ Move a basic block to before another one. }
LLVMMoveBasicBlockBefore: procedure(BB: PLLVMBasicBlock; MovePos: PLLVMBasicBlock); cdecl;
{ Move a basic block to after another one. }
LLVMMoveBasicBlockAfter: procedure(BB: PLLVMBasicBlock; MovePos: PLLVMBasicBlock); cdecl;
{ Obtain the first instruction in a basic block.
The returned PLLVMValue corresponds to a llvm::Instruction
instance. }
LLVMGetFirstInstruction: function(BB: PLLVMBasicBlock): PLLVMValue; cdecl;
{ Obtain the last instruction in a basic block.
The returned PLLVMValue corresponds to a LLVM:Instruction. }
LLVMGetLastInstruction: function(BB: PLLVMBasicBlock): PLLVMValue; cdecl;
{ Determine whether an instruction has any metadata attached. }
LLVMHasMetadata: function(Val: PLLVMValue): Integer; cdecl;
{ Return metadata associated with an instruction value. }
LLVMGetMetadata: function(Val: PLLVMValue; KindID: Cardinal): PLLVMValue; cdecl;
{ Set metadata associated with an instruction value. }
LLVMSetMetadata: procedure(Val: PLLVMValue; KindID: Cardinal; Node: PLLVMValue); cdecl;
{ Obtain the basic block to which an instruction belongs. }
LLVMGetInstructionParent: function(Inst: PLLVMValue): PLLVMBasicBlock; cdecl;
{ Obtain the instruction that occurs after the one specified.
The next instruction will be from the same basic block. If this is the
last instruction in a basic block, NULL will be returned. }
LLVMGetNextInstruction: function(Inst: PLLVMValue): PLLVMValue; cdecl;
{ Obtain the instruction that occurred before this one.
If the instruction is the first instruction in a basic block, NULL will be
returned. }
LLVMGetPreviousInstruction: function(Inst: PLLVMValue): PLLVMValue; cdecl;
{ Remove and delete an instruction.
The instruction specified is removed from its containing building block
and then deleted. }
LLVMInstructionEraseFromParent: procedure(Inst: PLLVMValue); cdecl;
{ Obtain the code opcode for an individual instruction. }
LLVMGetInstructionOpcode: function(Inst: PLLVMValue): TLLVMOpcode; cdecl;
{ Obtain the predicate of an instruction.
This is only valid for instructions that correspond to llvm::ICmpInst or
llvm::ConstantExpr whose opcode is llvm::Instruction::ICmp. }
LLVMGetICmpPredicate: function(Inst: PLLVMValue): TLLVMIntPredicate; cdecl;
{ Set the calling convention for a call instruction.
This expects an PLLVMValue that corresponds to a llvm::CallInst or
llvm::InvokeInst. }
LLVMSetInstructionCallConv: procedure(Instr: PLLVMValue; CC: Cardinal); cdecl;
{ Obtain the calling convention for a call instruction.
This is the opposite of LLVMSetInstructionCallConv. Reads its
usage. }
LLVMGetInstructionCallConv: function(Instr: PLLVMValue): Cardinal; cdecl;
LLVMAddInstrAttribute: procedure(Instr: PLLVMValue; Index: Cardinal; Unknown: TLLVMAttribute); cdecl;
LLVMRemoveInstrAttribute: procedure(Instr: PLLVMValue; Index: Cardinal; Unknown: TLLVMAttribute); cdecl;
LLVMSetInstrParamAlignment: procedure(Instr: PLLVMValue; Index: Cardinal; align: Cardinal); cdecl;
{ Obtain whether a call instruction is a tail call.
This only works on llvm::CallInst instructions. }
LLVMIsTailCall: function(CallInst: PLLVMValue): Boolean; cdecl;
{ Set whether a call instruction is a tail call.
This only works on llvm::CallInst instructions. }
LLVMSetTailCall: procedure(CallInst: PLLVMValue; IsTailCall: Boolean); cdecl;
{ Obtain the default destination basic block of a switch instruction.
This only works on llvm::SwitchInst instructions. }
LLVMGetSwitchDefaultDest: function(SwitchInstr: PLLVMValue): PLLVMBasicBlock; cdecl;
{ Add an incoming value to the end of a PHI list. }
LLVMAddIncoming: procedure(PhiNode: PLLVMValue; IncomingValues: PLLVMValuePtrArray; IncomingBlocks: PLLVMBasicBlockPtrArray; Count: Cardinal); cdecl;
{ Obtain the number of incoming basic blocks to a PHI node. }
LLVMCountIncoming: function(PhiNode: PLLVMValue): Cardinal; cdecl;
{ Obtain an incoming value to a PHI node as a PLLVMValue. }
LLVMGetIncomingValue: function(PhiNode: PLLVMValue; Index: Cardinal): PLLVMValue; cdecl;
{ Obtain an incoming value to a PHI node as a PLLVMBasicBlock. }
LLVMGetIncomingBlock: function(PhiNode: PLLVMValue; Index: Cardinal): PLLVMBasicBlock; cdecl;
LLVMCreateBuilderInContext: function(C: PLLVMContext): PLLVMBuilder; cdecl;
LLVMCreateBuilder: function: PLLVMBuilder; cdecl;
LLVMPositionBuilder: procedure(Builder: PLLVMBuilder; Block: PLLVMBasicBlock; Instr: PLLVMValue); cdecl;
LLVMPositionBuilderBefore: procedure(Builder: PLLVMBuilder; Instr: PLLVMValue); cdecl;
LLVMPositionBuilderAtEnd: procedure(Builder: PLLVMBuilder; Block: PLLVMBasicBlock); cdecl;
LLVMGetInsertBlock: function(Builder: PLLVMBuilder): PLLVMBasicBlock; cdecl;
LLVMClearInsertionPosition: procedure(Builder: PLLVMBuilder); cdecl;
LLVMInsertIntoBuilder: procedure(Builder: PLLVMBuilder; Instr: PLLVMValue); cdecl;
LLVMInsertIntoBuilderWithName: procedure(Builder: PLLVMBuilder; Instr: PLLVMValue; const Name: PAnsiChar); cdecl;
LLVMDisposeBuilder: procedure(Builder: PLLVMBuilder); cdecl;
{ Metadata }
LLVMSetCurrentDebugLocation: procedure(Builder: PLLVMBuilder; L: PLLVMValue); cdecl;
LLVMGetCurrentDebugLocation: function(Builder: PLLVMBuilder): PLLVMValue; cdecl;
LLVMSetInstDebugLocation: procedure(Builder: PLLVMBuilder; Instr: PLLVMValue); cdecl;
{ Terminators }
LLVMBuildRetVoid: function(Builder: PLLVMBuilder): PLLVMValue; cdecl;
LLVMBuildRet: function(Builder: PLLVMBuilder; V: PLLVMValue): PLLVMValue; cdecl;
LLVMBuildAggregateRet: function(Builder: PLLVMBuilder; var RetVals: PLLVMValuePtrArray; N: Cardinal): PLLVMValue; cdecl;
LLVMBuildBr: function(Builder: PLLVMBuilder; Dest: PLLVMBasicBlock): PLLVMValue; cdecl;
LLVMBuildCondBr: function(Builder: PLLVMBuilder; &If: PLLVMValue; &Then: PLLVMBasicBlock; &Else: PLLVMBasicBlock): PLLVMValue; cdecl;
LLVMBuildSwitch: function(Builder: PLLVMBuilder; V: PLLVMValue; &Else: PLLVMBasicBlock; NumCases: Cardinal): PLLVMValue; cdecl;
LLVMBuildIndirectBr: function(Builder: PLLVMBuilder; Addr: PLLVMValue; NumDests: Cardinal): PLLVMValue; cdecl;
LLVMBuildInvoke: function(Builder: PLLVMBuilder; Fn: PLLVMValue; var Args: PLLVMValuePtrArray; NumArgs: Cardinal; &Then: PLLVMBasicBlock; Catch: PLLVMBasicBlock; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildLandingPad: function(Builder: PLLVMBuilder; Ty: PLLVMType; PersFn: PLLVMValue; NumClauses: Cardinal; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildResume: function(Builder: PLLVMBuilder; Exn: PLLVMValue): PLLVMValue; cdecl;
LLVMBuildUnreachable: function(Builder: PLLVMBuilder): PLLVMValue; cdecl;
{ Add a case to the switch instruction }
LLVMAddCase: procedure(Switch: PLLVMValue; OnVal: PLLVMValue; Dest: PLLVMBasicBlock); cdecl;
{ Add a destination to the indirectbr instruction }
LLVMAddDestination: procedure(IndirectBr: PLLVMValue; Dest: PLLVMBasicBlock); cdecl;
{ Add a catch or filter clause to the landingpad instruction }
LLVMAddClause: procedure(LandingPad: PLLVMValue; ClauseVal: PLLVMValue); cdecl;
{ Set the 'cleanup' flag in the landingpad instruction }
LLVMSetCleanup: procedure(LandingPad: PLLVMValue; Val: Boolean); cdecl;
{ Arithmetic }
LLVMBuildAdd: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildNSWAdd: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildNUWAdd: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildFAdd: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildSub: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildNSWSub: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildNUWSub: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildFSub: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildMul: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildNSWMul: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildNUWMul: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildFMul: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildUDiv: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildSDiv: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildExactSDiv: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildFDiv: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildURem: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildSRem: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildFRem: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildShl: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildLShr: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildAShr: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildAnd: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildOr: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildXor: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildBinOp: function(B: PLLVMBuilder; Op: TLLVMOpcode; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildNeg: function(Builder: PLLVMBuilder; V: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildNSWNeg: function(Builder: PLLVMBuilder; V: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildNUWNeg: function(Builder: PLLVMBuilder; V: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildFNeg: function(Builder: PLLVMBuilder; V: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildNot: function(Builder: PLLVMBuilder; V: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
{ Memory }
LLVMBuildMalloc: function(Builder: PLLVMBuilder; Ty: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildArrayMalloc: function(Builder: PLLVMBuilder; Ty: PLLVMType; Val: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildAlloca: function(Builder: PLLVMBuilder; Ty: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildArrayAlloca: function(Builder: PLLVMBuilder; Ty: PLLVMType; Val: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildFree: function(Builder: PLLVMBuilder; PointerVal: PLLVMValue): PLLVMValue; cdecl;
LLVMBuildLoad: function(Builder: PLLVMBuilder; PointerVal: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildStore: function(Builder: PLLVMBuilder; Val: PLLVMValue; Ptr: PLLVMValue): PLLVMValue; cdecl;
LLVMBuildGEP: function(Builder: PLLVMBuilder; Pointer: PLLVMValue; Indices: PLLVMValuePtrArray; NumIndices: Cardinal; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildInBoundsGEP: function(Builder: PLLVMBuilder; Pointer: PLLVMValue; var Indices: PLLVMValuePtrArray; NumIndices: Cardinal; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildStructGEP: function(Builder: PLLVMBuilder; Pointer: PLLVMValue; Idx: Cardinal; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildGlobalString: function(Builder: PLLVMBuilder; Str: PAnsiChar; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildGlobalStringPtr: function(Builder: PLLVMBuilder; Str: PAnsiChar; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMGetVolatile: function(MemoryAccessInst: PLLVMValue): PLLVMValue; cdecl;
LLVMSetVolatile: procedure(MemoryAccessInst: PLLVMValue; IsVolatile: Boolean); cdecl;
{ Casts }
LLVMBuildTrunc: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildZExt: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildSExt: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildFPToUI: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildFPToSI: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildUIToFP: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildSIToFP: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildFPTrunc: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildFPExt: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildPtrToInt: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildIntToPtr: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildBitCast: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildZExtOrBitCast: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildSExtOrBitCast: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildTruncOrBitCast: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildCast: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildPointerCast: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildIntCast: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildFPCast: function(Builder: PLLVMBuilder; Val: PLLVMValue; DestTy: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
{ Comparisons }
LLVMBuildICmp: function(Builder: PLLVMBuilder; Op: TLLVMIntPredicate; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildFCmp: function(Builder: PLLVMBuilder; Op: TLLVMRealPredicate; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
{ Miscellaneous instructions }
LLVMBuildPhi: function(Builder: PLLVMBuilder; Ty: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildCall: function(Builder: PLLVMBuilder; Fn: PLLVMValue; Args: PLLVMValuePtrArray; NumArgs: Cardinal; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildSelect: function(Builder: PLLVMBuilder; &If: PLLVMValue; &Then: PLLVMValue; &Else: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildVAArg: function(Builder: PLLVMBuilder; List: PLLVMValue; Ty: PLLVMType; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildExtractElement: function(Builder: PLLVMBuilder; VecVal: PLLVMValue; Index: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildInsertElement: function(Builder: PLLVMBuilder; VecVal: PLLVMValue; EltVal: PLLVMValue; Index: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildShuffleVector: function(Builder: PLLVMBuilder; V1: PLLVMValue; V2: PLLVMValue; Mask: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildExtractValue: function(Builder: PLLVMBuilder; AggVal: PLLVMValue; Index: Cardinal; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildInsertValue: function(Builder: PLLVMBuilder; AggVal: PLLVMValue; EltVal: PLLVMValue; Index: Cardinal; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildIsNull: function(Builder: PLLVMBuilder; Val: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildIsNotNull: function(Builder: PLLVMBuilder; Val: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
LLVMBuildPtrDiff: function(Builder: PLLVMBuilder; LHS: PLLVMValue; RHS: PLLVMValue; const Name: PAnsiChar): PLLVMValue; cdecl;
{ Changes the type of M so it can be passed to FunctionPassManagers and the
JIT. They take ModuleProviders for historical reasons. }
LLVMCreateModuleProviderForExistingModule: function(M: PLLVMModule): PLLVMModuleProvider; cdecl;
{ Destroys the module M. }
LLVMDisposeModuleProvider: procedure(M: PLLVMModuleProvider); cdecl;
LLVMCreateMemoryBufferWithContentsOfFile: function(Path: PAnsiChar; out OutMemBuf: PLLVMMemoryBuffer; out OutMessage: PAnsiChar): Boolean; cdecl;
LLVMCreateMemoryBufferWithSTDIN: function(out OutMemBuf: PLLVMMemoryBuffer; out OutMessage: PAnsiChar): Boolean; cdecl;
LLVMDisposeMemoryBuffer: procedure(MemBuf: PLLVMMemoryBuffer); cdecl;
{ Return the global pass registry, for use with initialization functions.}
LLVMGetGlobalPassRegistry: function: PLLVMPassRegistry; cdecl;
{ Constructs a new whole-module pass pipeline. This type of pipeline is
suitable for link-time optimization and whole-module transformations. }
LLVMCreatePassManager: function: PLLVMPassManager; cdecl;
{ Constructs a new function-by-function pass pipeline over the module
provider. It does not take ownership of the module provider. This type of
pipeline is suitable for code generation and JIT compilation tasks. }
LLVMCreateFunctionPassManagerForModule: function(M: PLLVMModule): PLLVMPassManager; cdecl;
{ Deprecated: Use LLVMCreateFunctionPassManagerForModule instead. }
LLVMCreateFunctionPassManager: function(MP: PLLVMModuleProvider): PLLVMPassManager; cdecl;
{ Initializes, executes on the provided module, and finalizes all of the
passes scheduled in the pass manager. Returns 1 if any of the passes
modified the module, 0 otherwise. }
LLVMRunPassManager: function(FPM: PLLVMPassManager; M: PLLVMModule): Boolean; cdecl;
{ Initializes all of the function passes scheduled in the function pass
manager. Returns 1 if any of the passes modified the module, 0 otherwise. }
LLVMInitializeFunctionPassManager: function(FPM: PLLVMPassManager): Boolean; cdecl;
{ Executes all of the function passes scheduled in the function pass manager
on the provided function. Returns 1 if any of the passes modified the
function, false otherwise. }
LLVMRunFunctionPassManager: function(FPM: PLLVMPassManager; F: PLLVMValue): Boolean; cdecl;
{ Finalizes all of the function passes scheduled in in the function pass
manager. Returns 1 if any of the passes modified the module, 0 otherwise. }
LLVMFinalizeFunctionPassManager: function(FPM: PLLVMPassManager): Boolean; cdecl;
{ Frees the memory of a pass pipeline. For function pipelines, does not free
the module provider. }
LLVMDisposePassManager: procedure(PM: PLLVMPassManager); cdecl;
{ Verifies that a module is valid, taking the specified action if not.
Optionally returns a human-readable description of any invalid constructs.
OutMessage must be disposed with LLVMDisposeMessage. }
LLVMVerifyModule: function(M: PLLVMModule; Action: TLLVMVerifierFailureAction; out OutMessage: PAnsiChar): Boolean; cdecl;
{ Verifies that a single function is valid, taking the specified action. Useful
for debugging. }
LLVMVerifyFunction: function(Fn: PLLVMValue; Action: TLLVMVerifierFailureAction): Boolean; cdecl;
{ Open up a ghostview window that displays the CFG of the current function.
Useful for debugging. }
LLVMViewFunctionCFG: procedure(Fn: PLLVMValue); cdecl;
LLVMViewFunctionCFGOnly: procedure(Fn: PLLVMValue); cdecl;
{ Builds a module from the bitcode in the specified memory buffer, returning a
reference to the module via the OutModule parameter. Returns 0 on success.
Optionally returns a human-readable error message via OutMessage. }
LLVMParseBitcode: function(MemBuf: PLLVMMemoryBuffer; out OutModule: PLLVMModule; out OutMessage: PAnsiChar): Boolean; cdecl;
LLVMParseBitcodeInContext: function(ContextRef: PLLVMContext; MemBuf: PLLVMMemoryBuffer; out OutModule: PLLVMModule; out OutMessage: PAnsiChar): Boolean; cdecl;
{ Reads a module from the specified path, returning via the OutMP parameter
a module provider which performs lazy deserialization. Returns 0 on success.
Optionally returns a human-readable error message via OutMessage. }
LLVMGetBitcodeModuleInContext: function(ContextRef: PLLVMContext; MemBuf: PLLVMMemoryBuffer; out OutM: PLLVMModule; out OutMessage: PAnsiChar): Boolean; cdecl;
LLVMGetBitcodeModule: function(MemBuf: PLLVMMemoryBuffer; out OutM: PLLVMModule; out OutMessage: PAnsiChar): Boolean; cdecl;
{ Deprecated: Use LLVMGetBitcodeModuleInContext instead. }
LLVMGetBitcodeModuleProviderInContext: function(ContextRef: PLLVMContext; MemBuf: PLLVMMemoryBuffer; out OutMP: PLLVMModuleProvider; out OutMessage: PAnsiChar): Boolean; cdecl;
{ Deprecated: Use LLVMGetBitcodeModule instead. }
LLVMGetBitcodeModuleProvider: function(MemBuf: PLLVMMemoryBuffer; out OutMP: PLLVMModuleProvider; out OutMessage: PAnsiChar): Boolean; cdecl;
{ Writes a module to the specified path. Returns 0 on success. }
LLVMWriteBitcodeToFile: function(M: PLLVMModule; Path: PAnsiChar): Integer; cdecl;
{ Writes a module to an open file descriptor. Returns 0 on success. }
LLVMWriteBitcodeToFD: function(M: PLLVMModule; FD: Integer; ShouldClose: Integer; Unbuffered: Integer): Integer; cdecl;
{ Deprecated for LLVMWriteBitcodeToFD. Writes a module to an open file
descriptor. Returns 0 on success. Closes the Handle. }
LLVMWriteBitcodeToFileHandle: function(M: PLLVMModule; Handle: Integer): Integer; cdecl;
{ Create a disassembler for the TripleName. Symbolic disassembly is
supported by passing a block of information in the DisInfo parameter
and specifying the
TagType and callback functions as described above. These can all be passed
as NULL. If successful, this returns a disassembler context. If not, it
returns NULL. }
LLVMCreateDisasm: function(TripleName: PAnsiChar; DisInfo: Pointer; TagType: Integer; GetOpInfo: TLLVMOpInfoCallback; SymbolLookUp: TLLVMSymbolLookupCallback): PLLVMDisasmContext; cdecl;
{ Set the disassembler's options. Returns 1 if it can set the Options and 0
otherwise. }
LLVMSetDisasmOptions: function(DC: PLLVMDisasmContext; Options: TLLVMDisassemblerOptions): Integer; cdecl;
{ Dispose of a disassembler context. }
LLVMDisasmDispose: procedure(DC: PLLVMDisasmContext); cdecl;
{ Disassemble a single instruction using the disassembler context specified
in the parameter DC. The bytes of the instruction are specified in the
parameter Bytes, and contains at least BytesSize number of bytes. The
instruction is at the address specified by the PC parameter. If a valid
instruction can be disassembled, its string is returned indirectly in
OutString whose size is specified in the parameter OutStringSize. This
function returns the number of bytes in the instruction or zero if there
was no valid instruction. }
LLVMDisasmInstruction: function(DC: PLLVMDisasmContext; Bytes: PByte; BytesSize: UInt64; PC: UInt64; out OutString: PAnsiChar; OutStringSize: NativeUInt): NativeUInt; cdecl;
{ Execution Engine }
LLVMLinkInJIT: procedure; cdecl;
LLVMLinkInInterpreter: procedure; cdecl;
{ Operations on generic values }
LLVMCreateGenericValueOfInt: function(Ty: PLLVMType; N: UInt64; IsSigned: Boolean): PLLVMGenericValue; cdecl;
LLVMCreateGenericValueOfPointer: function(P: Pointer): PLLVMGenericValue; cdecl;
LLVMCreateGenericValueOfFloat: function(Ty: PLLVMType; N: Double): PLLVMGenericValue; cdecl;
LLVMGenericValueIntWidth: function(GenValRef: PLLVMGenericValue): Cardinal; cdecl;
LLVMGenericValueToInt: function(GenVal: PLLVMGenericValue; IsSigned: Boolean): UInt64; cdecl;
LLVMGenericValueToPointer: function(GenVal: PLLVMGenericValue): Pointer; cdecl;
LLVMGenericValueToFloat: function(TyRef: PLLVMType; GenVal: PLLVMGenericValue): Double; cdecl;
LLVMDisposeGenericValue: procedure(GenVal: PLLVMGenericValue); cdecl;
{ Operations on execution engines }
LLVMCreateExecutionEngineForModule: function(out OutEE: PLLVMExecutionEngine; M: PLLVMModule; out OutError: PAnsiChar): Boolean; cdecl;
LLVMCreateInterpreterForModule: function(out OutInterp: PLLVMExecutionEngine; M: PLLVMModule; out OutError: PAnsiChar): Boolean; cdecl;
LLVMCreateJITCompilerForModule: function(out OutJIT: PLLVMExecutionEngine; M: PLLVMModule; OptLevel: TLLVMCodeGenOptLevel; out OutError: PAnsiChar): Boolean; cdecl;
LLVMCreateExecutionEngine: function(out OutEE: PLLVMExecutionEngine; MP: PLLVMModuleProvider; out OutError: PAnsiChar): Boolean; cdecl; // -> deprecated, use LLVMCreateExecutionEngineForModule instead
LLVMCreateInterpreter: function(out OutInterp: PLLVMExecutionEngine; MP: PLLVMModuleProvider; out OutError: PAnsiChar): Boolean; cdecl; // -> deprecated, use LLVMCreateInterpreterForModule instead
LLVMCreateJITCompiler: function(out OutJIT: PLLVMExecutionEngine; MP: PLLVMModuleProvider; OptLevel: TLLVMCodeGenOptLevel; out OutError: PAnsiChar): Boolean; cdecl; // -> deprecated, use LLVMCreateJITCompilerForModule instead
LLVMDisposeExecutionEngine: procedure(EE: PLLVMExecutionEngine); cdecl;
LLVMRunStaticConstructors: procedure(EE: PLLVMExecutionEngine); cdecl;
LLVMRunStaticDestructors: procedure(EE: PLLVMExecutionEngine); cdecl;
LLVMRunFunctionAsMain: function(EE: PLLVMExecutionEngine; F: PLLVMValue; ArgC: Cardinal; var ArgV: PAnsiChar; var EnvP: PAnsiChar): Integer; cdecl;
LLVMRunFunction: function(EE: PLLVMExecutionEngine; F: PLLVMValue; NumArgs: Cardinal; var Args: PLLVMGenericValue): PLLVMGenericValue; cdecl;
LLVMFreeMachineCodeForFunction: procedure(EE: PLLVMExecutionEngine; F: PLLVMValue); cdecl;
LLVMAddModule: procedure(EE: PLLVMExecutionEngine; M: PLLVMModule); cdecl;
LLVMAddModuleProvider: procedure(EE: PLLVMExecutionEngine; MP: PLLVMModuleProvider); cdecl; // -> deprecated, use LLVMAddModule instead
LLVMRemoveModule: function(EE: PLLVMExecutionEngine; M: PLLVMModule; out OutMod: PLLVMModule; out OutError: PAnsiChar): Boolean; cdecl;
LLVMRemoveModuleProvider: function(EE: PLLVMExecutionEngine; MP: PLLVMModuleProvider; out OutMod: PLLVMModule; out OutError: PAnsiChar): Boolean; cdecl; // -> deprecated, use LLVMRemoveModule instead
LLVMFindFunction: function(EE: PLLVMExecutionEngine; const Name: PAnsiChar; out OutFn: PLLVMValue): Boolean; cdecl;
LLVMRecompileAndRelinkFunction: function(EE: PLLVMExecutionEngine; Fn: PLLVMValue): Pointer; cdecl;
LLVMGetExecutionEngineTargetData: function(EE: PLLVMExecutionEngine): PLLVMTargetData; cdecl;
LLVMAddGlobalMapping: procedure(EE: PLLVMExecutionEngine; Global: PLLVMValue; Addr: Pointer); cdecl;
LLVMGetPointerToGlobal: function(EE: PLLVMExecutionEngine; Global: PLLVMValue): Pointer; cdecl;
LLVMAddAggressiveDCEPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddCFGSimplificationPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddDeadStoreEliminationPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddGVNPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddIndVarSimplifyPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddInstructionCombiningPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddJumpThreadingPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddLICMPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddLoopDeletionPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddLoopIdiomPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddLoopRotatePass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddLoopUnrollPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddLoopUnswitchPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddMemCpyOptPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddPromoteMemoryToRegisterPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddReassociatePass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddSCCPPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddScalarReplAggregatesPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddScalarReplAggregatesPassSSA: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddScalarReplAggregatesPassWithThreshold: procedure(PM: PLLVMPassManager;
Threshold: Integer); cdecl;
LLVMAddSimplifyLibCallsPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddTailCallEliminationPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddConstantPropagationPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddDemoteMemoryToRegisterPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddVerifierPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddCorrelatedValuePropagationPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddEarlyCSEPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddLowerExpectIntrinsicPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddTypeBasedAliasAnalysisPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddBasicAliasAnalysisPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddBBVectorizePass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddLoopVectorizePass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddArgumentPromotionPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddConstantMergePass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddDeadArgEliminationPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddFunctionAttrsPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddFunctionInliningPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddAlwaysInlinerPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddGlobalDCEPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddGlobalOptimizerPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddIPConstantPropagationPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddPruneEHPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddIPSCCPPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddInternalizePass: procedure(PM: PLLVMPassManager; AllButMain: Cardinal); cdecl;
LLVMAddStripDeadPrototypesPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMAddStripSymbolsPass: procedure(PM: PLLVMPassManager); cdecl;
LLVMPassManagerBuilderCreate: function: PLLVMPassManagerBuilder; cdecl;
LLVMPassManagerBuilderDispose: procedure(PMB: PLLVMPassManagerBuilder); cdecl;
LLVMPassManagerBuilderSetOptLevel: procedure(PMB: PLLVMPassManagerBuilder; OptLevel: TLLVMCodeGenOptLevel); cdecl;
LLVMPassManagerBuilderSetSizeLevel: procedure(PMB: PLLVMPassManagerBuilder; SizeLevel: Cardinal); cdecl;
LLVMPassManagerBuilderSetDisableUnitAtATime: procedure(PMB: PLLVMPassManagerBuilder; Value: Boolean); cdecl;
LLVMPassManagerBuilderSetDisableUnrollLoops: procedure(PMB: PLLVMPassManagerBuilder; Value: Boolean); cdecl;
LLVMPassManagerBuilderSetDisableSimplifyLibCalls: procedure(PMB: PLLVMPassManagerBuilder; Value: Boolean); cdecl;
LLVMPassManagerBuilderUseInlinerWithThreshold: procedure(PMB: PLLVMPassManagerBuilder; Threshold: Cardinal); cdecl;
LLVMPassManagerBuilderPopulateFunctionPassManager: procedure(PMB: PLLVMPassManagerBuilder; PM: PLLVMPassManager); cdecl;
LLVMPassManagerBuilderPopulateModulePassManager: procedure(PMB: PLLVMPassManagerBuilder; PM: PLLVMPassManager); cdecl;
LLVMPassManagerBuilderPopulateLTOPassManager: procedure(PMB: PLLVMPassManagerBuilder; PM: PLLVMPassManager; Internalize, RunInliner: Boolean); cdecl;
LLVMInitializeCodeGen: procedure; cdecl;
{ LLVMInitializeX86* }
LLVMInitializeX86TargetInfo: procedure; cdecl;
LLVMInitializeX86Target: procedure; cdecl;
LLVMInitializeX86TargetMC: procedure; cdecl;
LLVMInitializeX86AsmPrinter: procedure; cdecl;
LLVMInitializeX86AsmParser: procedure; cdecl;
LLVMInitializeX86Disassembler: procedure; cdecl;
{ LLVMInitializeAllTargetInfos - The main program should call this function
if it wants access to all available targets that LLVM is configured to
support. }
LLVMInitializeAllTargetInfos: procedure; cdecl;
{ LLVMInitializeAllTargets - The main program should call this function if it
wants to link in all available targets that LLVM is configured to support. }
LLVMInitializeAllTargets: procedure; cdecl;
{ LLVMInitializeAllTargetMCs - The main program should call this function if
it wants access to all available target MC that LLVM is configured to
support. }
LLVMInitializeAllTargetMCs: procedure; cdecl;
{ LLVMInitializeAllAsmPrinters - The main program should call this function
if it wants all asm printers that LLVM is configured to support, to make
them available via the TargetRegistry. }
LLVMInitializeAllAsmPrinters: procedure; cdecl;
{ LLVMInitializeAllAsmParsers - The main program should call this function
if it wants all asm parsers that LLVM is configured to support, to make
them available via the TargetRegistry. }
LLVMInitializeAllAsmParsers: procedure; cdecl;
{ LLVMInitializeAllDisassemblers - The main program should call this function
if it wants all disassemblers that LLVM is configured to support, to make
them available via the TargetRegistry. }
LLVMInitializeAllDisassemblers: procedure; cdecl;
{ LLVMInitializeNativeTarget - The main program should call this function to
initialize the native target corresponding to the host. This is useful
for JIT applications to ensure that the target gets linked in correctly. }
LLVMInitializeNativeTarget: function: Boolean; cdecl;
{ Creates target data from a target layout string. }
LLVMCreateTargetData: function(StringRep: PAnsiChar): PLLVMTargetData; cdecl;
{ Deallocates a TargetData. }
LLVMDisposeTargetData: procedure(TargetData: PLLVMTargetData); cdecl;
{ Returns the first llvm::Target in the registered targets list. }
LLVMGetFirstTarget: function: PLLVMTarget; cdecl;
{ Returns the next llvm::Target given a previous one (or null if there's none) }
LLVMGetNextTarget: function(T: PLLVMTarget): PLLVMTarget; cdecl;
{ Returns the name of a target. See llvm::Target::getName }
LLVMGetTargetName: function(T: PLLVMTarget): PAnsiChar; cdecl;
{ Returns the description of a target. See llvm::Target::getDescription }
LLVMGetTargetDescription: function (T: PLLVMTarget): PAnsiChar; cdecl;
{ Returns if the target has a JIT }
LLVMTargetHasJIT: function(T: PLLVMTarget): Boolean; cdecl;
{ Returns if the target has a TargetMachine associated }
LLVMTargetHasTargetMachine: function(T: PLLVMTarget): Boolean; cdecl;
{ Returns if the target as an ASM backend (required for emitting output) }
LLVMTargetHasAsmBackend: function(T: PLLVMTarget): Boolean; cdecl;
{ Creates a new llvm::TargetMachine. See llvm::Target::createTargetMachine }
LLVMCreateTargetMachine: function(T: PLLVMTarget;
Triple: PAnsiChar; CPU: PAnsiChar; Features: PAnsiChar;
Level: TLLVMCodeGenOptLevel; Reloc: TLLVMRelocMode;
CodeModel: TLLVMCodeModel): PLLVMTargetMachine; cdecl;
{ Dispose the PLLVMTargetMachine instance generated by
LLVMCreateTargetMachine. }
LLVMDisposeTargetMachine: procedure(T: PLLVMTargetMachine); cdecl;
{ Returns the Target used in a TargetMachine }
LLVMGetTargetMachineTarget: function (T: PLLVMTargetMachine): PLLVMTarget; cdecl;
{ Returns the triple used creating this target machine. See
llvm::TargetMachine::getTriple. The result needs to be disposed with
LLVMDisposeMessage. }
LLVMGetTargetMachineTriple: function(T: PLLVMTargetMachine): PAnsiChar; cdecl;
{ Returns the cpu used creating this target machine. See
llvm::TargetMachine::getCPU. The result needs to be disposed with
LLVMDisposeMessage. }
LLVMGetTargetMachineCPU: function(T: PLLVMTargetMachine): PAnsiChar; cdecl;
{ Returns the feature string used creating this target machine. See
llvm::TargetMachine::getFeatureString. The result needs to be disposed with
LLVMDisposeMessage. }
LLVMGetTargetMachineFeatureString: function(T: PLLVMTargetMachine): PAnsiChar; cdecl;
{ Returns the llvm::DataLayout used for this llvm:TargetMachine. }
LLVMGetTargetMachineData: function(T: PLLVMTargetMachine): PLLVMTargetData; cdecl;
{ Emits an asm or object file for the given module to the filename. This
wraps several c++ only classes (among them a file stream). Returns any
error in ErrorMessage. Use LLVMDisposeMessage to dispose the message. }
LLVMTargetMachineEmitToFile: function(T: PLLVMTargetMachine; M: PLLVMModule;
Filename: PAnsiChar; Codegen: TLLVMCodeGenFileType;
var ErrorMessage: PAnsiChar): PLLVMTargetData; cdecl;
{ ObjectFile creation }
LLVMCreateObjectFile: function(MemBuf: PLLVMMemoryBuffer): PLLVMObjectFile; cdecl;
LLVMDisposeObjectFile: procedure(ObjectFile: PLLVMObjectFile); cdecl;
{ ObjectFile Section iterators }
LLVMGetSections: function(ObjectFile: PLLVMObjectFile): PLLVMSectionIterator; cdecl;
LLVMDisposeSectionIterator: procedure(SI: PLLVMSectionIterator); cdecl;
LLVMIsSectionIteratorAtEnd: function(ObjectFile: PLLVMObjectFile; SI: PLLVMSectionIterator): Boolean; cdecl;
LLVMMoveToNextSection: procedure(SI: PLLVMSectionIterator); cdecl;
LLVMMoveToContainingSection: procedure(Sect: PLLVMSectionIterator; Sym: PLLVMSymbolIterator); cdecl;
{ ObjectFile Symbol iterators }
LLVMGetSymbols: function(ObjectFile: PLLVMObjectFile): PLLVMSymbolIterator; cdecl;
LLVMDisposeSymbolIterator: procedure(SI: PLLVMSymbolIterator); cdecl;
LLVMIsSymbolIteratorAtEnd: function(ObjectFile: PLLVMObjectFile; SI: PLLVMSymbolIterator): Boolean; cdecl;
LLVMMoveToNextSymbol: procedure(SI: PLLVMSymbolIterator); cdecl;
{ SectionRef accessors }
LLVMGetSectionName: function(SI: PLLVMSectionIterator): PAnsiChar; cdecl;
LLVMGetSectionSize: function(SI: PLLVMSectionIterator): UInt64; cdecl;
LLVMGetSectionContents: function(SI: PLLVMSectionIterator): PAnsiChar; cdecl;
LLVMGetSectionAddress: function(SI: PLLVMSectionIterator): UInt64; cdecl;
LLVMGetSectionContainsSymbol: function(SI: PLLVMSectionIterator; Sym: PLLVMSymbolIterator): Boolean; cdecl;
{ Section Relocation iterators }
LLVMGetRelocations: function(Section: PLLVMSectionIterator): PLLVMRelocationIterator; cdecl;
LLVMDisposeRelocationIterator: procedure(RI: PLLVMRelocationIterator); cdecl;
LLVMIsRelocationIteratorAtEnd: function(Section: PLLVMSectionIterator; RI: PLLVMRelocationIterator): Boolean; cdecl;
LLVMMoveToNextRelocation: procedure(RI: PLLVMRelocationIterator); cdecl;
{ SymbolRef accessors }
LLVMGetSymbolName: function(SI: PLLVMSymbolIterator): PAnsiChar; cdecl;
LLVMGetSymbolAddress: function(SI: PLLVMSymbolIterator): UInt64; cdecl;
LLVMGetSymbolFileOffset: function(SI: PLLVMSymbolIterator): UInt64; cdecl;
LLVMGetSymbolSize: function(SI: PLLVMSymbolIterator): UInt64; cdecl;
{ RelocationRef accessors }
LLVMGetRelocationAddress: function(RI: PLLVMRelocationIterator): UInt64; cdecl;
LLVMGetRelocationOffset: function(RI: PLLVMRelocationIterator): UInt64; cdecl;
LLVMGetRelocationSymbol: function(RI: PLLVMRelocationIterator): PLLVMSymbolIterator; cdecl;
LLVMGetRelocationType: function(RI: PLLVMRelocationIterator): UInt64; cdecl;
{ NOTE: Caller takes ownership of returned string of the two following functions. }
LLVMGetRelocationTypeName: function(RI: PLLVMRelocationIterator): PAnsiChar; cdecl;
LLVMGetRelocationValueString: function(RI: PLLVMRelocationIterator): PAnsiChar; cdecl;
{ Adds target data information to a pass manager. This does not take ownership
of the target data. }
LLVMAddTargetData: procedure(TargetData: PLLVMTargetData; PassManager: PLLVMPassManager); cdecl;
{ Adds target library information to a pass manager. This does not take
ownership of the target library info. }
LLVMAddTargetLibraryInfo: procedure(TargetData: PLLVMTargetLibraryInfo; PassManager: PLLVMPassManager); cdecl;
{ Converts target data to a target layout string. The string must be disposed
with LLVMDisposeMessage. }
LLVMCopyStringRepOfTargetData: function(TargetData: PLLVMTargetData): PAnsiChar; cdecl;
{ Returns the byte order of a target, either LLVMBigEndian or
LLVMLittleEndian. }
LLVMByteOrder: function(TargetData: PLLVMTargetData): TLLVMByteOrdering; cdecl;
{ Returns the pointer size in bytes for a target. }
LLVMPointerSize: function(TargetData: PLLVMTargetData): Cardinal; cdecl;
{ Returns the pointer size in bytes for a target for a specified
address space. }
LLVMPointerSizeForAS: function(TargetData: PLLVMTargetData; AddressSpace: Cardinal): Cardinal; cdecl;
{ Returns the integer type that is the same size as a pointer on a target. }
LLVMIntPtrType: function(TargetData: PLLVMTargetData): PLLVMType; cdecl;
{ Returns the integer type that is the same size as a pointer on a target.
This version allows the address space to be specified. }
LLVMIntPtrTypeForAS: function(TargetData: PLLVMTargetData; AddressSpace: Cardinal): PLLVMType; cdecl;
{ Computes the size of a type in bytes for a target. }
LLVMSizeOfTypeInBits: function(TargetData: PLLVMTargetData; Unknown: PLLVMType): UInt64; cdecl;
{ Computes the storage size of a type in bytes for a target. }
LLVMStoreSizeOfType: function(TargetData: PLLVMTargetData; Unknown: PLLVMType): UInt64; cdecl;
{ Computes the ABI size of a type in bytes for a target. }
LLVMABISizeOfType: function(TargetData: PLLVMTargetData; Unknown: PLLVMType): UInt64; cdecl;
{ Computes the ABI alignment of a type in bytes for a target. }
LLVMABIAlignmentOfType: function(TargetData: PLLVMTargetData; Unknown: PLLVMType): Cardinal; cdecl;
{ Computes the call frame alignment of a type in bytes for a target. }
LLVMCallFrameAlignmentOfType: function(TargetData: PLLVMTargetData; Unknown: PLLVMType): Cardinal; cdecl;
{ Computes the preferred alignment of a type in bytes for a target. }
LLVMPreferredAlignmentOfType: function(TargetData: PLLVMTargetData; Unknown: PLLVMType): Cardinal; cdecl;
{ Computes the preferred alignment of a global variable in bytes for a
target. }
LLVMPreferredAlignmentOfGlobal: function(TargetData: PLLVMTargetData; GlobalVar: PLLVMValue): Cardinal; cdecl;
{ Computes the structure element that contains the byte offset for a
target. }
LLVMElementAtOffset: function(TargetData: PLLVMTargetData; StructTy: PLLVMType; Offset: UInt64): Cardinal; cdecl;
{ Computes the byte offset of the indexed struct element for a target. }
LLVMOffsetOfElement: function(TargetData: PLLVMTargetData; StructTy: PLLVMType; Element: Cardinal): UInt64; cdecl;
{ Returns a printable string. }
LTOGetVersion: function: PAnsiChar; cdecl;
{ Returns the last error string or NULL if last operation was successful. }
LTOGetErrorMessage: function: PAnsiChar; cdecl;
{ Checks if a file is a loadable object file. }
LTOModuleIsObjectFile: function(path: PAnsiChar): Boolean; cdecl;
{ Checks if a file is a loadable object compiled for requested target. }
LTOModuleIsObjectFileForTarget: function(path: PAnsiChar; targetTriplePrefix: PAnsiChar): Boolean; cdecl;
{ Checks if a buffer is a loadable object file. }
LTOModuleIsObjectFileInMemory: function(mem: Pointer; length: NativeUInt): Boolean; cdecl;
{ Checks if a buffer is a loadable object compiled for requested target. }
LTOModuleIsObjectFileInMemoryForTarget: function (mem: Pointer; length: NativeUInt; targetTriplePrefix: PAnsiChar): Boolean; cdecl;
{ Loads an object file from disk.
Returns NULL on error. }
LTOModuleCreate: function(path: PAnsiChar): PLTOModule; cdecl;
{ Loads an object file from memory.
Returns NULL on error. }
LTOModuleCreateFromMemory: function(mem: Pointer; length: NativeUInt): PLTOModule; cdecl;
{ Loads an object file from disk. The seek point of fd is not preserved.
Returns NULL on error. }
LTOModuleCreateFromFd: function(fd: Integer; path: PAnsiChar; fileSize: NativeUInt): PLTOModule; cdecl;
{ Loads an object file from disk. The seek point of fd is not preserved.
Returns NULL on error. }
LTOModuleCreateFromFdAtOffset: function(fd: Integer; path: PAnsiChar; fileSize: NativeUInt; mapSize: NativeUInt; offset: Int64): PLTOModule; cdecl;
{ Frees all memory internally allocated by the module.
Upon return the PLTOModule is no longer valid. }
LTOModuleDispose: procedure(Module: PLTOModule); cdecl;
{ Returns triple string which the object module was compiled under. }
LTOModuleGetTargetTriple: function(module: PLTOModule): PAnsiChar; cdecl;
{ Sets triple string with which the object will be codegened. }
LTOModuleSetTargetTriple: procedure(module: PLTOModule; triple: PAnsiChar); cdecl;
{ Returns the number of symbols in the object module. }
LTOModuleGetNumSymbols: function(module: PLTOModule): Integer; cdecl;
{ Returns the name of the ith symbol in the object module. }
LTOModuleGetSymbolName: function(module: PLTOModule; index: Cardinal): PAnsiChar; cdecl;
{ Returns the attributes of the ith symbol in the object module. }
LTOModuleGetSymbolAttribute: function(module: PLTOModule; index: Cardinal): TLTOSymbolAttributes; cdecl;
{ Instantiates a code generator.
Returns NULL on error. }
LTOCodegenCreate: function: PLTOCodeGenerator; cdecl;
{ Frees all code generator and all memory it internally allocated.
Upon return the PLTOCodeGenerator is no longer valid. }
LTOCodegenDispose: procedure(Unknown: PLTOCodeGenerator); cdecl;
{ Add an object module to the set of modules for which code will be generated.
Returns true on error. }
LTOCodegenAddModule: function(cg: PLTOCodeGenerator; &mod: PLTOModule): Boolean; cdecl;
{ Sets if debug info should be generated.
Returns true on error. }
LTOCodegenSetDebugModel: function(cg: PLTOCodeGenerator; Unknown: TLTODebugModel): Boolean; cdecl;
{ Sets which PIC code model to generated.
Returns true on error. }
LTOCodegenSetPicModel: function(cg: PLTOCodeGenerator; Unknown: TLTOCodegenModel): Boolean; cdecl;
{ Sets the cpu to generate code for. }
LTOCodegenSetCpu: procedure(cg: PLTOCodeGenerator; cpu: PAnsiChar); cdecl;
{ Sets the location of the assembler tool to run. If not set, libLTO
will use gcc to invoke the assembler. }
LTOCodegenSetAssemblerPath: procedure(cg: PLTOCodeGenerator; path: PAnsiChar); cdecl;
{ Sets extra arguments that libLTO should pass to the assembler. }
LTOCodegenSetAssemblerArgs: procedure(cg: PLTOCodeGenerator; var args: PAnsiChar; nargs: Integer); cdecl;
{ Adds to a list of all global symbols that must exist in the final
generated code. If a function is not listed, it might be
inlined into every usage and optimized away. }
LTOCodegenAddMustPreserveSymbol: procedure(cg: PLTOCodeGenerator; symbol: PAnsiChar); cdecl;
{ Writes a new object file at the specified path that contains the merged
contents of all modules added so far.
Returns true on error. }
LTOCodegenWriteMergedModules: function(cg: PLTOCodeGenerator; path: PAnsiChar): Boolean; cdecl;
{ Generates code for all added modules into one native object file.
On success returns a pointer to a generated mach-o/ELF buffer and
length set to the buffer size. The buffer is owned by the
PLTOCodeGenerator and will be freed when lto_codegen_dispose()
is called, or lto_codegen_compile() is called again.
On failure, returns NULL. }
LTOCodegenCompile: function(cg: PLTOCodeGenerator; length: pNativeUInt): Pointer; cdecl;
{ Generates code for all added modules into one native object file.
The name of the file is written to name. Returns true on error. }
LTOCodegenCompileToFile: function(cg: PLTOCodeGenerator; var name: PAnsiChar): Boolean; cdecl;
{ Sets options to help debug codegen bugs. }
LTOCodegenDebugOptions: procedure(cg: PLTOCodeGenerator; unknown: PAnsiChar); cdecl;
function IsLLVMLoaded: Boolean;
procedure LoadLLVM(const LLVMLibName: string);
procedure UnloadLLVM;
implementation
resourcestring
RStrCannotLoadLLVMLib = 'Cannot load LLVM library! (%s)';
RStrFunctionNotFound = '%s not found!';
var
GLLVMLibrary: THandle = 0;
function IsLLVMLoaded: Boolean;
begin
Result := (GLLVMLibrary <> 0);
end;
procedure LoadLLVM(const LLVMLibName: string);
function Bind(const aFuncName: string): Pointer;
begin
Result := GetProcAddress(GLLVMLibrary, PAnsiChar(AnsiString(aFuncName)));
if not Assigned(Result) then
raise Exception.CreateFmt('Function %s is not found', [aFuncName]);
end;
begin
if not IsLLVMLoaded then
GLLVMLibrary := LoadLibrary(PWideChar(LLVMLibName));
if (GLLVMLibrary <> 0) then
begin
@LLVMInitializeCore := Bind('LLVMInitializeCore');
@LLVMDisposeMessage := Bind('LLVMDisposeMessage');
@LLVMContextCreate := Bind('LLVMContextCreate');
@LLVMGetGlobalContext := Bind('LLVMGetGlobalContext');
@LLVMContextDispose := Bind('LLVMContextDispose');
@LLVMGetMDKindIDInContext := Bind('LLVMGetMDKindIDInContext');
@LLVMGetMDKindID := Bind('LLVMGetMDKindID');
@LLVMModuleCreateWithName := Bind('LLVMModuleCreateWithName');
@LLVMModuleCreateWithNameInContext := Bind('LLVMModuleCreateWithNameInContext');
@LLVMDisposeModule := Bind('LLVMDisposeModule');
@LLVMGetDataLayout := Bind('LLVMGetDataLayout');
@LLVMSetDataLayout := Bind('LLVMSetDataLayout');
@LLVMGetTarget := Bind('LLVMGetTarget');
@LLVMSetTarget := Bind('LLVMSetTarget');
@LLVMDumpModule := Bind('LLVMDumpModule');
@LLVMPrintModuleToFile := Bind('LLVMPrintModuleToFile');
@LLVMPrintModuleToString := Bind('LLVMPrintModuleToString');
@LLVMSetModuleInlineAsm := Bind('LLVMSetModuleInlineAsm');
@LLVMGetModuleContext := Bind('LLVMGetModuleContext');
@LLVMGetTypeByName := Bind('LLVMGetTypeByName');
@LLVMGetNamedMetadataNumOperands := Bind('LLVMGetNamedMetadataNumOperands');
@LLVMGetNamedMetadataOperands := Bind('LLVMGetNamedMetadataOperands');
@LLVMAddNamedMetadataOperand := Bind('LLVMAddNamedMetadataOperand');
@LLVMAddFunction := Bind('LLVMAddFunction');
@LLVMGetNamedFunction := Bind('LLVMGetNamedFunction');
@LLVMGetFirstFunction := Bind('LLVMGetFirstFunction');
@LLVMGetLastFunction := Bind('LLVMGetLastFunction');
@LLVMGetNextFunction := Bind('LLVMGetNextFunction');
@LLVMGetPreviousFunction := Bind('LLVMGetPreviousFunction');
@LLVMGetTypeKind := Bind('LLVMGetTypeKind');
@LLVMTypeIsSized := Bind('LLVMTypeIsSized');
@LLVMGetTypeContext := Bind('LLVMGetTypeContext');
@LLVMInt1TypeInContext := Bind('LLVMInt1TypeInContext');
@LLVMInt8TypeInContext := Bind('LLVMInt8TypeInContext');
@LLVMInt16TypeInContext := Bind('LLVMInt16TypeInContext');
@LLVMInt32TypeInContext := Bind('LLVMInt32TypeInContext');
@LLVMInt64TypeInContext := Bind('LLVMInt64TypeInContext');
@LLVMIntTypeInContext := Bind('LLVMIntTypeInContext');
@LLVMInt1Type := Bind('LLVMInt1Type');
@LLVMInt8Type := Bind('LLVMInt8Type');
@LLVMInt16Type := Bind('LLVMInt16Type');
@LLVMInt32Type := Bind('LLVMInt32Type');
@LLVMInt64Type := Bind('LLVMInt64Type');
@LLVMIntType := Bind('LLVMIntType');
@LLVMGetIntTypeWidth := Bind('LLVMGetIntTypeWidth');
@LLVMHalfTypeInContext := Bind('LLVMHalfTypeInContext');
@LLVMFloatTypeInContext := Bind('LLVMFloatTypeInContext');
@LLVMDoubleTypeInContext := Bind('LLVMDoubleTypeInContext');
@LLVMX86FP80TypeInContext := Bind('LLVMX86FP80TypeInContext');
@LLVMFP128TypeInContext := Bind('LLVMFP128TypeInContext');
@LLVMPPCFP128TypeInContext := Bind('LLVMPPCFP128TypeInContext');
@LLVMHalfType := Bind('LLVMHalfType');
@LLVMFloatType := Bind('LLVMFloatType');
@LLVMDoubleType := Bind('LLVMDoubleType');
@LLVMX86FP80Type := Bind('LLVMX86FP80Type');
@LLVMFP128Type := Bind('LLVMFP128Type');
@LLVMPPCFP128Type := Bind('LLVMPPCFP128Type');
@LLVMFunctionType := Bind('LLVMFunctionType');
@LLVMIsFunctionVarArg := Bind('LLVMIsFunctionVarArg');
@LLVMGetReturnType := Bind('LLVMGetReturnType');
@LLVMCountParamTypes := Bind('LLVMCountParamTypes');
@LLVMGetParamTypes := Bind('LLVMGetParamTypes');
@LLVMStructTypeInContext := Bind('LLVMStructTypeInContext');
@LLVMStructType := Bind('LLVMStructType');
@LLVMStructCreateNamed := Bind('LLVMStructCreateNamed');
@LLVMGetStructName := Bind('LLVMGetStructName');
@LLVMStructSetBody := Bind('LLVMStructSetBody');
@LLVMCountStructElementTypes := Bind('LLVMCountStructElementTypes');
@LLVMGetStructElementTypes := Bind('LLVMGetStructElementTypes');
@LLVMIsPackedStruct := Bind('LLVMIsPackedStruct');
@LLVMIsOpaqueStruct := Bind('LLVMIsOpaqueStruct');
@LLVMGetElementType := Bind('LLVMGetElementType');
@LLVMArrayType := Bind('LLVMArrayType');
@LLVMGetArrayLength := Bind('LLVMGetArrayLength');
@LLVMPointerType := Bind('LLVMPointerType');
@LLVMGetPointerAddressSpace := Bind('LLVMGetPointerAddressSpace');
@LLVMVectorType := Bind('LLVMVectorType');
@LLVMGetVectorSize := Bind('LLVMGetVectorSize');
@LLVMVoidTypeInContext := Bind('LLVMVoidTypeInContext');
@LLVMLabelTypeInContext := Bind('LLVMLabelTypeInContext');
@LLVMX86MMXTypeInContext := Bind('LLVMX86MMXTypeInContext');
@LLVMVoidType := Bind('LLVMVoidType');
@LLVMLabelType := Bind('LLVMLabelType');
@LLVMX86MMXType := Bind('LLVMX86MMXType');
@LLVMTypeOf := Bind('LLVMTypeOf');
@LLVMGetValueName := Bind('LLVMGetValueName');
@LLVMSetValueName := Bind('LLVMSetValueName');
@LLVMDumpValue := Bind('LLVMDumpValue');
@LLVMReplaceAllUsesWith := Bind('LLVMReplaceAllUsesWith');
@LLVMIsConstant := Bind('LLVMIsConstant');
@LLVMIsUndef := Bind('LLVMIsUndef');
@LLVMIsAArgument := Bind('LLVMIsAArgument');
@LLVMIsABasicBlock := Bind('LLVMIsABasicBlock');
@LLVMIsAInlineAsm := Bind('LLVMIsAInlineAsm');
@LLVMIsAMDNode := Bind('LLVMIsAMDNode');
@LLVMIsAMDString := Bind('LLVMIsAMDString');
@LLVMIsAUser := Bind('LLVMIsAUser');
@LLVMIsAConstant := Bind('LLVMIsAConstant');
@LLVMIsABlockAddress := Bind('LLVMIsABlockAddress');
@LLVMIsAConstantAggregateZero := Bind('LLVMIsAConstantAggregateZero');
@LLVMIsAConstantArray := Bind('LLVMIsAConstantArray');
@LLVMIsAConstantExpr := Bind('LLVMIsAConstantExpr');
@LLVMIsAConstantFP := Bind('LLVMIsAConstantFP');
@LLVMIsAConstantInt := Bind('LLVMIsAConstantInt');
@LLVMIsAConstantPointerNull := Bind('LLVMIsAConstantPointerNull');
@LLVMIsAConstantStruct := Bind('LLVMIsAConstantStruct');
@LLVMIsAConstantVector := Bind('LLVMIsAConstantVector');
@LLVMIsAGlobalValue := Bind('LLVMIsAGlobalValue');
@LLVMIsAFunction := Bind('LLVMIsAFunction');
@LLVMIsAGlobalAlias := Bind('LLVMIsAGlobalAlias');
@LLVMIsAGlobalVariable := Bind('LLVMIsAGlobalVariable');
@LLVMIsAUndefValue := Bind('LLVMIsAUndefValue');
@LLVMIsAInstruction := Bind('LLVMIsAInstruction');
@LLVMIsABinaryOperator := Bind('LLVMIsABinaryOperator');
@LLVMIsACallInst := Bind('LLVMIsACallInst');
@LLVMIsAIntrinsicInst := Bind('LLVMIsAIntrinsicInst');
@LLVMIsADbgInfoIntrinsic := Bind('LLVMIsADbgInfoIntrinsic');
@LLVMIsADbgDeclareInst := Bind('LLVMIsADbgDeclareInst');
@LLVMIsAMemIntrinsic := Bind('LLVMIsAMemIntrinsic');
@LLVMIsAMemCpyInst := Bind('LLVMIsAMemCpyInst');
@LLVMIsAMemMoveInst := Bind('LLVMIsAMemMoveInst');
@LLVMIsAMemSetInst := Bind('LLVMIsAMemSetInst');
@LLVMIsACmpInst := Bind('LLVMIsACmpInst');
@LLVMIsAFCmpInst := Bind('LLVMIsAFCmpInst');
@LLVMIsAICmpInst := Bind('LLVMIsAICmpInst');
@LLVMIsAExtractElementInst := Bind('LLVMIsAExtractElementInst');
@LLVMIsAGetElementPtrInst := Bind('LLVMIsAGetElementPtrInst');
@LLVMIsAInsertElementInst := Bind('LLVMIsAInsertElementInst');
@LLVMIsAInsertValueInst := Bind('LLVMIsAInsertValueInst');
@LLVMIsALandingPadInst := Bind('LLVMIsALandingPadInst');
@LLVMIsAPHINode := Bind('LLVMIsAPHINode');
@LLVMIsASelectInst := Bind('LLVMIsASelectInst');
@LLVMIsAShuffleVectorInst := Bind('LLVMIsAShuffleVectorInst');
@LLVMIsAStoreInst := Bind('LLVMIsAStoreInst');
@LLVMIsATerminatorInst := Bind('LLVMIsATerminatorInst');
@LLVMIsABranchInst := Bind('LLVMIsABranchInst');
@LLVMIsAIndirectBrInst := Bind('LLVMIsAIndirectBrInst');
@LLVMIsAInvokeInst := Bind('LLVMIsAInvokeInst');
@LLVMIsAReturnInst := Bind('LLVMIsAReturnInst');
@LLVMIsASwitchInst := Bind('LLVMIsASwitchInst');
@LLVMIsAUnreachableInst := Bind('LLVMIsAUnreachableInst');
@LLVMIsAResumeInst := Bind('LLVMIsAResumeInst');
@LLVMIsAUnaryInstruction := Bind('LLVMIsAUnaryInstruction');
@LLVMIsAAllocaInst := Bind('LLVMIsAAllocaInst');
@LLVMIsACastInst := Bind('LLVMIsACastInst');
@LLVMIsABitCastInst := Bind('LLVMIsABitCastInst');
@LLVMIsAFPExtInst := Bind('LLVMIsAFPExtInst');
@LLVMIsAFPToSIInst := Bind('LLVMIsAFPToSIInst');
@LLVMIsAFPToUIInst := Bind('LLVMIsAFPToUIInst');
@LLVMIsAFPTruncInst := Bind('LLVMIsAFPTruncInst');
@LLVMIsAIntToPtrInst := Bind('LLVMIsAIntToPtrInst');
@LLVMIsAPtrToIntInst := Bind('LLVMIsAPtrToIntInst');
@LLVMIsASExtInst := Bind('LLVMIsASExtInst');
@LLVMIsASIToFPInst := Bind('LLVMIsASIToFPInst');
@LLVMIsATruncInst := Bind('LLVMIsATruncInst');
@LLVMIsAUIToFPInst := Bind('LLVMIsAUIToFPInst');
@LLVMIsAZExtInst := Bind('LLVMIsAZExtInst');
@LLVMIsAExtractValueInst := Bind('LLVMIsAExtractValueInst');
@LLVMIsALoadInst := Bind('LLVMIsALoadInst');
@LLVMIsAVAArgInst := Bind('LLVMIsAVAArgInst');
@LLVMGetFirstUse := Bind('LLVMGetFirstUse');
@LLVMGetNextUse := Bind('LLVMGetNextUse');
@LLVMGetUser := Bind('LLVMGetUser');
@LLVMGetUsedValue := Bind('LLVMGetUsedValue');
@LLVMGetOperand := Bind('LLVMGetOperand');
@LLVMSetOperand := Bind('LLVMSetOperand');
@LLVMGetNumOperands := Bind('LLVMGetNumOperands');
@LLVMConstNull := Bind('LLVMConstNull');
@LLVMConstAllOnes := Bind('LLVMConstAllOnes');
@LLVMGetUndef := Bind('LLVMGetUndef');
@LLVMIsNull := Bind('LLVMIsNull');
@LLVMConstPointerNull := Bind('LLVMConstPointerNull');
@LLVMConstInt := Bind('LLVMConstInt');
@LLVMConstIntOfArbitraryPrecision := Bind('LLVMConstIntOfArbitraryPrecision');
@LLVMConstIntOfString := Bind('LLVMConstIntOfString');
@LLVMConstIntOfStringAndSize := Bind('LLVMConstIntOfStringAndSize');
@LLVMConstReal := Bind('LLVMConstReal');
@LLVMConstRealOfString := Bind('LLVMConstRealOfString');
@LLVMConstRealOfStringAndSize := Bind('LLVMConstRealOfStringAndSize');
@LLVMConstIntGetZExtValue := Bind('LLVMConstIntGetZExtValue');
@LLVMConstIntGetSExtValue := Bind('LLVMConstIntGetSExtValue');
@LLVMConstStringInContext := Bind('LLVMConstStringInContext');
@LLVMConstString := Bind('LLVMConstString');
@LLVMConstStructInContext := Bind('LLVMConstStructInContext');
@LLVMConstStruct := Bind('LLVMConstStruct');
@LLVMConstArray := Bind('LLVMConstArray');
@LLVMConstNamedStruct := Bind('LLVMConstNamedStruct');
@LLVMConstVector := Bind('LLVMConstVector');
@LLVMGetConstOpcode := Bind('LLVMGetConstOpcode');
@LLVMAlignOf := Bind('LLVMAlignOf');
@LLVMSizeOf := Bind('LLVMSizeOf');
@LLVMConstNeg := Bind('LLVMConstNeg');
@LLVMConstNSWNeg := Bind('LLVMConstNSWNeg');
@LLVMConstNUWNeg := Bind('LLVMConstNUWNeg');
@LLVMConstFNeg := Bind('LLVMConstFNeg');
@LLVMConstNot := Bind('LLVMConstNot');
@LLVMConstAdd := Bind('LLVMConstAdd');
@LLVMConstNSWAdd := Bind('LLVMConstNSWAdd');
@LLVMConstNUWAdd := Bind('LLVMConstNUWAdd');
@LLVMConstFAdd := Bind('LLVMConstFAdd');
@LLVMConstSub := Bind('LLVMConstSub');
@LLVMConstNSWSub := Bind('LLVMConstNSWSub');
@LLVMConstNUWSub := Bind('LLVMConstNUWSub');
@LLVMConstFSub := Bind('LLVMConstFSub');
@LLVMConstMul := Bind('LLVMConstMul');
@LLVMConstNSWMul := Bind('LLVMConstNSWMul');
@LLVMConstNUWMul := Bind('LLVMConstNUWMul');
@LLVMConstFMul := Bind('LLVMConstFMul');
@LLVMConstUDiv := Bind('LLVMConstUDiv');
@LLVMConstSDiv := Bind('LLVMConstSDiv');
@LLVMConstExactSDiv := Bind('LLVMConstExactSDiv');
@LLVMConstFDiv := Bind('LLVMConstFDiv');
@LLVMConstURem := Bind('LLVMConstURem');
@LLVMConstSRem := Bind('LLVMConstSRem');
@LLVMConstFRem := Bind('LLVMConstFRem');
@LLVMConstAnd := Bind('LLVMConstAnd');
@LLVMConstOr := Bind('LLVMConstOr');
@LLVMConstXor := Bind('LLVMConstXor');
@LLVMConstICmp := Bind('LLVMConstICmp');
@LLVMConstFCmp := Bind('LLVMConstFCmp');
@LLVMConstShl := Bind('LLVMConstShl');
@LLVMConstLShr := Bind('LLVMConstLShr');
@LLVMConstAShr := Bind('LLVMConstAShr');
@LLVMConstGEP := Bind('LLVMConstGEP');
@LLVMConstInBoundsGEP := Bind('LLVMConstInBoundsGEP');
@LLVMConstTrunc := Bind('LLVMConstTrunc');
@LLVMConstSExt := Bind('LLVMConstSExt');
@LLVMConstZExt := Bind('LLVMConstZExt');
@LLVMConstFPTrunc := Bind('LLVMConstFPTrunc');
@LLVMConstFPExt := Bind('LLVMConstFPExt');
@LLVMConstUIToFP := Bind('LLVMConstUIToFP');
@LLVMConstSIToFP := Bind('LLVMConstSIToFP');
@LLVMConstFPToUI := Bind('LLVMConstFPToUI');
@LLVMConstFPToSI := Bind('LLVMConstFPToSI');
@LLVMConstPtrToInt := Bind('LLVMConstPtrToInt');
@LLVMConstIntToPtr := Bind('LLVMConstIntToPtr');
@LLVMConstBitCast := Bind('LLVMConstBitCast');
@LLVMConstZExtOrBitCast := Bind('LLVMConstZExtOrBitCast');
@LLVMConstSExtOrBitCast := Bind('LLVMConstSExtOrBitCast');
@LLVMConstTruncOrBitCast := Bind('LLVMConstTruncOrBitCast');
@LLVMConstPointerCast := Bind('LLVMConstPointerCast');
@LLVMConstIntCast := Bind('LLVMConstIntCast');
@LLVMConstFPCast := Bind('LLVMConstFPCast');
@LLVMConstSelect := Bind('LLVMConstSelect');
@LLVMConstExtractElement := Bind('LLVMConstExtractElement');
@LLVMConstInsertElement := Bind('LLVMConstInsertElement');
@LLVMConstShuffleVector := Bind('LLVMConstShuffleVector');
@LLVMConstExtractValue := Bind('LLVMConstExtractValue');
@LLVMConstInsertValue := Bind('LLVMConstInsertValue');
@LLVMConstInlineAsm := Bind('LLVMConstInlineAsm');
@LLVMBlockAddress := Bind('LLVMBlockAddress');
@LLVMGetGlobalParent := Bind('LLVMGetGlobalParent');
@LLVMIsDeclaration := Bind('LLVMIsDeclaration');
@LLVMGetLinkage := Bind('LLVMGetLinkage');
@LLVMSetLinkage := Bind('LLVMSetLinkage');
@LLVMGetSection := Bind('LLVMGetSection');
@LLVMSetSection := Bind('LLVMSetSection');
@LLVMGetVisibility := Bind('LLVMGetVisibility');
@LLVMSetVisibility := Bind('LLVMSetVisibility');
@LLVMGetAlignment := Bind('LLVMGetAlignment');
@LLVMSetAlignment := Bind('LLVMSetAlignment');
@LLVMAddGlobal := Bind('LLVMAddGlobal');
@LLVMAddGlobalInAddressSpace := Bind('LLVMAddGlobalInAddressSpace');
@LLVMGetNamedGlobal := Bind('LLVMGetNamedGlobal');
@LLVMGetFirstGlobal := Bind('LLVMGetFirstGlobal');
@LLVMGetLastGlobal := Bind('LLVMGetLastGlobal');
@LLVMGetNextGlobal := Bind('LLVMGetNextGlobal');
@LLVMGetPreviousGlobal := Bind('LLVMGetPreviousGlobal');
@LLVMDeleteGlobal := Bind('LLVMDeleteGlobal');
@LLVMGetInitializer := Bind('LLVMGetInitializer');
@LLVMSetInitializer := Bind('LLVMSetInitializer');
@LLVMIsThreadLocal := Bind('LLVMIsThreadLocal');
@LLVMSetThreadLocal := Bind('LLVMSetThreadLocal');
@LLVMIsGlobalConstant := Bind('LLVMIsGlobalConstant');
@LLVMSetGlobalConstant := Bind('LLVMSetGlobalConstant');
@LLVMAddAlias := Bind('LLVMAddAlias');
@LLVMDeleteFunction := Bind('LLVMDeleteFunction');
@LLVMGetIntrinsicID := Bind('LLVMGetIntrinsicID');
@LLVMGetFunctionCallConv := Bind('LLVMGetFunctionCallConv');
@LLVMSetFunctionCallConv := Bind('LLVMSetFunctionCallConv');
@LLVMGetGC := Bind('LLVMGetGC');
@LLVMSetGC := Bind('LLVMSetGC');
@LLVMAddFunctionAttr := Bind('LLVMAddFunctionAttr');
@LLVMGetFunctionAttr := Bind('LLVMGetFunctionAttr');
@LLVMRemoveFunctionAttr := Bind('LLVMRemoveFunctionAttr');
@LLVMCountParams := Bind('LLVMCountParams');
@LLVMGetParams := Bind('LLVMGetParams');
@LLVMGetParam := Bind('LLVMGetParam');
@LLVMGetParamParent := Bind('LLVMGetParamParent');
@LLVMGetFirstParam := Bind('LLVMGetFirstParam');
@LLVMGetLastParam := Bind('LLVMGetLastParam');
@LLVMGetNextParam := Bind('LLVMGetNextParam');
@LLVMGetPreviousParam := Bind('LLVMGetPreviousParam');
@LLVMAddAttribute := Bind('LLVMAddAttribute');
@LLVMRemoveAttribute := Bind('LLVMRemoveAttribute');
@LLVMGetAttribute := Bind('LLVMGetAttribute');
@LLVMSetParamAlignment := Bind('LLVMSetParamAlignment');
@LLVMMDStringInContext := Bind('LLVMMDStringInContext');
@LLVMMDString := Bind('LLVMMDString');
@LLVMMDNodeInContext := Bind('LLVMMDNodeInContext');
@LLVMMDNode := Bind('LLVMMDNode');
@LLVMGetMDString := Bind('LLVMGetMDString');
@LLVMGetMDNodeNumOperands := Bind('LLVMGetMDNodeNumOperands');
@LLVMGetMDNodeOperands := Bind('LLVMGetMDNodeOperands');
@LLVMBasicBlockAsValue := Bind('LLVMBasicBlockAsValue');
@LLVMValueIsBasicBlock := Bind('LLVMValueIsBasicBlock');
@LLVMValueAsBasicBlock := Bind('LLVMValueAsBasicBlock');
@LLVMGetBasicBlockParent := Bind('LLVMGetBasicBlockParent');
@LLVMGetBasicBlockTerminator := Bind('LLVMGetBasicBlockTerminator');
@LLVMCountBasicBlocks := Bind('LLVMCountBasicBlocks');
@LLVMGetBasicBlocks := Bind('LLVMGetBasicBlocks');
@LLVMGetFirstBasicBlock := Bind('LLVMGetFirstBasicBlock');
@LLVMGetLastBasicBlock := Bind('LLVMGetLastBasicBlock');
@LLVMGetNextBasicBlock := Bind('LLVMGetNextBasicBlock');
@LLVMGetPreviousBasicBlock := Bind('LLVMGetPreviousBasicBlock');
@LLVMGetEntryBasicBlock := Bind('LLVMGetEntryBasicBlock');
@LLVMAppendBasicBlockInContext := Bind('LLVMAppendBasicBlockInContext');
@LLVMAppendBasicBlock := Bind('LLVMAppendBasicBlock');
@LLVMInsertBasicBlockInContext := Bind('LLVMInsertBasicBlockInContext');
@LLVMInsertBasicBlock := Bind('LLVMInsertBasicBlock');
@LLVMDeleteBasicBlock := Bind('LLVMDeleteBasicBlock');
@LLVMRemoveBasicBlockFromParent := Bind('LLVMRemoveBasicBlockFromParent');
@LLVMMoveBasicBlockBefore := Bind('LLVMMoveBasicBlockBefore');
@LLVMMoveBasicBlockAfter := Bind('LLVMMoveBasicBlockAfter');
@LLVMGetFirstInstruction := Bind('LLVMGetFirstInstruction');
@LLVMGetLastInstruction := Bind('LLVMGetLastInstruction');
@LLVMHasMetadata := Bind('LLVMHasMetadata');
@LLVMGetMetadata := Bind('LLVMGetMetadata');
@LLVMSetMetadata := Bind('LLVMSetMetadata');
@LLVMGetInstructionParent := Bind('LLVMGetInstructionParent');
@LLVMGetNextInstruction := Bind('LLVMGetNextInstruction');
@LLVMGetPreviousInstruction := Bind('LLVMGetPreviousInstruction');
@LLVMInstructionEraseFromParent := Bind('LLVMInstructionEraseFromParent');
@LLVMGetInstructionOpcode := Bind('LLVMGetInstructionOpcode');
@LLVMGetICmpPredicate := Bind('LLVMGetICmpPredicate');
@LLVMSetInstructionCallConv := Bind('LLVMSetInstructionCallConv');
@LLVMGetInstructionCallConv := Bind('LLVMGetInstructionCallConv');
@LLVMAddInstrAttribute := Bind('LLVMAddInstrAttribute');
@LLVMRemoveInstrAttribute := Bind('LLVMRemoveInstrAttribute');
@LLVMSetInstrParamAlignment := Bind('LLVMSetInstrParamAlignment');
@LLVMIsTailCall := Bind('LLVMIsTailCall');
@LLVMSetTailCall := Bind('LLVMSetTailCall');
@LLVMGetSwitchDefaultDest := Bind('LLVMGetSwitchDefaultDest');
@LLVMAddIncoming := Bind('LLVMAddIncoming');
@LLVMCountIncoming := Bind('LLVMCountIncoming');
@LLVMGetIncomingValue := Bind('LLVMGetIncomingValue');
@LLVMGetIncomingBlock := Bind('LLVMGetIncomingBlock');
@LLVMCreateBuilderInContext := Bind('LLVMCreateBuilderInContext');
@LLVMCreateBuilder := Bind('LLVMCreateBuilder');
@LLVMPositionBuilder := Bind('LLVMPositionBuilder');
@LLVMPositionBuilderBefore := Bind('LLVMPositionBuilderBefore');
@LLVMPositionBuilderAtEnd := Bind('LLVMPositionBuilderAtEnd');
@LLVMGetInsertBlock := Bind('LLVMGetInsertBlock');
@LLVMClearInsertionPosition := Bind('LLVMClearInsertionPosition');
@LLVMInsertIntoBuilder := Bind('LLVMInsertIntoBuilder');
@LLVMInsertIntoBuilderWithName := Bind('LLVMInsertIntoBuilderWithName');
@LLVMDisposeBuilder := Bind('LLVMDisposeBuilder');
@LLVMSetCurrentDebugLocation := Bind('LLVMSetCurrentDebugLocation');
@LLVMGetCurrentDebugLocation := Bind('LLVMGetCurrentDebugLocation');
@LLVMSetInstDebugLocation := Bind('LLVMSetInstDebugLocation');
@LLVMBuildRetVoid := Bind('LLVMBuildRetVoid');
@LLVMBuildRet := Bind('LLVMBuildRet');
@LLVMBuildAggregateRet := Bind('LLVMBuildAggregateRet');
@LLVMBuildBr := Bind('LLVMBuildBr');
@LLVMBuildCondBr := Bind('LLVMBuildCondBr');
@LLVMBuildSwitch := Bind('LLVMBuildSwitch');
@LLVMBuildIndirectBr := Bind('LLVMBuildIndirectBr');
@LLVMBuildInvoke := Bind('LLVMBuildInvoke');
@LLVMBuildLandingPad := Bind('LLVMBuildLandingPad');
@LLVMBuildResume := Bind('LLVMBuildResume');
@LLVMBuildUnreachable := Bind('LLVMBuildUnreachable');
@LLVMAddCase := Bind('LLVMAddCase');
@LLVMAddDestination := Bind('LLVMAddDestination');
@LLVMAddClause := Bind('LLVMAddClause');
@LLVMSetCleanup := Bind('LLVMSetCleanup');
@LLVMBuildAdd := Bind('LLVMBuildAdd');
@LLVMBuildNSWAdd := Bind('LLVMBuildNSWAdd');
@LLVMBuildNUWAdd := Bind('LLVMBuildNUWAdd');
@LLVMBuildFAdd := Bind('LLVMBuildFAdd');
@LLVMBuildSub := Bind('LLVMBuildSub');
@LLVMBuildNSWSub := Bind('LLVMBuildNSWSub');
@LLVMBuildNUWSub := Bind('LLVMBuildNUWSub');
@LLVMBuildFSub := Bind('LLVMBuildFSub');
@LLVMBuildMul := Bind('LLVMBuildMul');
@LLVMBuildNSWMul := Bind('LLVMBuildNSWMul');
@LLVMBuildNUWMul := Bind('LLVMBuildNUWMul');
@LLVMBuildFMul := Bind('LLVMBuildFMul');
@LLVMBuildUDiv := Bind('LLVMBuildUDiv');
@LLVMBuildSDiv := Bind('LLVMBuildSDiv');
@LLVMBuildExactSDiv := Bind('LLVMBuildExactSDiv');
@LLVMBuildFDiv := Bind('LLVMBuildFDiv');
@LLVMBuildURem := Bind('LLVMBuildURem');
@LLVMBuildSRem := Bind('LLVMBuildSRem');
@LLVMBuildFRem := Bind('LLVMBuildFRem');
@LLVMBuildShl := Bind('LLVMBuildShl');
@LLVMBuildLShr := Bind('LLVMBuildLShr');
@LLVMBuildAShr := Bind('LLVMBuildAShr');
@LLVMBuildAnd := Bind('LLVMBuildAnd');
@LLVMBuildOr := Bind('LLVMBuildOr');
@LLVMBuildXor := Bind('LLVMBuildXor');
@LLVMBuildBinOp := Bind('LLVMBuildBinOp');
@LLVMBuildNeg := Bind('LLVMBuildNeg');
@LLVMBuildNSWNeg := Bind('LLVMBuildNSWNeg');
@LLVMBuildNUWNeg := Bind('LLVMBuildNUWNeg');
@LLVMBuildFNeg := Bind('LLVMBuildFNeg');
@LLVMBuildNot := Bind('LLVMBuildNot');
@LLVMBuildMalloc := Bind('LLVMBuildMalloc');
@LLVMBuildArrayMalloc := Bind('LLVMBuildArrayMalloc');
@LLVMBuildAlloca := Bind('LLVMBuildAlloca');
@LLVMBuildArrayAlloca := Bind('LLVMBuildArrayAlloca');
@LLVMBuildFree := Bind('LLVMBuildFree');
@LLVMBuildLoad := Bind('LLVMBuildLoad');
@LLVMBuildStore := Bind('LLVMBuildStore');
@LLVMBuildGEP := Bind('LLVMBuildGEP');
@LLVMBuildInBoundsGEP := Bind('LLVMBuildInBoundsGEP');
@LLVMBuildStructGEP := Bind('LLVMBuildStructGEP');
@LLVMBuildGlobalString := Bind('LLVMBuildGlobalString');
@LLVMBuildGlobalStringPtr := Bind('LLVMBuildGlobalStringPtr');
@LLVMGetVolatile := Bind('LLVMGetVolatile');
@LLVMSetVolatile := Bind('LLVMSetVolatile');
@LLVMBuildTrunc := Bind('LLVMBuildTrunc');
@LLVMBuildZExt := Bind('LLVMBuildZExt');
@LLVMBuildSExt := Bind('LLVMBuildSExt');
@LLVMBuildFPToUI := Bind('LLVMBuildFPToUI');
@LLVMBuildFPToSI := Bind('LLVMBuildFPToSI');
@LLVMBuildUIToFP := Bind('LLVMBuildUIToFP');
@LLVMBuildSIToFP := Bind('LLVMBuildSIToFP');
@LLVMBuildFPTrunc := Bind('LLVMBuildFPTrunc');
@LLVMBuildFPExt := Bind('LLVMBuildFPExt');
@LLVMBuildPtrToInt := Bind('LLVMBuildPtrToInt');
@LLVMBuildIntToPtr := Bind('LLVMBuildIntToPtr');
@LLVMBuildBitCast := Bind('LLVMBuildBitCast');
@LLVMBuildZExtOrBitCast := Bind('LLVMBuildZExtOrBitCast');
@LLVMBuildSExtOrBitCast := Bind('LLVMBuildSExtOrBitCast');
@LLVMBuildTruncOrBitCast := Bind('LLVMBuildTruncOrBitCast');
@LLVMBuildCast := Bind('LLVMBuildCast');
@LLVMBuildPointerCast := Bind('LLVMBuildPointerCast');
@LLVMBuildIntCast := Bind('LLVMBuildIntCast');
@LLVMBuildFPCast := Bind('LLVMBuildFPCast');
@LLVMBuildICmp := Bind('LLVMBuildICmp');
@LLVMBuildFCmp := Bind('LLVMBuildFCmp');
@LLVMBuildPhi := Bind('LLVMBuildPhi');
@LLVMBuildCall := Bind('LLVMBuildCall');
@LLVMBuildSelect := Bind('LLVMBuildSelect');
@LLVMBuildVAArg := Bind('LLVMBuildVAArg');
@LLVMBuildExtractElement := Bind('LLVMBuildExtractElement');
@LLVMBuildInsertElement := Bind('LLVMBuildInsertElement');
@LLVMBuildShuffleVector := Bind('LLVMBuildShuffleVector');
@LLVMBuildExtractValue := Bind('LLVMBuildExtractValue');
@LLVMBuildInsertValue := Bind('LLVMBuildInsertValue');
@LLVMBuildIsNull := Bind('LLVMBuildIsNull');
@LLVMBuildIsNotNull := Bind('LLVMBuildIsNotNull');
@LLVMBuildPtrDiff := Bind('LLVMBuildPtrDiff');
@LLVMCreateModuleProviderForExistingModule := Bind('LLVMCreateModuleProviderForExistingModule');
@LLVMDisposeModuleProvider := Bind('LLVMDisposeModuleProvider');
@LLVMCreateMemoryBufferWithContentsOfFile := Bind('LLVMCreateMemoryBufferWithContentsOfFile');
@LLVMCreateMemoryBufferWithSTDIN := Bind('LLVMCreateMemoryBufferWithSTDIN');
@LLVMDisposeMemoryBuffer := Bind('LLVMDisposeMemoryBuffer');
@LLVMGetGlobalPassRegistry := Bind('LLVMGetGlobalPassRegistry');
@LLVMCreatePassManager := Bind('LLVMCreatePassManager');
@LLVMCreateFunctionPassManagerForModule := Bind('LLVMCreateFunctionPassManagerForModule');
@LLVMCreateFunctionPassManager := Bind('LLVMCreateFunctionPassManager');
@LLVMRunPassManager := Bind('LLVMRunPassManager');
@LLVMInitializeFunctionPassManager := Bind('LLVMInitializeFunctionPassManager');
@LLVMRunFunctionPassManager := Bind('LLVMRunFunctionPassManager');
@LLVMFinalizeFunctionPassManager := Bind('LLVMFinalizeFunctionPassManager');
@LLVMDisposePassManager := Bind('LLVMDisposePassManager');
@LLVMVerifyModule := Bind('LLVMVerifyModule');
@LLVMVerifyFunction := Bind('LLVMVerifyFunction');
@LLVMViewFunctionCFG := Bind('LLVMViewFunctionCFG');
@LLVMViewFunctionCFGOnly := Bind('LLVMViewFunctionCFGOnly');
@LLVMParseBitcode := Bind('LLVMParseBitcode');
@LLVMParseBitcodeInContext := Bind('LLVMParseBitcodeInContext');
@LLVMGetBitcodeModuleInContext := Bind('LLVMGetBitcodeModuleInContext');
@LLVMGetBitcodeModule := Bind('LLVMGetBitcodeModule');
@LLVMGetBitcodeModuleProviderInContext := Bind('LLVMGetBitcodeModuleProviderInContext');
@LLVMGetBitcodeModuleProvider := Bind('LLVMGetBitcodeModuleProvider');
@LLVMWriteBitcodeToFile := Bind('LLVMWriteBitcodeToFile');
@LLVMWriteBitcodeToFD := Bind('LLVMWriteBitcodeToFD');
@LLVMWriteBitcodeToFileHandle := Bind('LLVMWriteBitcodeToFileHandle');
@LLVMCreateDisasm := Bind('LLVMCreateDisasm');
@LLVMSetDisasmOptions := Bind('LLVMSetDisasmOptions');
@LLVMDisasmDispose := Bind('LLVMDisasmDispose');
@LLVMDisasmInstruction := Bind('LLVMDisasmInstruction');
@LLVMLinkInJIT := Bind('LLVMLinkInJIT');
@LLVMLinkInInterpreter := Bind('LLVMLinkInInterpreter');
@LLVMCreateGenericValueOfInt := Bind('LLVMCreateGenericValueOfInt');
@LLVMCreateGenericValueOfPointer := Bind('LLVMCreateGenericValueOfPointer');
@LLVMCreateGenericValueOfFloat := Bind('LLVMCreateGenericValueOfFloat');
@LLVMGenericValueIntWidth := Bind('LLVMGenericValueIntWidth');
@LLVMGenericValueToInt := Bind('LLVMGenericValueToInt');
@LLVMGenericValueToPointer := Bind('LLVMGenericValueToPointer');
@LLVMGenericValueToFloat := Bind('LLVMGenericValueToFloat');
@LLVMDisposeGenericValue := Bind('LLVMDisposeGenericValue');
@LLVMCreateExecutionEngineForModule := Bind('LLVMCreateExecutionEngineForModule');
@LLVMCreateInterpreterForModule := Bind('LLVMCreateInterpreterForModule');
@LLVMCreateJITCompilerForModule := Bind('LLVMCreateJITCompilerForModule');
@LLVMCreateExecutionEngine := Bind('LLVMCreateExecutionEngine');
@LLVMCreateInterpreter := Bind('LLVMCreateInterpreter');
@LLVMCreateJITCompiler := Bind('LLVMCreateJITCompiler');
@LLVMDisposeExecutionEngine := Bind('LLVMDisposeExecutionEngine');
@LLVMRunStaticConstructors := Bind('LLVMRunStaticConstructors');
@LLVMRunStaticDestructors := Bind('LLVMRunStaticDestructors');
@LLVMRunFunctionAsMain := Bind('LLVMRunFunctionAsMain');
@LLVMRunFunction := Bind('LLVMRunFunction');
@LLVMFreeMachineCodeForFunction := Bind('LLVMFreeMachineCodeForFunction');
@LLVMAddModule := Bind('LLVMAddModule');
@LLVMAddModuleProvider := Bind('LLVMAddModuleProvider');
@LLVMRemoveModule := Bind('LLVMRemoveModule');
@LLVMRemoveModuleProvider := Bind('LLVMRemoveModuleProvider');
@LLVMFindFunction := Bind('LLVMFindFunction');
@LLVMRecompileAndRelinkFunction := Bind('LLVMRecompileAndRelinkFunction');
@LLVMGetExecutionEngineTargetData := Bind('LLVMGetExecutionEngineTargetData');
@LLVMAddGlobalMapping := Bind('LLVMAddGlobalMapping');
@LLVMGetPointerToGlobal := Bind('LLVMGetPointerToGlobal');
@LLVMAddAggressiveDCEPass := Bind('LLVMAddAggressiveDCEPass');
@LLVMAddCFGSimplificationPass := Bind('LLVMAddCFGSimplificationPass');
@LLVMAddDeadStoreEliminationPass := Bind('LLVMAddDeadStoreEliminationPass');
@LLVMAddGVNPass := Bind('LLVMAddGVNPass');
@LLVMAddIndVarSimplifyPass := Bind('LLVMAddIndVarSimplifyPass');
@LLVMAddInstructionCombiningPass := Bind('LLVMAddInstructionCombiningPass');
@LLVMAddJumpThreadingPass := Bind('LLVMAddJumpThreadingPass');
@LLVMAddLICMPass := Bind('LLVMAddLICMPass');
@LLVMAddLoopDeletionPass := Bind('LLVMAddLoopDeletionPass');
@LLVMAddLoopIdiomPass := Bind('LLVMAddLoopIdiomPass');
@LLVMAddLoopRotatePass := Bind('LLVMAddLoopRotatePass');
@LLVMAddLoopUnrollPass := Bind('LLVMAddLoopUnrollPass');
@LLVMAddLoopUnswitchPass := Bind('LLVMAddLoopUnswitchPass');
@LLVMAddMemCpyOptPass := Bind('LLVMAddMemCpyOptPass');
@LLVMAddPromoteMemoryToRegisterPass := Bind('LLVMAddPromoteMemoryToRegisterPass');
@LLVMAddReassociatePass := Bind('LLVMAddReassociatePass');
@LLVMAddSCCPPass := Bind('LLVMAddSCCPPass');
@LLVMAddScalarReplAggregatesPass := Bind('LLVMAddScalarReplAggregatesPass');
@LLVMAddScalarReplAggregatesPassSSA := Bind('LLVMAddScalarReplAggregatesPassSSA');
@LLVMAddScalarReplAggregatesPassWithThreshold := Bind('LLVMAddScalarReplAggregatesPassWithThreshold');
@LLVMAddSimplifyLibCallsPass := Bind('LLVMAddSimplifyLibCallsPass');
@LLVMAddTailCallEliminationPass := Bind('LLVMAddTailCallEliminationPass');
@LLVMAddConstantPropagationPass := Bind('LLVMAddConstantPropagationPass');
@LLVMAddDemoteMemoryToRegisterPass := Bind('LLVMAddDemoteMemoryToRegisterPass');
@LLVMAddVerifierPass := Bind('LLVMAddVerifierPass');
@LLVMAddCorrelatedValuePropagationPass := Bind('LLVMAddCorrelatedValuePropagationPass');
@LLVMAddEarlyCSEPass := Bind('LLVMAddEarlyCSEPass');
@LLVMAddLowerExpectIntrinsicPass := Bind('LLVMAddLowerExpectIntrinsicPass');
@LLVMAddTypeBasedAliasAnalysisPass := Bind('LLVMAddTypeBasedAliasAnalysisPass');
@LLVMAddBasicAliasAnalysisPass := Bind('LLVMAddBasicAliasAnalysisPass');
@LLVMAddBBVectorizePass := Bind('LLVMAddBBVectorizePass');
@LLVMAddLoopVectorizePass := Bind('LLVMAddLoopVectorizePass');
@LLVMAddArgumentPromotionPass := Bind('LLVMAddArgumentPromotionPass');
@LLVMAddConstantMergePass := Bind('LLVMAddConstantMergePass');
@LLVMAddDeadArgEliminationPass := Bind('LLVMAddDeadArgEliminationPass');
@LLVMAddFunctionAttrsPass := Bind('LLVMAddFunctionAttrsPass');
@LLVMAddFunctionInliningPass := Bind('LLVMAddFunctionInliningPass');
@LLVMAddAlwaysInlinerPass := Bind('LLVMAddAlwaysInlinerPass');
@LLVMAddGlobalDCEPass := Bind('LLVMAddGlobalDCEPass');
@LLVMAddGlobalOptimizerPass := Bind('LLVMAddGlobalOptimizerPass');
@LLVMAddIPConstantPropagationPass := Bind('LLVMAddIPConstantPropagationPass');
@LLVMAddPruneEHPass := Bind('LLVMAddPruneEHPass');
@LLVMAddIPSCCPPass := Bind('LLVMAddIPSCCPPass');
@LLVMAddInternalizePass := Bind('LLVMAddInternalizePass');
@LLVMAddStripDeadPrototypesPass := Bind('LLVMAddStripDeadPrototypesPass');
@LLVMAddStripSymbolsPass := Bind('LLVMAddStripSymbolsPass');
@LLVMPassManagerBuilderCreate := Bind('LLVMPassManagerBuilderCreate');
@LLVMPassManagerBuilderDispose := Bind('LLVMPassManagerBuilderDispose');
@LLVMPassManagerBuilderSetOptLevel := Bind('LLVMPassManagerBuilderSetOptLevel');
@LLVMPassManagerBuilderSetSizeLevel := Bind('LLVMPassManagerBuilderSetSizeLevel');
@LLVMPassManagerBuilderSetDisableUnitAtATime := Bind('LLVMPassManagerBuilderSetDisableUnitAtATime');
@LLVMPassManagerBuilderSetDisableUnrollLoops := Bind('LLVMPassManagerBuilderSetDisableUnrollLoops');
@LLVMPassManagerBuilderSetDisableSimplifyLibCalls := Bind('LLVMPassManagerBuilderSetDisableSimplifyLibCalls');
@LLVMPassManagerBuilderUseInlinerWithThreshold := Bind('LLVMPassManagerBuilderUseInlinerWithThreshold');
@LLVMPassManagerBuilderPopulateFunctionPassManager := Bind('LLVMPassManagerBuilderPopulateFunctionPassManager');
@LLVMPassManagerBuilderPopulateModulePassManager := Bind('LLVMPassManagerBuilderPopulateModulePassManager');
@LLVMPassManagerBuilderPopulateLTOPassManager := Bind('LLVMPassManagerBuilderPopulateLTOPassManager');
@LLVMInitializeX86TargetInfo := Bind('LLVMInitializeX86TargetInfo');
@LLVMInitializeX86Target := Bind('LLVMInitializeX86Target');
@LLVMInitializeX86TargetMC := Bind('LLVMInitializeX86TargetMC');
@LLVMInitializeX86AsmPrinter := Bind('LLVMInitializeX86AsmPrinter');
@LLVMInitializeX86AsmParser := Bind('LLVMInitializeX86AsmParser');
@LLVMInitializeX86Disassembler := Bind('LLVMInitializeX86Disassembler');
// @LLVMInitializeAllTargetInfos := Bind('LLVMInitializeAllTargetInfosX');
// @LLVMInitializeAllTargets := Bind('LLVMInitializeAllTargetsX');
// @LLVMInitializeAllTargetMCs := Bind('LLVMInitializeAllTargetMCsX');
// @LLVMInitializeAllAsmPrinters := Bind('LLVMInitializeAllAsmPrintersX');
// @LLVMInitializeAllAsmParsers := Bind('LLVMInitializeAllAsmParsersX');
// @LLVMInitializeAllDisassemblers := Bind('LLVMInitializeAllDisassemblersX');
// @LLVMInitializeNativeTarget := Bind('LLVMInitializeNativeTargetX');
@LLVMCreateTargetData := Bind('LLVMCreateTargetData');
@LLVMAddTargetData := Bind('LLVMAddTargetData');
@LLVMAddTargetLibraryInfo := Bind('LLVMAddTargetLibraryInfo');
@LLVMCopyStringRepOfTargetData := Bind('LLVMCopyStringRepOfTargetData');
@LLVMByteOrder := Bind('LLVMByteOrder');
@LLVMPointerSize := Bind('LLVMPointerSize');
@LLVMPointerSizeForAS := Bind('LLVMPointerSizeForAS');
@LLVMIntPtrType := Bind('LLVMIntPtrType');
@LLVMIntPtrTypeForAS := Bind('LLVMIntPtrTypeForAS');
@LLVMSizeOfTypeInBits := Bind('LLVMSizeOfTypeInBits');
@LLVMStoreSizeOfType := Bind('LLVMStoreSizeOfType');
@LLVMABISizeOfType := Bind('LLVMABISizeOfType');
@LLVMABIAlignmentOfType := Bind('LLVMABIAlignmentOfType');
@LLVMCallFrameAlignmentOfType := Bind('LLVMCallFrameAlignmentOfType');
@LLVMPreferredAlignmentOfType := Bind('LLVMPreferredAlignmentOfType');
@LLVMPreferredAlignmentOfGlobal := Bind('LLVMPreferredAlignmentOfGlobal');
@LLVMElementAtOffset := Bind('LLVMElementAtOffset');
@LLVMOffsetOfElement := Bind('LLVMOffsetOfElement');
@LLVMDisposeTargetData := Bind('LLVMDisposeTargetData');
@LLVMGetFirstTarget := Bind('LLVMGetFirstTarget');
@LLVMGetNextTarget := Bind('LLVMGetNextTarget');
@LLVMGetTargetName := Bind('LLVMGetTargetName');
@LLVMGetTargetDescription := Bind('LLVMGetTargetDescription');
@LLVMTargetHasJIT := Bind('LLVMTargetHasJIT');
@LLVMTargetHasTargetMachine := Bind('LLVMTargetHasTargetMachine');
@LLVMTargetHasAsmBackend := Bind('LLVMTargetHasAsmBackend');
@LLVMCreateTargetMachine := Bind('LLVMCreateTargetMachine');
@LLVMDisposeTargetMachine := Bind('LLVMDisposeTargetMachine');
@LLVMGetTargetMachineTarget := Bind('LLVMGetTargetMachineTarget');
@LLVMGetTargetMachineTriple := Bind('LLVMGetTargetMachineTriple');
@LLVMGetTargetMachineCPU := Bind('LLVMGetTargetMachineCPU');
@LLVMGetTargetMachineFeatureString := Bind('LLVMGetTargetMachineFeatureString');
@LLVMGetTargetMachineData := Bind('LLVMGetTargetMachineData');
@LLVMTargetMachineEmitToFile := Bind('LLVMTargetMachineEmitToFile');
@LLVMCreateObjectFile := Bind('LLVMCreateObjectFile');
@LLVMDisposeObjectFile := Bind('LLVMDisposeObjectFile');
@LLVMGetSections := Bind('LLVMGetSections');
@LLVMDisposeSectionIterator := Bind('LLVMDisposeSectionIterator');
@LLVMIsSectionIteratorAtEnd := Bind('LLVMIsSectionIteratorAtEnd');
@LLVMMoveToNextSection := Bind('LLVMMoveToNextSection');
@LLVMMoveToContainingSection := Bind('LLVMMoveToContainingSection');
@LLVMGetSymbols := Bind('LLVMGetSymbols');
@LLVMDisposeSymbolIterator := Bind('LLVMDisposeSymbolIterator');
@LLVMIsSymbolIteratorAtEnd := Bind('LLVMIsSymbolIteratorAtEnd');
@LLVMMoveToNextSymbol := Bind('LLVMMoveToNextSymbol');
@LLVMGetSectionName := Bind('LLVMGetSectionName');
@LLVMGetSectionSize := Bind('LLVMGetSectionSize');
@LLVMGetSectionContents := Bind('LLVMGetSectionContents');
@LLVMGetSectionAddress := Bind('LLVMGetSectionAddress');
@LLVMGetSectionContainsSymbol := Bind('LLVMGetSectionContainsSymbol');
@LLVMGetRelocations := Bind('LLVMGetRelocations');
@LLVMDisposeRelocationIterator := Bind('LLVMDisposeRelocationIterator');
@LLVMIsRelocationIteratorAtEnd := Bind('LLVMIsRelocationIteratorAtEnd');
@LLVMMoveToNextRelocation := Bind('LLVMMoveToNextRelocation');
@LLVMGetSymbolName := Bind('LLVMGetSymbolName');
@LLVMGetSymbolAddress := Bind('LLVMGetSymbolAddress');
@LLVMGetSymbolFileOffset := Bind('LLVMGetSymbolFileOffset');
@LLVMGetSymbolSize := Bind('LLVMGetSymbolSize');
@LLVMGetRelocationAddress := Bind('LLVMGetRelocationAddress');
@LLVMGetRelocationOffset := Bind('LLVMGetRelocationOffset');
@LLVMGetRelocationSymbol := Bind('LLVMGetRelocationSymbol');
@LLVMGetRelocationType := Bind('LLVMGetRelocationType');
@LLVMGetRelocationTypeName := Bind('LLVMGetRelocationTypeName');
@LLVMGetRelocationValueString := Bind('LLVMGetRelocationValueString');
{ @LTOGetVersion := Bind('LTOGetVersion');
@LTOGetErrorMessage := Bind('LTOGetErrorMessage');
@LTOModuleIsObjectFile := Bind('LTOModuleIsObjectFile');
@LTOModuleIsObjectFileForTarget := Bind('LTOModuleIsObjectFileForTarget');
@LTOModuleIsObjectFileInMemory := Bind('LTOModuleIsObjectFileInMemory');
@LTOModuleIsObjectFileInMemoryForTarget := Bind('LTOModuleIsObjectFileInMemoryForTarget');
@LTOModuleCreate := Bind('LTOModuleCreate');
@LTOModuleCreateFromMemory := Bind('LTOModuleCreateFromMemory');
@LTOModuleCreateFromFd := Bind('LTOModuleCreateFromFd');
@LTOModuleCreateFromFdAtOffset := Bind('LTOModuleCreateFromFdAtOffset');
@LTOModuleDispose := Bind('LTOModuleDispose');
@LTOModuleGetTargetTriple := Bind('LTOModuleGetTargetTriple');
@LTOModuleSetTargetTriple := Bind('LTOModuleSetTargetTriple');
@LTOModuleGetNumSymbols := Bind('LTOModuleGetNumSymbols');
@LTOModuleGetSymbolName := Bind('LTOModuleGetSymbolName');
@LTOModuleGetSymbolAttribute := Bind('LTOModuleGetSymbolAttribute');
@LTOCodegenCreate := Bind('LTOCodegenCreate');
@LTOCodegenDispose := Bind('LTOCodegenDispose');
@LTOCodegenAddModule := Bind('LTOCodegenAddModule');
@LTOCodegenSetDebugModel := Bind('LTOCodegenSetDebugModel');
@LTOCodegenSetPicModel := Bind('LTOCodegenSetPicModel');
@LTOCodegenSetCpu := Bind('LTOCodegenSetCpu');
@LTOCodegenSetAssemblerPath := Bind('LTOCodegenSetAssemblerPath');
@LTOCodegenSetAssemblerArgs := Bind('LTOCodegenSetAssemblerArgs');
@LTOCodegenAddMustPreserveSymbol := Bind('LTOCodegenAddMustPreserveSymbol');
@LTOCodegenWriteMergedModules := Bind('LTOCodegenWriteMergedModules');
@LTOCodegenCompile := Bind('LTOCodegenCompile');
@LTOCodegenCompileToFile := Bind('LTOCodegenCompileToFile');
@LTOCodegenDebugOptions := Bind('LTOCodegenDebugOptions');}
end
else
raise Exception.CreateFmt(RStrCannotLoadLLVMLib, [LLVMLibName]);
end;
procedure UnloadLLVM;
begin
if IsLLVMLoaded then
begin
FreeLibrary(GLLVMLibrary);
GLLVMLibrary := 0;
end;
end;
initialization
finalization
end.
|
unit Connected_Emp_Info;
interface
uses
ExtCtrls, Classes, SysUtils;
type
(*
Code : Integer;
Name : String;
Dept : String;
Rank : String;
ID_Pic : TImage;
*)
TEmployee_Logined = Class(TObject)
Private
FCode: Integer;
FName: String;
FRank: STring;
FID_PIC: TImage;
FDept: String;
FResult: Boolean;
FRegion: String;
FRecievecode : integer;
FMsgprotocol: integer;
FSendCode: Integer;
procedure SetCode(const Value: Integer);
procedure SetName(const Value: String);
procedure SetDept(const Value: String);
procedure SetID_PIC(const Value: TImage);
procedure SetRank(const Value: STring);
Function Get_LoginedTableInfo : Boolean;
procedure SetRegion(const Value: String);
procedure SetMsgProtocol(const Value: integer);
procedure SetRecievecode(const Value: integer);
procedure SetSendCode(const Value: Integer);
function GetSendCode: Integer;
Public
Constructor create; virtual;
desTructor Destroy; virtual;
property Code : Integer read FCode write SetCode;
property Name : String read FName write SetName;
Property Dept : String read FDept write SetDept;
Property Rank : STring read FRank write SetRank;
proPerty Region : String read FRegion write SetRegion;
property ID_PIC : TImage read FID_PIC write SetID_PIC;
property Get_Result : Boolean read FResult Write FResult;
property RecieveCode : integer read FRecievecode Write SetRecievecode; // 메세지 받는 사람의 사번..
property MsgProtocol : integer read FMsgprotocol Write SetMsgProtocol;
Function SendMsg( Msg : String): String;
Function TalkMsg( Talk : String): string;
Function LoginMsg: String;
Function StatMsg_Out : String;
Function StatMsg_Lunch : String;
End;
var
MyInfo : TEmployee_Logined;
LoginedCode : Integer;
implementation
uses
uDMclient, MessageProtocol;
{ TEmployee_Logined }
{ TEmployee_Logined }
constructor TEmployee_Logined.create;
begin
//Get_Result := Get_LoginedTableInfo;
RecieveCode := 99999999; // 리시비코드를 기본 값으로 셋팅;;안하면 로그인 메세지 보낼때 리시브 코드가 없어서 에로사항;;
FID_PIC := TImage.Create(Nil);
fid_pIC.Width := 41;
fID_pic.Height := 53;
end;
destructor TEmployee_Logined.Destroy;
begin
FID_PIc.Free;
end;
function TEmployee_Logined.GetSendCode: Integer;
begin
Result := FCode;
end;
function TEmployee_Logined.Get_LoginedTableInfo: Boolean;
var
stream : Tstream;
begin
(* try
DMClient.ClientDataSet_Login.Close;
DMClient.ClientDataSet_Login.Params[0].AsInteger := LoginedCode;
DMClient.ClientDataSet_Login.Open;
with DMClient.ClientDataSet_Login do
begin
fCode := FieldByName('code').AsInteger;
FName := FieldByName('NAME').AsString;
FRank := FieldByName('class').AsString;
//FID_PIC := FieldByName('ID_PIC').as;
FDept := FieldByName('dept').AsString;
RecieveCode := 99999999; // 리시비코드를 기본 값으로 셋팅;;안하면 로그인 메세지 보낼때 리시브 코드가 없어서 에로사항;;
end;
except
Result := False;
end;
Result := True;
*)
end;
function TEmployee_Logined.LoginMsg: String;
begin
Result := InttoStr(MsgProtocol) + ';' + IntToStr(Code) + ';' + inttostr(RecieveCode) + ';' + '로그인완료!';
end;
function TEmployee_Logined.SendMsg( Msg: String): String;
var
Temp : String;
begin
Temp := Inttostr(mpMsg) + ';' + IntToStr(Code) + ';' + inttostr(RecieveCode) + ';' + Msg;
Result := StringReplace(temp, #13#10, '|', [rfReplaceAll]);
end;
procedure TEmployee_Logined.SetCode(const Value: Integer);
begin
FCode := Value;
end;
procedure TEmployee_Logined.SetDept(const Value: String);
begin
FDept := Value;
end;
procedure TEmployee_Logined.SetID_PIC(const Value: TImage);
begin
FID_PIC := Value;
end;
procedure TEmployee_Logined.SetMsgProtocol(const Value: integer);
begin
FMsgprotocol := Value;
end;
procedure TEmployee_Logined.SetName(const Value: String);
begin
FName := Value;
end;
procedure TEmployee_Logined.SetRank(const Value: STring);
begin
FRank := Value;
end;
procedure TEmployee_Logined.SetRecievecode(const Value: integer);
begin
FRecievecode := Value;
end;
procedure TEmployee_Logined.SetRegion(const Value: String);
begin
FRegion := Value;
end;
procedure TEmployee_Logined.SetSendCode(const Value: Integer);
begin
FSendCode := Value;
end;
function TEmployee_Logined.StatMsg_Lunch: String;
begin
Result := InttoStr(mpLunch) + ';' + IntToStr(Code) + ';' + inttostr(99999999) + ';' + '식사중!';
end;
function TEmployee_Logined.StatMsg_Out: String;
begin
Result := InttoStr(mpOut) + ';' + IntToStr(Code) + ';' + inttostr(99999999) + ';' + '외출중!';
end;
function TEmployee_Logined.TalkMsg( Talk: String): string;
begin
Result := Inttostr(mpTalk) + ';' + IntToStr(Code) + ';' + inttostr(RecieveCode) + ';' + Talk;
end;
end.
|
program _demo;
Array[0]
var
Network1 : MultiLayerPerceptron;
Network2 : MultiLayerPerceptron;
Network3 : MultiLayerPerceptron;
X : TReal1DArray;
Y : TReal1DArray;
R : TReal1DArray;
RLen : AlglibInteger;
V1 : Double;
V2 : Double;
begin
//
// Generate two networks filled with small random values.
// Use MLPSerialize/MLPUnserialize to make network copy.
//
MLPCreate0(1, 1, Network1);
MLPCreate0(1, 1, Network2);
MLPSerialize(Network1, R, RLen);
MLPUnserialize(R, Network2);
//
// Now Network1 and Network2 should be identical.
// Let's demonstrate it.
//
Write(Format('Test serialization/unserialization'#13#10'',[]));
SetLength(X, 1);
SetLength(Y, 1);
X[0] := 2*RandomReal-1;
MLPProcess(Network1, X, Y);
V1 := Y[0];
Write(Format('Network1(X) = %0.2f'#13#10'',[
Y[0]]));
MLPProcess(Network2, X, Y);
V2 := Y[0];
Write(Format('Network2(X) = %0.2f'#13#10'',[
Y[0]]));
if AP_FP_Eq(V1,V2) then
begin
Write(Format('Results are equal, OK.'#13#10'',[]));
end
else
begin
Write(Format('Results are not equal... Strange...',[]));
end;
end. |
unit Model.Entity.Category;
interface
type
TCategory = class
private
FID: Integer;
FCategoryName: string;
FParentID: Integer;
public
constructor Create(AName: string); overload;
public
property ID: Integer read FID write FID;
property CategoryName: string read FCategoryName write FCategoryName;
end;
implementation
{ TCategory }
constructor TCategory.Create(AName: string);
begin
FCategoryName := AName;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$HPPEMIT LINKUNIT}
unit Data.DbxHTTPLayer;
interface
uses
System.Classes,
Data.DBXCommon,
System.SysUtils;
type
/// <summary>
/// Exception with HTTP error information.
/// </summary>
EHTTPProtocolException = class(Exception)
private
FErrorMessage: string;
FErrorCode: Integer;
public
/// <summary>Create an exception object</summary>
constructor Create(AErrorCode: Integer; const AErrorMessage: string; const AMessage: string);
/// <summary>The HTTP error code</summary>
property ErrorCode: Integer read FErrorCode;
/// <summary>The HTTP error message</summary>
property ErrorMessage: string read FErrorMessage;
end;
TDSHTTPClient = class;
TDBXHTTPLayer = class(TDBXCommunicationLayer)
protected
FURITunnel: string;
FSessionId: string;
Fhttp: TDSHTTPClient;
FIPImplementationID: string;
procedure InitHTTPClient; virtual;
function HTTPProtocol: string; virtual;
public
constructor Create; override;
destructor Destroy; override;
procedure Close; override;
procedure Open(const DBXProperties: TDBXProperties); override;
function Read(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; override;
function Write(const Buffer: TArray<Byte>; const Offset: Integer; const Count: Integer): Integer; override;
function Info: string; override;
end;
TDBXHTTPSLayer = class(TDBXHTTPLayer)
protected
procedure InitHTTPClient; override;
function HTTPProtocol: string; override;
public
procedure Open(const DBXProperties: TDBXProperties); override;
end;
TDSHTTPResponseStream = class;
///<summary>
/// Abstract HTTP client
///</summary>
TDSHTTPClient = class
protected
function GetResponseCode: Integer; virtual; abstract;
function GetResponseText: string; virtual; abstract;
public
function Post(AURL: string; ASource: TStrings): string; virtual; abstract;
function Put(AURL: string; ASource: TStream): string; virtual; abstract;
function Get(AURL: string): TDSHTTPResponseStream; virtual; abstract;
procedure SetConnectTimeout(AMilisec: Integer); virtual;
procedure SetReadTimeout(AMilisec: Integer); virtual;
procedure SetBasicAuthentication(const user, password: string); virtual; abstract;
property ResponseCode: Integer read GetResponseCode;
property ResponseText: string read GetResponseText;
end;
///<summary>
/// Abstract HTTP response stream
///</summary>
TDSHTTPResponseStream = class
protected
function GetContentLength: Int64; virtual; abstract;
public
function Read(Buffer: TArray<Byte>; Count: Longint): Integer; virtual; abstract;
procedure Close; virtual; abstract;
property ContentLength: Int64 read GetContentLength;
end;
implementation
uses
System.JSON,
System.TypInfo,
System.Net.HTTPClient, System.Net.URLClient,
Data.DBXClientResStrs,
Data.DBXJSONReflect,
Data.DBXTransport,
Data.DBXCommonResStrs;
type
/// <summary> wrapper implementation of TX500Principal</summary>
TX500NETPrincipal = class(TX500Principal)
protected
FName: string;
public
constructor Create(const AName: string); virtual;
function GetName: string; override;
function GetEncoded: Longint; override;
end;
TX509NETPublicKey = class(TPublicKey)
private
FAlgorithm: string;
FFormat: string;
public
constructor Create(const PKAlgorithm, PKFormat: string);
function GetAlgorithm: string; override;
function GetFormat: string; override;
function GetEncoded: TArray<Byte>; override;
end;
TX509NetWrapperCertificate = class(TX509Certificate)
private
FExpiry: TDateTime;
/// <summary> Start date of the certificate</summary>
FStart: TDateTime;
/// <summary> Subject of the certificate</summary>
FSubject: string;
/// <summary> Issuer of the certificate</summary>
FIssuer: string;
/// <summary> ProtocolName of the certificate eg RSAEncryption</summary>
FProtocolName: string;
/// <summary> Algorithm Signature of the certificate eg. 00:d3:a4:50:6e:c8:ff:56:6b:e6:cf:5d:b6:... </summary>
FAlgSignature: string;
/// <summary> Algorithm Encryption of the certificate eg md5WithRSAEncryption</summary>
FAlgEncryption: string;
/// <summary> Encryption's KeySize of the certificate eg 128</summary>
FKeySize: Integer;
/// <summary> subject Principle information</summary>
FSubjectPrincipal: TX500NETPrincipal;
/// <summary> Issuer Principle information</summary>
FIssuerPrincipal: TX500NETPrincipal;
/// <summary> Public key information</summary>
FPublicKey: TX509NETPublicKey;
public
constructor Create(const ACert: System.Net.URLClient.TCertificate);
destructor Destroy; override;
{ Inherited from the base Certificate class }
function GetEncoded: TArray<Byte>; override;
function GetPublicKey: TPublicKey; override;
function Verify(key: TPublicKey): Boolean; override;
{ Inherited from the X.509 Certificate class }
procedure CheckValidity; overload; override;
procedure CheckValidity(ADate: TDateTime); overload; override;
function GetNotAfter: TDateTime; override;
function GetNotBefore: TDateTime; override;
function GetBasicConstraints: Integer; override;
function GetSerialNumber: string; override;
function GetVersion: Longint; override;
function GetSigAlgName: string; override;
function GetSignature: string; override;
function GetIssuerX500Principal: TX500Principal; override;
function GetSubjectX500Principal: TX500Principal; override;
property Expiry: TDateTime read FExpiry;
property Start: TDateTime read FStart;
end;
TDSHTTPNativeResponseStream = class(TDSHTTPResponseStream)
private
FStream: TStream;
FContentLength: Int64;
protected
function GetContentLength: Int64; override;
public
constructor Create(AContentLength: Integer; AStream: TStream);
destructor Destroy; override;
function Read(Buffer: TArray<Byte>; Count: Longint): Integer; override;
procedure Close; override;
end;
TDSHTTPNativeClient = class(TDSHTTPClient)
protected type
/// <summary>Proxy server connection parameters</summary>
IProxyConnectionInfo = interface
/// <summary>Set the port of the proxy server</summary>
procedure SetProxyPort(AValue: Integer);
/// <summary>Get the port of the proxy server</summary>
function GetProxyPort: Integer;
/// <summary>Get or set the port of the proxy server</summary>
property ProxyPort: Integer read GetProxyPort write SetProxyPort;
/// <summary>Get the proxy server host name</summary>
function GetProxyServer: string;
/// <summary>Set the proxy server host name</summary>
procedure SetProxyServer(const AValue: string);
/// <summary>Get or set the proxy server host name</summary>
property ProxyServer: string read GetProxyServer write SetProxyServer;
/// <summary>Get the proxy server scheme</summary>
function GetProxyScheme: string;
/// <summary>Set the proxy server scheme</summary>
procedure SetProxyScheme(const AValue: string);
/// <summary>Get or set the proxy server scheme</summary>
property ProxyScheme: string read GetProxyScheme write SetProxyScheme;
/// <summary>Get a the username used to access the proxy server</summary>
function GetProxyUserName: string;
/// <summary>Set a the username used to access the proxy server</summary>
procedure SetProxyUserName(const AUser: string);
/// <summary>Get or set the username used to access the proxy server</summary>
property ProxyUserName: string read GetProxyUserName write SetProxyUserName;
/// <summary>Get the password used to access the proxy server</summary>
function GetProxyPassword: string;
/// <summary>Set the password used to access the proxy server</summary>
procedure SetProxyPassword(const APass: string);
/// <summary>Get or set the passwor used to access the proxy server</summary>
property ProxyPassword: string read GetProxyPassword write SetProxyPassword;
end;
/// <summary>List of HTTP headers</summary>
IHeaderList = interface
/// <summary>Get the count of header.</summary>
function GetCount: Integer;
/// <summary>Get the count of header.</summary>
property Count: Integer read GetCount;
/// <summary>Get the name of a header.</summary>
function GetName(Index: Integer): string;
/// <summary>Get the name of a header.</summary>
property Names[Index: Integer]: string read GetName;
/// <summary>Get the value of a header.</summary>
function GetValue(const Name: string): string;
/// <summary>Get the value of a header.</summary>
property Values[const Name: string]: string read GetValue;
end;
/// <summary>List of HTTP headers that can be modified</summary>
IRequestHeaderList = interface(IHeaderList)
/// <summary>Clear all headers</summary>
procedure Clear;
/// <summary>Add or modify a header</summary>
procedure SetValue(const AName, AValue: string);
/// <summary>Get or set the value of a header</summary>
property Values[const Name: string]: string read GetValue write SetValue;
end;
/// <summary>Properties of an HTTP request</summary>
IRequest = interface
/// <summary>Get the HTTP request accept string</summary>
function GetAccept: string;
/// <summary>Set the HTTP request accept string</summary>
procedure SetAccept(const AValue: string);
/// <summary>Get or set the HTTP request accept string</summary>
property Accept: string read GetAccept write SetAccept;
/// <summary>Get the HTTP request charset string</summary>
function GetAcceptCharSet: string;
/// <summary>Set the HTTP request charset string</summary>
procedure SetAcceptCharSet(const AValue: string);
/// <summary>Get or set the HTTP request charset string</summary>
property AcceptCharSet: string read GetAcceptCharSet write SetAcceptCharSet;
/// <summary>Get the HTTP request custom headers.</summary>
function GetCustomHeaders: IRequestHeaderList;
/// <summary>Get the HTTP request custom headers.</summary>
property CustomHeaders: IRequestHeaderList read GetCustomHeaders;
/// <summary>Get the HTTP request acceptencoding string</summary>
function GetAcceptEncoding: string;
/// <summary>Set the HTTP request acceptencoding string</summary>
procedure SetAcceptEncoding(const AValue: string);
/// <summary>Get or set the HTTP request acceptencoding string</summary>
property AcceptEncoding: string read GetAcceptEncoding write SetAcceptEncoding;
/// <summary>Get the HTTP request contenttype string</summary>
function GetContentType: string;
/// <summary>Set the HTTP request contenttype string</summary>
procedure SetContentType(const AContentType: string);
/// <summary>Get or set the HTTP request contenttype string</summary>
property ContentType: string read GetContentType write SetContentType;
/// <summary>Get the HTTP request useragent string</summary>
function GetUserAgent: string;
/// <summary>Set the HTTP request useragent string</summary>
procedure SetUserAgent(const AValue: string);
/// <summary>Get or set the HTTP request useragent string</summary>
property UserAgent: string read GetUserAgent write SetUserAgent;
/// <summary>Get the HTTP request Username string</summary>
function GetUserName: string;
/// <summary>Get the HTTP request password string</summary>
function GetPassword: string;
/// <summary>Set the HTTP request username and password</summary>
procedure SetAuthentication(const AUserName, APassword: string);
end;
/// <summary>Properties of an HTTP response</summary>
IResponse = interface
/// <summary>Get the HTTP response character set string</summary>
function GetCharSet: string;
/// <summary>Get the HTTP response character set string</summary>
property CharSet: string read GetCharSet;
/// <summary>Get the HTTP response content type string</summary>
function GetContentType: string;
/// <summary>Get the HTTP response content type string</summary>
property ContentType: string read GetContentType;
/// <summary>Get the HTTP response content encoding string</summary>
function GetContentEncoding: string;
/// <summary>Get the HTTP response content encoding string</summary>
property ContentEncoding: string read GetContentEncoding;
/// <summary>Get the HTTP response headers</summary>
function GetHeaders: IHeaderList;
/// <summary>Get the HTTP response headers</summary>
property Headers: IHeaderList read GetHeaders;
end;
TIPProxyConnectionInfo = class(TInterfacedObject, IProxyConnectionInfo)
private
FProxySettings: TProxySettings;
procedure SetProxyPort(AValue: Integer);
function GetProxyPort: Integer;
function GetProxyServer: string;
procedure SetProxyServer(const AValue: string);
function GetProxyScheme: string;
procedure SetProxyScheme(const AValue: string);
function GetProxyUserName: string;
procedure SetProxyUserName(const AUser: string);
function GetProxyPassword: string;
procedure SetProxyPassword(const APass: string);
end;
TIPRequestHeaderList = class(TInterfacedObject, IHeaderList, IRequestHeaderList)
private
FStrings: TStrings;
function GetCount: Integer;
function GetName(AIndex: Integer): string;
function GetValue(const AName: string): string;
procedure Clear;
procedure SetValue(const AName, AValue: string);
public
constructor Create(const AStrings: TStrings);
end;
TIPResponseHeaderList = class(TInterfacedObject, IHeaderList)
private
FStrings: TStrings;
function GetCount: Integer;
function GetName(Index: Integer): string;
function GetValue(const AName: string): string;
procedure Populate(const AResponse: IHTTPResponse);
public
constructor Create(const AResponse: IHTTPResponse);
destructor Destroy; override;
end;
TIPHTTPRequest = class(TInterfacedObject, IRequest)
private
FAccept: string;
FAcceptCharSet: string;
FUserAgent: string;
FContentType: string;
FAcceptEncoding: string;
FCustomHeaders: TStrings;
FUserName: string;
FPassword: string;
function GetAccept: string;
procedure SetAccept(const AValue: string);
function GetAcceptCharSet: string;
procedure SetAcceptCharSet(const AValue: string);
function GetCustomHeaders: IRequestHeaderList;
function GetAcceptEncoding: string;
procedure SetAcceptEncoding(const AValue: string);
function GetContentType: string;
procedure SetContentType(const AContentType: string);
function GetUserAgent: string;
procedure SetUserAgent(const AValue: string);
function GetUserName: string;
function GetPassword: string;
procedure SetAuthentication(const AUserName, APassword: string);
public
constructor Create;
destructor Destroy; override;
end;
TIPHTTPResponse = class(TInterfacedObject, IResponse)
private
FResponse: IHTTPResponse;
function GetCharSet: string;
function GetContentType: string;
function GetContentEncoding: string;
function GetHeaders: IHeaderList;
public
constructor Create(const AResponse: IHTTPResponse);
end;
protected
FHTTPClient: THTTPClient;
FHTTPResponse: IHTTPResponse;
FIPHTTPRequestIntf: IRequest;
FProxyConnectionInfo: IProxyConnectionInfo;
FOnValidateCertificate: TValidateCertificateEvent;
FOnValidatePeerCertificate: TValidateCertificate;
FOnValidatePeerCertificateErr: TValidateCertificateErr;
function GetRequest: IRequest;
function GetResponse: IResponse;
function GetProxyParams: IProxyConnectionInfo;
procedure CheckResponse;
function GetResponseCode: Integer; override;
function GetResponseText: string; override;
procedure PrepareRequest(const ARequest: IHTTPRequest);
procedure Execute(const AMethod, AURL: string; const ASource, AResponseContent: TStream); overload;
procedure Execute(const AMethod, AURL: string; const AResponseContent: TStream); overload;
procedure DoValidateServerCertificate(const ASender: TObject; const ARequest: TURLRequest;
const ACertificate: TCertificate; var Accepted: Boolean);
procedure RaiseProtocolException(const AResponse: IHTTPResponse);
public
constructor Create(const AIPImplementationID: string); virtual;
destructor Destroy; override;
function Post(AURL: string; ASource: TStrings): string; override;
function Put(AURL: string; ASource: TStream): string; override;
function Get(AURL: string): TDSHTTPResponseStream; override;
procedure SetConnectTimeout(AMilisec: Integer); override;
procedure SetReadTimeout(AMilisec: Integer); override;
procedure SetBasicAuthentication(const AUser, APassword: string); override;
/// <summary>Get the HTTP request properties</summary>
property Request: IRequest read GetRequest;
property Response: IResponse read GetResponse;
/// <summary>Get the proxy server connection properties</summary>
property ProxyParams: IProxyConnectionInfo read GetProxyParams;
/// <summary>Event is fired when errors exist in the SSL certificates, that require user validation </summary>
property OnValidateCertificate: TValidateCertificateEvent read FOnValidateCertificate write FOnValidateCertificate;
// for backward compatibility
/// <summary>Event is fired when errors exist in the SSL certificates, that require user validation </summary>
property OnValidatePeerCertificate: TValidateCertificate read FOnValidatePeerCertificate write FOnValidatePeerCertificate;
/// <summary>Event is fired when errors exist in the SSL certificates, that require user validation </summary>
property OnValidatePeerCertificateErr: TValidateCertificateErr read FOnValidatePeerCertificateErr write FOnValidatePeerCertificateErr;
end;
TDSHTTPSNativeClient = class(TDSHTTPNativeClient)
public
constructor Create(const AIPImplementationID: string); override;
procedure SetPeerCertificateValidation(UserValidation: TValidateCertificate); virtual;
end;
{ TIPProxyConnectionInfo }
function TDSHTTPNativeClient.TIPProxyConnectionInfo.GetProxyPassword: string;
begin
Result := FProxySettings.password;
end;
function TDSHTTPNativeClient.TIPProxyConnectionInfo.GetProxyPort: Integer;
begin
Result := FProxySettings.Port;
end;
function TDSHTTPNativeClient.TIPProxyConnectionInfo.GetProxyServer: string;
begin
Result := FProxySettings.Host;
end;
function TDSHTTPNativeClient.TIPProxyConnectionInfo.GetProxyScheme: string;
begin
Result := FProxySettings.Scheme;
end;
function TDSHTTPNativeClient.TIPProxyConnectionInfo.GetProxyUserName: string;
begin
Result := FProxySettings.UserName;
end;
procedure TDSHTTPNativeClient.TIPProxyConnectionInfo.SetProxyPassword(const APass: string);
begin
FProxySettings.password := APass;
end;
procedure TDSHTTPNativeClient.TIPProxyConnectionInfo.SetProxyPort(AValue: Integer);
begin
FProxySettings.Port := AValue;
end;
procedure TDSHTTPNativeClient.TIPProxyConnectionInfo.SetProxyServer(const AValue: string);
begin
FProxySettings.Host := AValue;
end;
procedure TDSHTTPNativeClient.TIPProxyConnectionInfo.SetProxyScheme(const AValue: string);
begin
FProxySettings.Scheme := AValue;
end;
procedure TDSHTTPNativeClient.TIPProxyConnectionInfo.SetProxyUserName(const AUser: string);
begin
FProxySettings.UserName := AUser;
end;
{ TIPRequestHeaderList }
function TDSHTTPNativeClient.TIPRequestHeaderList.GetCount: Integer;
begin
Result := FStrings.Count;
end;
function TDSHTTPNativeClient.TIPRequestHeaderList.GetName(AIndex: Integer): string;
begin
Result := FStrings.Names[AIndex];
end;
function TDSHTTPNativeClient.TIPRequestHeaderList.GetValue(const AName: string): string;
begin
Result := FStrings.Values[AName];
end;
constructor TDSHTTPNativeClient.TIPRequestHeaderList.Create(const AStrings: TStrings);
begin
FStrings := AStrings;
end;
procedure TDSHTTPNativeClient.TIPRequestHeaderList.Clear;
begin
FStrings.Clear;
end;
procedure TDSHTTPNativeClient.TIPRequestHeaderList.SetValue(const AName, AValue: string);
begin
FStrings.Values[AName] := AValue;
end;
{ TIPResponseHeaderList }
destructor TDSHTTPNativeClient.TIPResponseHeaderList.Destroy;
begin
FStrings.Free;
inherited;
end;
function TDSHTTPNativeClient.TIPResponseHeaderList.GetCount: Integer;
begin
Result := FStrings.Count;
end;
function TDSHTTPNativeClient.TIPResponseHeaderList.GetName(Index: Integer): string;
begin
Result := FStrings.Names[Index];
end;
function TDSHTTPNativeClient.TIPResponseHeaderList.GetValue(const AName: string): string;
begin
Result := FStrings.Values[AName];
end;
constructor TDSHTTPNativeClient.TIPResponseHeaderList.Create(const AResponse: IHTTPResponse);
begin
FStrings := TStringList.Create;
Populate(AResponse);
end;
procedure TDSHTTPNativeClient.TIPResponseHeaderList.Populate(const AResponse: IHTTPResponse);
var
LHeader: TNetHeader;
begin
for LHeader in AResponse.Headers do
FStrings.Values[LHeader.Name] := LHeader.Value;
end;
{ TIPHTTPRequest }
constructor TDSHTTPNativeClient.TIPHTTPRequest.Create;
begin
FCustomHeaders := TStringList.Create;
end;
destructor TDSHTTPNativeClient.TIPHTTPRequest.Destroy;
begin
FCustomHeaders.Free;
inherited;
end;
function TDSHTTPNativeClient.TIPHTTPRequest.GetAccept: string;
begin
Result := FAccept;
end;
function TDSHTTPNativeClient.TIPHTTPRequest.GetAcceptCharSet: string;
begin
Result := FAcceptCharSet;
end;
function TDSHTTPNativeClient.TIPHTTPRequest.GetAcceptEncoding: string;
begin
Result := FAcceptEncoding;
end;
function TDSHTTPNativeClient.TIPHTTPRequest.GetContentType: string;
begin
Result := FContentType;
end;
function TDSHTTPNativeClient.TIPHTTPRequest.GetCustomHeaders: IRequestHeaderList;
begin
Result := TIPRequestHeaderList.Create(FCustomHeaders);
end;
function TDSHTTPNativeClient.TIPHTTPRequest.GetPassword: string;
begin
Result := FPassword;
end;
function TDSHTTPNativeClient.TIPHTTPRequest.GetUserAgent: string;
begin
Result := FUserAgent;
end;
function TDSHTTPNativeClient.TIPHTTPRequest.GetUserName: string;
begin
Result := FUserName;
end;
procedure TDSHTTPNativeClient.TIPHTTPRequest.SetAccept(const AValue: string);
begin
FAccept := AValue;
end;
procedure TDSHTTPNativeClient.TIPHTTPRequest.SetAcceptCharSet(const AValue: string);
begin
FAcceptCharSet := AValue;
end;
procedure TDSHTTPNativeClient.TIPHTTPRequest.SetAcceptEncoding(const AValue: string);
begin
FAcceptEncoding := AValue;
end;
procedure TDSHTTPNativeClient.TIPHTTPRequest.SetAuthentication(const AUserName, APassword: string);
begin
if AUserName <> emptystr then
begin
FUserName := AUserName;
FPassword := APassword;
end;
end;
procedure TDSHTTPNativeClient.TIPHTTPRequest.SetContentType(const AContentType: string);
begin
FContentType := AContentType;
end;
procedure TDSHTTPNativeClient.TIPHTTPRequest.SetUserAgent(const AValue: string);
begin
FUserAgent := AValue;
end;
{ TIPHTTPResponse }
constructor TDSHTTPNativeClient.TIPHTTPResponse.Create(const AResponse: IHTTPResponse);
begin
FResponse := AResponse;
end;
function TDSHTTPNativeClient.TIPHTTPResponse.GetCharSet: string;
begin
Result := FResponse.ContentCharSet;
end;
function TDSHTTPNativeClient.TIPHTTPResponse.GetContentEncoding: string;
begin
Result := FResponse.ContentEncoding;
end;
function TDSHTTPNativeClient.TIPHTTPResponse.GetContentType: string;
var
LSplitted: TArray<string>;
LResultValues: TArray<string>;
S: string;
begin
Result := FResponse.MimeType;
LSplitted := Result.Split([';']);
// Remove charset
for S in LSplitted do
if not S.TrimLeft.StartsWith('charset', True) then // do not translate
LResultValues := LResultValues + [S];
if Length(LResultValues) <> Length(LSplitted) then
begin
Result := '';
// Rebuild
for S in LResultValues do
begin
if Result <> '' then
Result := Result + ';';
Result := Result + S;
end;
end;
end;
function TDSHTTPNativeClient.TIPHTTPResponse.GetHeaders: IHeaderList;
begin
Result := TIPResponseHeaderList.Create(FResponse);
end;
{TDBXHTTPLayer}
constructor TDBXHTTPLayer.Create;
begin
inherited;
FSessionId := '0';
InitHTTPClient;
end;
destructor TDBXHTTPLayer.Destroy;
begin
Close;
FreeAndNil(Fhttp);
end;
function TDBXHTTPLayer.HTTPProtocol: string;
begin
Result := 'http';
end;
procedure TDBXHTTPLayer.Close;
var
RParams: TStringList;
begin
if FSessionId <> '0' then
begin
RParams := TStringList.Create;
RParams.Values['dss'] := '-' + FSessionId;
try
try
Fhttp.Post(FURITunnel + '?dss=' + FSessionId, RParams);
except
// ignore
end;
finally
RParams.Free;
end;
FSessionId := '0';
end;
end;
procedure TDBXHTTPLayer.Open(const DBXProperties: TDBXProperties);
var
LDatasnapPath, LPath, LProxyHost, LProxyPassword, LProxyUsername: string;
Password, Scheme, Timeout, User: string;
LProxyPort: Integer;
LURI: TURI;
begin
Close;
FIPImplementationID := DbxProperties[TDBXPropertyNames.IPImplementationID];
LPath := DBXProperties[TDBXPropertyNames.URLPath];
if LPath <> '' then
LPath := LPath + '/';
LDatasnapPath := DBXProperties[TDBXPropertyNames.DatasnapContext];
Assert(LDatasnapPath.Length > 0);
if LDatasnapPath = '/' then
LDatasnapPath := EmptyStr
else if (LDatasnapPath.Chars[LDatasnapPath.Length - 1] <> '/') then
LDatasnapPath := LDatasnapPath + '/';
LURI.ComposeURI(HTTPProtocol, '', '', DBXProperties[TDBXPropertyNames.HostName],
DBXProperties[TDBXPropertyNames.Port].ToInteger, '/'+LPath+LDatasnapPath+'tunnel', [], '');
FURITunnel := LURI.ToString;
//set up HTTP proxy
LProxyHost := DBXProperties[TDBXPropertyNames.DSProxyHost].Trim;
if LProxyHost <> '' then
begin
LProxyPort := StrToIntDef(DBXProperties.Values[TDBXPropertyNames.DSProxyPort], 8888);
if LProxyPort > 0 then
begin
LProxyUsername := DBXProperties[TDBXPropertyNames.DSProxyUsername];
LProxyPassword := DBXProperties[TDBXPropertyNames.DSProxyPassword];
TDSHTTPNativeClient(Fhttp).ProxyParams.ProxyServer := LProxyHost;
TDSHTTPNativeClient(Fhttp).ProxyParams.ProxyPort := LProxyPort;
TDSHTTPNativeClient(Fhttp).ProxyParams.ProxyUserName := LProxyUsername;
TDSHTTPNativeClient(Fhttp).ProxyParams.ProxyPassword := LProxyPassword;
TDSHTTPNativeClient(Fhttp).ProxyParams.ProxyScheme := DBXProperties[TDBXPropertyNames.CommunicationProtocol];
end;
end;
FSessionId := '0';
Scheme := DbxProperties[TDBXPropertyNames.DSAuthenticationScheme];
if SameText(Scheme, 'basic') then
begin
// Make user/password available in the HTTP headers, in addition
// to the DBX connection string. Allows a inter-process DataSnap
// HTTP tunnel server to authenticate the user.
User := DBXProperties[TDBXPropertyNames.DSAuthenticationUser];
Password := DBXProperties[TDBXPropertyNames.DSAuthenticationPassword];
if (User <> '') then
Fhttp.SetBasicAuthentication(User, Password);
end;
Timeout := DbxProperties[TDBXPropertyNames.ConnectTimeout];
if Timeout = '' then
ConnectTimeout := 0
else
begin
ConnectTimeout := StrToInt(Timeout);
if ConnectTimeout < 0 then
ConnectTimeout := 0
else
Fhttp.SetConnectTimeout(ConnectTimeout);
end;
Timeout := DbxProperties[TDBXPropertyNames.CommunicationTimeout];
if Timeout = '' then
CommunicationTimeout := 0
else
begin
CommunicationTimeout := StrToInt(Timeout);
if CommunicationTimeout < 0 then
CommunicationTimeout := 0
else
Fhttp.SetReadTimeout(CommunicationTimeout);
end
end;
function TDBXHTTPLayer.Write(const Buffer: TArray<Byte>; const Offset,
Count: Integer): Integer;
var
MemStream: TDBXBytesStream;
StrData: string;
JSONRes: TJSONObject;
JSONParams: TJSONArray;
Len: Integer;
begin
Assert(Offset = 0);
MemStream := TDBXBytesStream.Create(Buffer, Count);
Result := 0;
try
try
// send the query string with session and count
StrData := Fhttp.Put(FURITunnel + '?dss=' + FSessionId + '&c=' + IntToStr(Count),
MemStream);
except
on ex: Exception do
Exception.RaiseOuterException(TDBXError.Create(ex.Message));
end;
// parse the response, populate the session id and result
if Fhttp.ResponseCode = 200 then
begin
JSONRes := TJSONObject(TJSONObject.ParseJSONValue(BytesOf(StrData), 0));
if JSONRes = nil then
raise TDBXError.Create(Format(SProtocolErrorJSON, [StrData]));
try
if JSONRes.Pairs[0].JsonString.Value = 'error' then
raise TDBXError.Create(TJSONString(JSONRes.Pairs[0].JsonValue).Value);
// session id
JSONParams := TJSONArray(JSONRes.Pairs[0].JsonValue);
FSessionId := TJSONString(JSONParams.Items[0]).Value;
// bytes written
Len := StrToInt(TJSONNumber(JSONParams.Items[1]).Value);
if Len < Count then
raise TDBXError.Create(Format(SProtocolErrorWrite, [Count, Len]));
finally
JSONRes.Free;
end;
end
else
raise TDBXError.Create(Fhttp.ResponseText);
finally
MemStream.Free;
end;
end;
function TDBXHTTPLayer.Read(const Buffer: TArray<Byte>; const Offset,
Count: Integer): Integer;
var
ResponseStream: TDSHTTPResponseStream;
begin
Assert(Offset = 0);
Result := 0;
ResponseStream := nil;
try
// send session and count
ResponseStream := Fhttp.Get(FURITunnel + '?dss=' + FSessionId + '&c=' + IntToStr(Count));
except
on ex: Exception do
Exception.RaiseOuterException(TDBXError.Create(ex.Message));
end;
if ResponseStream <> nil then
try
// read from the stream the number of bytes (compare with response size)
if ResponseStream.ContentLength > Count then
raise TDBXError.Create(Format(SProtocolErrorSize, [ResponseStream, Count]));
Result := ResponseStream.Read(Buffer, ResponseStream.ContentLength);
finally
try
ResponseStream.Close;
finally
ResponseStream.Free;
end;
end;
end;
function TDBXHTTPLayer.Info: string;
begin
Result := FURITunnel;
end;
procedure TDBXHTTPLayer.InitHTTPClient;
begin
Fhttp := TDSHTTPNativeClient.Create(FIPImplementationID);
TDSHTTPNativeClient(Fhttp).Request.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8';
TDSHTTPNativeClient(Fhttp).Request.AcceptEncoding := 'identity';
TDSHTTPNativeClient(Fhttp).Request.ContentType := 'application/octet-stream';
end;
constructor TDSHTTPNativeClient.Create(const AIPImplementationID: string);
begin
inherited Create;
FHTTPClient := THTTPClient.Create;
FHTTPClient.OnValidateServerCertificate := DoValidateServerCertificate;
FIPHTTPRequestIntf := TIPHTTPRequest.Create; // Reference count
end;
destructor TDSHTTPNativeClient.Destroy;
begin
FHTTPClient.Free;
inherited;
end;
procedure TDSHTTPNativeClient.Execute(const AMethod, AURL: string; const AResponseContent: TStream);
var
LRequest: IHTTPRequest;
LResponse: IHTTPResponse;
begin
LRequest := FHTTPClient.GetRequest(AMethod, AURL);
PrepareRequest(LRequest);
LResponse := FHTTPClient.Execute(LRequest, AResponseContent);
FHTTPResponse := LResponse;
if LResponse.StatusCode >= 300 then
RaiseProtocolException(LResponse);
end;
procedure TDSHTTPNativeClient.DoValidateServerCertificate(const ASender: TObject; const ARequest: TURLRequest;
const ACertificate: TCertificate; var Accepted: Boolean);
var
X509Cert: TX509Certificate;
begin
if Assigned(FOnValidateCertificate) then
FOnValidateCertificate(ASender, ARequest, ACertificate, Accepted)
else if Assigned(FOnValidatePeerCertificate) then
begin
X509Cert := TX509NetWrapperCertificate.Create(ACertificate);
try
FOnValidatePeerCertificate(ASender, X509cert, 0, Accepted)
finally
X509Cert.Free;
end;
end
else if Assigned(FOnValidatePeerCertificateErr) then
begin
X509Cert := TX509NetWrapperCertificate.Create(ACertificate);
try
FOnValidatePeerCertificateErr(ASender, X509cert, 0, 0, Accepted)
finally
X509Cert.Free;
end;
end
else
// Accept by default
Accepted := True;
end;
procedure TDSHTTPNativeClient.Execute(const AMethod, AURL: string; const ASource, AResponseContent: TStream);
var
LRequest: IHTTPRequest;
LResponse: IHTTPResponse;
begin
LRequest := FHTTPClient.GetRequest(AMethod, AURL);
PrepareRequest(LRequest); // Problem with FIPHTTPRequestIntf, not initialized
ASource.Seek(Longint(0), soFromBeginning);
LRequest.SourceStream := ASource;
LResponse := FHTTPClient.Execute(LRequest, AResponseContent);
FHTTPResponse := LResponse;
if LResponse.StatusCode >= 300 then
RaiseProtocolException(LResponse);
end;
function TDSHTTPNativeClient.Get(AURL: string): TDSHTTPResponseStream;
var
Data: TStream;
begin
Data := TMemoryStream.Create;
try
Execute('GET', AURL, Data);
Data.Position := 0;
Result := TDSHTTPNativeResponseStream.Create(Data.Size, Data);
Data := nil;
except
Data.Free;
raise;
end;
end;
function TDSHTTPNativeClient.GetRequest: IRequest;
begin
Result := FIPHTTPRequestIntf;
end;
function TDSHTTPNativeClient.GetResponse: IResponse;
begin
CheckResponse;
Result := TIPHTTPResponse.Create(FHTTPResponse);
end;
function TDSHTTPNativeClient.GetProxyParams: IProxyConnectionInfo;
begin
if FProxyConnectionInfo = nil then
FProxyConnectionInfo := TIPProxyConnectionInfo.Create;
Result := FProxyConnectionInfo;
end;
procedure TDSHTTPNativeClient.CheckResponse;
begin
if FHTTPResponse = nil then
raise Exception.Create(sResponseObjectNotFound);
end;
function TDSHTTPNativeClient.GetResponseCode: Integer;
begin
CheckResponse;
Result := FHTTPResponse.StatusCode;
end;
function TDSHTTPNativeClient.GetResponseText: string;
begin
CheckResponse;
Result := FHTTPResponse.StatusText;
end;
function TDSHTTPNativeClient.Post(AURL: string; ASource: TStrings): string;
var
LSource: TStream;
LPrevWriteBOM: Boolean;
begin
LSource := TMemoryStream.Create;
LPrevWriteBOM := ASource.WriteBOM;
try
ASource.WriteBOM := False;
ASource.SaveToStream(LSource);
Execute('POST', AURL, LSource, nil);
Result := FHTTPResponse.ContentAsString;
finally
ASource.WriteBOM := LPrevWriteBOM;
LSource.Free;
end;
end;
procedure TDSHTTPNativeClient.PrepareRequest(const ARequest: IHTTPRequest);
var
LIPRequest: TIPHTTPRequest;
I: Integer;
begin
if FProxyConnectionInfo <> nil then
FHTTPClient.ProxySettings := TIPProxyConnectionInfo(FProxyConnectionInfo).FProxySettings;
LIPRequest := TIPHTTPRequest(FIPHTTPRequestIntf);
for I := 0 to LIPRequest.FCustomHeaders.Count - 1 do
ARequest.AddHeader(LIPRequest.FCustomHeaders.Names[I], LIPRequest.FCustomHeaders.ValueFromIndex[I]);
if LIPRequest.FAccept <> '' then
ARequest.Accept := LIPRequest.FAccept;
if LIPRequest.FAcceptCharSet <> '' then
ARequest.AcceptCharSet := LIPRequest.FAcceptCharSet;
if LIPRequest.FUserAgent <> '' then
ARequest.UserAgent := LIPRequest.FUserAgent;
if LIPRequest.FAcceptEncoding <> '' then
ARequest.AcceptEncoding := LIPRequest.FAcceptEncoding;
if LIPRequest.FContentType <> '' then
ARequest.AddHeader('Content-type', LIPRequest.FContentType);
if LIPRequest.FUserName <> '' then
begin
ARequest.SetCredential(LIPRequest.FUserName, LIPRequest.FPassword);
FHTTPClient.PreemptiveAuthentication := True;
end;
end;
function TDSHTTPNativeClient.Put(AURL: string; ASource: TStream): string;
begin
try
Execute('PUT', AURL, ASource, nil);
Result := FHTTPResponse.ContentAsString;
except
raise
end;
end;
procedure TDSHTTPNativeClient.RaiseProtocolException(const AResponse: IHTTPResponse);
const
sHTTP10 = 'HTTP/1.0';
sHTTP11 = 'HTTP/1.1';
sHTTP20 = 'HTTP/2.0';
var
LMessage: string;
begin
case AResponse.Version of
THTTPProtocolVersion.UNKNOWN_HTTP:
LMessage := '';
THTTPProtocolVersion.HTTP_1_0:
LMessage := sHTTP10 + ' ';
THTTPProtocolVersion.HTTP_1_1:
LMessage := sHTTP11 + ' ';
THTTPProtocolVersion.HTTP_2_0:
LMessage := sHTTP20 + ' ';
end;
LMessage := LMessage + Format('%d %s', [AResponse.StatusCode, AResponse.StatusText]);
raise EHTTPProtocolException.Create(AResponse.StatusCode, AResponse.ContentAsString, LMessage);
end;
procedure TDSHTTPNativeClient.SetBasicAuthentication(const AUser, APassword: string);
begin
FHTTPClient.CredentialsStorage.AddCredential(
TCredentialsStorage.TCredential.Create(TAuthTargetType.Server, '', '', AUser, APassword));
end;
procedure TDSHTTPNativeClient.SetConnectTimeout(AMilisec: Integer);
begin
FHTTPClient.ConnectionTimeout := AMilisec;
end;
procedure TDSHTTPNativeClient.SetReadTimeout(AMilisec: Integer);
begin
FHTTPClient.ResponseTimeout := AMilisec;
end;
{ TDSHTTPNativeResponseStream }
procedure TDSHTTPNativeResponseStream.Close;
begin
// Do nothing
end;
constructor TDSHTTPNativeResponseStream.Create(AContentLength: Integer; AStream: TStream);
begin
FStream := AStream;
FContentLength := AContentLength;
end;
destructor TDSHTTPNativeResponseStream.Destroy;
begin
FreeAndNil(FStream);
end;
function TDSHTTPNativeResponseStream.GetContentLength: Int64;
begin
Result := FContentLength;
end;
function TDSHTTPNativeResponseStream.Read(Buffer: TArray<Byte>;
Count: Longint): Integer;
begin
Result := FStream.Read(Buffer[0], Count);
end;
{ TDBXHTTPSLayer }
function TDBXHTTPSLayer.HTTPProtocol: string;
begin
Result := 'https';
end;
procedure TDBXHTTPSLayer.InitHTTPClient;
begin
Fhttp := TDSHTTPSNativeClient.Create(FIPImplementationID);
TDSHTTPNativeClient(Fhttp).Request.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8';
TDSHTTPNativeClient(Fhttp).Request.AcceptEncoding := 'identity';
TDSHTTPNativeClient(Fhttp).Request.ContentType := 'application/octet-stream';
end;
procedure TDBXHTTPSLayer.Open(const DBXProperties: TDBXProperties);
var
Proc: TEventPointer;
begin
inherited;
Proc := DBXProperties.Events.Events[sValidatePeerCertificate];
if Assigned(Proc) then
TDSHTTPSNativeClient(Fhttp).SetPeerCertificateValidation(TValidateCertificate(Proc));
end;
{ TDSHTTPSNativeClient }
constructor TDSHTTPSNativeClient.Create(const AIPImplementationID: string);
begin
inherited Create(AIPImplementationID);
FOnValidatePeerCertificate := nil;
end;
procedure TDSHTTPSNativeClient.SetPeerCertificateValidation(
UserValidation: TValidateCertificate);
begin
FOnValidatePeerCertificate := UserValidation;
end;
{ TDSHTTPClient }
procedure TDSHTTPClient.SetConnectTimeout(AMilisec: Integer);
begin
// do nothing here
end;
procedure TDSHTTPClient.SetReadTimeout(AMilisec: Integer);
begin
//do nothing here
end;
{ TX509NetAdaptorCertificate }
procedure TX509NetWrapperCertificate.CheckValidity;
begin
CheckValidity(Now);
end;
procedure TX509NetWrapperCertificate.CheckValidity(ADate: TDateTime);
begin
if ADate > FExpiry then
raise ECertificateExpiredException.Create(SCertExpired);
if ADate < FStart then
raise ECertificateNotYetValidException.Create(SCertNotYetValid);
end;
constructor TX509NetWrapperCertificate.Create(const ACert: System.Net.URLClient.TCertificate);
begin
FExpiry := ACert.Expiry;
FStart := ACert.Start;
FSubject := ACert.Subject;
FIssuer := ACert.Issuer;
FProtocolName := ACert.ProtocolName;
FAlgSignature := ACert.AlgSignature;
FAlgEncryption := ACert.AlgEncryption;
FKeySize := ACert.KeySize;
FSubjectPrincipal := TX500NETPrincipal.Create(ACert.Subject);
FIssuerPrincipal := TX500NETPrincipal.Create(ACert.Issuer);
FPublicKey := TX509NETPublicKey.Create(FProtocolName, '');
end;
destructor TX509NetWrapperCertificate.Destroy;
begin
FIssuerPrincipal.Free;
FSubjectPrincipal.Free;
FPublicKey.Free;
inherited;
end;
function TX509NetWrapperCertificate.GetBasicConstraints: Integer;
begin
Result := 0;
end;
function TX509NetWrapperCertificate.GetEncoded: TArray<Byte>;
begin
Result := TBytes.Create();
end;
function TX509NetWrapperCertificate.GetIssuerX500Principal: TX500Principal;
begin
Result := FIssuerPrincipal;
end;
function TX509NetWrapperCertificate.GetNotAfter: TDateTime;
begin
Result := FExpiry;
end;
function TX509NetWrapperCertificate.GetNotBefore: TDateTime;
begin
Result := FStart;
end;
function TX509NetWrapperCertificate.GetPublicKey: TPublicKey;
begin
Result := FPublicKey;
end;
function TX509NetWrapperCertificate.GetSerialNumber: string;
begin
Result := 'not available';
end;
function TX509NetWrapperCertificate.GetSigAlgName: string;
begin
Result := FAlgEncryption;
end;
function TX509NetWrapperCertificate.GetSignature: string;
begin
Result := FAlgSignature;
end;
function TX509NetWrapperCertificate.GetSubjectX500Principal: TX500Principal;
begin
Result := FSubjectPrincipal;
end;
function TX509NetWrapperCertificate.GetVersion: Longint;
begin
Result := 0;
end;
function TX509NetWrapperCertificate.Verify(key: TPublicKey): Boolean;
begin
Result := True;
end;
{ TX500NETPrincipal }
constructor TX500NETPrincipal.Create(const AName: string);
begin
FName := AName;
end;
function TX500NETPrincipal.GetEncoded: Longint;
begin
Result := 0;
end;
function TX500NETPrincipal.GetName: string;
begin
Result := FName;
end;
{ TX509NETPublicKey }
constructor TX509NETPublicKey.Create(const PKAlgorithm, PKFormat: string);
begin
FAlgorithm := PKAlgorithm;
FFormat := PKFormat;
end;
function TX509NETPublicKey.GetAlgorithm: string;
begin
Result := FAlgorithm;
end;
function TX509NETPublicKey.GetEncoded: TArray<Byte>;
begin
Result := TBytes.Create(); // FIdX509.EncodedKey;
end;
function TX509NETPublicKey.GetFormat: string;
begin
Result := FFormat;
end;
{ EHTTPProtocolException }
constructor EHTTPProtocolException.Create(AErrorCode: Integer; const AErrorMessage, AMessage: string);
begin
FErrorCode := AErrorCode;
FErrorMessage := AErrorMessage;
inherited Create(AMessage);
end;
initialization
TDBXCommunicationLayerFactory.RegisterLayer('http', TDBXHTTPLayer);
TDBXCommunicationLayerFactory.RegisterLayer('https', TDBXHTTPSLayer);
finalization
TDBXCommunicationLayerFactory.UnregisterLayer('http');
TDBXCommunicationLayerFactory.UnregisterLayer('https');
end.
|
unit SigarEdit;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, cxControls, cxContainer,
cxEdit, cxTextEdit;
type
TSigarEdit = class(TcxTextEdit)
private
FSigarField: String;
procedure SetSigarField(const Value: String);
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
published
property SigarField: String read FSigarField write SetSigarField;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Sigar', [TSigarEdit]);
end;
{ TSigarEdit }
procedure TSigarEdit.SetSigarField(const Value: String);
begin
FSigarField := Value;
end;
end.
|
unit Ths.Erp.Database.Table.View.SysViewColumns;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, System.Variants, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table,
Ths.Erp.Database.Table.View;
type
TSysViewColumns = class(TView)
private
FTableName: TFieldDB;
FColumnName: TFieldDB;
FIsNullable: TFieldDB;
FDataType: TFieldDB;
FCharacterMaximumLength: TFieldDB;
FOrdinalPosition: TFieldDB;
FNumericPrecision: TFieldDB;
FNumericScale: TFieldDB;
FOrjTableName: TFieldDB;
FOrjColumnName: TFieldDB;
protected
published
constructor Create(OwnerDatabase:TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Clear();override;
function Clone():TTable;override;
Property TableName1: TFieldDB read FTableName write FTableName;
Property ColumnName: TFieldDB read FColumnName write FColumnName;
property IsNullable: TFieldDB read FIsNullable write FIsNullable;
property DataType: TFieldDB read FDataType write FDataType;
property CharacterMaximumLength: TFieldDB read FCharacterMaximumLength write FCharacterMaximumLength;
property OrdinalPosition: TFieldDB read FOrdinalPosition write FOrdinalPosition;
property NumericPrecision: TFieldDB read FNumericPrecision write FNumericPrecision;
property NumericScale: TFieldDB read FNumericScale write FNumericScale;
property OrjTableName: TFieldDB read FOrjTableName write FOrjTableName;
property OrjColumnName: TFieldDB read FOrjColumnName write FOrjColumnName;
end;
implementation
uses
Ths.Erp.Database.Singleton;
constructor TSysViewColumns.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'sys_view_columns';
SourceCode := '1000';
FTableName := TFieldDB.Create('table_name', ftString, '', 0, False, False);
FColumnName := TFieldDB.Create('column_name', ftString, '', 0, False, False);
FIsNullable := TFieldDB.Create('is_nullable', ftString, 'YES', 0, False, False);
FDataType := TFieldDB.Create('data_type', ftString, '', 0, False, False);
FCharacterMaximumLength := TFieldDB.Create('character_maximum_length', ftInteger, 0, 0, False, False);
FOrdinalPosition := TFieldDB.Create('ordinal_position', ftInteger, 0, 0, False, False);
FNumericPrecision := TFieldDB.Create('numeric_precision', ftInteger, 0, 0, False, False);
FNumericScale := TFieldDB.Create('numeric_scale', ftInteger, 0, 0, False, False);
FOrjTableName := TFieldDB.Create('orj_table_name', ftString, '', 0, False, False);
FOrjColumnName := TFieldDB.Create('orj_column_name', ftString, '', 0, False, False);
end;
procedure TSysViewColumns.SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + FTableName.FieldName,
TableName + '.' + FColumnName.FieldName,
TableName + '.' + FIsNullable.FieldName,
TableName + '.' + FDataType.FieldName,
TableName + '.' + FCharacterMaximumLength.FieldName,
TableName + '.' + FOrdinalPosition.FieldName,
TableName + '.' + FNumericPrecision.FieldName,
TableName + '.' + FNumericScale.FieldName,
TableName + '.' + FOrjTableName.FieldName,
TableName + '.' + FOrjColumnName.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(FTableName.FieldName).DisplayLabel := 'Table Name';
Self.DataSource.DataSet.FindField(FColumnName.FieldName).DisplayLabel := 'Column Name';
Self.DataSource.DataSet.FindField(FIsNullable.FieldName).DisplayLabel := 'Nullable?';
Self.DataSource.DataSet.FindField(FDataType.FieldName).DisplayLabel := 'Data Type';
Self.DataSource.DataSet.FindField(FCharacterMaximumLength.FieldName).DisplayLabel := 'Character Max Length';
Self.DataSource.DataSet.FindField(FOrdinalPosition.FieldName).DisplayLabel := 'Ordinal Position';
Self.DataSource.DataSet.FindField(FNumericPrecision.FieldName).DisplayLabel := 'Numeric Precision';
Self.DataSource.DataSet.FindField(FNumericScale.FieldName).DisplayLabel := 'Numeric Scale';
Self.DataSource.DataSet.FindField(FOrjTableName.FieldName).DisplayLabel := 'Orj Table Name';
Self.DataSource.DataSet.FindField(FOrjColumnName.FieldName).DisplayLabel := 'Orj Column Name';
end;
end;
end;
procedure TSysViewColumns.SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + FTableName.FieldName,
TableName + '.' + FColumnName.FieldName,
TableName + '.' + FIsNullable.FieldName,
TableName + '.' + FDataType.FieldName,
TableName + '.' + FCharacterMaximumLength.FieldName,
TableName + '.' + FOrdinalPosition.FieldName,
TableName + '.' + FNumericPrecision.FieldName,
TableName + '.' + FNumericScale.FieldName,
TableName + '.' + FOrjTableName.FieldName,
TableName + '.' + FOrjColumnName.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
FTableName.Value := FormatedVariantVal(FindField(FTableName.FieldName).DataType, FindField(FTableName.FieldName).Value);
FColumnName.Value := FormatedVariantVal(FindField(FColumnName.FieldName).DataType, FindField(FColumnName.FieldName).Value);
FIsNullable.Value := FormatedVariantVal(FindField(FIsNullable.FieldName).DataType, FindField(FIsNullable.FieldName).Value);
FDataType.Value := FormatedVariantVal(FindField(FDataType.FieldName).DataType, FindField(FDataType.FieldName).Value);
FCharacterMaximumLength.Value := FormatedVariantVal(FindField(FCharacterMaximumLength.FieldName).DataType, FindField(FCharacterMaximumLength.FieldName).Value);
FOrdinalPosition.Value := FormatedVariantVal(FindField(FOrdinalPosition.FieldName).DataType, FindField(FOrdinalPosition.FieldName).Value);
FNumericPrecision.Value := FormatedVariantVal(FindField(FNumericPrecision.FieldName).DataType, FindField(FNumericPrecision.FieldName).Value);
FNumericScale.Value := FormatedVariantVal(FindField(FNumericScale.FieldName).DataType, FindField(FNumericScale.FieldName).Value);
FOrjTableName.Value := FormatedVariantVal(FindField(FOrjTableName.FieldName).DataType, FindField(FOrjTableName.FieldName).Value);
FOrjColumnName.Value := FormatedVariantVal(FindField(FOrjColumnName.FieldName).DataType, FindField(FOrjColumnName.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
EmptyDataSet;
Close;
end;
end;
end;
procedure TSysViewColumns.Clear();
begin
inherited;
FIsNullable.Value := 'NO';
end;
function TSysViewColumns.Clone():TTable;
begin
Result := TSysViewColumns.Create(Database);
FTableName.Clone(TSysViewColumns(Result).FTableName);
FColumnName.Clone(TSysViewColumns(Result).FColumnName);
FIsNullable.Clone(TSysViewColumns(Result).FIsNullable);
FDataType.Clone(TSysViewColumns(Result).FDataType);
FCharacterMaximumLength.Clone(TSysViewColumns(Result).FCharacterMaximumLength);
FOrdinalPosition.Clone(TSysViewColumns(Result).FOrdinalPosition);
FNumericPrecision.Clone(TSysViewColumns(Result).FNumericPrecision);
FNumericScale.Clone(TSysViewColumns(Result).FNumericScale);
FOrjTableName.Clone(TSysViewColumns(Result).FOrjTableName);
FOrjColumnName.Clone(TSysViewColumns(Result).FOrjColumnName);
end;
end.
|
unit delphi_guid;
interface
implementation
procedure WriteGUID(const GUID: TGUID); external 'system';
procedure ReadGUID(out GUID: TGUID); external 'system';
var G1, G2: TGUID;
procedure Test;
begin
G1 := '{00000000-0000-0000-C000-000000000046}';
WriteGUID(G1);
ReadGUID(G2);
end;
initialization
Test();
finalization
Assert(G1 = G2);
end. |
unit untCadastroServico;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.DBCtrls, Vcl.Mask, Vcl.StdCtrls,
Vcl.Buttons, Vcl.ExtCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls,
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;
type
TfrmCadastroServico = class(TForm)
pnlRodape: TPanel;
btnNovo: TBitBtn;
btnGravar: TBitBtn;
btnCancelar: TBitBtn;
btnExcluir: TBitBtn;
btnFechar: TBitBtn;
pnlCentro: TPanel;
lblUsuario: TLabel;
lblSenha: TLabel;
lblCodigo: TLabel;
btnPesquisar: TBitBtn;
edtDescricao: TDBEdit;
edtCodigo: TEdit;
edtValorUnit: TDBEdit;
chkSituacao: TDBCheckBox;
procedure btnFecharClick(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure btnGravarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure edtCodigoExit(Sender: TObject);
procedure edtCodigoKeyPress(Sender: TObject; var Key: Char);
procedure FormActivate(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure edtCodigoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
vID : String;
fNovo : Boolean;
procedure PesquisaBD(vStatus : boolean);
procedure CarregaCampos;
end;
var
frmCadastroServico: TfrmCadastroServico;
implementation
{$R *.dfm}
uses untDM, untPesquisa, untFuncoes, untPrincipal;
procedure TfrmCadastroServico.btnCancelarClick(Sender: TObject);
begin
if edtCodigo.Text <> '' then
begin
if fNovo = False then
begin
dm.qryServico.UndoLastChange(True);
CarregaCampos;
end
else
begin
edtCodigo.Enabled := true;
edtCodigo.Clear;
CarregaCampos;
btnNovo.Enabled := True;
btnGravar.Enabled := True;
btnExcluir.Enabled := True;
fNovo := False;
end;
end;
end;
procedure TfrmCadastroServico.btnExcluirClick(Sender: TObject);
begin
if fNovo = False then
begin
if DM.qryServico.RecordCount > 0 then
begin
frmFuncoes.Botoes('Excluir', DM.qryServico);
edtCodigo.Clear;
edtCodigo.SetFocus;
end;
end;
end;
procedure TfrmCadastroServico.btnFecharClick(Sender: TObject);
begin
close;
end;
procedure TfrmCadastroServico.btnGravarClick(Sender: TObject);
begin
if fNovo = True then
begin
dm.qryServico.FieldByName('id').AsString := edtCodigo.Text;
end;
dm.qryServico.FieldByName('alteracao').AsDateTime := Date+time;
dm.qryServico.FieldByName('usuario').AsInteger := frmPrincipal.vUsuario;
dm.qryServico.FieldByName('CODEMPRESA').AsInteger := frmPrincipal.vEmpresa; //Versao 1.4 - 14/10/2018
btnNovo.Enabled := True;
btnExcluir.Enabled := True;
edtCodigo.Enabled := True;
try
frmFuncoes.Botoes('Gravar', dm.qryServico);
frmFuncoes.AutoIncre('SERVICO', 'Gravar');
PesquisaBD(True);
fNovo := False;
Except on E: Exception do
ShowMessage('Erro na gravação. >>>> ' + E.Message);
end;
end;
procedure TfrmCadastroServico.btnNovoClick(Sender: TObject);
begin
fNovo := True;
dm.qryServico.Insert;
btnNovo.Enabled := False;
btnGravar.Enabled := True;
btnExcluir.Enabled := False;
edtCodigo.Enabled := False;
edtDescricao.SetFocus;
chkSituacao.Checked := True;
chkSituacao.Field.Value := 'Ativo';
edtValorUnit.Field.Value := 0;
edtCodigo.Text := IntToStr(frmFuncoes.AutoIncre('SERVICO', 'Novo'));
end;
procedure TfrmCadastroServico.btnPesquisarClick(Sender: TObject);
begin
if fNovo = False then
PesquisaBD(False);
edtCodigo.SetFocus;
end;
procedure TfrmCadastroServico.CarregaCampos;
begin
edtDescricao.DataField := 'DESCRICAO';
edtValorUnit.DataField := 'VALOR';
chkSituacao.DataField := 'SITUACAO';
TFMTBCDField(dm.qryServico.FieldByName('valor')).DisplayFormat := '###,####,###,##0.00';
end;
procedure TfrmCadastroServico.edtCodigoExit(Sender: TObject);
begin
if fNovo = False then
begin
if Trim(edtCodigo.Text) <> '' then
PesquisaBD(True);
end;
end;
procedure TfrmCadastroServico.edtCodigoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_F2 then
btnPesquisarClick(Self);
end;
procedure TfrmCadastroServico.edtCodigoKeyPress(Sender: TObject; var Key: Char);
begin
If not( key in['0'..'9',#08] ) then
key := #0;
end;
procedure TfrmCadastroServico.FormActivate(Sender: TObject);
begin
vID := '0';
frmFuncoes.ExecutaSQL('Select * from SERVICO where ID = ' + vID, 'Abrir', DM.qryServico);
CarregaCampos;
edtCodigo.SetFocus;
end;
procedure TfrmCadastroServico.FormKeyPress(Sender: TObject; var Key: Char);
begin
If key = #13 then
Begin
Key:= #0;
Perform(Wm_NextDlgCtl,0,0);
end;
end;
procedure TfrmCadastroServico.PesquisaBD(vStatus: boolean);
begin
if vStatus = True then
begin
if Trim(edtCodigo.Text) <> '' then
begin
frmFuncoes.ExecutaSQL('Select * from SERVICO where ID = ' + QuotedStr(edtCodigo.Text), 'Abrir', dm.qryServico);
if dm.qryServico.RecordCount > 0 then
begin
dm.qryServico.Edit;
CarregaCampos;
end
else
begin
Application.MessageBox('Registro não encontrado.', 'Curral Novo', MB_OK);
edtCodigo.SetFocus;
end;
end;
end
else
begin
frmPesquisa := TfrmPesquisa.Create(Self);
try
frmPesquisa.vTabela := 'SERVICO';
frmPesquisa.vComando := 'Select ID, DESCRICAO, VALOR from SERVICO';
frmPesquisa.vTela := 'CAD_SERVICO';
frmPesquisa.ShowModal;
finally
frmPesquisa.Release;
end;
end;
end;
end.
|
unit FSeleciona;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Buttons,
Vcl.ExtCtrls, uGBMontaSelect, Data.DB, Datasnap.DBClient, Vcl.Grids,
Vcl.DBGrids, uConexaoPadrao, uDM;
const
cPanelFiltro : String = 'PanelFiltro';
cComboFiltro : string = 'ComboFiltro';
cEdtFiltro : String = 'EdtFiltro';
cChkFiltro : String = 'ChkFiltro';
cFormatoData : string = 'dd/MM/yyyy';
type
TfrmSeleciona = class(TForm)
pgcGeral: TPageControl;
tsCondicoes: TTabSheet;
tsResultado: TTabSheet;
pnlBottom: TPanel;
btnCancelar: TBitBtn;
btnProcurar: TBitBtn;
btnConfirmar: TBitBtn;
Scroll: TScrollBox;
dbGrid: TDBGrid;
cds: TClientDataSet;
ds: TDataSource;
procedure pgcGeralChange(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnConfirmarClick(Sender: TObject);
procedure btnProcurarClick(Sender: TObject);
procedure cdsAfterOpen(DataSet: TDataSet);
procedure cdsAfterExecute(Sender: TObject; var OwnerData: OleVariant);
private
_MontaSelect : TGBMontaSelect;
function desenhaPanelFiltro(AName: string): TPanel;
procedure desenhaLabelFiltro(APanel: TPanel; ACaption: string);
procedure desenhaComboFiltro(APanel: TPanel; ATipoDeDado: string; AName: String);
procedure desenhaTextoFiltro (APanel: TPanel; AName: string; AIndex: Integer);
procedure desenhaDataFiltro (APanel: TPanel; AName: string; AIndex: Integer);
procedure desenhaNumeroFiltro(APanel: TPanel; AName: string);
procedure desenhaEditText(APanel: TPanel; AName: String);
procedure desenhaFiltro(
AColunas : TStrings;
ADescricao : TStrings;
ATipoDeDado: TStrings
);
function listaCampoTexto : TStrings;
function listaCampoData : TStrings;
function listaCampoNumerico : TStrings;
function getItems(ATipoDado: String): TStrings;
function montaConsulta: string;
function getFiltro : TStrings;
procedure montaCds;
{ Private declarations }
public
constructor Create(AOwner : TComponent; AMontaSelect: TGBMontaSelect);
{ Public declarations }
end;
var
frmSeleciona: TfrmSeleciona;
implementation
{$R *.dfm}
{ TfrmSeleciona }
procedure TfrmSeleciona.btnCancelarClick(Sender: TObject);
begin
Close;
end;
procedure TfrmSeleciona.btnConfirmarClick(Sender: TObject);
var
i : Integer;
begin
if cds.RecordCount > 0 then
begin
for I := 0 to _MontaSelect.CamposChave.Count - 1 do
_MontaSelect.ValoresChave[i] := cds.FieldByName(_MontaSelect.CamposChave[i]).AsString;
ModalResult := mrOk;
end
else
Close;
end;
procedure TfrmSeleciona.btnProcurarClick(Sender: TObject);
var
sql: string;
begin
sql := montaConsulta;
pgcGeral.ActivePage := tsResultado;
ShowMessage(sql);
if ConexaoPadrao = nil then
begin
ShowMessage('Nulo');
ConexaoPadrao := TConexaoPadrao.create;
end;
cds.Data := ConexaoPadrao.GetDataPacket(sql);
end;
procedure TfrmSeleciona.cdsAfterExecute(Sender: TObject;
var OwnerData: OleVariant);
begin
ShowMessage('Execute');
end;
procedure TfrmSeleciona.cdsAfterOpen(DataSet: TDataSet);
var
column : TColumn;
i : Integer;
begin
if dbGrid.Columns.Count = 0 then
begin
for i := 0 to cds.FieldCount - 1 do
begin
column := dbGrid.Columns.Add;
column.Field := cds.Fields[i];
column.Title.Caption := cds.Fields[i].DisplayLabel;
end;
end;
end;
constructor TfrmSeleciona.Create(AOwner : TComponent; AMontaSelect: TGBMontaSelect);
begin
inherited Create(AOwner);
Application.CreateForm(TDM, DM);
_MontaSelect := AMontaSelect;
Self.Caption := _MontaSelect.Caption;
pgcGeral.ActivePage := tsCondicoes;
desenhaFiltro(_MontaSelect.Colunas, _MontaSelect.Descricao, _MontaSelect.TipoDeDado);
montaCds;
end;
procedure TfrmSeleciona.desenhaComboFiltro(APanel: TPanel; ATipoDeDado: string; AName: String);
begin
with TComboBox.Create(APanel) do
begin
Parent := APanel;
Items := getItems(ATipoDeDado);
ItemIndex := 0;
Left := 192;
Width := 145;
Style := csDropDownList;
Top := 6;
Name := AName;
end;
end;
procedure TfrmSeleciona.desenhaDataFiltro(APanel: TPanel; AName: string; AIndex: Integer);
begin
with TDateTimePicker.Create(APanel) do
begin
Parent := APanel;
Name := AName;
Text := '';
Left := 343;
Height := 21;
Kind := dtkDate;
Width := 290;
Top := 6;
end;
with TCheckBox.Create(APanel) do
begin
Parent := APanel;
Name := cChkFiltro + IntToStr(AIndex);
Caption:= '';
Checked := False;
Height := 17;
Left := 638;
Width := 49;
Top := 8;
end;
end;
procedure TfrmSeleciona.desenhaEditText(APanel: TPanel; AName: String);
begin
with TEdit.Create(APanel) do
begin
Parent := APanel;
Name := AName;
Text := '';
Left := 343;
Width := 290;
Top := 6;
end;
end;
procedure TfrmSeleciona.desenhaFiltro(AColunas, ADescricao, ATipoDeDado: TStrings);
var
i : Integer;
panel : TPanel;
begin
for i := AColunas.Count - 1 downto 0 do
begin
panel := desenhaPanelFiltro(cPanelFiltro + IntToStr( i ));
desenhaLabelFiltro(panel, ADescricao[i]);
desenhaComboFiltro(panel, ATipoDeDado[i], cComboFiltro + IntToStr( i ));
if ATipoDeDado[i] = 'C' then
desenhaTextoFiltro(panel, cEdtFiltro + IntToStr(i), i)
else
if ATipoDeDado[i] = 'D' then
desenhaDataFiltro(panel, cEdtFiltro + IntToStr(i), i)
else
if ATipoDeDado[i] = 'N' then
desenhaNumeroFiltro(panel, cEdtFiltro + IntToStr(i));
end;
end;
procedure TfrmSeleciona.desenhaLabelFiltro(APanel: TPanel; ACaption: string);
begin
with TLabel.Create(APanel) do
begin
Parent := APanel;
Caption := ACaption;
Left := 10;
Top := 10;
end;
end;
procedure TfrmSeleciona.desenhaNumeroFiltro(APanel: TPanel; AName: string);
begin
with TEdit.Create(APanel) do
begin
Parent := APanel;
Name := AName;
Text := '';
Left := 343;
Width := 290;
Top := 6;
end;
end;
function TfrmSeleciona.desenhaPanelFiltro(AName: string): TPanel;
begin
result := TPanel.Create(Scroll);
with result do
begin
Parent := Scroll;
Align := alTop;
Name := AName;
Height := 33;
Caption := '';
end;
end;
procedure TfrmSeleciona.desenhaTextoFiltro(APanel: TPanel; AName: string; AIndex: Integer);
begin
with TEdit.Create(APanel) do
begin
Parent := APanel;
Name := AName;
Text := '';
Left := 343;
Width := 290;
Top := 6;
end;
with TCheckBox.Create(APanel) do
begin
Parent := APanel;
Name := cChkFiltro + IntToStr(AIndex);
Caption:= 'A = a';
Checked := True;
Height := 17;
Left := 638;
Width := 49;
Top := 8;
end;
end;
function TfrmSeleciona.getFiltro: TStrings;
var
i : Integer;
panel : TPanel;
combo : TComboBox;
edit : TEdit;
dateEdit : TDateTimePicker;
chkFiltro : TCheckBox;
valorEdit : String;
function getClausulaTexto(AIndex: Integer; AValor: string): string;
begin
case combo.ItemIndex of
(*
Add('começa com');
Add('é igual a');
Add('possui o texto');
Add('é maior que');
Add('é maior ou igual que');
Add('é menor que');
Add('é menor ou igual que');
Add('é diferente de');
*)
0: result := ' LIKE ' + QuotedStr(AValor + '%');
1: result := ' = ' + QuotedStr(AValor);
2: result := ' LIKE ' + QuotedStr('%' + AValor + '%');
3: result := ' > ' + QuotedStr(AValor);
4: result := ' >= ' + QuotedStr(AValor);
5: Result := ' < ' + QuotedStr(AValor);
6: Result := ' <= ' + QuotedStr(AValor);
7: Result := ' <> ' + QuotedStr(AValor);
end;
end;
function getClausulaData(AIndex: Integer; AValor: string): string;
begin
(*
Add('é igual a');
Add('é maior que');
Add('é maior ou igual que');
Add('é menor que');
Add('é menor ou igual que');
Add('é diferente de');
*)
case combo.ItemIndex of
0: result := ' = ' + QuotedStr(AValor);
1: result := ' > ' + QuotedStr(AValor);
2: result := ' >= ' + QuotedStr(AValor);
3: Result := ' < ' + QuotedStr(AValor);
4: Result := ' <= ' + QuotedStr(AValor);
5: Result := ' <> ' + QuotedStr(AValor);
end;
end;
function getClausulaNumerico(AIndex: Integer; AValor: string): string;
begin
(*
Add('é igual a');
Add('é maior que');
Add('é maior ou igual que');
Add('é menor que');
Add('é menor ou igual que');
Add('é diferente de');
*)
case combo.ItemIndex of
0: result := ' = ' + QuotedStr(AValor);
1: result := ' > ' + QuotedStr(AValor);
2: result := ' >= ' + QuotedStr(AValor);
3: Result := ' < ' + QuotedStr(AValor);
4: Result := ' <= ' + QuotedStr(AValor);
5: Result := ' <> ' + QuotedStr(AValor);
end;
end;
begin
result := TStringList.Create;
with result do
begin
for i := 0 to _MontaSelect.Colunas.Count - 1 do
begin
panel := TPanel ( Scroll.FindComponent(cPanelFiltro + IntToStr(i) ) );
combo := TComboBox ( panel.FindComponent(cComboFiltro + IntToStr(i) ) );
//////////////////////////////////////////////////////////////////////////
/// Texto
//////////////////////////////////////////////////////////////////////////
if _MontaSelect.TipoDeDado[i] = 'C' then
begin
edit := TEdit ( panel.FindComponent( cEdtFiltro + IntToStr(i) ));
valorEdit := Trim( edit.Text );
if valorEdit <> '' then
result.Add('AND ' + _MontaSelect.Colunas[i] + getClausulaTexto(i, valorEdit));
end;
//////////////////////////////////////////////////////////////////////////
/// Data
//////////////////////////////////////////////////////////////////////////
if _MontaSelect.TipoDeDado[i] = 'D' then
begin
dateEdit := TDateTimePicker( panel.FindComponent( cEdtFiltro + IntToStr(i) ));
chkFiltro := TCheckBox ( panel.FindComponent(cChkFiltro + IntToStr(i) ));
if chkFiltro.Checked then
begin
valorEdit := FormatDateTime(cFormatoData, dateEdit.Date);
Result.Add('AND ' + _MontaSelect.Colunas[i] + getClausulaData(i, valorEdit));
end;
end;
//////////////////////////////////////////////////////////////////////////
/// Numérico
//////////////////////////////////////////////////////////////////////////
if _MontaSelect.TipoDeDado[i] = 'N' then
begin
edit := TEdit ( panel.FindComponent( cEdtFiltro + IntToStr(i) ));
valorEdit := Trim( edit.Text );
if valorEdit <> '' then
result.Add('AND ' + _MontaSelect.Colunas[i] + getClausulaNumerico(i, valorEdit));
end;
end;
end;
end;
function TfrmSeleciona.getItems(ATipoDado: String): TStrings;
begin
if ATipoDado = 'C' then Result := listaCampoTexto;
if ATipoDado = 'N' then Result := listaCampoNumerico;
if ATipoDado = 'D' then Result := listaCampoData;
end;
function TfrmSeleciona.listaCampoData: TStrings;
begin
Result := TStringList.Create;
with result do
begin
Add('é igual a');
Add('é maior que');
Add('é maior ou igual que');
Add('é menor que');
Add('é menor ou igual que');
Add('é diferente de');
end;
end;
function TfrmSeleciona.listaCampoNumerico: TStrings;
begin
Result := TStringList.Create;
with result do
begin
Add('é igual a');
Add('é maior que');
Add('é maior ou igual que');
Add('é menor que');
Add('é menor ou igual que');
Add('é diferente de');
end;
end;
function TfrmSeleciona.listaCampoTexto: TStrings;
begin
result := TStringList.Create;
with Result do
begin
Add('começa com');
Add('é igual a');
Add('possui o texto');
Add('é maior que');
Add('é maior ou igual que');
Add('é menor que');
Add('é menor ou igual que');
Add('é diferente de');
end;
end;
procedure TfrmSeleciona.montaCds;
var
i: Integer;
column : TColumn;
begin
for i := 0 to _MontaSelect.Colunas.Count - 1 do
begin
with cds.FieldDefs.AddFieldDef do
begin
Name := _MontaSelect.Colunas[i];
Size := 200;
if _MontaSelect.TipoDeDado[i] = 'C' then DataType := ftString;
if _MontaSelect.TipoDeDado[i] = 'D' then DataType := ftDateTime;
if _MontaSelect.TipoDeDado[i] = 'N' then DataType := ftFloat;
end;
end;
cds.CreateDataSet;
for i := 0 to cds.FieldCount - 1 do
cds.Fields[i].DisplayLabel := _MontaSelect.Descricao[i];
if dbGrid.Columns.Count = 0 then
begin
for i := 0 to cds.FieldCount - 1 do
begin
column := dbGrid.Columns.Add;
column.Field := cds.Fields[i];
column.Title.Caption := cds.Fields[i].DisplayLabel;
end;
end;
end;
function TfrmSeleciona.montaConsulta: string;
var
i : Integer;
begin
with TStringList.Create do
begin
if _MontaSelect.UsaDistinct then
Add('SELECT DISTINCT')
else
Add('SELECT ');
////////////////////////////////////////////////////////////////////////////
/// Adicionando Colunas
////////////////////////////////////////////////////////////////////////////
for i := 0 to _MontaSelect.Colunas.Count - 1 do
begin
if i < (_MontaSelect.Colunas.Count - 1) then
Add(' ' + _MontaSelect.Colunas[i] + ', ')
else
Add(' ' + _MontaSelect.Colunas[i]);
end;
Add('FROM ');
/////////////////////////////////////////////////////////////////////////
/// Tabelas
/////////////////////////////////////////////////////////////////////////
for i := 0 to _MontaSelect.Tabelas.Count - 1 do
begin
if i < (_MontaSelect.Tabelas.Count - 1) then
Add(' ' + _MontaSelect.Tabelas[i] + ', ')
else
Add(' ' + _MontaSelect.Tabelas[i]);
end;
/////////////////////////////////////////////////////////////////////////
/// Filtro
/////////////////////////////////////////////////////////////////////////
Add('WHERE ');
Add(' 1 = 1 ');
for i := 0 to _MontaSelect.Filtros.Count - 1 do
Add('AND ' + _MontaSelect.Filtros[i]);
Add('');
Result := Text + getFiltro.Text;
Free;
end;
end;
procedure TfrmSeleciona.pgcGeralChange(Sender: TObject);
begin
btnCancelar.Visible := pgcGeral.ActivePage = tsCondicoes;
btnConfirmar.Visible:= pgcGeral.ActivePage = tsResultado;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.PlatformDefaultStyleActnCtrls, Vcl.Menus, Vcl.ActnPopup, System.Actions, Vcl.ActnList,
Vcl.ActnMan;
type
TForm1 = class(TForm)
PopupActionBar1: TPopupActionBar;
procedure FormCreate(Sender: TObject);
private
{ Déclarations privées }
public
{ Déclarations publiques }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
Images: TImageList;
Image: TBitmap;
ActionManager: TActionManager;
Option1, Option2: TMenuItem;
begin
// display an information message
ShowMessage('Right click the form to display the customized popup menu');
// create an image list
Images := TImageList.Create(self);
Images.Height := 32;
Images.Width := 32;
try
Image := TBitmap.Create;
Image.Height := 32;
Image.Width := 32;
Image.Canvas.Font.Name := 'Times New Roman';
Image.Canvas.Font.Size := 22;
Image.Canvas.TextOut((Image.Width - Image.Canvas.TextWidth('1')) div 2, 0, '1');
Images.Add(Image, nil);
finally Image.Free;
end;
// create an action manager and assign the image list to some of its properties
ActionManager := TActionManager.Create(self);
ActionManager.DisabledImages := Images;
ActionManager.LargeDisabledImages := Images;
ActionManager.LargeImages := Images;
// add some items to the popup menu associated with the popup action bar
Option1 := TMenuItem.Create(self);
Option1.Caption := 'New';
PopupActionBar1.Items.Add(Option1);
Option2 := TMenuItem.Create(self);
Option2.Caption := 'Save';
PopupActionBar1.Items.Add(Option2);
// let the popup action bar be the form's popup menu
Form1.PopupMenu := PopupActionBar1;
end;
end.
|
unit Vigilante.View.URLDialog.Impl;
interface
uses
System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Module.View.FormBase, Vcl.StdCtrls,
Vigilante.View.URLDialog, Module.ValueObject.URL;
type
TURLDialog = class(TFormBase)
edtURLInformada: TEdit;
lblLabelURL: TLabel;
btnOk: TButton;
btnCancelar: TButton;
protected
function GetLabelURL: string;
function GetURLInformada: string;
procedure SetLabelURL(const Value: string);
procedure SetURLInformada(const Value: string);
public
function Executar: boolean;
property LabelURL: string read GetLabelURL write SetLabelURL;
property URLInformada: string read GetURLInformada write SetURLInformada;
end;
TURLDialogController = class(TInterfacedObject, IURLDialog)
private
FURLDialog: TURLDialog;
procedure DestruirFormInterno;
protected
procedure SetURLDialog(const URLDialog: TURLDialog);
function GetURLDialog: TURLDialog;
public
constructor Create; virtual;
destructor Destroy; override;
function Executar: boolean;
function GetLabelURL: string;
function GetURLInformada: IURL;
procedure SetLabelURL(const Value: string);
procedure SetURLInformada(const Value: IURL);
end;
implementation
{$R *.dfm}
uses
ContainerDI;
constructor TURLDialogController.Create;
begin
SetURLDialog(TURLDialog.Create(nil));
end;
destructor TURLDialogController.Destroy;
begin
DestruirFormInterno;
inherited;
end;
procedure TURLDialogController.DestruirFormInterno;
begin
FreeAndNil(FURLDialog);
end;
function TURLDialogController.Executar: boolean;
begin
Result := GetURLDialog.ShowModal = mrOk;
end;
function TURLDialogController.GetLabelURL: string;
begin
Result := FURLDialog.GetLabelURL;
end;
function TURLDialogController.GetURLDialog: TURLDialog;
begin
Result := FURLDialog;
end;
function TURLDialogController.GetURLInformada: IURL;
begin
Result := CDI.Resolve<IURL>([FURLDialog.GetURLInformada]);
end;
procedure TURLDialogController.SetLabelURL(const Value: string);
begin
FURLDialog.SetLabelURL(Value);
end;
procedure TURLDialogController.SetURLDialog(const URLDialog: TURLDialog);
begin
if Assigned(FURLDialog) then
DestruirFormInterno;
FURLDialog := URLDialog;
end;
procedure TURLDialogController.SetURLInformada(const Value: IURL);
begin
FURLDialog.SetURLInformada(Value.AsString);
end;
{ TURLDialog }
function TURLDialog.Executar: boolean;
begin
Result := ShowModal = mrOk;
end;
function TURLDialog.GetLabelURL: string;
begin
Result := lblLabelURL.Caption;
end;
function TURLDialog.GetURLInformada: string;
begin
Result := edtURLInformada.Text;
end;
procedure TURLDialog.SetLabelURL(const Value: string);
begin
lblLabelURL.Caption := Value;
end;
procedure TURLDialog.SetURLInformada(const Value: string);
begin
edtURLInformada.Text := Value;
end;
end.
|
unit declu;
interface
uses Windows, DefaultTranslator;
type
TBaseSite = (bsLeft, bsTop, bsRight, bsBottom);
TBaseOrientation = (boHorizontal, boVertical);
RAWMOUSE = packed record
usFlags: USHORT;
usButtonFlags: USHORT;
usButtonData: USHORT;
ulRawButtons: ULONG;
lLastX: LONG;
lLastY: LONG;
ulExtraInformation: ULONG;
end;
RAWINPUTHEADER = packed record
dwType: DWORD;
dwSize: DWORD;
hDevice: DWORD;
wParam: WPARAM;
end;
RAWINPUT = packed record
header: RAWINPUTHEADER;
mouse: RAWMOUSE;
end;
PRAWINPUT = ^RAWINPUT;
MONITORINFO = record
cbSize: dword;
rcMonitor: TRect;
rcWork: TRect;
dwFlags: dword;
end;
function MonitorFromWindow(HWND: hwnd; dwFlags: DWORD): THandle; stdcall; external 'user32.dll';
function GetMonitorInfoA(hMonitor: THandle; lpmi: pointer): bool; stdcall; external 'user32.dll';
const
WINITEM_CLASS = 'Descal::WinItem';
GUID = '{F4BA4D0C-B36F-4A4B-91F8-CAF7000AED49}';
RollStep = 4;
NoAll = swp_nosize + swp_nomove + swp_nozorder + swp_noreposition;
NOT_AN_ITEM = $ffff; // result const in case when item (items[]) not found
// system timer event ID's //
ID_TIMER = 1;
ID_SLOWTIMER = 2;
resourcestring
XErrorContactDeveloper = 'Contact developer if error is permanent.';
XErrorIn = 'Error in';
XStartButtonText = 'Start';
XMsgFirstRun = 'Hello. This is the first time to run Descal.';
XMsgAddAutostart = 'Would you like to run it every time Windows starts?';
XProgramSettings = 'Program settings';
XExit = 'Exit';
XPageGeneral = 'General';
XPageStyle = 'Style';
XPageAbout = 'About';
XZOrderBottom = 'Stay at the bottom (desktop)';
XZOrderNormal = 'As normal window';
XZOrderStayOnTop = 'Stay at the top of other windows';
implementation
end.
|
unit uTranslateSystemSysConst;
interface
uses
Windows,
System.SysConst,
uTranslate;
Type
TTranslateSystemSysConst = Class(TTranslate)
private
public
class procedure ChangeValues; override;
End;
Implementation
class procedure TTranslateSystemSysConst.ChangeValues;
begin
SetResourceString(@SUnknown, '<unknown>');
SetResourceString(@SInvalidInteger, '"%s" Não é um valor inteiro válido');
SetResourceString(@SInvalidFloat, '"%s" Não é um valor de ponto flutuante válido');
SetResourceString(@SInvalidCurrency, '"%s" não é um valor corrente (Moeda) válido');
SetResourceString(@SInvalidDate, '"%s" não é uma data válida');
SetResourceString(@SInvalidTime, '"%s" não é uma hora válida');
SetResourceString(@SInvalidDateTime, '"%s" não é um valor DateTime válido');
SetResourceString(@SInvalidDateTimeFloat, '"%g" não é um valor DateTime válido');
SetResourceString(@SInvalidTimeStamp, '"%d.%d" não é um valor Timestamp válido');
SetResourceString(@SInvalidGUID, '"%s" não é um valor GUID válido');
SetResourceString(@SInvalidBoolean, '"%s" não é um valor booleando válido');
SetResourceString(@STimeEncodeError, 'Argumento inválido para codificaçào da hora');
SetResourceString(@SDateEncodeError, 'Argumento inválido para codificaçào da data');
SetResourceString(@SOutOfMemory, 'Sem memória');
SetResourceString(@SInOutError, 'Erro de I/O %d');
SetResourceString(@SFileNotFound, 'Arquivo não encontrado');
SetResourceString(@SInvalidFilename, 'Nome de arquivo inválido');
SetResourceString(@STooManyOpenFiles, 'Muitos arquivos abertos');
SetResourceString(@SAccessDenied, 'Acesso ao arquivo negado');
SetResourceString(@SEndOfFile, 'Tentativa de leitura além do final do arquivo');
SetResourceString(@SDiskFull, 'Unidade de disco cheia');
SetResourceString(@SInvalidInput, 'Entrada de valor numérico inválido');
SetResourceString(@SDivByZero, 'Divisão por zero');
SetResourceString(@SRangeError, 'Erro verificando a escala');
SetResourceString(@SIntOverflow, 'Acima da capacidade do inteiro');
SetResourceString(@SInvalidOp, 'operação inválida com ponto flutuante');
SetResourceString(@SZeroDivide, 'Divisão de ponto flutuante por zero');
SetResourceString(@SOverflow, 'Acima da capacidade do ponto flutuante');
SetResourceString(@SUnderflow, 'Abaixo da capacidade do ponto flutuante');
SetResourceString(@SInvalidPointer, 'Operação com ponteiro inválida');
SetResourceString(@SInvalidCast, 'Tipo de classe inválida');
{$IFDEF MSWINDOWS}
SetResourceString(@SAccessViolationArg3, 'Violação de acesso no endereço %p. %s do endereço %p');
{$ENDIF MSWINDOWS}
{$IF Defined(LINUX) or Defined(MACOS) or Defined(ANDROID)}
SetResourceString(@SAccessViolationArg2, 'Violação de acesso no endereço %p, acessando endereço %p');
{$ENDIF LINUX or MACOS or ANDROID}
SetResourceString(@SAccessViolationNoArg, 'Violação de acesso');
SetResourceString(@SStackOverflow, 'Estouro da capacidade da pilha');
SetResourceString(@SControlC, 'Control-C pressionada');
SetResourceString(@SQuit, 'Quit key pressionada');
SetResourceString(@SPrivilege, 'Instrução privilegiada');
SetResourceString(@SOperationAborted, 'Operação abortada');
SetResourceString(@SException, 'Exceção %s no módulo %s em %p.' + sLineBreak + '%s%s' + sLineBreak);
SetResourceString(@SExceptTitle, 'Erro na aplicação');
{$IF Defined(LINUX) or Defined(MACOS) or Defined(ANDROID)}
SetResourceString(@SSigactionFailed, 'Chamada à SigAction falhou');
SetResourceString(@SOSExceptionHandlingFailed, 'OS exception handling initialization failed');
{$ENDIF LINUX or MACOS or ANDROID}
SetResourceString(@SInvalidFormat, 'Formato "%s" inválido ou incompatível com o argumento');
SetResourceString(@SArgumentMissing, 'Nenhum argumento para o formato "%s"');
SetResourceString(@SDispatchError, 'Chamada ao método variante não suportado');
SetResourceString(@SReadAccess, 'Ler');
SetResourceString(@SWriteAccess, 'Gravar');
SetResourceString(@SExecuteAccess, 'Execution');
SetResourceString(@SInvalidAccess, 'Invalid access');
SetResourceString(@SResultTooLong, 'Formato resultante maior que 4096 caracteres');
SetResourceString(@SFormatTooLong, 'Formato da string muito grante');
{$IFDEF MACOS}
SetResourceString(@SCFStringFailed, 'Error creating CFString');
{$ENDIF MACOS}
{$IF defined(USE_LIBICU)}
SetResourceString(@SICUError, 'ICU Error: %d, %s');
SetResourceString(@SICUErrorOverflow, 'ICU Overflow Error: %d, %s, Needed Length=%d');
{$ENDIF defined(USE_LIBICU)}
SetResourceString(@SVarArrayCreate, 'Erro criando variante ou ordenação segura');
SetResourceString(@SVarArrayBounds, 'Índice da Variante ou ordenação segura fora dos limites');
SetResourceString(@SVarArrayLocked, 'Variante ou ordenação segura está bloqueada');
SetResourceString(@SVarArrayWithHResult, 'Erro não esperado na variante ou ordenação segura: %s%.8x');
SetResourceString(@SInvalidVarCast, 'tipo de conversão variante inválido');
SetResourceString(@SInvalidVarOp, 'Operação de variante inválida');
SetResourceString(@SInvalidVarNullOp, 'Operação de variante NULA inválida');
SetResourceString(@SInvalidVarOpWithHResultWithPrefix, 'Operação de variante inválida (%s%.8x)'#10'%s');
SetResourceString(@SVarTypeRangeCheck1, 'Erro verificando a escala para variante do tipo (%s)');
SetResourceString(@SVarTypeRangeCheck2, 'Erro verificando a escala enquanto convertendo variante do tipo (%s) para o tipo (%s)');
SetResourceString(@SVarTypeOutOfRangeWithPrefix, 'Variante personalizada do tipo (%s%.4x) está fora da faixa');
SetResourceString(@SVarTypeAlreadyUsedWithPrefix, 'Variante personalizada do tipo (%s%.4x) Já está usada por %s');
SetResourceString(@SVarTypeNotUsableWithPrefix, 'Variante personalizada do tipo (%s%.4x) não é utilizável');
SetResourceString(@SVarTypeTooManyCustom, 'Muitas variantes do tipo personalizadas foram registrados');
// the following are not used anymore
// SetResourceString(@SVarNotArray, 'Variante não é um array' deprecated; // not used, use SVarInvalid instea)d
// SetResourceString(@SVarTypeUnknown, 'Tipo de variante personalizada ($%.4x) desconhecida' deprecated; // not used anymor)e
// SetResourceString(@SVarTypeOutOfRange, 'Tipo de variante personalizada ($%.4x) está fora da faixa' deprecated);
// SetResourceString(@SVarTypeAlreadyUsed, 'Tipo de variante personalizada ($%.4x) já está em uso por %s' deprecated);
// SetResourceString(@SVarTypeNotUsable, 'Tipo de variante personalizada ($%.4x) não é utilizável' deprecated);
// SetResourceString(@SInvalidVarOpWithHResult, 'Operação variante inválida ($%.8x)' deprecated);
SetResourceString(@SVarTypeCouldNotConvert, 'Não é possível converter variante do tipo (%s) no tipo (%s)');
SetResourceString(@SVarTypeConvertOverflow, 'Estouro de capacidade enquanto convetendo variante do tipo (%s) no tipo (%s)');
SetResourceString(@SVarOverflow, 'Estouro de capacidade da variante');
SetResourceString(@SVarInvalid, 'Argumento inválido');
SetResourceString(@SVarBadType, 'Tipo de variante inválida');
SetResourceString(@SVarNotImplemented, 'Operação não suportada');
SetResourceString(@SVarOutOfMemory, 'Sem memória para operação variante');
SetResourceString(@SVarUnexpected, 'Erro não esperado na variante');
SetResourceString(@SVarDataClearRecursing, 'Recursividade enquanto fazendo um VarDataClear');
SetResourceString(@SVarDataCopyRecursing, 'Recursividade enquanto fazendo um VarDataCopy');
SetResourceString(@SVarDataCopyNoIndRecursing, 'Recursividade enquanto fazendo um VarDataCopyNoInd');
SetResourceString(@SVarDataInitRecursing, 'Recursividade enquanto fazendo um VarDataInit');
SetResourceString(@SVarDataCastToRecursing, 'Recursividade enquanto fazendo um VarDataCastTo');
SetResourceString(@SVarIsEmpty, 'A variante está vazia');
SetResourceString(@sUnknownFromType, 'Não é possível converter para o arquivo especificado');
SetResourceString(@sUnknownToType, 'Não é possível converter para o tipo especificado');
SetResourceString(@SExternalException, 'Excessão externa %x');
SetResourceString(@SAssertionFailed, 'Afirmação falhou');
SetResourceString(@SIntfCastError, 'Interface não suportada');
SetResourceString(@SSafecallException, 'Exceção em método de chamada segura');
SetResourceString(@SMonitorLockException, 'Object lock not owned');
SetResourceString(@SNoMonitorSupportException, 'Monitor support function not initialized');
SetResourceString(@SNotImplemented, 'Feature not implemented');
SetResourceString(@SObjectDisposed, 'Method called on disposed object');
SetResourceString(@SAssertError, '%s (%s, linha %d)');
SetResourceString(@SAbstractError, 'Erro abstrato');
SetResourceString(@SModuleAccessViolation, 'Violação de acesso no endereço %p no módulo "%s". %s do endereço %p');
SetResourceString(@SCannotReadPackageInfo, 'Não é possível acessar o pacote de informações para a package "%s"');
SetResourceString(@sErrorLoadingPackage, 'Não é possível carregar a package %s.'+sLineBreak+'%s');
SetResourceString(@SInvalidPackageFile, 'Arquivo de package "%s" inválida');
SetResourceString(@SInvalidPackageHandle, 'Handle da package inválida');
SetResourceString(@SDuplicatePackageUnit, 'Não é possível carregar a package "%s." Ela contem a unit "%s,"' + 'que já está contida na Package "%s"');
SetResourceString(@SOSError, 'Erro de sistema. Código: %d.'+sLineBreak+'%s');
SetResourceString(@SUnkOSError, 'Uma chamada desconhecida ao SO falhou');
{$IFDEF MSWINDOWS}
// SetResourceString(@SWin32Error, 'Erro Win32. Código: %d.'#10'%s' deprecated; // use SOSErro)r
// SetResourceString(@SUnkWin32Error, 'Uma função da API Win32 falhou' deprecated; // use SUnkOSErro)r
{$ENDIF}
SetResourceString(@SNL, 'Aplicação não é autorizada para ter esta característica');
SetResourceString(@SShortMonthNameJan, 'Jan');
SetResourceString(@SShortMonthNameFeb, 'Fev');
SetResourceString(@SShortMonthNameMar, 'Mar');
SetResourceString(@SShortMonthNameApr, 'Abr');
SetResourceString(@SShortMonthNameMay, 'Mai');
SetResourceString(@SShortMonthNameJun, 'Jun');
SetResourceString(@SShortMonthNameJul, 'Jul');
SetResourceString(@SShortMonthNameAug, 'Ago');
SetResourceString(@SShortMonthNameSep, 'Set');
SetResourceString(@SShortMonthNameOct, 'Out');
SetResourceString(@SShortMonthNameNov, 'Nov');
SetResourceString(@SShortMonthNameDec, 'Dez');
SetResourceString(@SLongMonthNameJan, 'Janeiro');
SetResourceString(@SLongMonthNameFeb, 'Fevereiro');
SetResourceString(@SLongMonthNameMar, 'Março');
SetResourceString(@SLongMonthNameApr, 'Abril');
SetResourceString(@SLongMonthNameMay, 'Maio');
SetResourceString(@SLongMonthNameJun, 'Junho');
SetResourceString(@SLongMonthNameJul, 'Julho');
SetResourceString(@SLongMonthNameAug, 'Agosto');
SetResourceString(@SLongMonthNameSep, 'Setembro');
SetResourceString(@SLongMonthNameOct, 'Outubro');
SetResourceString(@SLongMonthNameNov, 'Novembro');
SetResourceString(@SLongMonthNameDec, 'Dezembro');
SetResourceString(@SShortDayNameSun, 'Dom');
SetResourceString(@SShortDayNameMon, 'Seg');
SetResourceString(@SShortDayNameTue, 'Ter');
SetResourceString(@SShortDayNameWed, 'Qua');
SetResourceString(@SShortDayNameThu, 'Qui');
SetResourceString(@SShortDayNameFri, 'Sex');
SetResourceString(@SShortDayNameSat, 'Sab');
SetResourceString(@SLongDayNameSun, 'Domingo');
SetResourceString(@SLongDayNameMon, 'Segunda');
SetResourceString(@SLongDayNameTue, 'Terça');
SetResourceString(@SLongDayNameWed, 'Quarta');
SetResourceString(@SLongDayNameThu, 'Quinta');
SetResourceString(@SLongDayNameFri, 'Sexta');
SetResourceString(@SLongDayNameSat, 'Sábado');
{$IFDEF POSIX}
SetResourceString(@SEraEntries, '');
{$ENDIF}
SetResourceString(@SCannotCreateDir, 'Não é possível criar o diretório');
SetResourceString(@SCodesetConversionError, 'Falha na conversão do codset');
// Used by TEncoding
SetResourceString(@SInvalidSourceArray, 'Invalid source array');
SetResourceString(@SInvalidDestinationArray, 'Invalid destination array');
SetResourceString(@SCharIndexOutOfBounds, 'Character index out of bounds (%d)');
SetResourceString(@SByteIndexOutOfBounds, 'Start index out of bounds (%d)');
SetResourceString(@SInvalidCharCount, 'Invalid count (%d)');
SetResourceString(@SInvalidDestinationIndex, 'Invalid destination index (%d)');
SetResourceString(@SInvalidCodePage, 'Invalid code page');
SetResourceString(@SInvalidEncodingName, 'Invalid encoding name');
SetResourceString(@SNoMappingForUnicodeCharacter, 'No mapping for the Unicode character exists in the target multi-byte code page');
SetResourceString(@SOperationCancelled, 'Operação cancelada');
end;
End. |
unit ufrmMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Wke, ExtCtrls;
type
TfrmMain = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Button3: TButton;
Button2: TButton;
Button1: TButton;
Button4: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
FWebView: TWkeWebView;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
function test: String;
var
AMsg: string;
begin
AMsg := '这是Delphi字符串!!!';
ShowMessage(AMsg);
Result := AMsg;
end;
function test1(msg: String): String;
var
AMsg: string;
begin
AMsg := msg + ', 这是Delphi字符串!!!';
Result := AMsg;
end;
function _Test(p1, p2, es_: wkeJSState): wkeJSValue;
begin
Result := es_.String_(test);
end;
function _Test1(p1, p2, es_: wkeJSState): wkeJSValue;
var
_msg: String;
begin
_msg := (es_.ArgToString(es_, 0)); // 获取从Html传入的参数
Result := es_.String_(test1(_msg));
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
FWebView:= wkeCreateWebWindow(WKE_WINDOW_TYPE_CONTROL, Panel1.Handle, 0, 0, Panel1.Width, Panel1.Height);
FWebView.Initialize;
FWebView.ShowWindow(True);
JScript.BindFunction('delphi_Test', @_Test, 1);
JScript.BindFunction('delphi_Test1', @_Test1, 1);
end;
procedure TfrmMain.Button1Click(Sender: TObject);
begin
FWebView.LoadFile('html\BallPool.html');
end;
procedure TfrmMain.Button2Click(Sender: TObject);
begin
wkeRunJS(FWebView, 'appTitle.checkText = "hahaha"')
end;
procedure TfrmMain.Button3Click(Sender: TObject);
begin
FWebView.LoadFile('html\index.vue.html');
end;
procedure TfrmMain.Button4Click(Sender: TObject);
begin
FWebView.LoadFile('html\index.html');
end;
end.
|
unit DAO;
{$mode objfpc}{$H+}
interface
uses
SynCommons,
mORMot;
type
{ TSQLGrupo }
TSQLGrupo = class(TSQLRecord)
private
FAtivo: Boolean;
FCodigo: RawUTF8;
procedure SetAtivo(AValue: Boolean);
published
property Codigo:RawUTF8 read FCodigo write FCodigo;
property Ativo: Boolean read FAtivo write SetAtivo;
end;
TSQLProduto = class(TSQLRecord)
private
FCodigo: RawUTF8;
FDescricao: RawUTF8;
FGrupo: TSQLGrupo;
published
property Grupo: TSQLGrupo read FGrupo write FGrupo;
property Codigo:RawUTF8 read FCodigo write FCodigo;
property Descricao: RawUTF8 read FDescricao write FDescricao;
end;
implementation
{ TSQLGrupo }
procedure TSQLGrupo.SetAtivo(AValue: Boolean);
begin
if FAtivo=AValue then Exit;
FAtivo:=AValue;
end;
end.
|
unit BillQuery;
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, Vcl.StdCtrls, DSWrap, BaseEventsQuery, NotifyEvents,
BillInterface, InsertEditMode, BillContentInterface;
type
TBillW = class(TDSWrap)
private
FBillContent: IBillContent;
FID: TFieldWrap;
FNumber: TFieldWrap;
FBillDate: TFieldWrap;
FWidth: TFieldWrap;
FShipmentDate: TFieldWrap;
FDollar: TFieldWrap;
FEuro: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Save(AMode: TMode; ABillInt: IBill): Integer;
procedure ApplyNotShipmentFilter;
procedure ApplyShipmentFilter;
procedure Ship(ADate: TDate);
procedure CancelShip;
property BillContent: IBillContent read FBillContent write FBillContent;
property ID: TFieldWrap read FID;
property Number: TFieldWrap read FNumber;
property BillDate: TFieldWrap read FBillDate;
property Width: TFieldWrap read FWidth;
property ShipmentDate: TFieldWrap read FShipmentDate;
property Dollar: TFieldWrap read FDollar;
property Euro: TFieldWrap read FEuro;
end;
TQryBill = class(TQueryBaseEvents)
private
FW: TBillW;
procedure DoBeforePost(Sender: TObject);
{ Private declarations }
protected
function CreateDSWrap: TDSWrap; override;
public
constructor Create(AOwner: TComponent); override;
function SearchByNumber(ANumber: Integer): Integer;
class function SearchByNumberStatic(ANumber: Integer): Integer; static;
function SearchByPeriod(ABeginDate, AEndDate: TDate): Integer;
property W: TBillW read FW;
{ Public declarations }
end;
implementation
uses
MaxBillNumberQuery, BaseQuery, StrHelper;
{$R *.dfm}
constructor TQryBill.Create(AOwner: TComponent);
begin
inherited;
FW := FDSWrap as TBillW;
TNotifyEventWrap.Create(W.BeforePost, DoBeforePost, W.EventList);
end;
function TQryBill.CreateDSWrap: TDSWrap;
begin
Result := TBillW.Create(FDQuery);
end;
procedure TQryBill.DoBeforePost(Sender: TObject);
begin
if W.BillDate.F.IsNull then
raise Exception.Create('Дата создания счёта не может быть пустой');
if (not W.ShipmentDate.F.IsNull) and
(W.ShipmentDate.F.AsDateTime < W.BillDate.F.AsDateTime) then
raise Exception.Create
('Дата отгрузки не может быть меньше даты создания счёта');
end;
function TQryBill.SearchByNumber(ANumber: Integer): Integer;
begin
Assert(ANumber > 0);
Result := SearchEx([TParamRec.Create(W.Number.FullName, ANumber)]);
end;
class function TQryBill.SearchByNumberStatic(ANumber: Integer): Integer;
var
Q: TQryBill;
begin
Q := TQryBill.Create(nil);
try
Result := Q.SearchByNumber(ANumber);
finally
FreeAndNil(Q);
end;
end;
function TQryBill.SearchByPeriod(ABeginDate, AEndDate: TDate): Integer;
var
AED: TDate;
ANewSQL: string;
ASD: TDate;
AStipulation: string;
begin
if ABeginDate <= AEndDate then
begin
ASD := ABeginDate;
AED := AEndDate;
end
else
begin
ASD := AEndDate;
AED := ABeginDate;
end;
// Делаем замену в SQL запросе
AStipulation := Format('%s >= date(''%s'')',
[W.BillDate.FieldName, FormatDateTime('YYYY-MM-DD', ASD)]);
ANewSQL := ReplaceInSQL(SQL, AStipulation, 0);
// Делаем замену в SQL запросе
AStipulation := Format('%s <= date(''%s'')',
[W.BillDate.FieldName, FormatDateTime('YYYY-MM-DD', AED)]);
ANewSQL := ReplaceInSQL(ANewSQL, AStipulation, 1);
FDQuery.SQL.Text := ANewSQL;
W.RefreshQuery;
Result := FDQuery.RecordCount;
end;
constructor TBillW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FNumber := TFieldWrap.Create(Self, 'Number', 'Номер');
FBillDate := TFieldWrap.Create(Self, 'BillDate', 'Дата');
FShipmentDate := TFieldWrap.Create(Self, 'ShipmentDate', 'Дата отгрузки');
FDollar := TFieldWrap.Create(Self, 'Dollar', 'Курс $');
FEuro := TFieldWrap.Create(Self, 'Euro', 'Курс €');
FWidth := TFieldWrap.Create(Self, 'Width');
end;
destructor TBillW.Destroy;
begin
inherited;
end;
function TBillW.Save(AMode: TMode; ABillInt: IBill): Integer;
begin
Assert(ABillInt <> nil);
if AMode = EditMode then
TryEdit
else
TryAppend;
try
Number.F.Value := ABillInt.BillNumber;
Width.F.Value := ABillInt.BillWidth;
BillDate.F.Value := ABillInt.BillDate;
Dollar.F.Value := ABillInt.DollarCource;
Euro.F.Value := ABillInt.EuroCource;
TryPost;
Result := PK.Value;
Assert(Result > 0);
except
TryCancel;
raise;
end;
// Выполняем операцию по отгрузке / отмене отгрузки
if AMode = EditMode then
begin
if (ABillInt.ShipmentDate > 0) and (ShipmentDate.F.AsDateTime <= 0) then
// Просим контент отгрузить товар и уменьшить его количество на складе
Ship(ABillInt.ShipmentDate)
else if (ABillInt.ShipmentDate <= 0) and (ShipmentDate.F.AsDateTime > 0)
then
// Просим контент отменить отгрузку товара и увеличить его количество на складе
CancelShip();
end;
end;
procedure TBillW.ApplyNotShipmentFilter;
begin
DataSet.Filter := Format('%s is null', [ShipmentDate.FieldName]);
DataSet.Filtered := True;
end;
procedure TBillW.ApplyShipmentFilter;
begin
DataSet.Filter := Format('%s is not null', [ShipmentDate.FieldName]);
DataSet.Filtered := True;
end;
procedure TBillW.Ship(ADate: TDate);
begin
Assert(ShipmentDate.F.IsNull);
Assert(BillContent <> nil);
if ADate < BillDate.F.AsDateTime then
raise Exception.Create
('Дата отгрузки не может быть меньше даты создания счёта');
// Просим контент отгрузить товар и уменьшить его количество на складе
BillContent.ShipAll;
TryEdit;
ShipmentDate.F.AsDateTime := ADate;
TryPost;
end;
procedure TBillW.CancelShip;
begin
Assert(not ShipmentDate.F.IsNull);
Assert(BillContent <> nil);
// Просим контент вернуть товар на склад
BillContent.CalcelAllShip;
TryEdit;
ShipmentDate.F.Value := NULL;
TryPost;
end;
end.
|
unit constexpr_1;
interface
implementation
function GetDigit: Int32; pure;
begin
Result := 6;
end;
var V: Int32;
procedure Test;
begin
V := GetDigit();
end;
initialization
Test();
finalization
Assert(V = 6);
end. |
/////////////////////////////////////////////////////////
// //
// FlexGraphics library //
// Copyright (c) 2002-2009, FlexGraphics software. //
// //
// FlexGraphics library file formats support //
// Standard raster files //
// //
/////////////////////////////////////////////////////////
unit FormatStdFiles;
{$I FlexDefs.inc}
interface
uses
Windows, Types, UITypes, Graphics, SysUtils, Classes, FlexBase, FlexFileFormats;
type
TFlexStandardFormats = class(TFlexFileFormat)
protected
procedure RegisterSupportedExtensions; override;
public
procedure ImportFromStream(AStream: TStream; AFlexPanel: TFlexPanel;
const Extension: TFlexFileExtension; const AFileName: string); override;
procedure ExportToStream(AStream: TStream; AFlexPanel: TFlexPanel;
const Extension: TFlexFileExtension; const AFileName: string); override;
end;
implementation
uses
Consts, Jpeg, JConsts, FlexControls, FlexUtils;
{$IFNDEF FG_D5}
resourcestring
sJPEGImageFile = 'JPEG Image File';
{$ENDIF}
type
TStdFormatExt = (
sfxNone,
sfxBitmap,
sfxIcon,
sfxJpeg
);
// TFlexStandardFormats ///////////////////////////////////////////////////////
procedure TFlexStandardFormats.RegisterSupportedExtensions;
begin
// Register standard extensions
RegisterExtension('ico', SVIcons, [skImport, skExport], integer(sfxIcon));
RegisterExtension('bmp', SVBitmaps, [skImport, skExport], integer(sfxBitmap));
RegisterExtension('jpeg', sJPEGImageFile, [skImport, skExport],
integer(sfxJpeg));
RegisterExtension('jpg', sJPEGImageFile, [skImport, skExport],
integer(sfxJpeg));
end;
procedure TFlexStandardFormats.ExportToStream(AStream: TStream;
AFlexPanel: TFlexPanel; const Extension: TFlexFileExtension;
const AFileName: string);
var
Bitmap: TBitmap;
Graphic: TGraphic;
IconHandle: cardinal;
IconInfo: TIconInfo;
begin
Graphic := Nil;
Bitmap := TBitmap.Create;
try
Bitmap.Width := ScaleValue(AFlexPanel.DocWidth, 100);
Bitmap.Height := ScaleValue(AFlexPanel.DocHeight, 100);
AFlexPanel.PaintTo(Bitmap.Canvas, Rect(0, 0, Bitmap.Width, Bitmap.Height),
Point(0, 0), 100, AFlexPanel.ActiveScheme, False, False, False, True);
case TStdFormatExt(Extension.Tag) of
sfxBitmap:
begin
Graphic := Bitmap;
Bitmap := Nil;
end;
sfxIcon:
begin
FillChar(IconInfo, SizeOf(IconInfo), 0);
with IconInfo do begin
fIcon := True;
hbmMask := Bitmap.Handle;
hbmColor := Bitmap.Handle;
end;
IconHandle := CreateIconIndirect(IconInfo);
if IconHandle = 0 then
raise Exception.CreateFmt(sExportError,
[SysErrorMessage(GetLastError)]);
Graphic := TIcon.Create;
TIcon(Graphic).Handle := IconHandle;
end;
sfxJpeg:
begin
Graphic := TJpegImage.Create;
Graphic.Assign(Bitmap);
end;
else
raise Exception.CreateFmt(sUnsupportedFormat, [Extension.Extension]);
end;
Graphic.SaveToStream(AStream);
finally
Bitmap.Free;
Graphic.Free;
end;
end;
procedure TFlexStandardFormats.ImportFromStream(AStream: TStream;
AFlexPanel: TFlexPanel; const Extension: TFlexFileExtension;
const AFileName: string);
var
Graphic: TGraphic;
FlexPicture: TFlexPicture;
begin
Graphic := Nil;
try
case TStdFormatExt(Extension.Tag) of
sfxBitmap:
Graphic := TBitmap.Create;
sfxIcon:
Graphic := TIcon.Create;
sfxJpeg:
Graphic := TJpegImage.Create;
else
raise Exception.CreateFmt(sUnsupportedFormat, [Extension.Extension]);
end;
Graphic.LoadFromStream(AStream);
FlexPicture := TFlexPicture.Create(AFlexPanel, AFlexPanel.ActiveScheme,
AFlexPanel.ActiveLayer);
FlexPicture.PictureProp.Graphic := Graphic;
FlexPicture.AutoSizeProp.Value := True;
FlexPicture.AutoSizeProp.Value := False;
AFlexPanel.DocWidth := FlexPicture.WidthProp.Value;
AFlexPanel.DocHeight := FlexPicture.HeightProp.Value;
finally
Graphic.Free;
end;
end;
initialization
RegisteredFlexFileFormats.RegisterFormat(TFlexStandardFormats);
end.
|
unit ACartuchoCotacao;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios,
Componentes1, ExtCtrls, PainelGradiente, Grids, CGrades, StdCtrls,
Localizacao, Buttons, Db, DBTables, UnDadosProduto, UnCotacao,
DBKeyViolation, SQLEXPR, FMTBcd, Mask, numericos, DBCtrls, Tabela;
type
TFCartuchoCotacao = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor1: TPanelColor;
GCartuchos: TRBStringGridColor;
Label2: TLabel;
SpeedButton3: TSpeedButton;
Label5: TLabel;
ECotacao: TEditLocaliza;
Label1: TLabel;
Localiza: TConsultaPadrao;
ESequencial: TEditColor;
Aux: TSQLQuery;
Label3: TLabel;
ETransportadora: TRBEditLocaliza;
SpeedButton1: TSpeedButton;
Label4: TLabel;
ValidaGravacao1: TValidaGravacao;
PVolume: TPanelColor;
Label6: TLabel;
PanelColor2: TPanelColor;
BCadatrar: TBitBtn;
BGravar: TBitBtn;
BCancelar: TBitBtn;
BFechar: TBitBtn;
BImprimeVolume: TBitBtn;
EQtdVolume: Tnumerico;
SpeedButton10: TSpeedButton;
Label83: TLabel;
Label82: TLabel;
ERegiaoVenda: TRBEditLocaliza;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ECotacaoSelect(Sender: TObject);
procedure GCartuchosCarregaItemGrade(Sender: TObject;
VpaLinha: Integer);
procedure ESequencialExit(Sender: TObject);
procedure ECotacaoFimConsulta(Sender: TObject);
procedure ESequencialKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure BFecharClick(Sender: TObject);
procedure BCancelarClick(Sender: TObject);
procedure BGravarClick(Sender: TObject);
procedure BCadatrarClick(Sender: TObject);
procedure ECotacaoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ETransportadoraChange(Sender: TObject);
procedure BImprimeVolumeClick(Sender: TObject);
private
{ Private declarations }
VprCartuchos : TList;
VprDNovoCartucho,
VprDCartucho : TRBDCartuchoCotacao;
VprDCotacao : TRBDOrcamento;
procedure CarTitulosGrade;
procedure CarDClasse;
procedure AdicionaCartucho(VpaLanOrcamento, VpaSeqCartucho : integer);
procedure EstadoBotoes(VpaEstado : Boolean);
procedure InicializaTela;
function ExisteCartucho(VpaSequencial : Integer) : Boolean;
function ExisteProdutoCotacao(VpaSeqproduto : Integer) : Boolean;
public
{ Public declarations }
procedure AssociaCartuchoCotacao;
end;
var
FCartuchoCotacao: TFCartuchoCotacao;
implementation
uses APrincipal,constantes,FunObjeto, FunSql, Constmsg, FunString,
ACartuchoCotacaoProduto;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFCartuchoCotacao.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
CarTitulosGrade;
VprCartuchos.free;
VprCartuchos := TList.create;
GCartuchos.ADados := VprCartuchos;
ValidaGravacao1.execute;
if not Config.NoCartuchoCotacaoImprimirEtiquetaVolume then
begin
PVolume.Visible:= False;
BImprimeVolume.Visible:= False;
end;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFCartuchoCotacao.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
{******************************************************************************}
procedure TFCartuchoCotacao.CarDClasse;
begin
// VprDCotacao.QtdVolumesTransportadora:= EQtdVolume.AsInteger;
end;
{******************************************************************************}
procedure TFCartuchoCotacao.CarTitulosGrade;
begin
GCartuchos.Cells[1,0] := 'Sequencial';
GCartuchos.Cells[2,0] := 'Código';
GCartuchos.Cells[3,0] := 'Produto';
GCartuchos.Cells[4,0] := 'Peso';
GCartuchos.Cells[5,0] := 'Embalado';
GCartuchos.Cells[6,0] := 'Celula Trabalho';
end;
{******************************************************************************}
procedure TFCartuchoCotacao.AdicionaCartucho(VpaLanOrcamento, VpaSeqCartucho : integer);
var
VpfResultado : string;
begin
VpfResultado := '';
if not ExisteCartucho(VpaSeqCartucho) then
VpfResultado := 'SEQUENCIAL CARTUCHO INVÁLIDO!!!'#13'O sequencial do cartucho digitado não existe pesado no sistema.';
if VpfResultado = '' then
begin
VprDNovoCartucho.CodFilial := varia.CodigoEmpFil;
VprDNovoCartucho.LanOrcamento := ECotacao.AInteiro;
VprDNovoCartucho.DatSaida := now;
if not ExisteProdutoCotacao(VprDNovoCartucho.SeqProduto) then
begin
FCartuchoCotacaoCartucho := TFCartuchoCotacaoCartucho.CriarSDI(self,'',FPrincipal.VerificaPermisao('FCartuchoCotacaoCartucho'));
if not FCartuchoCotacaoCartucho.TrocaCartuchoCotacao(VprDNovoCartucho) then
begin
VprDNovoCartucho.free;
vpfResultado := 'PRODUTO NÃO ADICIONADO NA COTAÇÃO!!!'#13'O produto referente ao sequencial selecionado não existe adicionado na cotação.';
end;
FCartuchoCotacaoCartucho.free;
end;
if VpfResultado = '' then
begin
VprCartuchos.Add(VprDNovoCartucho);
GCartuchos.CarregaGrade;
if Config.NoCartuchoCotacaoImprimirEtiquetaVolume then
EQtdVolume.AValor:= EQtdVolume.AValor+1;
end;
end;
if VpfResultado <> '' then
aviso(VpfResultado);
end;
{******************************************************************************}
procedure TFCartuchoCotacao.EstadoBotoes(VpaEstado : Boolean);
begin
BCadatrar.Enabled := not VpaEstado;
BGravar.Enabled := VpaEstado;
BCancelar.Enabled := VpaEstado;
BFechar.Enabled := VpaEstado;
end;
{******************************************************************************}
procedure TFCartuchoCotacao.InicializaTela;
begin
// FreeTObjectsList(VprCartuchos);
VprDCotacao.Free;
VprDCotacao := TRBDOrcamento.cria;
VprCartuchos.free;
VprCartuchos := TList.create;
GCartuchos.ADados := VprCartuchos;
GCartuchos.CarregaGrade;
ECotacao.Clear;
ECotacao.Atualiza;
ESequencial.clear;
if ETransportadora.AInteiro = 0 then
ActiveControl := ETransportadora
else
ActiveControl := ECotacao;
EstadoBotoes(true);
end;
{******************************************************************************}
function TFCartuchoCotacao.ExisteCartucho(VpaSequencial : Integer) : Boolean;
begin
if VpaSequencial <> 0 then
begin
AdicionaSQLAbreTabela(Aux,'Select CAR.SEQPRODUTO, CAR.DATPESO, CAR.PESCARTUCHO, '+
' CEL.NOMCELULA, PRO.C_COD_PRO, PRO.C_NOM_PRO '+
' From PESOCARTUCHO CAR, CADPRODUTOS PRO, CELULATRABALHO CEL '+
' Where CAR.SEQCARTUCHO = ' +IntToStr(VpaSequencial)+
' and CAR.SEQPRODUTO = PRO.I_SEQ_PRO '+
' and CAR.CODCELULA = CEL.CODCELULA ');
result := not Aux.eof;
if result then
begin
VprDNovoCartucho := TRBDCartuchoCotacao.cria;
VprDNovoCartucho.SeqCartucho := VpaSequencial;
VprDNovoCartucho.SeqProduto := Aux.FieldByname('SEQPRODUTO').AsInteger;
VprDNovoCartucho.CodProduto := Aux.FieldByname('C_COD_PRO').AsString;
VprDNovoCartucho.NomProduto := Aux.FieldByname('C_NOM_PRO').AsString;
VprDNovoCartucho.CelulaTrabalho := Aux.FieldByname('NOMCELULA').AsString;
VprDNovoCartucho.PesCartucho := Aux.FieldByname('PESCARTUCHO').AsFloat;
VprDNovoCartucho.DatEmbalado := Aux.FieldByname('DATPESO').AsDateTime;
end;
Aux.close;
end;
end;
{******************************************************************************}
function TFCartuchoCotacao.ExisteProdutoCotacao(VpaSeqproduto : Integer) : Boolean;
var
VpfLaco : Integer;
VpfDItem : TRBDOrcProduto;
begin
result := false;
for VpfLaco := 0 to VprDCotacao.Produtos.Count - 1 do
begin
VpfDItem := TRBDOrcProduto(VprDCotacao.Produtos.Items[VpfLaco]);
if VpfDItem.SeqProduto = VpaSeqproduto then
begin
result := true;
break;
end;
end;
end;
{******************************************************************************}
procedure TFCartuchoCotacao.AssociaCartuchoCotacao;
begin
InicializaTela;
showmodal;
end;
{******************************************************************************}
procedure TFCartuchoCotacao.ECotacaoSelect(Sender: TObject);
begin
ECotacao.ASelectLocaliza.Text := 'Select CLI.C_NOM_CLI, COT.I_LAN_ORC '+
' from CADCLIENTES CLI, CADORCAMENTOS COT '+
' Where CLI.I_COD_CLI = COT.I_COD_CLI '+
' and COT.I_EMP_FIL = '+inttoStr(Varia.CodigoEmpFil)+
' and CLI.C_NOM_CLI LIKE ''@%''';
ECotacao.ASelectValida.Text := 'Select CLI.C_NOM_CLI, COT.I_LAN_ORC '+
' from CADCLIENTES CLI, CADORCAMENTOS COT '+
' Where CLI.I_COD_CLI = COT.I_COD_CLI '+
' and COT.I_EMP_FIL = '+inttoStr(Varia.CodigoEmpFil)+
' and COT.I_LAN_ORC = @';
end;
{******************************************************************************}
procedure TFCartuchoCotacao.GCartuchosCarregaItemGrade(Sender: TObject;
VpaLinha: Integer);
begin
VprDCartucho := TRBDCartuchoCotacao(VprCartuchos.Items[VpaLinha-1]);
GCartuchos.Cells[1,VpaLinha] := IntToStr(VprDCartucho.SeqCartucho);
GCartuchos.Cells[2,VpaLinha] := VprDCartucho.CodProduto;
GCartuchos.Cells[3,VpaLinha] := VprDCartucho.NomProduto;
GCartuchos.Cells[4,VpaLinha] := FormatFloat('###,###,##0.0####',VprDCartucho.PesCartucho);
GCartuchos.Cells[5,VpaLinha] := FormatDateTime('DD/MM/YYYY HH:MM:SS',VprDCartucho.DatEmbalado);
GCartuchos.Cells[6,VpaLinha] := VprDCartucho.CelulaTrabalho;
end;
{******************************************************************************}
procedure TFCartuchoCotacao.ESequencialExit(Sender: TObject);
begin
if ESequencial.AInteiro <> 0 then
AdicionaCartucho(ECotacao.AInteiro,ESequencial.AInteiro);
end;
{******************************************************************************}
procedure TFCartuchoCotacao.ECotacaoFimConsulta(Sender: TObject);
begin
if VprDCotacao <> nil then
VprDCotacao.free;
VprDCotacao := TRBDOrcamento.cria;
VprDCotacao.CodEmpFil := varia.CodigoEmpFil;
VprDCotacao.LanOrcamento := ECotacao.AInteiro;
FunCotacao.CarDOrcamento(VprDCotacao);
FreeTObjectsList(VprCartuchos);
GCartuchos.CarregaGrade;
end;
{******************************************************************************}
procedure TFCartuchoCotacao.ESequencialKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if key = 13 then
begin
if ESequencial.Text <> '' then
begin
ESequencialExit(ESequencial);
ESequencial.Clear;
end
else
BGravar.Click;
end;
end;
{******************************************************************************}
procedure TFCartuchoCotacao.BFecharClick(Sender: TObject);
begin
Close;
end;
procedure TFCartuchoCotacao.BCancelarClick(Sender: TObject);
begin
close;
end;
{******************************************************************************}
procedure TFCartuchoCotacao.BGravarClick(Sender: TObject);
var
VpfResultado : String;
VpfTransacao : TTransactionDesc;
begin
if VprDCotacao.LanOrcamento <> 0 then
begin
if FunCotacao.TodosCartuchosAssociados(VprDCotacao,VprCartuchos) then
begin
VpfTransacao.IsolationLevel := xilREADCOMMITTED;
FPrincipal.BaseDados.StartTransaction(VpfTransacao);
VpfResultado := FunCotacao.GravaCartuchoCotacao(VprDCotacao,VprCartuchos);
if VpfResultado = '' then
begin
if ETransportadora.AInteiro <> 0 then
begin
VprDCotacao.CodRegiaoVenda:= ERegiaoVenda.AInteiro;
FunCotacao.AlteraTransportadora(VprDCotacao,ETransportadora.AInteiro);
VpfResultado:= FunCotacao.GravaRoteiroEntrega(VprDCotacao);
if VpfResultado <> '' then
FunCotacao.AlteraEstagioCotacao(VprDCotacao.CodEmpFil,varia.CodigoUsuario,VprDCotacao.LanOrcamento,Varia.EstagioNaEntrega,'');
end;
end;
if vpfresultado <> '' then
begin
FPrincipal.BaseDados.Rollback(VpfTransacao);
aviso(VpfResultado);
end
else
begin
FPrincipal.BaseDados.commit(VpfTransacao);
EstadoBotoes(false);
BCadatrar.Click;
end;
end;
end;
end;
{******************************************************************************}
procedure TFCartuchoCotacao.BImprimeVolumeClick(Sender: TObject);
begin
VprDCotacao.QtdVolumesTransportadora:= EQtdVolume.AsInteger;
FunCotacao.ImprimeEtiquetaVolume(VprDCotacao);
EQtdVolume.AsInteger:= 0;
end;
{******************************************************************************}
procedure TFCartuchoCotacao.BCadatrarClick(Sender: TObject);
begin
InicializaTela;
end;
{******************************************************************************}
procedure TFCartuchoCotacao.ECotacaoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = 13 then
begin
ECotacao.Text := DeletaChars(ECotacao.text,'.');
ActiveControl := ESequencial;
end;
end;
{******************************************************************************}
procedure TFCartuchoCotacao.ETransportadoraChange(Sender: TObject);
begin
ValidaGravacao1.execute;
end;
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFCartuchoCotacao]);
end.
|
unit uROR_Resources;
interface
uses
Controls, Forms, Graphics, ImgList, SysUtils;
resourcestring
rscAddHint = 'Add|Add selected item(s) to the list';
rscAddAllHint = 'Add All|Add all items to the list';
rscBreakLink = 'Break the Clinical Link';
rscRemoveHint = 'Remove|Remove selected item(s) from the list';
rscRemoveAllHint = 'Remove All|Clear the list';
rscUseAppData = 'Rejoin and Use Application Data';
rscUseGlobalData = 'Rejoin and Use Global Data';
RSC0001 = 'CCOW Contextor';
RSC0002 = 'Update the clinical context with the application''s data?';
RSC0003 = 'Contextor has not been run and the application has not joined a context.';
RSC0004 = 'Contextor has been run and the application is participating in a context.';
RSC0005 = 'Contextor has been run but the application is not participating in a context.';
RSC0006 = 'Cannot determine the contextor state.';
RSC0010 = 'Search pattern should contain at least %d character(s).';
RSC0011 = 'Invalid search pattern.';
RSC0012 = 'Start Search';
RSC0013 = 'Cancel Search';
RSC0020 = 'Field value cannot be converted to Date/Time.';
RSC0021 = 'Value should not be longer than %d characters. Truncate?';
RSC0030 = 'The "%s" item is already selected in the "%s".';
var
bmAdd: TBitmap = nil;
bmAddAll: TBitmap = nil;
bmRemove: TBitmap = nil;
bmRemoveAll: TBitmap = nil;
bmSearchCancel: TBitmap = nil;
bmSearchStart: TBitmap = nil;
procedure LoadCCREditSearchResources;
procedure LoadCCRSelectorResources;
implementation
{$R *.res}
procedure LoadCCREditSearchResources;
begin
if Assigned(bmSearchStart) then Exit;
bmSearchCancel := TBitmap.Create;
bmSearchStart := TBitmap.Create;
bmSearchCancel.LoadFromResourceName(HInstance, 'BTN_CANCEL');
bmSearchStart.LoadFromResourceName(HInstance, 'BTN_SEARCH');
end;
procedure LoadCCRSelectorResources;
begin
if Assigned(bmAdd) then Exit;
bmAdd := TBitmap.Create;
bmAddAll := TBitmap.Create;
bmRemove := TBitmap.Create;
bmRemoveAll := TBitmap.Create;
bmAdd.LoadFromResourceName(HInstance, 'BTN_ADD');
bmAddAll.LoadFromResourceName(HInstance, 'BTN_ADDALL');
bmRemove.LoadFromResourceName(HInstance, 'BTN_REMOVE');
bmRemoveAll.LoadFromResourceName(HInstance, 'BTN_REMOVEALL');
end;
initialization
finalization
FreeAndNil(bmAdd);
FreeAndNil(bmAddAll);
FreeAndNil(bmRemove);
FreeAndNil(bmRemoveAll);
end.
|
unit FileVer;
interface
Uses Windows, SysUtils, Classes, Dialogs, Controls, FileCtrl;
function GetFileVerLang(FileName :String; var Lang :String) :String;
// Return : -1 Version1 < Version2
// 0 Version1 = Version2
// +1 Version1 > Version2
function CompareVer(Version1, Version2 :String) :Integer;
function InstallFile(FilesList :TStringList;
SourceDir, DestDir, SourceFile :String) :Boolean;
implementation
Type
TL_DWord =packed record
Hi :Word;
Lo :Word;
end;
PL_DWord =^TL_DWord;
function GetFileVerLang(FileName :String; var Lang :String) :String;
Var
viResult :DWord;
verSize :Integer;
verBuff,
verResult :Pointer;
verLang :PL_DWord;
verLangStr :String;
begin
Result :='?';
Lang :='?';
verBuff :=Nil;
verResult :=Nil;
try
verSize :=GetFileVersionInfoSize(PChar(FileName), viResult);
if (verSize>0) then
begin
GetMem(verBuff, verSize+2);
GetFileVersionInfo(PChar(FileName), 0, verSize, verBuff);
VerQueryValue(verBuff, PChar('\VarFileInfo\Translation'),
Pointer(verLang), viResult);
verLangStr :=IntToHex(verLang^.Hi, 4)+IntToHex(verLang^.Lo, 4);
SetLength(Lang, MAX_PATH);
VerLanguageName(DWord(verLang^), PChar(Lang), MAX_PATH);
Lang :=PChar(Lang);
VerQueryValue(verBuff, PChar('\StringFileInfo\'+verLangStr+'\FileVersion'),
verResult, viResult);
Result :=PChar(verResult);
end;
finally
if (verBuff<>Nil) then FreeMem(verBuff);
end;
end;
function CompareVer(Version1, Version2 :String) :Integer;
Var
ver1, ver2 :String;
pos1, pos2 :Integer;
last :Boolean;
begin
last :=False;
repeat
pos1 :=Pos('.', Version1);
pos2 :=Pos('.', Version2);
if (pos1>1)
then begin
ver1 :=Copy(Version1, 1, pos1-1);
Delete(Version1, 1, pos1);
end
else begin
ver1 :=Version1;
Version1 :='';
last :=True;
end;
if (pos2>1)
then begin
ver2 :=Copy(Version2, 1, pos2-1);
Delete(Version2, 1, pos2);
end
else begin
ver2 :=Version2;
Version2 :='';
last :=True;
end;
if (ver1<ver2)
then Result := -1
else begin
if (ver1=ver2)
then begin
Result := 0;
if last then
begin
if (Version1<>'')
then Result := 1 //esempio : 1.0.x è maggiore di 1.0
else if (Version2<>'')
then Result := -1;
end;
end
else Result := 1;
end;
Until (Result<>0) or last;
end;
function InstallFile(FilesList :TStringList;
SourceDir, DestDir, SourceFile :String) :Boolean;
Var
Ver1,
Ver2,
Lang1,
Lang2 :String;
begin
Result :=True;
(* Ma cumu mai nun funziona................?
M'a 'e fari sempri a manu????
viResult :=VerInstallFile(0,
PChar(SourceFile), PChar(SourceFile),
PChar(SourceDir), PChar(DestDir),
PChar(viPrevFile), PChar(viTempFile), viSizeTemp);
Result :=Not((viResult and VIF_SRCOLD<>0) or
(viResult and VIF_DIFFLANG<>0) or
(viResult and VIF_DIFFCODEPG<>0));
if Not(Result) then
*)
if FileExists(DestDir+SourceFile) then
begin
Ver1 :=GetFileVerLang(DestDir+SourceFile, Lang1);
Ver2 :=GetFileVerLang(SourceDir+SourceFile, Lang2);
Result :=(MessageDlg('Overwrite File '+DestDir+SourceFile+#13#10+
' Version= '+Ver1+' Language= '+Lang1+#13#10+
'With Version= '+Ver2+' Language= '+Lang2+#13#10, mtConfirmation, [mbYes, mbNo], 0)
=mrYes);
end;
if Result then
begin
ForceDirectories(ExtractFilePath(DestDir+SourceFile));
Result :=CopyFile(PChar(SourceDir+SourceFile),
PChar(DestDir+SourceFile), False);
if (FilesList<>Nil) then FilesList.Add(DestDir+SourceFile);
end;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ Common BDE and DBClient Code }
{ }
{ Copyright (c) 1995,98 Inprise Corporation }
{ }
{*******************************************************}
unit DBCommon;
interface
uses Windows, Classes, DB, BDE;
{ FieldType Mappings }
const
FldTypeMap: array[TFieldType] of Byte = (
fldUNKNOWN, fldZSTRING, fldINT16, fldINT32, fldUINT16, fldBOOL,
fldFLOAT, fldFLOAT, fldBCD, fldDATE, fldTIME, fldTIMESTAMP, fldBYTES,
fldVARBYTES, fldINT32, fldBLOB, fldBLOB, fldBLOB, fldBLOB, fldBLOB,
fldBLOB, fldBLOB, fldCURSOR, fldZSTRING, fldZSTRING, fldINT64, fldADT,
fldArray, fldREF, fldTABLE);
FldSubTypeMap: array[TFieldType] of Word = (
0, 0, 0, 0, 0, 0, 0, fldstMONEY, 0, 0, 0, 0, 0, 0, fldstAUTOINC,
fldstBINARY, fldstMEMO, fldstGRAPHIC, fldstFMTMEMO, fldstOLEOBJ,
fldstDBSOLEOBJ, fldstTYPEDBINARY, 0, fldstFIXED, fldstUNICODE,
0, 0, 0, 0, 0);
DataTypeMap: array[0..MAXLOGFLDTYPES - 1] of TFieldType = (
ftUnknown, ftString, ftDate, ftBlob, ftBoolean, ftSmallint,
ftInteger, ftFloat, ftBCD, ftBytes, ftTime, ftDateTime,
ftWord, ftInteger, ftUnknown, ftVarBytes, ftUnknown, ftUnknown,
ftLargeInt, ftLargeInt, ftADT, ftArray, ftReference, ftDataSet);
BlobTypeMap: array[fldstMEMO..fldstBFILE] of TFieldType = (
ftMemo, ftBlob, ftFmtMemo, ftParadoxOle, ftGraphic, ftDBaseOle,
ftTypedBinary, ftBlob, ftBlob, ftBlob, ftBlob, ftMemo, ftBlob,
ftBlob, ftBlob);
{ TFilterExpr }
type
TParserOption = (poExtSyntax, poAggregate, poDefaultExpr, poUseOrigNames,
poFieldNameGiven, poFieldDepend);
TParserOptions = set of TParserOption;
TExprNodeKind = (enField, enConst, enOperator, enFunc);
TExprScopeKind = (skField, skAgg, skConst);
PExprNode = ^TExprNode;
TExprNode = record
FNext: PExprNode;
FKind: TExprNodeKind;
FPartial: Boolean;
FOperator: CanOp;
FData: Variant;
FLeft: PExprNode;
FRight: PExprNode;
FDataType: Integer;
FDataSize: Integer;
FArgs: TList;
FScopeKind: TExprScopeKind;
end;
TFilterExpr = class
private
FDataSet: TDataSet;
FOptions: TFilterOptions;
FParserOptions: TParserOptions;
FNodes: PExprNode;
FExprBuffer: PCANExpr;
FExprBufSize: Integer;
FExprNodeSize: Integer;
FExprDataSize: Integer;
FFieldName: string;
FDependentFields: TBits;
function FieldFromNode(Node: PExprNode): TField;
function GetExprData(Pos, Size: Integer): PChar;
function PutConstBCD(const Value: Variant; Decimals: Integer): Integer;
function PutConstBool(const Value: Variant): Integer;
function PutConstDate(const Value: Variant): Integer;
function PutConstDateTime(const Value: Variant): Integer;
function PutConstFloat(const Value: Variant): Integer;
function PutConstInt(DataType: Integer; const Value: Variant): Integer;
function PutConstNode(DataType: Integer; Data: PChar;
Size: Integer): Integer;
function PutConstStr(const Value: string): Integer;
function PutConstTime(const Value: Variant): Integer;
function PutData(Data: PChar; Size: Integer): Integer;
function PutExprNode(Node: PExprNode; ParentOp: CanOp): Integer;
function PutFieldNode(Field: TField; Node: PExprNode): Integer;
function PutNode(NodeType: NodeClass; OpType: CanOp;
OpCount: Integer): Integer;
procedure SetNodeOp(Node, Index, Data: Integer);
function PutConstant(Node: PExprNode): Integer;
function GetFieldByName(Name: string) : TField;
public
constructor Create(DataSet: TDataSet; Options: TFilterOptions;
ParseOptions: TParserOptions; const FieldName: string; DepFields: TBits);
destructor Destroy; override;
function NewCompareNode(Field: TField; Operator: CanOp;
const Value: Variant): PExprNode;
function NewNode(Kind: TExprNodeKind; Operator: CanOp;
const Data: Variant; Left, Right: PExprNode): PExprNode;
function GetFilterData(Root: PExprNode): PCANExpr;
property DataSet: TDataSet write FDataSet;
end;
{ TExprParser }
TExprToken = (etEnd, etSymbol, etName, etLiteral, etLParen, etRParen,
etEQ, etNE, etGE, etLE, etGT, etLT, etADD, etSUB, etMUL, etDIV,
etComma, etLIKE, etISNULL, etISNOTNULL, etIN);
TExprParser = class
private
FFilter: TFilterExpr;
FText: string;
FSourcePtr: PChar;
FTokenPtr: PChar;
FTokenString: string;
FStrTrue: string;
FStrFalse: string;
FToken: TExprToken;
FPrevToken: TExprToken;
FFilterData: PCANExpr;
FNumericLit: Boolean;
FDataSize: Integer;
FParserOptions: TParserOptions;
FFieldName: string;
FDataSet: TDataSet;
FDependentFields: TBits;
procedure NextToken;
function NextTokenIsLParen : Boolean;
function ParseExpr: PExprNode;
function ParseExpr2: PExprNode;
function ParseExpr3: PExprNode;
function ParseExpr4: PExprNode;
function ParseExpr5: PExprNode;
function ParseExpr6: PExprNode;
function ParseExpr7: PExprNode;
function TokenName: string;
function TokenSymbolIs(const S: string): Boolean;
function TokenSymbolIsFunc(const S: string) : Boolean;
procedure GetFuncResultInfo(Node: PExprNode);
procedure TypeCheckArithOp(Node: PExprNode);
procedure GetScopeKind(Root, Left, Right : PExprNode);
public
constructor Create(DataSet: TDataSet; const Text: string;
Options: TFilterOptions; ParserOptions: TParserOptions;
const FieldName: string; DepFields: TBits);
destructor Destroy; override;
procedure SetExprParams(const Text: string; Options: TFilterOptions;
ParserOptions: TParserOptions; const FieldName: string);
property FilterData: PCANExpr read FFilterData;
property DataSize: Integer read FDataSize;
end;
{ TMasterDataLink }
TMasterDataLink = class(TDetailDataLink)
private
FDataSet: TDataSet;
FFieldNames: string;
FFields: TList;
FOnMasterChange: TNotifyEvent;
FOnMasterDisable: TNotifyEvent;
procedure SetFieldNames(const Value: string);
protected
procedure ActiveChanged; override;
procedure CheckBrowseMode; override;
function GetDetailDataSet: TDataSet; override;
procedure LayoutChanged; override;
procedure RecordChanged(Field: TField); override;
public
constructor Create(DataSet: TDataSet);
destructor Destroy; override;
property FieldNames: string read FFieldNames write SetFieldNames;
property Fields: TList read FFields;
property OnMasterChange: TNotifyEvent read FOnMasterChange write FOnMasterChange;
property OnMasterDisable: TNotifyEvent read FOnMasterDisable write FOnMasterDisable;
end;
function FMTBCDToCurr(const BCD: FMTBcd; var Curr: Currency): Boolean;
function CurrToFMTBCD(Curr: Currency; var BCD: FMTBcd; Precision,
Decimals: Integer): Boolean;
function GetFieldSource(ADataSet: TDataSet; var ADataSources: DataSources): Boolean;
implementation
uses SysUtils, DBConsts;
function GetFieldSource(ADataSet: TDataSet; var ADataSources: DataSources): Boolean;
var
Current: PChar;
Field: TField;
Values: array[0..4] of string;
I: Integer;
function GetPChar(const S: string): PChar;
begin
if S <> '' then Result := PChar(Pointer(S)) else Result := '';
end;
procedure Split(const S: string);
begin
Current := PChar(Pointer(S));
end;
function NextItem: string;
var
C: PChar;
I: PChar;
Terminator: Char;
Ident: array[0..1023] of Char;
begin
Result := '';
C := Current;
I := Ident;
while C^ in ['.',' ',#0] do
if C^ = #0 then Exit else Inc(C);
Terminator := '.';
if C^ = '"' then
begin
Terminator := '"';
Inc(C);
end;
while not (C^ in [Terminator, #0]) do
begin
if C^ in LeadBytes then
begin
I^ := C^;
Inc(C);
Inc(I);
end
else if C^ = '\' then
begin
Inc(C);
if C^ in LeadBytes then
begin
I^ := C^;
Inc(C);
Inc(I);
end;
if C^ = #0 then Dec(C);
end;
I^ := C^;
Inc(C);
Inc(I);
end;
SetString(Result, Ident, I - Ident);
if (Terminator = '"') and (C^ <> #0) then Inc(C);
Current := C;
end;
function PopValue: PChar;
begin
if I >= 0 then
begin
Result := GetPChar(Values[I]);
Dec(I);
end else Result := '';
end;
begin
Result := False;
Field := ADataSet.FindField(ADataSources.szSourceFldName);
if (Field = nil) or (Field.Origin = '') then Exit;
Split(Field.Origin);
I := -1;
repeat
Inc(I);
Values[I] := NextItem;
until (Values[I] = '') or (I = High(Values));
if I = High(Values) then Exit;
Dec(I);
StrCopy(ADataSources.szOrigFldName, PopValue);
StrCopy(ADataSources.szTblName, PopValue);
StrCopy(ADataSources.szDbName, PopValue);
Result := (ADataSources.szOrigFldName[0] <> #0) and
(ADataSources.szTblName[0] <> #0);
end;
function FMTBCDToCurr(const BCD: FMTBcd; var Curr: Currency): Boolean;
const
FConst10: Single = 10;
CWNear: Word = $133F;
var
CtrlWord: Word;
Temp: Integer;
Digits: array[0..63] of Byte;
asm
PUSH EBX
PUSH ESI
MOV EBX,EAX
MOV ESI,EDX
MOV AL,0
MOVZX EDX,[EBX].FMTBcd.iPrecision
OR EDX,EDX
JE @@8
LEA ECX,[EDX+1]
SHR ECX,1
@@1: MOV AL,[EBX].FMTBcd.iFraction.Byte[ECX-1]
MOV AH,AL
SHR AL,4
AND AH,0FH
MOV Digits.Word[ECX*2-2],AX
DEC ECX
JNE @@1
XOR EAX,EAX
@@2: MOV AL,Digits.Byte[ECX]
OR AL,AL
JNE @@3
INC ECX
CMP ECX,EDX
JNE @@2
FLDZ
JMP @@7
@@3: MOV Temp,EAX
FILD Temp
@@4: INC ECX
CMP ECX,EDX
JE @@5
FMUL FConst10
MOV AL,Digits.Byte[ECX]
MOV Temp,EAX
FIADD Temp
JMP @@4
@@5: MOV AL,[EBX].FMTBcd.iSignSpecialPlaces
OR AL,AL
JNS @@6
FCHS
@@6: AND EAX,3FH
SUB EAX,4
NEG EAX
CALL FPower10
@@7: FSTCW CtrlWord
FLDCW CWNear
FISTP [ESI].Currency
FSTSW AX
NOT AL
AND AL,1
FCLEX
FLDCW CtrlWord
FWAIT
@@8: POP ESI
POP EBX
end;
function CurrToFMTBCD(Curr: Currency; var BCD: FMTBcd; Precision,
Decimals: Integer): Boolean;
const
Power10: array[0..3] of Single = (10000, 1000, 100, 10);
var
Digits: array[0..63] of Byte;
asm
PUSH EBX
PUSH ESI
PUSH EDI
MOV ESI,EAX
XCHG ECX,EDX
MOV [ESI].FMTBcd.iPrecision,CL
MOV [ESI].FMTBcd.iSignSpecialPlaces,DL
@@1: SUB EDX,4
JE @@3
JA @@2
FILD Curr
FDIV Power10.Single[EDX*4+16]
FISTP Curr
JMP @@3
@@2: DEC ECX
MOV Digits.Byte[ECX],0
DEC EDX
JNE @@2
@@3: MOV EAX,Curr.Integer[0]
MOV EBX,Curr.Integer[4]
OR EBX,EBX
JNS @@4
NEG EBX
NEG EAX
SBB EBX,0
OR [ESI].FMTBcd.iSignSpecialPlaces,80H
@@4: MOV EDI,10
@@5: MOV EDX,EAX
OR EDX,EBX
JE @@7
XOR EDX,EDX
OR EBX,EBX
JE @@6
XCHG EAX,EBX
DIV EDI
XCHG EAX,EBX
@@6: DIV EDI
@@7: MOV Digits.Byte[ECX-1],DL
DEC ECX
JNE @@5
OR EAX,EBX
MOV AL,0
JNE @@9
MOV CL,[ESI].FMTBcd.iPrecision
INC ECX
SHR ECX,1
@@8: MOV AX,Digits.Word[ECX*2-2]
SHL AL,4
OR AL,AH
MOV [ESI].FMTBcd.iFraction.Byte[ECX-1],AL
DEC ECX
JNE @@8
MOV AL,1
@@9: POP EDI
POP ESI
POP EBX
end;
function IsNumeric(DataType: Integer): Boolean;
begin
Result := DataType in [fldINT16, fldINT32, fldFLOAT, fldBCD];
end;
function IsTemporal(DataType: Integer): Boolean;
begin
Result := DataType in [fldDATE, fldTIME, fldTIMESTAMP];
end;
{ TFilterExpr }
constructor TFilterExpr.Create(DataSet: TDataSet; Options: TFilterOptions;
ParseOptions: TParserOptions; const FieldName: string; DepFields: TBits);
begin
FDataSet := DataSet;
FOptions := Options;
FFieldName := FieldName;
FParserOptions := ParseOptions;
FDependentFields := DepFields;
end;
destructor TFilterExpr.Destroy;
var
Node: PExprNode;
begin
FreeMem(FExprBuffer, FExprBufSize);
while FNodes <> nil do
begin
Node := FNodes;
FNodes := Node^.FNext;
if (Node^.FKind = enFunc) and (Node^.FArgs <> nil) then
Node^.FArgs.Free;
Dispose(Node);
end;
end;
function TFilterExpr.FieldFromNode(Node: PExprNode): TField;
begin
Result := GetFieldByName(Node^.FData);
if not (Result.FieldKind in [fkData, fkInternalCalc]) then
DatabaseErrorFmt(SExprBadField, [Result.FieldName]);
end;
function TFilterExpr.GetExprData(Pos, Size: Integer): PChar;
begin
ReallocMem(FExprBuffer, FExprBufSize + Size);
Move(PChar(FExprBuffer)[Pos], PChar(FExprBuffer)[Pos + Size],
FExprBufSize - Pos);
Inc(FExprBufSize, Size);
Result := PChar(FExprBuffer) + Pos;
end;
function TFilterExpr.GetFilterData(Root: PExprNode): PCANExpr;
begin
FExprBufSize := SizeOf(CANExpr);
GetMem(FExprBuffer, FExprBufSize);
PutExprNode(Root, canNOTDEFINED);
with FExprBuffer^ do
begin
iVer := CANEXPRVERSION;
iTotalSize := FExprBufSize;
iNodes := $FFFF;
iNodeStart := SizeOf(CANExpr);
iLiteralStart := FExprNodeSize + SizeOf(CANExpr);
end;
Result := FExprBuffer;
end;
function TFilterExpr.NewCompareNode(Field: TField; Operator: CanOp;
const Value: Variant): PExprNode;
var
ConstExpr: PExprNode;
begin
ConstExpr := NewNode(enConst, canNOTDEFINED, Value, nil, nil);
ConstExpr^.FDataType := FldTypeMap[ Field.DataType ];
ConstExpr^.FDataSize := Field.Size;
Result := NewNode(enOperator, Operator, Unassigned,
NewNode(enField, canNOTDEFINED, Field.FieldName, nil, nil), ConstExpr);
end;
function TFilterExpr.NewNode(Kind: TExprNodeKind; Operator: CanOp;
const Data: Variant; Left, Right: PExprNode): PExprNode;
var
Field : TField;
begin
New(Result);
with Result^ do
begin
FNext := FNodes;
FKind := Kind;
FPartial := False;
FOperator := Operator;
FData := Data;
FLeft := Left;
FRight := Right;
end;
FNodes := Result;
if Kind = enField then
begin
Field := GetFieldByName(Data);
if Field = nil then
DatabaseErrorFmt(SFieldNotFound, [Data]);
Result^.FDataType := FldTypeMap[ Field.DataType ];
Result^.FDataSize := Field.Size;
end;
end;
function TFilterExpr.PutConstBCD(const Value: Variant;
Decimals: Integer): Integer;
var
C: Currency;
BCD: FMTBcd;
begin
if VarType(Value) = varString then
C := StrToCurr(string(TVarData(Value).VString)) else
C := Value;
CurrToFMTBCD(C, BCD, 32, Decimals);
Result := PutConstNode(fldBCD, @BCD, 18);
end;
function TFilterExpr.PutConstBool(const Value: Variant): Integer;
var
B: WordBool;
begin
B := Value;
Result := PutConstNode(fldBOOL, @B, SizeOf(WordBool));
end;
function TFilterExpr.PutConstDate(const Value: Variant): Integer;
var
DateTime: TDateTime;
TimeStamp: TTimeStamp;
begin
if VarType(Value) = varString then
DateTime := StrToDate(string(TVarData(Value).VString)) else
DateTime := VarToDateTime(Value);
TimeStamp := DateTimeToTimeStamp(DateTime);
Result := PutConstNode(fldDATE, @TimeStamp.Date, 4);
end;
function TFilterExpr.PutConstDateTime(const Value: Variant): Integer;
var
DateTime: TDateTime;
DateData: Double;
begin
if VarType(Value) = varString then
DateTime := StrToDateTime(string(TVarData(Value).VString)) else
DateTime := VarToDateTime(Value);
DateData := TimeStampToMSecs(DateTimeToTimeStamp(DateTime));
Result := PutConstNode(fldTIMESTAMP, @DateData, 8);
end;
function TFilterExpr.PutConstFloat(const Value: Variant): Integer;
var
F: Double;
begin
if VarType(Value) = varString then
F := StrToFloat(string(TVarData(Value).VString)) else
F := Value;
Result := PutConstNode(fldFLOAT, @F, SizeOf(Double));
end;
function TFilterExpr.PutConstInt(DataType: Integer;
const Value: Variant): Integer;
var
I, Size: Integer;
begin
if VarType(Value) = varString then
I := StrToInt(string(TVarData(Value).VString)) else
I := Value;
Size := 2;
case DataType of
fldINT16:
if (I < -32768) or (I > 32767) then DatabaseError(SExprRangeError);
fldUINT16:
if (I < 0) or (I > 65535) then DatabaseError(SExprRangeError);
else
Size := 4;
end;
Result := PutConstNode(DataType, @I, Size);
end;
function TFilterExpr.PutConstNode(DataType: Integer; Data: PChar;
Size: Integer): Integer;
begin
Result := PutNode(nodeCONST, canCONST2, 3);
SetNodeOp(Result, 0, DataType);
SetNodeOp(Result, 1, Size);
SetNodeOp(Result, 2, PutData(Data, Size));
end;
function TFilterExpr.PutConstStr(const Value: string): Integer;
var
Str: string;
Buffer: array[0..255] of Char;
begin
if Length(Value) >= SizeOf(Buffer) then
Str := Copy(Value, 1, SizeOf(Buffer) - 1) else
Str := Value;
FDataSet.Translate(PChar(Str), Buffer, True);
Result := PutConstNode(fldZSTRING, Buffer, Length(Str) + 1);
end;
function TFilterExpr.PutConstTime(const Value: Variant): Integer;
var
DateTime: TDateTime;
TimeStamp: TTimeStamp;
begin
if VarType(Value) = varString then
DateTime := StrToTime(string(TVarData(Value).VString)) else
DateTime := VarToDateTime(Value);
TimeStamp := DateTimeToTimeStamp(DateTime);
Result := PutConstNode(fldTIME, @TimeStamp.Time, 4);
end;
function TFilterExpr.PutData(Data: PChar; Size: Integer): Integer;
begin
Move(Data^, GetExprData(FExprBufSize, Size)^, Size);
Result := FExprDataSize;
Inc(FExprDataSize, Size);
end;
function TFilterExpr.PutConstant(Node: PExprNode): Integer;
begin
Result := 0;
case Node^.FDataType of
fldINT16, fldINT32:
Result := PutConstInt(Node^.FDataType, Node^.FData);
fldFLOAT:
Result := PutConstFloat(Node^.FData);
fldZSTRING:
Result := PutConstStr(Node^.FData);
fldDATE:
Result := PutConstDate(Node^.FData);
fldTIME:
Result := PutConstTime(Node^.FData);
fldTIMESTAMP:
Result := PutConstDateTime(Node^.FData);
fldBOOL:
Result := PutConstBool(Node^.FData);
fldBCD:
Result := PutConstBCD(Node^.FData, Node^.FDataSize);
else
DatabaseErrorFmt(SExprBadConst, [Node^.FData]);
end;
end;
function TFilterExpr.PutExprNode(Node: PExprNode; ParentOp: CanOp): Integer;
const
ReverseOperator: array[canEQ..canLE] of CanOp = (canEQ, canNE, canLT,
canGT, canLE, canGE);
BoolFalse: WordBool = False;
var
Field: TField;
Left, Right, Temp : PExprNode;
LeftPos, RightPos, ListElem, PrevListElem, I: Integer;
Operator: CanOp;
CaseInsensitive, PartialLength, L: Integer;
S: string;
begin
Result := 0;
case Node^.FKind of
enField:
begin
Field := FieldFromNode(Node);
if (ParentOp in [canOR, canNOT, canAND, canNOTDEFINED]) and
(Field.DataType = ftBoolean) then
begin
Result := PutNode(nodeBINARY, canNE, 2);
SetNodeOp(Result, 0, PutFieldNode(Field, Node));
SetNodeOp(Result, 1, PutConstNode(fldBOOL, @BoolFalse,
SizeOf(WordBool)));
end
else
Result := PutFieldNode(Field, Node);
end;
enConst:
Result := PutConstant(Node);
enOperator:
case Node^.FOperator of
canIN:
begin
Result := PutNode(nodeBINARY, canIN, 2);
SetNodeOp(Result, 0, PutExprNode(Node^.FLeft,Node^.FOperator));
ListElem := PutNode(nodeLISTELEM, canLISTELEM2, 2);
SetNodeOp(Result, 1, ListElem);
PrevListElem := ListElem;
for I := 0 to Node^.FArgs.Count - 1 do
begin
LeftPos := PutExprNode(Node^.FArgs.Items[I],Node^.FOperator);
if I = 0 then
begin
SetNodeOp(PrevListElem, 0, LeftPos);
SetNodeOp(PrevListElem, 1, 0);
end
else
begin
ListElem := PutNode(nodeLISTELEM, canLISTELEM2, 2);
SetNodeOp(ListElem, 0, LeftPos);
SetNodeOp(ListElem, 1, 0);
SetNodeOp(PrevListElem, 1, ListElem);
PrevListElem := ListElem;
end;
end;
end;
canNOT,
canISBLANK,
canNOTBLANK:
begin
Result := PutNode(nodeUNARY, Node^.FOperator, 1);
SetNodeOp(Result, 0, PutExprNode(Node^.FLeft,Node^.FOperator));
end;
canEQ..canLE,
canAND,canOR,
canADD..canDIV,
canLIKE,
canASSIGN:
begin
Operator := Node^.FOperator;
Left := Node^.FLeft;
Right := Node^.FRight;
if (Operator in [CanEQ..canLE]) and (Right^.FKind = enField) and
(Left^.FKind <> enField) then
begin
Temp := Left;
Left := Right;
Right := Temp;
Operator := ReverseOperator[Operator];
end;
Result := 0;
if (Left^.FKind = enField) and (Right^.FKind = enConst)
and ((Node^.FOperator = canEQ) or (Node^.FOperator = canNE)
or (Node^.FOperator = canLIKE)) then
begin
if VarIsNull(Right^.FData) then
begin
case Node^.FOperator of
canEQ: Operator := canISBLANK;
canNE: Operator := canNOTBLANK;
else
DatabaseError(SExprBadNullTest);
end;
Result := PutNode(nodeUNARY, Operator, 1);
SetNodeOp(Result, 0, PutExprNode(Left,Node^.FOperator));
end
else if (Right^.FDataType = fldZSTRING) then
begin
S := Right^.FData;
L := Length(S);
if L <> 0 then
begin
CaseInsensitive := 0;
PartialLength := 0;
if foCaseInsensitive in FOptions then CaseInsensitive := 1;
if Node^.FPartial then PartialLength := L else
if not (foNoPartialCompare in FOptions) and (L > 1) and
(S[L] = '*') then
begin
Delete(S, L, 1);
PartialLength := L - 1;
end;
if (CaseInsensitive <> 0) or (PartialLength <> 0) then
begin
Result := PutNode(nodeCOMPARE, Operator, 4);
SetNodeOp(Result, 0, CaseInsensitive);
SetNodeOp(Result, 1, PartialLength);
SetNodeOp(Result, 2, PutExprNode(Left,Node^.FOperator));
SetNodeOp(Result, 3, PutConstStr(S));
end;
end;
end;
end;
if Result = 0 then
begin
if (Operator = canISBLANK) or (Operator = canNOTBLANK) then
begin
Result := PutNode(nodeUNARY, Operator, 1);
LeftPos := PutExprNode(Left,Node^.FOperator);
SetNodeOp(Result, 0, LeftPos);
end else
begin
Result := PutNode(nodeBINARY, Operator, 2);
LeftPos := PutExprNode(Left,Node^.FOperator);
RightPos := PutExprNode(Right,Node^.FOperator);
SetNodeOp(Result, 0, LeftPos);
SetNodeOp(Result, 1, RightPos);
end;
end;
end;
end;
enFunc:
begin
Result := PutNode(nodeFUNC, canFUNC2, 2);
SetNodeOp(Result, 0, PutData(PChar(string(Node^.FData)),
Length(string(Node^.FData)) + 1));
if Node^.FArgs <> nil then
begin
ListElem := PutNode(nodeLISTELEM, canLISTELEM2, 2);
SetNodeOp(Result, 1, ListElem);
PrevListElem := ListElem;
for I := 0 to Node^.FArgs.Count - 1 do
begin
LeftPos := PutExprNode(Node^.FArgs.Items[I],Node^.FOperator);
if I = 0 then
begin
SetNodeOp(PrevListElem, 0, LeftPos);
SetNodeOp(PrevListElem, 1, 0);
end
else
begin
ListElem := PutNode(nodeLISTELEM, canLISTELEM2, 2);
SetNodeOp(ListElem, 0, LeftPos);
SetNodeOp(ListElem, 1, 0);
SetNodeOp(PrevListElem, 1, ListElem);
PrevListElem := ListElem;
end;
end;
end else
SetNodeOp(Result, 1, 0);
end;
end;
end;
function TFilterExpr.PutFieldNode(Field: TField; Node: PExprNode): Integer;
var
Buffer: array[0..255] of Char;
begin
if poFieldNameGiven in FParserOptions then
FDataSet.Translate(PChar(Field.FieldName), Buffer, True)
else
FDataSet.Translate(PChar(string(Node^.FData)), Buffer, True);
Result := PutNode(nodeFIELD, canFIELD2, 2);
SetNodeOp(Result, 0, Field.FieldNo);
SetNodeOp(Result, 1, PutData(Buffer, StrLen(Buffer) + 1));
end;
function TFilterExpr.PutNode(NodeType: NodeClass; OpType: CanOp;
OpCount: Integer): Integer;
var
Size: Integer;
begin
Size := SizeOf(CANHdr) + OpCount * SizeOf(Word);
with PCANHdr(GetExprData(SizeOf(CANExpr) + FExprNodeSize, Size))^ do
begin
nodeClass := NodeType;
canOp := OpType;
end;
Result := FExprNodeSize;
Inc(FExprNodeSize, Size);
end;
procedure TFilterExpr.SetNodeOp(Node, Index, Data: Integer);
begin
PWordArray(PChar(FExprBuffer) + (SizeOf(CANExpr) + Node +
SizeOf(CANHdr)))^[Index] := Data;
end;
function TFilterExpr.GetFieldByName(Name: string) : TField;
var
I: Integer;
F: TField;
ADataSources: DataSources;
begin
Result := nil;
if poFieldNameGiven in FParserOptions then
Result := FDataSet.FieldByName(FFieldName)
else if poUseOrigNames in FParserOptions then
begin
for I := 0 to FDataset.FieldCount - 1 do
begin
F := FDataSet.Fields[I];
StrCopy(ADataSources.szSourceFldName, PChar(F.FieldName));
if GetFieldSource(FDataSet, ADataSources)
and (AnsiStrComp(PChar(Name), ADataSources.szOrigFldName) = 0) then
begin
Result := F;
Exit;
end;
end;
end;
if Result = nil then
Result := FDataSet.FieldByName(Name);
if (poFieldDepend in FParserOptions) and (Result <> nil) and
(FDependentFields <> nil) then
FDependentFields[Result.FieldNo-1] := True;
end;
constructor TExprParser.Create(DataSet: TDataSet; const Text: string;
Options: TFilterOptions; ParserOptions: TParserOptions; const FieldName: string;
DepFields: TBits);
begin
FStrTrue := STextTrue;
FStrFalse := STextFalse;
FDataSet := DataSet;
FDependentFields := DepFields;
FFilter := TFilterExpr.Create(DataSet, Options, ParserOptions, FieldName, DepFields);
if Text <> '' then
SetExprParams(Text, Options, ParserOptions, FieldName);
end;
destructor TExprParser.Destroy;
begin
FFilter.Free;
end;
procedure TExprParser.SetExprParams(const Text: string; Options: TFilterOptions;
ParserOptions: TParserOptions; const FieldName: string);
var
Root, DefField: PExprNode;
begin
FParserOptions := ParserOptions;
if FFilter <> nil then
FFilter.Free;
FFilter := TFilterExpr.Create(FDataSet, Options, ParserOptions, FieldName,
FDependentFields);
FText := Text;
FSourcePtr := PChar(Text);
FFieldName := FieldName;
NextToken;
Root := ParseExpr;
if FToken <> etEnd then DatabaseError(SExprTermination);
if (poAggregate in FParserOptions) and (Root^.FScopeKind <> skAgg) then
DatabaseError(SExprNotAgg);
if (not (poAggregate in FParserOptions)) and (Root^.FScopeKind = skAgg) then
DatabaseError(SExprNoAggFilter);
if poDefaultExpr in ParserOptions then
begin
DefField := FFilter.NewNode(enField, canNOTDEFINED, FFieldName, nil, nil);
if (IsTemporal(DefField^.FDataType) and (Root^.FDataType = fldZSTRING)) or
((DefField^.FDataType = fldBOOL ) and (Root^.FDataType = fldZSTRING)) then
Root^.FDataType := DefField^.FDataType;
if not ((IsTemporal(DefField^.FDataType) and IsTemporal(Root^.FDataType))
or (IsNumeric(DefField^.FDataType) and IsNumeric(Root^.FDataType))
or ((DefField^.FDataType = fldZSTRING) and (Root^.FDataType = fldZSTRING))
or ((DefField^.FDataType = fldBOOL) and (Root^.FDataType = fldBOOL))) then
DatabaseError(SExprTypeMis);
Root := FFilter.NewNode(enOperator, canASSIGN, Unassigned, Root, DefField);
end;
FFilterData := FFilter.GetFilterData(Root);
FDataSize := FFilter.FExprBufSize;
end;
function TExprParser.NextTokenIsLParen : Boolean;
var
P : PChar;
begin
P := FSourcePtr;
while (P^ <> #0) and (P^ <= ' ') do Inc(P);
Result := P^ = '(';
end;
procedure TExprParser.NextToken;
type
ASet = Set of Char;
var
P, TokenStart: PChar;
L: Integer;
StrBuf: array[0..255] of Char;
function IsKatakana(const Chr: Byte): Boolean;
begin
Result := (SysLocale.PriLangID = LANG_JAPANESE) and (Chr in [$A1..$DF]);
end;
procedure Skip(TheSet: ASet);
begin
while TRUE do
begin
if P^ in LeadBytes then
Inc(P, 2)
else if (P^ in TheSet) or IsKatakana(Byte(P^)) then
Inc(P)
else
Exit;
end;
end;
begin
FPrevToken := FToken;
FTokenString := '';
P := FSourcePtr;
while (P^ <> #0) and (P^ <= ' ') do Inc(P);
if (P^ <> #0) and (P^ = '/') and (P[1] <> #0) and (P[1] = '*')then
begin
P := P + 2;
while (P^ <> #0) and (P^ <> '*') do Inc(P);
if (P^ = '*') and (P[1] <> #0) and (P[1] = '/') then
P := P + 2
else
DatabaseErrorFmt(SExprInvalidChar, [P^]);
end;
while (P^ <> #0) and (P^ <= ' ') do Inc(P);
FTokenPtr := P;
case P^ of
'A'..'Z', 'a'..'z', '_', #$81..#$fe:
begin
TokenStart := P;
if not SysLocale.FarEast then
begin
Inc(P);
while P^ in ['A'..'Z', 'a'..'z', '0'..'9', '_', '.', '[', ']'] do Inc(P);
end
else
Skip(['A'..'Z', 'a'..'z', '0'..'9', '_', '.', '[', ']']);
SetString(FTokenString, TokenStart, P - TokenStart);
FToken := etSymbol;
if CompareText(FTokenString, 'LIKE') = 0 then { do not localize }
FToken := etLIKE
else if CompareText(FTokenString, 'IN') = 0 then { do not localize }
FToken := etIN
else if CompareText(FTokenString, 'IS') = 0 then { do not localize }
begin
while (P^ <> #0) and (P^ <= ' ') do Inc(P);
TokenStart := P;
Skip(['A'..'Z', 'a'..'z']);
SetString(FTokenString, TokenStart, P - TokenStart);
if CompareText(FTokenString, 'NOT')= 0 then { do not localize }
begin
while (P^ <> #0) and (P^ <= ' ') do Inc(P);
TokenStart := P;
Skip(['A'..'Z', 'a'..'z']);
SetString(FTokenString, TokenStart, P - TokenStart);
if CompareText(FTokenString, 'NULL') = 0 then
FToken := etISNOTNULL
else
DatabaseError(SInvalidKeywordUse);
end
else if CompareText (FTokenString, 'NULL') = 0 then { do not localize }
begin
FToken := etISNULL;
end
else
DatabaseError(SInvalidKeywordUse);
end;
end;
'[':
begin
Inc(P);
TokenStart := P;
P := AnsiStrScan(P, ']');
if P = nil then DatabaseError(SExprNameError);
SetString(FTokenString, TokenStart, P - TokenStart);
FToken := etName;
Inc(P);
end;
'''':
begin
Inc(P);
L := 0;
while True do
begin
if P^ = #0 then DatabaseError(SExprStringError);
if P^ = '''' then
begin
Inc(P);
if P^ <> '''' then Break;
end;
if L < SizeOf(StrBuf) then
begin
StrBuf[L] := P^;
Inc(L);
end;
Inc(P);
end;
SetString(FTokenString, StrBuf, L);
FToken := etLiteral;
FNumericLit := False;
end;
'-', '0'..'9':
begin
if (FPrevToken <> etLiteral) and (FPrevToken <> etName) and
(FPrevToken <> etSymbol)and (FPrevToken <> etRParen) then
begin
TokenStart := P;
Inc(P);
while P^ in ['0'..'9', '.', 'e', 'E', '+', '-'] do Inc(P);
SetString(FTokenString, TokenStart, P - TokenStart);
FToken := etLiteral;
FNumericLit := True;
end
else
begin
FToken := etSUB;
Inc(P);
end;
end;
'(':
begin
Inc(P);
FToken := etLParen;
end;
')':
begin
Inc(P);
FToken := etRParen;
end;
'<':
begin
Inc(P);
case P^ of
'=':
begin
Inc(P);
FToken := etLE;
end;
'>':
begin
Inc(P);
FToken := etNE;
end;
else
FToken := etLT;
end;
end;
'=':
begin
Inc(P);
FToken := etEQ;
end;
'>':
begin
Inc(P);
if P^ = '=' then
begin
Inc(P);
FToken := etGE;
end else
FToken := etGT;
end;
'+':
begin
Inc(P);
FToken := etADD;
end;
'*':
begin
Inc(P);
FToken := etMUL;
end;
'/':
begin
Inc(P);
FToken := etDIV;
end;
',':
begin
Inc(P);
FToken := etComma;
end;
#0:
FToken := etEnd;
else
DatabaseErrorFmt(SExprInvalidChar, [P^]);
end;
FSourcePtr := P;
end;
function TExprParser.ParseExpr: PExprNode;
begin
Result := ParseExpr2;
while TokenSymbolIs('OR') do
begin
NextToken;
Result := FFilter.NewNode(enOperator, canOR, Unassigned,
Result, ParseExpr2);
GetScopeKind(Result, Result^.FLeft, Result^.FRight);
end;
end;
function TExprParser.ParseExpr2: PExprNode;
begin
Result := ParseExpr3;
while TokenSymbolIs('AND') do
begin
NextToken;
Result := FFilter.NewNode(enOperator, canAND, Unassigned,
Result, ParseExpr3);
GetScopeKind(Result, Result^.FLeft, Result^.FRight);
end;
end;
function TExprParser.ParseExpr3: PExprNode;
begin
if TokenSymbolIs('NOT') then
begin
NextToken;
Result := FFilter.NewNode(enOperator, canNOT, Unassigned,
ParseExpr4, nil);
end else
Result := ParseExpr4;
GetScopeKind(Result, Result^.FLeft, Result^.FRight);
end;
function TExprParser.ParseExpr4: PExprNode;
const
Operators: array[etEQ..etLT] of CanOp = (
canEQ, canNE, canGE, canLE, canGT, canLT);
var
Operator: CanOp;
Left, Right: PExprNode;
begin
Result := ParseExpr5;
if (FToken in [etEQ..etLT]) or (FToken = etLIKE)
or (FToken = etISNULL) or (FToken = etISNOTNULL)
or (FToken = etIN) then
begin
case FToken of
etEQ..etLT:
Operator := Operators[FToken];
etLIKE:
Operator := canLIKE;
etISNULL:
Operator := canISBLANK;
etISNOTNULL:
Operator := canNOTBLANK;
etIN:
Operator := canIN;
else
Operator := canNOTDEFINED;
end;
NextToken;
Left := Result;
if Operator = canIN then
begin
if FToken <> etLParen then
DatabaseErrorFmt(SExprNoLParen, [TokenName]);
NextToken;
Result := FFilter.NewNode(enOperator, canIN, Unassigned,
Left, nil);
if FToken <> etRParen then
begin
Result.FArgs := TList.Create;
repeat
Right := ParseExpr;
if IsTemporal(Left.FDataType) then
Right.FDataType := Left.FDataType;
Result.FArgs.Add(Right);
if (FToken <> etComma) and (FToken <> etRParen) then
DatabaseErrorFmt(SExprNoRParenOrComma, [TokenName]);
if FToken = etComma then NextToken;
until (FToken = etRParen) or (FToken = etEnd);
if FToken <> etRParen then
DatabaseErrorFmt(SExprNoRParen, [TokenName]);
NextToken;
end else
DatabaseError(SExprEmptyInList);
end else
begin
if (Operator <> canISBLANK) and (Operator <> canNOTBLANK) then
Right := ParseExpr5
else
Right := nil;
Result := FFilter.NewNode(enOperator, Operator, Unassigned,
Left, Right);
if Right <> nil then
begin
if (Left^.FKind = enField) and (Right^.FKind = enConst) then
begin
Right^.FDataType := Left^.FDataType;
Right^.FDataSize := Left^.FDataSize;
end
else if (Right^.FKind = enField) and (Left^.FKind = enConst) then
begin
Left^.FDataType := Right^.FDataType;
Left^.FDataSize := Right^.FDataSize;
end;
end;
if (Left^.FDataType = fldBLOB) and (Operator = canLIKE) then
begin
if Right^.FKind = enConst then Right^.FDataType := fldZSTRING;
end
else if (Operator <> canISBLANK) and (Operator <> canNOTBLANK)
and ((Left^.FDataType in [ fldBLOB, fldBYTES]) or
((Right <> nil) and (Right^.FDataType in [ fldBLOB, fldBYTES]))) then
DatabaseError(SExprTypeMis);
Result.FDataType := fldBOOL;
if Right <> nil then
begin
if IsTemporal(Left.FDataType) and (Right.FDataType = fldZSTRING) then
Right.FDataType := Left.FDataType
else if IsTemporal(Right.FDataType) and (Left.FDataType = fldZSTRING) then
Left.FDataType := Right.FDataType;
end;
GetScopeKind(Result, Left, Right);
end;
end;
end;
function TExprParser.ParseExpr5: PExprNode;
const
Operators: array[etADD..etDIV] of CanOp = (
canADD, canSUB, canMUL, canDIV);
var
Operator: CanOp;
Left, Right: PExprNode;
begin
Result := ParseExpr6;
while FToken in [etADD, etSUB] do
begin
if not (poExtSyntax in FParserOptions) then
DatabaseError(SExprNoArith);
Operator := Operators[FToken];
Left := Result;
NextToken;
Right := ParseExpr6;
Result := FFilter.NewNode(enOperator, Operator, Unassigned, Left, Right);
TypeCheckArithOp(Result);
GetScopeKind(Result, Left, Right);
end;
end;
function TExprParser.ParseExpr6: PExprNode;
const
Operators: array[etADD..etDIV] of CanOp = (
canADD, canSUB, canMUL, canDIV);
var
Operator: CanOp;
Left, Right: PExprNode;
begin
Result := ParseExpr7;
while FToken in [etMUL, etDIV] do
begin
if not (poExtSyntax in FParserOptions) then
DatabaseError(SExprNoArith);
Operator := Operators[FToken];
Left := Result;
NextToken;
Right := ParseExpr7;
Result := FFilter.NewNode(enOperator, Operator, Unassigned, Left, Right);
TypeCheckArithOp(Result);
GetScopeKind(Result, Left, Right);
end;
end;
function TExprParser.ParseExpr7: PExprNode;
var
FuncName: string;
begin
case FToken of
etSymbol:
if (poExtSyntax in FParserOptions)
and NextTokenIsLParen and TokenSymbolIsFunc(FTokenString) then
begin
Funcname := FTokenString;
NextToken;
if FToken <> etLParen then
DatabaseErrorFmt(SExprNoLParen, [TokenName]);
NextToken;
if (CompareText(FuncName,'count') = 0) and (FToken = etMUL) then
begin
FuncName := 'COUNT(*)';
NextToken;
end;
Result := FFilter.NewNode(enFunc, canNOTDEFINED, FuncName,
nil, nil);
if FToken <> etRParen then
begin
Result.FArgs := TList.Create;
repeat
Result.FArgs.Add(ParseExpr);
if (FToken <> etComma) and (FToken <> etRParen) then
DatabaseErrorFmt(SExprNoRParenOrComma, [TokenName]);
if FToken = etComma then NextToken;
until (FToken = etRParen) or (FToken = etEnd);
end else
Result.FArgs := nil;
GetFuncResultInfo(Result);
end
else if TokenSymbolIs('NULL') then
begin
Result := FFilter.NewNode(enConst, canNOTDEFINED, System.Null, nil, nil);
Result.FScopeKind := skConst;
end
else if TokenSymbolIs(FStrTrue) then
begin
Result := FFilter.NewNode(enConst, canNOTDEFINED, 1, nil, nil);
Result.FScopeKind := skConst;
end
else if TokenSymbolIs(FStrFalse) then
begin
Result := FFilter.NewNode(enConst, canNOTDEFINED, 0, nil, nil);
Result.FScopeKind := skConst;
end
else
begin
Result := FFilter.NewNode(enField, canNOTDEFINED, FTokenString, nil, nil);
Result.FScopeKind := skField;
end;
etName:
begin
Result := FFilter.NewNode(enField, canNOTDEFINED, FTokenString, nil, nil);
Result.FScopeKind := skField;
end;
etLiteral:
begin
Result := FFilter.NewNode(enConst, canNOTDEFINED, FTokenString, nil, nil);
if FNumericLit then Result^.FDataType := fldFLOAT else
Result^.FDataType := fldZSTRING;
Result.FScopeKind := skConst;
end;
etLParen:
begin
NextToken;
Result := ParseExpr;
if FToken <> etRParen then DatabaseErrorFmt(SExprNoRParen, [TokenName]);
end;
else
DatabaseErrorFmt(SExprExpected, [TokenName]);
Result := nil;
end;
NextToken;
end;
procedure TExprParser.GetScopeKind(Root, Left, Right : PExprNode);
begin
if (Left = nil) and (Right = nil) then Exit;
if Right = nil then
begin
Root.FScopeKind := Left.FScopeKind;
Exit;
end;
if ((Left^.FScopeKind = skField) and (Right^.FScopeKind = skAgg))
or ((Left^.FScopeKind = skAgg) and (Right^.FScopeKind = skField)) then
DatabaseError(SExprBadScope);
if (Left^.FScopeKind = skConst) and (Right^.FScopeKind = skConst) then
Root^.FScopeKind := skConst
else if (Left^.FScopeKind = skAgg) or (Right^.FScopeKind = skAgg) then
Root^.FScopeKind := skAgg
else if (Left^.FScopeKind = skField) or (Right^.FScopeKind = skField) then
Root^.FScopeKind := skField;
end;
procedure TExprParser.GetFuncResultInfo(Node : PExprNode);
begin
Node^.FDataType := fldZSTRING;
if (CompareText(Node^.FData, 'COUNT(*)') <> 0 )
and (CompareText(Node^.FData,'GETDATE') <> 0 )
and ( (Node^.FArgs = nil ) or ( Node^.FArgs.Count = 0) ) then
DatabaseError(SExprTypeMis);
if (Node^.FArgs <> nil) and (Node^.FArgs.Count > 0) then
Node^.FScopeKind := PExprNode(Node^.FArgs.Items[0])^.FScopeKind;
if (CompareText(Node^.FData , 'SUM') = 0) or
(CompareText(Node^.FData , 'AVG') = 0) then
begin
Node^.FDataType := fldFLOAT;
Node^.FScopeKind := skAgg;
end
else if (CompareText(Node^.FData , 'MIN') = 0) or
(CompareText(Node^.FData , 'MAX') = 0) then
begin
Node^.FDataType := PExprNode(Node^.FArgs.Items[0])^.FDataType;
Node^.FScopeKind := skAgg;
end
else if (CompareText(Node^.FData , 'COUNT') = 0) or
(CompareText(Node^.FData , 'COUNT(*)') = 0) then
begin
Node^.FDataType := fldINT32;
Node^.FScopeKind := skAgg;
end
else if (CompareText(Node^.FData , 'YEAR') = 0) or
(CompareText(Node^.FData , 'MONTH') = 0) or
(CompareText(Node^.FData , 'DAY') = 0) or
(CompareText(Node^.FData , 'HOUR') = 0) or
(CompareText(Node^.FData , 'MINUTE') = 0) or
(CompareText(Node^.FData , 'SECOND') = 0 ) then
begin
Node^.FDataType := fldINT32;
Node^.FScopeKind := PExprNode(Node^.FArgs.Items[0])^.FScopeKind;
end
else if CompareText(Node^.FData , 'GETDATE') = 0 then
begin
Node^.FDataType := fldTIMESTAMP;
Node^.FScopeKind := skConst;
end
else if CompareText(Node^.FData , 'DATE') = 0 then
begin
Node^.FDataType := fldDATE;
Node^.FScopeKind := PExprNode(Node^.FArgs.Items[0])^.FScopeKind;
end
else if CompareText(Node^.FData , 'TIME') = 0 then
begin
Node^.FDataType := fldTIME;
Node^.FScopeKind := PExprNode(Node^.FArgs.Items[0])^.FScopeKind;
end;
end;
function TExprParser.TokenName: string;
begin
if FSourcePtr = FTokenPtr then Result := SExprNothing else
begin
SetString(Result, FTokenPtr, FSourcePtr - FTokenPtr);
Result := '''' + Result + '''';
end;
end;
function TExprParser.TokenSymbolIs(const S: string): Boolean;
begin
Result := (FToken = etSymbol) and (CompareText(FTokenString, S) = 0);
end;
function TExprParser.TokenSymbolIsFunc(const S: string) : Boolean;
begin
Result := (CompareText(S, 'UPPER') = 0) or
(CompareText(S, 'LOWER') = 0) or
(CompareText(S, 'SUBSTRING') = 0) or
(CompareText(S, 'TRIM') = 0) or
(CompareText(S, 'TRIMLEFT') = 0) or
(CompareText(S, 'TRIMRIGHT') = 0) or
(CompareText(S, 'YEAR') = 0) or
(CompareText(S, 'MONTH') = 0) or
(CompareText(S, 'DAY') = 0) or
(CompareText(S, 'HOUR') = 0) or
(CompareText(S, 'MINUTE') = 0) or
(CompareText(S, 'SECOND') = 0) or
(CompareText(S, 'GETDATE') = 0) or
(CompareText(S, 'DATE') = 0) or
(CompareText(S, 'TIME') = 0) or
(CompareText(S, 'SUM') = 0) or
(CompareText(S, 'MIN') = 0) or
(CompareText(S, 'MAX') = 0) or
(CompareText(S, 'AVG') = 0) or
(CompareText(S, 'COUNT') = 0);
end;
procedure TExprParser.TypeCheckArithOp(Node: PExprNode);
begin
with Node^ do
begin
if IsNumeric(FLeft.FDataType) and IsNumeric(FRight.FDataType) then
FDataType := fldFLOAT
else if (FLeft.FDataType = fldZSTRING) and
(FRight.FDataType = fldZSTRING) and (FOperator = canADD) then
FDataType := fldZSTRING
else if IsTemporal(FLeft.FDataType) and IsNumeric(FRight.FDataType) and
(FOperator = canADD) then
FDataType := fldTIMESTAMP
else if IsTemporal(FLeft.FDataType) and IsNumeric(FRight.FDataType) and
(FOperator = canSUB) then
FDataType := FLeft.FDataType
else if IsTemporal(FLeft.FDataType) and IsTemporal(FRight.FDataType) and
(FOperator = canSUB) then
FDataType := fldFLOAT
else if (FLeft.FDataType = fldZSTRING) and IsTemporal(FRight.FDataType) and
(FOperator = canSUB) then
begin
FLeft.FDataType := FRight.FDataType;
FDataType := fldFLOAT;
end
else if ( FLeft.FDataType = fldZSTRING) and IsNumeric(FRight.FDataType )and
(FLeft.FKind = enConst) then
FLeft.FDataType := fldTIMESTAMP
else
DatabaseError(SExprTypeMis);
end;
end;
{ TMasterDataLink }
constructor TMasterDataLink.Create(DataSet: TDataSet);
begin
inherited Create;
FDataSet := DataSet;
FFields := TList.Create;
end;
destructor TMasterDataLink.Destroy;
begin
FFields.Free;
inherited Destroy;
end;
procedure TMasterDataLink.ActiveChanged;
begin
FFields.Clear;
if Active then
try
DataSet.GetFieldList(FFields, FFieldNames);
except
FFields.Clear;
raise;
end;
if FDataSet.Active and not (csDestroying in FDataSet.ComponentState) then
if Active and (FFields.Count > 0) then
begin
if Assigned(FOnMasterChange) then FOnMasterChange(Self);
end else
if Assigned(FOnMasterDisable) then FOnMasterDisable(Self);
end;
procedure TMasterDataLink.CheckBrowseMode;
begin
if FDataSet.Active then FDataSet.CheckBrowseMode;
end;
function TMasterDataLink.GetDetailDataSet: TDataSet;
begin
Result := FDataSet;
end;
procedure TMasterDataLink.LayoutChanged;
begin
ActiveChanged;
end;
procedure TMasterDataLink.RecordChanged(Field: TField);
begin
if (DataSource.State <> dsSetKey) and FDataSet.Active and
(FFields.Count > 0) and ((Field = nil) or
(FFields.IndexOf(Field) >= 0)) and
Assigned(FOnMasterChange) then
FOnMasterChange(Self);
end;
procedure TMasterDataLink.SetFieldNames(const Value: string);
begin
if FFieldNames <> Value then
begin
FFieldNames := Value;
ActiveChanged;
end;
end;
end.
|
unit FUNC_REG_Estadisticas;
interface
type
REG_Estadisticas = record
ID: LongWord;
DNI: LongWord;
Codigo_Provincia: Byte;
Estado: String[10];
Dado_de_baja: Boolean;
Forma_de_contagio: String[25];
end;
procedure Inicializar_Registro_Estadisticas (VAR REG: REG_Estadisticas);
procedure Cargar_Registro_Estadisticas (VAR R_Estadisticas: REG_Estadisticas; DNI: LongWord);
procedure Cargo_estado_del_paciente(VAR Estado_paciente: String);
procedure Cargo_Forma_de_contagio(VAR Forma_de_contagio_del_paciente: String);
procedure Cargar_dado_de_baja(VAR Estado_Baja: Boolean);
implementation
uses graph, wincrt, Graph_Graficos;
procedure Inicializar_Registro_Estadisticas (VAR REG: REG_Estadisticas);
begin
REG.ID:= 0;
REG.DNI:= 0;
REG.Codigo_Provincia:= 0;
REG.Estado:= '';
REG.Dado_de_baja:= False;
REG.Forma_de_contagio:= '';
end;
function Devuelvo_la_Forma_de_contagio(Opcion: Char) : String;
begin
CASE Opcion OF
'1':
Devuelvo_la_Forma_de_contagio:= 'Contagio directo';
'2':
Devuelvo_la_Forma_de_contagio:= 'Transmision comunitaria';
'3':
Devuelvo_la_Forma_de_contagio:= 'Desconocida';
end;
end;
function Devuelvo_el_Estado_del_Paciente(Opcion: Char) : String;
begin
CASE Opcion OF
'1':
Devuelvo_el_Estado_del_Paciente:= 'ACTIVO';
'2':
Devuelvo_el_Estado_del_Paciente:= 'RECUPERADO';
'3':
Devuelvo_el_Estado_del_Paciente:= 'FALLECIDO';
end;
end;
procedure Cargo_estado_del_paciente(VAR Estado_paciente: String);
var
Opcion: Char;
begin
Rectangle((3*16), (17*16), 26*16,22*16);
SetFillStyle(SolidFill, 92);
bar((3*16)+1, (17*16)+1, 26*16-1,22*16-1);
SetFillStyle(SolidFill, 91);
OutTextXY(5*16, 15*16, 'Estado del paciente');
OutTextXY(4*16, 18*16, '[1]-ACTIVO');
OutTextXY(4*16, 19*16, '[2]-RECUPERADO');
OutTextXY(4*16, 20*16, '[3]-FALLECIDO');
repeat
Opcion:= Upcase(readkey);
until(Opcion in ['1', '2','3']);
Estado_paciente:= Devuelvo_el_Estado_del_Paciente(Opcion);
end;
procedure Cargo_Forma_de_contagio(VAR Forma_de_contagio_del_paciente: String);
var
Opcion: Char;
begin
Rectangle((3*16), (17*16), 32*16,22*16);
SetFillStyle(SolidFill, 92);
bar((3*16)+1, (17*16)+1, 32*16-1,22*16-1);
SetFillStyle(SolidFill, 91);
OutTextXY(9*16, 15*16, 'Forma de contagio');
OutTextXY(4*16, 18*16, '[1]-Contagio directo');
OutTextXY(4*16, 19*16, '[2]-Transmision comunitaria');
OutTextXY(4*16, 20*16, '[3]-Desconocida');
repeat
Opcion:= Upcase(readkey);
until(Opcion in ['1', '2','3']);
Forma_de_contagio_del_paciente:= Devuelvo_la_Forma_de_contagio(Opcion);
end;
procedure Cargar_dado_de_baja(VAR Estado_Baja: Boolean);
Var
opcion: char;
begin
if Estado_Baja = False then
begin
Estado_Baja:= True;
Mostrar_MSJ('El usuairo fue dado de baja con exito!', 'Presione una tecla para continuar...');
readkey;
end
else
begin
Mostrar_MSJ('El usuario ya eesta dado de baja', 'Desea darlo de alta? [Y] / [N]');
repeat
opcion:= upcase(readkey);
until(opcion in ['Y', 'N']);
if opcion = 'Y' then
begin
Estado_Baja:= False;
Mostrar_MSJ('El usuairo fue dado de alta con exito!', 'Presione una tecla para continuar...');
readkey;
end;
Bar((57*16), (152+16*23), 3*16,256);
end;
end;
procedure Cargar_Registro_Estadisticas (VAR R_Estadisticas: REG_Estadisticas; DNI: LongWord);
begin
R_Estadisticas.DNI:= DNI;
R_Estadisticas.Dado_de_baja:= False;
Cargo_estado_del_paciente(R_Estadisticas.Estado);
Bar((32*16), (128+16*7), 3*16,128+16*16);
Cargo_Forma_de_contagio(R_Estadisticas.Forma_de_contagio);
Bar((32*16), (128+16*7), 3*16,128+16*16);
end;
END. |
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXMetaDataWriterFactory;
interface
uses
System.Classes,
System.Generics.Collections,
System.Generics.Defaults,
Data.DBXMetaDataWriter
;
const
SWriterPrefix = 'Borland.MetaDataWriter.';
type
TDBXMetaDataWriterFactory = class
private
class var
FProviderRegistry: TDictionary<string, TClass>;
public
class procedure RegisterWriter(DialectName: string; WriterClass: TClass);
class procedure UnRegisterWriter(DialectName: string; WriterClass: TClass);
class procedure FreeWriterRegistry;
class function CreateWriter(DialectName: string): TDBXMetaDataWriter;
end;
implementation
uses
Data.DBXCommon,
System.SysUtils,
Data.DBXClassRegistry,
Data.DBXCommonResStrs
;
{ TDBXMetaDataWriterFactory }
class function TDBXMetaDataWriterFactory.CreateWriter(
DialectName: string): TDBXMetaDataWriter;
begin
if not FProviderRegistry.ContainsKey(DialectName) then
raise TDBXError.Create(TDBXErrorCodes.DriverInitFailed, Format(SNoMetadataProvider, [DialectName])+' Add driver unit to your uses (DbxInterBase or DbxDb2 or DbxMsSql or DBXMySQL or DbxOracle or DbxSybaseASA or DbxSybaseASE)');
Result := TClassRegistry.GetClassRegistry.CreateInstance(FProviderRegistry.Items[DialectName].ClassName) as TDBXMetaDataWriter;
Result.Open;
end;
class procedure TDBXMetaDataWriterFactory.FreeWriterRegistry;
begin
FProviderRegistry.Free;
end;
class procedure TDBXMetaDataWriterFactory.RegisterWriter(
DialectName: string;
WriterClass: TClass);
var
ClassRegistry: TClassRegistry;
ClassName: string;
begin
if not FProviderRegistry.ContainsKey(DialectName) then
FProviderRegistry.Add(DialectName, WriterClass);
ClassRegistry := TClassRegistry.GetClassRegistry;
ClassName := WriterClass.ClassName;
if not ClassRegistry.HasClass(ClassName) then
ClassRegistry.RegisterClass(ClassName, WriterClass);
end;
class procedure TDBXMetaDataWriterFactory.UnRegisterWriter(DialectName: string;
WriterClass: TClass);
begin
TClassRegistry.GetClassRegistry.UnregisterClass(WriterClass.ClassName);
end;
initialization
TDBXMetaDataWriterFactory.FProviderRegistry := TDictionary<string, TClass>.Create(TIStringComparer.Ordinal);
finalization
TDBXMetaDataWriterFactory.FreeWriterRegistry;
end.
|
unit UTools;
{$mode objfpc}{$H+}
interface
uses
Classes, Graphics, UShapes, UBaseShape, UShapesList, UViewPort, UGeometry,
UInspector, sysutils;
type
{ TTool }
TTool = Class abstract
private
FIcon: TBitmap;
FCaption: string;
public
constructor Create; virtual;
procedure MouseClick(APoint: TPoint; Shift: TShiftState); virtual; abstract;
procedure MouseMove(APoint: TPoint; Shift: TShiftState); virtual;
procedure MouseUp; virtual;
procedure Leave; virtual;
procedure Reset; virtual;
function GetShape: TShape; virtual; abstract;
function CreateShape: TShape; virtual; abstract;
property Icon: TBitmap read FIcon;
property Caption: string read FCaption;
end;
{ TShapeTool }
TShapeTool = Class(TTool)
private
FShape: TShape;
FIsTemp: Boolean;
public
constructor Create; override;
function GetShape: TShape; override;
function CreateShape: TShape; override;
procedure MouseUp; override;
procedure MouseMove(APoint: TPoint; Shift: TShiftState); override;
procedure MouseClick(APoint: TPoint; Shift: TShiftState); override;
procedure Leave; override;
end;
{ TPenTool }
TPenTool = Class(TShapeTool)
public
constructor Create; override;
function CreateShape: TShape; override;
procedure MouseMove(APoint: TPoint; Shift: TShiftState); override;
end;
{ TLineTool }
TLineTool = Class(TShapeTool)
public
constructor Create; override;
function CreateShape: TShape; override;
end;
{ TPolylineTool }
TPolylineTool = Class(TShapeTool)
public
constructor Create; override;
function CreateShape: TShape; override;
procedure MouseClick(APoint: TPoint; Shift: TShiftState); override;
procedure MouseMove(APoint: TPoint; Shift: TShiftState); override;
procedure MouseUp; override;
procedure Leave; override;
procedure Reset; override;
private
FDrawingNow: boolean;
end;
{ TRectangleTool }
TRectangleTool = Class(TShapeTool)
public
constructor Create; override;
function CreateShape: TShape; override;
end;
{ TEllipseTool }
TEllipseTool = Class(TShapeTool)
public
constructor Create; override;
function CreateShape: TShape; override;
end;
{ TRoundRectTool }
TRoundRectTool = Class(TShapeTool)
public
constructor Create; override;
function CreateShape: TShape; override;
end;
{ TZoomInTool }
TZoomInTool = Class(TTool)
public
constructor Create; override;
function GetShape: TShape; override;
function CreateShape: TShape; override;
procedure MouseClick(APoint: TPoint; Shift: TShiftState); override;
end;
{ TZoomOutTool }
TZoomOutTool = Class(TTool)
public
constructor Create; override;
function GetShape: TShape; override;
function CreateShape: TShape; override;
procedure MouseClick(APoint: TPoint; Shift: TShiftState); override;
end;
{ THandTool }
THandTool = Class(TTool)
private
FStartPoint: TPoint;
public
constructor Create; override;
function GetShape: TShape; override;
function CreateShape: TShape; override;
procedure MouseClick(APoint: TPoint; Shift: TShiftState); override;
procedure MouseMove(APoint: TPoint; Shift: TShiftState); override;
end;
{ TRectangleZoomTool }
TRectangleZoomTool = Class(TTool)
private
FPointOne: TFloatPoint;
FPointTwo: TFloatPoint;
public
constructor Create; override;
function GetShape: TShape; override;
function CreateShape: TShape; override;
procedure MouseClick(APoint: TPoint; Shift: TShiftState); override;
procedure MouseMove(APoint: TPoint; Shift: TShiftState); override;
procedure MouseUp; override;
end;
{ TSelectionTool }
TSelectionToolMode = (stmSelect, stmMove, stmEdit);
TSelectionTool = Class(TTool)
private
FStartPoint: TPoint;
FShape: TShape;
FIndex: Integer;
FMode: TSelectionToolMode;
public
constructor Create; override;
function GetShape: TShape; override;
function CreateShape: TShape; override;
procedure MouseClick(APoint: TPoint; Shift: TShiftState); override;
procedure MouseMove(APoint: TPoint; Shift: TShiftState); override;
procedure MouseUp; override;
procedure Leave; override;
end;
ClassOfTool = class of TTool;
ArrayOfTool = array of TTool;
{ TToolsContainer }
TToolsContainer = class
private
FTools: ArrayOfTool;
public
property Tools: ArrayOfTool read FTools;
procedure RegisterTool(AClass: ClassOfTool);
end;
var
ToolContainer: TToolsContainer;
implementation
{ TSelectionTool }
procedure TSelectionTool.MouseMove(APoint: TPoint; Shift: TShiftState);
begin
if FMode = stmMove then
begin
Figures.ShiftSelected(APoint - FStartPoint);
FStartPoint := APoint;
Exit;
end;
if (FMode = stmEdit) and (FShape <> nil) then
begin
FShape.MoveEditPoint(APoint - FStartPoint, FIndex);
FStartPoint := APoint;
Exit;
end;
if (FMode = stmSelect) and (Figures.SelectionRectangle <> nil) then
begin
Figures.SelectionRectangle.MovePoint(APoint);
if ssCtrl in Shift then
Figures.SwitchSelect
else
Figures.Select;
end;
end;
procedure TSelectionTool.MouseClick(APoint: TPoint; Shift: TShiftState);
begin
if (ssShift in Shift) and Figures.PointOnFigure(APoint) then
begin
FMode := stmMove;
FStartPoint := APoint;
Exit;
end
else if (ssShift in Shift) then
Exit;
if (ssAlt in Shift) and Figures.PointOnEditPoint(APoint, FShape, FIndex) then
begin
FMode := stmEdit;
FStartPoint := APoint;
Exit;
end
else if (ssAlt in Shift) then
Exit;
if not (ssCtrl in Shift) then
begin
Figures.UnSelect;
Figures.Select(APoint);
end
else
Figures.SwitchSelect(APoint);
FMode := stmSelect;
Figures.SelectionRectangle := TRectangle.Create;
Figures.SelectionRectangle.SetPoint(APoint);
Figures.SelectionRectangle.PenStyle := psDot;
Figures.SelectionRectangle.BrushStyle := bsClear;
end;
procedure TSelectionTool.MouseUp;
begin
if (FMode = stmEdit) or (FMode = stmMove) then
Figures.UpdateHistory;
Figures.LoadSelected;
Figures.SelectionRectangle.Free;
Figures.SelectionRectangle := nil;
FShape := nil;
FMode := stmSelect;
end;
procedure TSelectionTool.Leave;
begin
Figures.UnSelect;
Inspector.OnParamsUpdate;
FMode := stmSelect;
end;
constructor TSelectionTool.Create;
begin
inherited Create;
FCaption := 'Selection';
FMode := stmSelect;
end;
function TSelectionTool.GetShape: TShape;
begin
Result := nil;
end;
function TSelectionTool.CreateShape: TShape;
begin
Result := nil;
end;
{ TToolsContainer }
procedure TToolsContainer.RegisterTool(AClass: ClassOfTool);
begin
SetLength(FTools, Length(FTools) + 1);
FTools[High(FTools)] := AClass.Create;
end;
{ TShapeTool }
constructor TShapeTool.Create;
begin
inherited Create;
FIsTemp := True;
end;
function TShapeTool.GetShape: TShape;
begin
Result := FShape;
end;
function TShapeTool.CreateShape: TShape;
begin
FIsTemp := True;
Result := FShape;
end;
procedure TShapeTool.MouseUp;
begin
Figures.UpdateHistory;
Inspector.LoadNew(CreateShape);
end;
procedure TShapeTool.MouseMove(APoint: TPoint; Shift: TShiftState);
begin
FShape.MovePoint(APoint);
end;
procedure TShapeTool.MouseClick(APoint: TPoint; Shift: TShiftState);
begin
Figures.Add(FShape);
FIsTemp := False;
FShape.SetPoint(APoint);
end;
procedure TShapeTool.Leave;
begin
if FIsTemp then
FreeAndNil(FShape);
end;
{ TRectangleZoomTool }
constructor TRectangleZoomTool.Create;
begin
inherited Create;
FCaption := 'Zoom to area';
end;
function TRectangleZoomTool.GetShape: TShape;
begin
Result := nil;
end;
function TRectangleZoomTool.CreateShape: TShape;
begin
Result := nil;
end;
procedure TRectangleZoomTool.MouseClick(APoint: TPoint; Shift: TShiftState);
begin
Figures.SelectionRectangle := TRectangle.Create;
Figures.SelectionRectangle.SetPoint(APoint);
Figures.SelectionRectangle.PenStyle := psDot;
Figures.SelectionRectangle.BrushStyle := bsClear;
FPointOne := VP.ScreenToWorld(APoint);
FPointTwo := VP.ScreenToWorld(APoint);
end;
procedure TRectangleZoomTool.MouseMove(APoint: TPoint; Shift: TShiftState);
begin
Figures.SelectionRectangle.MovePoint(APoint);
FPointTwo := VP.ScreenToWorld(APoint);
end;
procedure TRectangleZoomTool.MouseUp;
begin
if not Figures.IsEmpty then
begin
VP.ViewPosition := (FPointOne + FPointTwo) / 2;
VP.ScaleTo(FloatRect(FPointOne, FPointTwo));
end;
Figures.SelectionRectangle.Free;
Figures.SelectionRectangle := nil;
end;
{ THandTool }
constructor THandTool.Create;
begin
inherited Create;
FCaption := 'Hand';
end;
function THandTool.GetShape: TShape;
begin
Result := Nil;
end;
function THandTool.CreateShape: TShape;
begin
Result := Nil;
end;
procedure THandTool.MouseClick(APoint: TPoint; Shift: TShiftState);
begin
FStartPoint := APoint;
end;
procedure THandTool.MouseMove(APoint: TPoint; Shift: TShiftState);
begin
if not Figures.IsEmpty then
VP.ViewPosition := VP.ViewPosition + (FStartPoint - APoint) / VP.Scale;
FStartPoint := APoint;
end;
{ TZoomOutTool }
constructor TZoomOutTool.Create;
begin
inherited Create;
FCaption := 'Zoom out';
end;
function TZoomOutTool.GetShape: TShape;
begin
Result := Nil;
end;
function TZoomOutTool.CreateShape: TShape;
begin
Result := Nil;
end;
procedure TZoomOutTool.MouseClick(APoint: TPoint; Shift: TShiftState);
var mem: TFloatPoint;
begin
if not Figures.IsEmpty then
begin
mem := VP.ScreenToWorld(APoint);
VP.ViewPosition := VP.ScreenToWorld(APoint);
VP.Scale := VP.Scale - 0.25;
VP.ViewPosition := VP.ViewPosition + mem - VP.ScreenToWorld(APoint);
end;
end;
{ TZoomInTool }
constructor TZoomInTool.Create;
begin
inherited Create;
FCaption := 'Zoom in';
end;
function TZoomInTool.GetShape: TShape;
begin
Result := Nil;
end;
function TZoomInTool.CreateShape: TShape;
begin
Result := Nil;
end;
procedure TZoomInTool.MouseClick(APoint: TPoint; Shift: TShiftState);
var mem: TFloatPoint;
begin
if not Figures.IsEmpty then
begin
mem := VP.ScreenToWorld(APoint);
VP.ViewPosition := VP.ScreenToWorld(APoint);
VP.Scale := VP.Scale + 0.25;
VP.ViewPosition := VP.ViewPosition + mem - VP.ScreenToWorld(APoint);
end;
end;
{ TTool }
constructor TTool.Create;
begin
FIcon := TBitmap.Create;
FIcon.LoadFromFile('icons/' + ClassName + '.bmp');
end;
procedure TTool.MouseMove(APoint: TPoint; Shift: TShiftState);
begin
{Do nothing, because I need it to be called and not to throw exceptions}
end;
procedure TTool.MouseUp;
begin
{Do nothing, because I need it to be called and not to throw exceptions}
end;
procedure TTool.Leave;
begin
{This procedure is called on leaving the tool and does nothing by default}
end;
procedure TTool.Reset;
begin
{This procedure is called to reset the tool state to default}
end;
{ TRoundRectTool }
constructor TRoundRectTool.Create;
begin
inherited Create;
FCaption := 'Rounded rectangle';
end;
function TRoundRectTool.CreateShape: TShape;
begin
FShape := TRoundRect.Create;
Result := inherited CreateShape;
end;
{ TEllipseTool }
constructor TEllipseTool.Create;
begin
inherited Create;
FCaption := 'Ellipse';
end;
function TEllipseTool.CreateShape: TShape;
begin
FShape := TEllipse.Create;
Result := inherited CreateShape;
end;
{ TRectangleTool }
constructor TRectangleTool.Create;
begin
inherited Create;
FCaption := 'Rectangle';
end;
function TRectangleTool.CreateShape: TShape;
begin
FShape := TRectangle.Create;
Result := inherited CreateShape;
end;
{ TPolylineTool }
constructor TPolylineTool.Create;
begin
inherited Create;
FCaption := 'Polyline';
end;
function TPolylineTool.CreateShape: TShape;
begin
FShape := TPolyline.Create;
Result := inherited CreateShape;
end;
procedure TPolylineTool.MouseClick(APoint: TPoint; Shift: TShiftState);
begin
if ssRight in Shift then
begin
Reset;
Exit;
end;
if not FDrawingNow then
begin
inherited;
FDrawingNow := true;
end
else
TPolyline(FShape).AddPoint(APoint);
end;
procedure TPolylineTool.MouseMove(APoint: TPoint; Shift: TShiftState);
begin
if FDrawingNow then FShape.MovePoint(APoint);
end;
procedure TPolylineTool.MouseUp;
begin
Figures.UpdateHistory;
{Do not create new shape}
end;
procedure TPolylineTool.Leave;
begin
if FDrawingNow then
begin
Figures.UpdateHistory;
FDrawingNow := False;
end;
inherited;
end;
procedure TPolylineTool.Reset;
begin
FDrawingNow := false;
Inspector.LoadNew(CreateShape);
end;
{ TLineTool }
constructor TLineTool.Create;
begin
inherited Create;
FCaption := 'Line';
end;
function TLineTool.CreateShape: TShape;
begin
FShape := TLine.Create;
Result := inherited CreateShape;
end;
{ TPenTool }
constructor TPenTool.Create;
begin
inherited Create;
FCaption := 'Pencil';
end;
function TPenTool.CreateShape: TShape;
begin
FShape := TPolyline.Create;
Result := inherited CreateShape;
end;
procedure TPenTool.MouseMove(APoint: TPoint; Shift: TShiftState);
begin
TPolyline(FShape).AddPoint(APoint);
end;
initialization
ToolContainer := TToolsContainer.Create;
ToolContainer.RegisterTool(TPenTool);
ToolContainer.RegisterTool(TLineTool);
ToolContainer.RegisterTool(TPolylineTool);
ToolContainer.RegisterTool(TRectangleTool);
ToolContainer.RegisterTool(TEllipseTool);
ToolContainer.RegisterTool(TRoundRectTool);
ToolContainer.RegisterTool(TZoomInTool);
ToolContainer.RegisterTool(TZoomOutTool);
ToolContainer.RegisterTool(THandTool);
ToolContainer.RegisterTool(TRectangleZoomTool);
ToolContainer.RegisterTool(TSelectionTool);
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.RegularExpressions, Vcl.StdCtrls,
System.DateUtils;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
regex: TRegEx;
s: string;
Arquivo: TStringList;
t0: TDateTime;
begin
Arquivo := TStringList.Create;
// Arquivo.Text := '"comment": "Esquina Do Posto Ipiranga. Pen\última Casa Do Lado Esquerdo. Portão De Madeira Escrito \"Deus É Fiel\"",'+
// '"first_name": "Gu\ri de \Uruguiana",'+
// '"last_name": "Guri\",';
Arquivo.LoadFromFile('D:\Luci\RegexTest\JsonComBarra2.json');
s := Arquivo.Text;
t0 := MilliSecondsBetween(Now, 0);
s := TRegEx.Replace(s, '(\\")', '"');
s := TRegEx.Replace(s, '\\(?!")', '');
Memo1.Lines.Add(FloatToStr(MilliSecondsBetween(Now, 0)-t0));
s := Arquivo.Text;
t0 := MilliSecondsBetween(Now, 0);
s := StringReplace(s, '\"', '"', [rfReplaceAll]);
s := StringReplace(s, '\\(?!")', '', [rfReplaceAll]);
Memo1.Lines.Add(FloatToStr(MilliSecondsBetween(Now, 0)-t0));
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Vcl.HtmlHelpViewer;
{ ************************************************************************ }
{ }
{ This unit implements a help viewer for the 32-bit windows Html help API. }
{ The design goal is for this unit to be indistinguishable from other }
{ viewers as far as the VCL help manager can determine. Accordingly, at }
{ at this time, it only wraps those features of the HtmlHelp API which are }
{ used by the help system implemented in HelpIntfs.pas. }
{ }
{ This unit is intended for use from within 32-bit windows applications. }
{ It does not wrap the .NET interface to the HtmlHelp API. }
{ }
{ Because Microsoft HtmlHelp does not support direct querying without }
{ displaying results, it is necessary for the HtmlHelp viewer to maintain }
{ topic, keyword, and alink lists itself. In the case of the built-in IDE }
{ help viewer, this list is drawn out of the .ALS file, and the analysis }
{ of this list is delegated to an implementation of IHtmlHelp tester }
{ (which is analagous to IWinHelpTester in WinHelpViewer.pas). Individual }
{ applications wishing to support this functionality must implement }
{ IHtmlHelpTester themselves. Absent an implementation of IHtmlHelpTester, }
{ the HtmlHelp viewer will *always* assume that the query should succeed }
{ and HtmlHelp can be asked to provide help. }
{ }
{ Note that this means that an application which uses both WinHelpViewer }
{ and HtmlHelpViewer MUST implement either IWinHelpTester, IHtmlHelpTester,}
{ or both, in order to avoid both the HtmlHelp Viewer and the WinHelp }
{ Viewer from attempting to act as a default viewer. The behavior of }
{ default viewers may be open for review in future revisions of the RTL. }
{ }
{ ************************************************************************ }
interface
uses System.Classes;
{ Because HtmlHelp is uncooperative about responding to queries along the
lines of 'do you support this', the HtmlHelp viewer in essence needs to
hack a response to that. This interface is a hook by which user applications
can override the HtmlHelp viewer's default answer. }
type
IHtmlHelpTester = interface(IInterface)
['{82DF78E6-B675-4F5D-8A5B-F9BEEDDC14F6}']
function CanShowALink(const ALink, FileName: string): Boolean;
function CanShowTopic(const Topic, FileName: string): Boolean;
function CanShowContext(const Context: Integer;
const FileName: string): Boolean;
function GetHelpStrings(const ALink: string): TStringList;
function GetHelpPath: string;
function GetDefaultHelpFile: string;
function ConvertWinHelp(var Command: Word; var Data: NativeUInt): Boolean;
end;
var
HtmlHelpTester: IHtmlHelpTester;
ViewerName: string;
{ =========================================================================== }
implementation
uses
{$IF DEFINED(CLR)}
System.Runtime.InteropServices,
{$IFEND}
System.HelpIntfs, System.SysUtils, Winapi.Windows;
type
THTMLHelpViewer = class(TInterfacedObject, ICustomHelpViewer,
IExtendedHelpViewer, IExtendedHelpViewer2, ISpecialWinHelpViewer)
private
FViewerID: Integer;
{ fields used to handle popup configuration }
FTopCenter: TPoint;
FForeground: TColorRef;
FBackground: TColorRef;
FMargins: TRect;
FFontDesc: string;
FPopupResourceHandle: HWND;
FPopupResourceID: LongInt;
FPopupText: string;
FInitialized: Boolean;
FHelpManager: IHelpManager;
procedure ValidateHelpViewer;
{$IF DEFINED(CLR)}
strict protected
procedure Finalize; override;
{$IFEND}
public
constructor Create;
destructor Destroy; override;
{ internal support functions }
function GetHelpFile(const Name: string): string;
procedure InternalShutDown;
procedure SynchTopic(Handle: HWND; const HelpFileName: string);
{$IF DEFINED(CLR)}
procedure LookupALink(Handle: HWND; const HelpFileName: string;
LinkPtr: HH_AkLink); overload;
procedure LookupALink(Handle: HWND; const HelpFileName: string;
LinkPtr: DWORD); overload;
procedure LookupKeyword(Handle: HWND; const HelpFileName: string;
LinkPtr: HH_AKLink); overload;
procedure LookupKeyword(Handle: HWND; const HelpFileName: string;
LinkPtr: DWORD); overload;
procedure DisplayTextPopup(Handle: HWND; Data: HH_Popup); overload;
procedure DisplayTextPopup(Handle: HWND; Data: NativeUInt); overload;
{$ELSE}
procedure LookupALink(Handle: HWND; const HelpFileName: string;
LinkPtr: PHH_AkLink);
procedure LookupKeyword(Handle: HWND; const HelpFileName: string;
LinkPtr: PHH_AKLink);
procedure DisplayTextPopup(Handle: HWND; Data: PHH_Popup);
{$IFEND}
{ ICustomHelpViewer }
function GetViewerName : string;
function UnderstandsKeyword(const HelpString: string): Integer;
function GetHelpStrings(const HelpString: string): TStringList;
function CanShowTableOfContents: Boolean;
procedure ShowTableOfContents;
procedure ShowHelp(const HelpString: string);
procedure NotifyID(const ViewerID: Integer);
procedure SoftShutDown;
procedure ShutDown;
{ IExtendedHelpViewer }
function UnderstandsTopic(const Topic: string): Boolean;
procedure DisplayTopic(const Topic: string); overload;
function UnderstandsContext(const ContextID: Integer;
const HelpFileName: string): Boolean;
procedure DisplayHelpByContext(const ContextId: Integer;
const HelpFileName: string);
{ ISpecialHtmlHelpViewer }
function CallHtmlHelp(Handle: HWND; HelpFileName: string;
Command: Integer; Data: NativeUInt): HWND;
{ IExtendedHelpViewer2 }
procedure DisplaySearch(const Topic: string);
procedure DisplayIndex(const Topic: string);
procedure DisplayTopic(const Topic, Anchor: string); overload;
{ IPopupHelp }
procedure SetupPopupWindow(TopCenter: TPoint; Foreground, Background: DWord;
Margins: TRect; const FontDesc: string);
procedure SetupPopupSource(Handle: HWND; ID: LongInt; const Text: string);
procedure Popup(KeepWindowSetup: Boolean; KeepSourceSetup: Boolean);
procedure ClearSetup;
{ ISpecialWinHelpViewer }
function CallWinHelp(Handle: THandle; const HelpFileName: string;
Command: Word; Data: NativeUInt) : Boolean;
{ properties }
property ViewerID : Integer read FViewerID;
property HelpManager : IHelpManager read FHelpManager write FHelpManager;
property TopCenter: TPoint read FTopCenter write FTopCenter;
property Foreground: TColorRef read FForeground write FForeground;
property Background: TColorRef read FBackground write FBackground;
property Margins: TRect read FMargins write FMargins;
property FontDesc: string read FFontDesc write FFontDesc;
property PopupResourceHandle: HWND read FPopupResourceHandle write FPopupResourceHandle;
property PopupResourceId: LongInt read FPopupResourceId write FPopupResourceId;
property PopupText: string read FPopupText write FPopupText;
end;
var
HelpViewer: THtmlHelpViewer;
HelpViewerIntf: ICustomHelpViewer;
{$IF DEFINED(CLR)}
FInitializedCookie: DWORD_PTR;
{$ELSE}
FInitializedCookie: LongInt;
{$IFEND}
procedure THtmlHelpViewer.ValidateHelpViewer;
begin
{ commented out to allow an error message for the field test. when help is
delivered, restore this. ALSO, note, that checking for the return from
HH_INITIALIZE appears to be wrong, and the raise should remain commented
out: HH_INITIALIZE always returns 0 and fails to set the cookie. }
if not FInitialized then
begin
{$IF DEFINED(CLR)}
HtmlHelp(0, nil, HH_INITIALIZE, FInitializedCookie);
{$ELSE}
HtmlHelp(0, nil, HH_INITIALIZE, DWORD_PTR(@FInitializedCookie));
{$IFEND}
if FInitializedCookie = 0 then
begin
//raise EHelpSystemException.CreateRes(@hNoHtmlHelp);
end;
FInitialized := True;
end;
//raise EHelpSystemException.CreateRes(@hNoHelpInThisRelease);
end;
{ ICustomHelpViewer. }
{ GetViewerName returns a string that the Help Manager can use to identify
this Viewer in a UI element asking users to choose among Viewers. }
function THtmlHelpViewer.GetViewerName: string;
begin
Result := ViewerName;
end;
{ UnderstandsKeyword is a querying function that the Help Manager calls to
determine if the Viewer provide helps on a particular keyword string. }
function THtmlHelpViewer.UnderstandsKeyword(const HelpString: string): Integer;
var
CanShowHelp : Boolean;
HelpFile: string;
begin
HelpFile := GetHelpFile('');
Result := 1;
if Assigned(HtmlHelpTester) then
begin
CanShowHelp := HtmlHelpTester.CanShowALink(HelpString, HelpFile);
if not CanShowHelp then Result := 0;
end;
end;
{ GetHelpStrings is used by the Help Manager to display a list of keyword
matches from which an application's user can select one. It assumes
that the String List is properly allocated, so this function should
never return nil. }
function THtmlHelpViewer.GetHelpStrings(const HelpString: string): TStringList;
begin
if Assigned(HtmlHelpTester) then
Result := HtmlHelpTester.GetHelpStrings(HelpString)
else begin
Result := TStringList.Create;
Result.Add(GetViewerName + ': ' + HelpString);
end;
end;
{ CanShowTableOfContents is a querying function that the Help Manager
calls to determine if the Viewer supports tables of contents. HtmlHelp does. }
function THtmlHelpViewer.CanShowTableOfContents: Boolean;
begin
Result := True;
end;
{ ShowTableOfContents is a command function that the Help Manager uses
to direct the Viewer to display a table of contents. It is never
called without being preceded by a call to CanShowTableOfContents. }
procedure THtmlHelpViewer.ShowTableOfContents;
var
FileName : string;
Handle: HWND;
begin
ValidateHelpViewer;
FileName := GetHelpFile('');
Handle := HelpManager.GetHandle;
SynchTopic(Handle, FileName);
HtmlHelp(Handle, FileName, HH_DISPLAY_TOPIC, 0);
end;
procedure THtmlHelpViewer.ShowHelp(const HelpString: string);
var
FileName : string;
Link: THH_AKLink;
begin
ValidateHelpViewer;
FileName := GetHelpFile('');
{$IF DEFINED(CLR)}
Link.cbStruct := Marshal.SizeOf(TypeOf(THH_AKLink));
Link.pszKeywords := HelpString;
{$ELSE}
Link.cbStruct := SizeOf(THH_AKLink);
Link.pszKeywords := PChar(HelpString);
{$IFEND}
Link.fReserved := false;
Link.pszUrl := nil;
Link.pszMsgText := nil;
Link.pszMsgTitle := nil;
Link.pszWindow := nil;
Link.fIndexOnFail := True;
LookupKeyword(HelpManager.GetHandle, FileName, {$IFNDEF CLR}@{$ENDIF}Link);
end;
{ NotifyID is called by the Help Manager after a successful registration
to provide the Help Viewer with a cookie which uniquely identifies the
Viewer to the Manager, and can be used in communications between the two. }
procedure THtmlHelpViewer.NotifyId(const ViewerId: Integer);
begin
FViewerID := ViewerID;
end;
{ SoftShutDown is called by the help manager to ask the viewer to
terminate any externally spawned subsystem without shutting itself down. }
procedure THtmlHelpViewer.SoftShutDown;
begin
if FInitialized then
HtmlHelp(0, nil, HH_CLOSE_ALL, 0);
end;
procedure THtmlHelpViewer.ShutDown;
begin
SoftShutDown;
if FInitialized then
begin
{$IF DEFINED(CLR)}
HtmlHelp(0, nil, HH_UNINITIALIZE, FInitializedCookie);
{$ELSE}
HtmlHelp(0, nil, HH_UNINITIALIZE, DWORD_PTR(@FInitializedCookie));
{$IFEND}
FInitialized := false;
FInitializedCookie := 0;
end;
if Assigned(FHelpManager) then HelpManager := nil;
if Assigned(HtmlHelpTester) then HtmlHelpTester := nil;
end;
{ IExtendedHelpViewer }
{ UnderstandsTopic is called by the Help Manager to ask if the Viewer
is capable of displaying a topic-based help query for a given topic.
It's default behavior is to say 'yes'. }
function THtmlHelpVIewer.UnderstandsTopic(const Topic: string): Boolean;
var
HelpFile: string;
begin;
HelpFile := GetHelpFile('');
if Assigned(HtmlHelpTester) then
Result := HtmlHelpTester.CanShowTopic(Topic, HelpFile)
else
Result := True;
end;
{ DisplayTopic is called by the Help Manager if a Help Viewer claims
in its response to UnderstandsTopic to be able to provide Topic-based
help for a particular keyword. }
procedure THtmlHelpViewer.DisplayTopic(const Topic: string);
const
InvokeSep = '::/';
InvokeSuf = '.htm';
var
HelpFile: string;
InvocationString: string;
begin
ValidateHelpViewer;
HelpFile := GetHelpFile('');
InvocationString := HelpFile + InvokeSep + Topic + InvokeSuf;
HtmlHelp(HelpManager.GetHandle, InvocationString, HH_DISPLAY_TOPIC, 0);
end;
{ UnderstandsContext is a querying function called by the Help Manager
to determine if an Extended Help Viewer is capable of providing
help for a particular context-ID. Like all querying functions in
this file, the default behavior is to say 'yes' unless overridden by
a Tester. }
function THtmlHelpViewer.UnderstandsContext(const ContextId: Integer;
const HelpFileName: string): Boolean;
begin
Result := True;
if Assigned(HtmlHelpTester) then
Result := HtmlHelpTester.CanShowContext(ContextId, GetHelpFile(HelpFileName));
end;
{ DisplayHelpByContext is used by the Help Manager to request that a
Help Viewer display help for a particular Context-ID. It is only
invoked after a successful call to CanShowContext. }
procedure THtmlHelpviewer.DisplayHelpByContext(const ContextId: Integer;
const HelpFileName: string);
var
Handle: HWND;
FileName: string;
begin
ValidateHelpViewer;
FileName := GetHelpFile(HelpFileName);
Handle := HelpManager.GetHandle;
SynchTopic(Handle, FileName);
HtmlHelp(Handle, FileName, HH_HELP_CONTEXT, ContextId);
end;
{ ISpecialWinHelpViewer }
{ This function reveals a design flaw in the D6/7 help system. :(
ISpecialWinHelpViewer.CallWinHelp is intended to allow third-party
help systems to process WinHelp messages which were not generalizable
by the system designer. In this case, the expected behavior would be
to convert WinHelp messages into HtmlHelp messages and forward them
along.
However, the same necessity that compels developers to be able to send
non-generalizable winhelp messages also compels the ability to send
non-generalizable htmlhelp messages. There is no mechanism in the
existing architecture to do that.
The function signature for WinHelp() and HtmlHelp() are sufficiently
similar, however, to allow the function to multiplex. Depending on the
answer provided by an implementation of IHtmlHelpTester, the function
will either convert messages (under the assumption that they are
WinHelp messages) or pass them through (under the assumption that they
are HtmlHelp messages).
The need for this should be resolved in the next revision of the RTL, but
this function will continue to behave that way for purposes of backwards
compatability. }
function THtmlHelpViewer.CallWinHelp(Handle: THandle; const HelpFileName: string; Command: Word; Data: NativeUInt): Boolean;
var
Converted : Boolean;
FileName: string;
begin
ValidateHelpViewer;
Result := false;
FileName := GetHelpFile(HelpFileName);
if FileName <> '' then
begin
if Assigned(HtmlHelpTester) then
Converted := HtmlHelpTester.ConvertWinHelp(Command, Data)
else
Converted := False;
if not Converted then
// Before giving up, lets try to translate some basic
// WinHelp commands to their HtmlHelp equivalents
case Command of
HELP_CONTEXT: Command := HH_HELP_CONTEXT;
HELP_QUIT: Command := HH_CLOSE_ALL;
HELP_INDEX: Command := HH_DISPLAY_INDEX;
HELP_HELPONHELP: Command := HH_DISPLAY_INDEX;
HELP_FINDER: Command := HH_DISPLAY_TOC;
else
Exit;
end;
CallHtmlHelp(Handle, FileName, Command, Data);
Result := True;
end;
end;
{ ISpecialHtmlHelpViewer }
function THtmlHelpViewer.CallHtmlHelp(Handle: HWND; HelpFileName: string;
Command: Integer; Data: NativeUInt): HWND;
begin
ValidateHelpViewer;
Result := 0;
case Command of
HH_CLOSE_ALL:
begin
SoftShutDown;
end;
HH_DISPLAY_TEXT_POPUP:
begin
{$IF DEFINED(CLR)}
DisplayTextPopup(Handle, Data);
{$ELSE}
DisplayTextPopup(Handle, PHH_Popup(Data));
{$IFEND}
end;
HH_HELP_CONTEXT:
begin
DisplayHelpByContext(Data, HelpFileName);
end;
HH_ALINK_LOOKUP:
begin
{$IF DEFINED(CLR)}
LookupALink(Handle, HelpFileName, Data);
{$ELSE}
LookupALink(Handle, HelpFileName, PHH_AkLink(Data));
{$IFEND}
end;
{ DisplayIndex, DisplaySearch, DisplayToc }
else
begin
SynchTopic(Handle, HelpFileName);
Result := HtmlHelp(Handle, HelpFileName, Command, Data);
end;
end;
end;
{ IExtendedHelpViewer2 }
procedure THtmlHelpViewer.DisplayIndex(const Topic: string);
var
HelpFile: string;
begin
ValidateHelpViewer;
HelpFile := GetHelpFile('');
HtmlHelp(HelpManager.GetHandle, HelpFile, HH_DISPLAY_INDEX, Topic);
end;
procedure THtmlHelpViewer.DisplaySearch(const Topic: string);
var
HelpFile: string;
Query: HH_FTS_QUERY;
begin
ValidateHelpViewer;
HelpFile := GetHelpFile('');
{$IF DEFINED(CLR)}
Query.cbStruct := Marshal.SizeOf(TypeOf(Query));
Query.pszSearchQuery := Topic;
{$ELSE}
FillChar(Query, SizeOf(Query), 0);
Query.cbStruct := SizeOf(Query);
Query.pszSearchQuery := PChar(Topic);
{$IFEND}
Query.fUniCodeStrings := True;
Query.iProximity := -1;
Query.fStemmedSearch := False;
Query.fTitleOnly := False;
Query.fExecute := True;
Query.pszWindow := nil;
//Note: There is a bug in the Windows SDK call HtmlHelp(). Even though
// fExecute is set to true, the search is not executed. The following
// webpage has more info:
// http://support.microsoft.com/kb/q241381/
HtmlHelp(HelpManager.GetHandle, HelpFile, HH_DISPLAY_SEARCH, Query);
end;
procedure THtmlHelpViewer.DisplayTopic(const Topic, Anchor: string);
const
InvokeSep = '::/';
InvokeSuf = '.htm';
AnchorSep = '#';
var
HelpFile: string;
InvocationString: string;
begin
ValidateHelpViewer;
HelpFile := GetHelpFile('');
InvocationString := HelpFile + InvokeSep + Topic + InvokeSuf + AnchorSep + Anchor;
HtmlHelp(HelpManager.GetHandle, InvocationString, HH_DISPLAY_TOPIC, 0);
end;
{ IPopupHelp }
procedure THtmlHelpViewer.SetupPopupWindow(TopCenter: TPoint;
Foreground, Background: DWord;
Margins: TRect;
const FontDesc: string);
begin
Self.TopCenter := TopCenter;
Self.Foreground := Foreground;
Self.Background := Background;
Self.Margins := Margins;
Self.FontDesc := FontDesc;
end;
procedure THtmlHelpVIewer.SetupPopupSource(Handle: HWND; ID: LongInt;
const Text: string);
begin
Self.PopupResourceHandle := Handle;
Self.PopupResourceId := ID;
Self.PopupText := Text;
end;
procedure THtmlHelpViewer.Popup(KeepWindowSetup: Boolean;
KeepSourceSetup: Boolean);
begin
{ execute popup call }
if not KeepWindowSetup then
begin
end;
if not KeepSourceSetup then
begin
end;
end;
procedure THtmlHelpViewer.ClearSetup;
begin
end;
{==========================================================================}
procedure THtmlHelpViewer.SynchTopic(Handle: HWND; const HelpFileName: string);
begin
HtmlHelp(Handle, HelpFileName, HH_DISPLAY_TOPIC, 0);
end;
{$IF DEFINED(CLR)}
procedure THtmlHelpViewer.LookupALink(Handle: HWND;
const HelpFileName: string; LinkPtr: HH_AkLink);
begin
HtmlHelp(Handle, HelpFileName, HH_ALINK_LOOKUP, LinkPtr);
end;
procedure THtmlHelpViewer.LookupALink(Handle: HWND;
const HelpFileName: string; LinkPtr: DWORD);
begin
HtmlHelp(Handle, HelpFileName, HH_ALINK_LOOKUP, LinkPtr);
end;
procedure THtmlHelpViewer.LookupKeyword(Handle: HWND;
const HelpFileName: string; LinkPtr: HH_AkLink);
begin
HtmlHelp(Handle, HelpFileName, HH_KEYWORD_LOOKUP, LinkPtr);
end;
procedure THtmlHelpViewer.LookupKeyword(Handle: HWND;
const HelpFileName: string; LinkPtr: DWORD);
begin
HtmlHelp(Handle, HelpFileName, HH_KEYWORD_LOOKUP, LinkPtr);
end;
procedure THtmlHelpViewer.DisplayTextPopup(Handle: HWND; Data: HH_Popup);
var
FileName: string;
begin
HtmlHelp(Handle, FileName, HH_DISPLAY_TEXT_POPUP, Data);
end;
procedure THtmlHelpViewer.DisplayTextPopup(Handle: HWND; Data: NativeUInt);
var
FileName: string;
begin
HtmlHelp(Handle, FileName, HH_DISPLAY_TEXT_POPUP, Data);
end;
{$ELSE}
procedure THtmlHelpViewer.LookupALink(Handle: HWND;
const HelpFileName: string; LinkPtr: PHH_AkLink);
begin
HtmlHelp(Handle, PChar(HelpFileName), HH_ALINK_LOOKUP, DWORD_PTR(LinkPtr));
end;
procedure THtmlHelpViewer.LookupKeyword(Handle: HWND;
const HelpFileName: string; LinkPtr: PHH_AkLink);
begin
HtmlHelp(Handle, PChar(HelpFileName), HH_KEYWORD_LOOKUP, DWORD_PTR(LinkPtr));
end;
procedure THtmlHelpViewer.DisplayTextPopup(Handle: HWND; Data: PHH_Popup);
var
FileName: string;
begin
HtmlHelp(Handle, PChar(FileName), HH_DISPLAY_TEXT_POPUP, DWORD_PTR(Data));
end;
{$IFEND}
constructor THtmlHelpViewer.Create;
begin
inherited Create;
HelpViewerIntf := Self;
FInitialized := False;
FInitializedCookie := 0;
ClearSetup;
end;
destructor THtmlHelpViewer.Destroy;
begin
HelpViewer := nil;
inherited Destroy;
end;
function THtmlHelpViewer.GetHelpFile(const Name: string): string;
var
FileName: string;
begin
Result := '';
if (Name = '') and Assigned(FHelpManager) then
FileName := HelpManager.GetHelpFile
else
FileName := Name;
if (FileName = '') and Assigned(HtmlHelpTester) then
FileName := HtmlHelpTester.GetDefaultHelpFile;
if Assigned(HtmlHelpTester) then
FileName := HtmlHelpTester.GetHelpPath + PathDelim + FileName;
Result := FileName;
end;
procedure THtmlHelpViewer.InternalShutDown;
begin
SoftShutDown;
if Assigned(FHelpManager) then
begin
HelpManager.Release(ViewerID);
HelpManager := nil;
end;
end;
{$IF DEFINED(CLR)}
procedure THTMLHelpViewer.Finalize;
begin
InternalShutDown;
end;
{$IFEND}
initialization
HelpViewer := THtmlHelpViewer.Create;
System.HelpIntfs.RegisterViewer(HelpViewerIntf, HelpViewer.FHelpManager);
{$IF NOT DEFINED(CLR)}
finalization
if Assigned(HelpViewer.HelpManager) then
HelpViewer.InternalShutDown;
HelpViewerIntf := nil;
HtmlHelpTester := nil;
{$IFEND}
end.
|
unit BCEditor.Print.HeaderFooter;
interface
uses
Windows, Classes, SysUtils, Graphics, BCEditor.Print.Types, BCEditor.Print.Margins,
BCEditor.Utils;
type
TBCEditorSectionItem = class
strict private
FAlignment: TAlignment;
FFont: TFont;
FIndex: Integer;
FLineNumber: Integer;
FText: string;
procedure SetFont(const Value: TFont);
public
constructor Create;
destructor Destroy; override;
function GetText(NumberOfPages, PageNum: Integer; Roman: Boolean; Title, ATime, ADate: string): string;
procedure LoadFromStream(AStream: TStream);
procedure SaveToStream(AStream: TStream);
public
property Alignment: TAlignment read FAlignment write FAlignment;
property Font: TFont read FFont write SetFont;
property Index: Integer read FIndex write FIndex;
property LineNumber: Integer read FLineNumber write FLineNumber;
property Text: string read FText write FText;
end;
TBCEditorSectionType = (stHeader, stFooter);
TBCEditorLineInfo = class
public
LineHeight: Integer;
MaxBaseDist: Integer;
end;
TBCEditorSection = class(TPersistent)
strict private
FDate: string;
FDefaultFont: TFont;
FFrameHeight: Integer;
FFrameTypes: TBCEditorFrameTypes;
FItems: TList;
FLineColor: TColor;
FLineCount: Integer;
FLineInfo: TList;
FMargins: TBCEditorPrintMargins;
FMirrorPosition: Boolean;
FNumberOfPages: Integer;
FOldBrush: TBrush;
FOldFont: TFont;
FOldPen: TPen;
FRomanNumbers: Boolean;
FShadedColor: TColor;
FTime: string;
FTitle: string;
FSectionType: TBCEditorSectionType;
procedure CalculateHeight(ACanvas: TCanvas);
procedure DrawFrame(ACanvas: TCanvas);
procedure RestoreFontPenBrush(ACanvas: TCanvas);
procedure SaveFontPenBrush(ACanvas: TCanvas);
procedure SetDefaultFont(const Value: TFont);
public
constructor Create;
destructor Destroy; override;
function Add(Text: string; Font: TFont; Alignment: TAlignment; LineNumber: Integer): Integer;
function Count: Integer;
function Get(Index: Integer): TBCEditorSectionItem;
procedure Assign(Source: TPersistent); override;
procedure Clear;
procedure Delete(Index: Integer);
procedure FixLines;
procedure InitPrint(ACanvas: TCanvas; NumberOfPages: Integer; Title: string; Margins: TBCEditorPrintMargins);
procedure LoadFromStream(AStream: TStream);
procedure Print(ACanvas: TCanvas; PageNum: Integer);
procedure SaveToStream(AStream: TStream);
procedure SetPixelsPerInch(Value: Integer);
property SectionType: TBCEditorSectionType read FSectionType write FSectionType;
published
property DefaultFont: TFont read FDefaultFont write SetDefaultFont;
property FrameTypes: TBCEditorFrameTypes read FFrameTypes write FFrameTypes default [ftLine];
property LineColor: TColor read FLineColor write FLineColor default clBlack;
property MirrorPosition: Boolean read FMirrorPosition write FMirrorPosition default False;
property RomanNumbers: Boolean read FRomanNumbers write FRomanNumbers default False;
property ShadedColor: TColor read FShadedColor write FShadedColor default clSilver;
end;
TBCEditorPrintHeader = class(TBCEditorSection)
public
constructor Create;
end;
TBCEditorPrintFooter = class(TBCEditorSection)
public
constructor Create;
end;
implementation
uses
Math, BCEditor.Consts;
{ TBCEditorSectionItem }
constructor TBCEditorSectionItem.Create;
begin
inherited;
FFont := TFont.Create;
end;
destructor TBCEditorSectionItem.Destroy;
begin
inherited;
FFont.Free;
end;
function TBCEditorSectionItem.GetText(NumberOfPages, PageNum: Integer; Roman: Boolean; Title, ATime, ADate: string): string;
var
LLength, Start, Run: Integer;
LString: string;
procedure DoAppend(AText: string);
begin
Result := Result + AText;
end;
procedure TryAppend(var First: Integer; After: Integer);
begin
if After > First then
begin
DoAppend(Copy(LString, First, After - First));
First := After;
end;
end;
function TryExecuteMacro: Boolean;
var
Macro: string;
begin
Result := True;
Macro := UpperCase(Copy(FText, Start, Run - Start + 1));
if Macro = '$PAGENUM$' then
begin
if Roman then
DoAppend(IntToRoman(PageNum))
else
DoAppend(IntToStr(PageNum));
Exit;
end;
if Macro = '$PAGECOUNT$' then
begin
if Roman then
DoAppend(IntToRoman(NumberOfPages))
else
DoAppend(IntToStr(NumberOfPages));
Exit;
end;
if Macro = '$TITLE$' then
begin
DoAppend(Title);
Exit;
end;
if Macro = '$DATE$' then
begin
DoAppend(ADate);
Exit;
end;
if Macro = '$TIME$' then
begin
DoAppend(ATime);
Exit;
end;
if Macro = '$DATETIME$' then
begin
DoAppend(ADate + ' ' + ATime);
Exit;
end;
if Macro = '$TIMEDATE$' then
begin
DoAppend(ATime + ' ' + ADate);
Exit;
end;
Result := False;
end;
begin
Result := '';
LString := FText;
if Trim(LString) = '' then
Exit;
LLength := Length(LString);
if LLength > 0 then
begin
Start := 1;
Run := 1;
while Run <= LLength do
begin
if LString[Run] = '$' then
begin
TryAppend(Start, Run);
Inc(Run);
while Run <= LLength do
begin
if LString[Run] = '$' then
begin
if TryExecuteMacro then
begin
Inc(Run);
Start := Run;
break;
end
else
begin
TryAppend(Start, Run);
Inc(Run);
end;
end
else
Inc(Run);
end;
end
else
Inc(Run);
end;
TryAppend(Start, Run);
end;
end;
procedure TBCEditorSectionItem.LoadFromStream(AStream: TStream);
var
LCharset: TFontCharset;
LColor: TColor;
LHeight: Integer;
LName: TFontName;
LPitch: TFontPitch;
LSize: Integer;
LStyle: TFontStyles;
LLength, BufferSize: Integer;
LBuffer: Pointer;
begin
with AStream do
begin
Read(LLength, sizeof(LLength));
BufferSize := LLength * sizeof(Char);
GetMem(LBuffer, BufferSize + sizeof(Char));
try
Read(LBuffer^, BufferSize);
PChar(LBuffer)[BufferSize div sizeof(Char)] := BCEDITOR_NONE_CHAR;
FText := PChar(LBuffer);
finally
FreeMem(LBuffer);
end;
Read(FLineNumber, SizeOf(FLineNumber));
Read(LCharset, SizeOf(lCharset));
Read(LColor, SizeOf(LColor));
Read(LHeight, SizeOf(LHeight));
Read(BufferSize, SizeOf(BufferSize));
GetMem(LBuffer, BufferSize + 1);
try
Read(LBuffer^, BufferSize);
PAnsiChar(LBuffer)[BufferSize div SizeOf(AnsiChar)] := BCEDITOR_NONE_CHAR;
LName := string(PAnsiChar(LBuffer));
finally
FreeMem(LBuffer);
end;
Read(LPitch, SizeOf(LPitch));
Read(LSize, SizeOf(LSize));
Read(LStyle, SizeOf(LStyle));
FFont.Charset := LCharset;
FFont.Color := LColor;
FFont.Height := LHeight;
FFont.Name := LName;
FFont.Pitch := LPitch;
FFont.Size := LSize;
FFont.Style := LStyle;
Read(FAlignment, SizeOf(FAlignment));
end;
end;
procedure TBCEditorSectionItem.SaveToStream(AStream: TStream);
var
LCharset: TFontCharset;
LColor: TColor;
LHeight: Integer;
LName: TFontName;
LPitch: TFontPitch;
LSize: Integer;
LStyle: TFontStyles;
LLength: Integer;
begin
with AStream do
begin
LLength := Length(FText);
Write(LLength, SizeOf(LLength));
Write(PChar(FText)^, LLength * SizeOf(Char));
Write(FLineNumber, SizeOf(FLineNumber));
lCharset := FFont.Charset;
LColor := FFont.Color;
LHeight := FFont.Height;
LName := FFont.Name;
LPitch := FFont.Pitch;
LSize := FFont.Size;
LStyle := FFont.Style;
Write(LCharset, SizeOf(LCharset));
Write(LColor, SizeOf(LColor));
Write(LHeight, SizeOf(LHeight));
LLength := Length(LName);
Write(LLength, SizeOf(LLength));
Write(PAnsiChar(AnsiString(LName))^, LLength);
Write(LPitch, SizeOf(LPitch));
Write(LSize, SizeOf(LSize));
Write(LStyle, SizeOf(LStyle));
Write(FAlignment, SizeOf(FAlignment));
end;
end;
procedure TBCEditorSectionItem.SetFont(const Value: TFont);
begin
FFont.Assign(Value);
end;
{ TBCEditorSection }
constructor TBCEditorSection.Create;
begin
inherited;
FFrameTypes := [ftLine];
FShadedColor := clSilver;
FLineColor := clBlack;
FItems := TList.Create;
FDefaultFont := TFont.Create;
FOldPen := TPen.Create;
FOldBrush := TBrush.Create;
FOldFont := TFont.Create;
FRomanNumbers := False;
FMirrorPosition := False;
FLineInfo := TList.Create;
with FDefaultFont do
begin
Name := 'Courier New';
Size := 9;
Color := clBlack;
end;
end;
destructor TBCEditorSection.Destroy;
var
i: Integer;
begin
Clear;
FItems.Free;
FDefaultFont.Free;
FOldPen.Free;
FOldBrush.Free;
FOldFont.Free;
for i := 0 to FLineInfo.Count - 1 do
TBCEditorLineInfo(FLineInfo[i]).Free;
FLineInfo.Free;
inherited;
end;
function TBCEditorSection.Add(Text: string; Font: TFont; Alignment: TAlignment; LineNumber: Integer): Integer;
var
SectionItem: TBCEditorSectionItem;
begin
SectionItem := TBCEditorSectionItem.Create;
if not Assigned(Font) then
SectionItem.Font := FDefaultFont
else
SectionItem.Font := Font;
SectionItem.Alignment := Alignment;
SectionItem.LineNumber := LineNumber;
SectionItem.Index := FItems.Add(SectionItem);
SectionItem.Text := Text;
Result := SectionItem.Index;
end;
procedure TBCEditorSection.Delete(Index: Integer);
var
i: Integer;
begin
for i := 0 to FItems.Count - 1 do
if TBCEditorSectionItem(FItems[i]).Index = index then
begin
FItems.Delete(i);
break;
end;
end;
procedure TBCEditorSection.Clear;
var
i: Integer;
begin
for i := 0 to FItems.Count - 1 do
TBCEditorSectionItem(FItems[i]).Free;
FItems.Clear;
end;
procedure TBCEditorSection.SetDefaultFont(const Value: TFont);
begin
FDefaultFont.Assign(Value);
end;
procedure TBCEditorSection.FixLines;
var
i, CurrentLine: Integer;
LineInfo: TBCEditorLineInfo;
begin
for i := 0 to FLineInfo.Count - 1 do
TBCEditorLineInfo(FLineInfo[i]).Free;
FLineInfo.Clear;
CurrentLine := 0;
FLineCount := 0;
for i := 0 to FItems.Count - 1 do
begin
if TBCEditorSectionItem(FItems[i]).LineNumber <> CurrentLine then
begin
CurrentLine := TBCEditorSectionItem(FItems[i]).LineNumber;
FLineCount := FLineCount + 1;
LineInfo := TBCEditorLineInfo.Create;
FLineInfo.Add(LineInfo);
end;
TBCEditorSectionItem(FItems[i]).LineNumber := FLineCount;
end;
end;
procedure TBCEditorSection.CalculateHeight(ACanvas: TCanvas);
var
i, CurrentLine: Integer;
SectionItem: TBCEditorSectionItem;
OrginalHeight: Integer;
TextMetric: TTextMetric;
begin
FFrameHeight := -1;
if FItems.Count <= 0 then
Exit;
CurrentLine := 1;
FFrameHeight := 0;
OrginalHeight := FFrameHeight;
for i := 0 to FItems.Count - 1 do
begin
SectionItem := TBCEditorSectionItem(FItems[i]);
if SectionItem.LineNumber <> CurrentLine then
begin
CurrentLine := SectionItem.LineNumber;
OrginalHeight := FFrameHeight;
end;
ACanvas.Font.Assign(SectionItem.Font);
GetTextMetrics(ACanvas.Handle, TextMetric);
with TBCEditorLineInfo(FLineInfo[CurrentLine - 1]), TextMetric do
begin
LineHeight := Max(LineHeight, TextHeight(ACanvas, 'W'));
MaxBaseDist := Max(MaxBaseDist, tmHeight - tmDescent);
end;
FFrameHeight := Max(FFrameHeight, OrginalHeight + TextHeight(ACanvas, 'W'));
end;
FFrameHeight := FFrameHeight + 2 * FMargins.PixelInternalMargin;
end;
function CompareItems(Item1, Item2: Pointer): Integer;
begin
Result := TBCEditorSectionItem(Item1).LineNumber - TBCEditorSectionItem(Item2).LineNumber;
if Result = 0 then
Result := Integer(Item1) - Integer(Item2);
end;
procedure TBCEditorSection.SetPixelsPerInch(Value: Integer);
var
i, TmpSize: Integer;
LFont: TFont;
begin
for i := 0 to FItems.Count - 1 do
begin
LFont := TBCEditorSectionItem(FItems[i]).Font;
TmpSize := LFont.Size;
LFont.PixelsPerInch := Value;
LFont.Size := TmpSize;
end;
end;
procedure TBCEditorSection.InitPrint(ACanvas: TCanvas; NumberOfPages: Integer; Title: string; Margins: TBCEditorPrintMargins);
begin
SaveFontPenBrush(ACanvas);
FDate := DateToStr(Now);
FTime := TimeToStr(Now);
FNumberOfPages := NumberOfPages;
FMargins := Margins;
FTitle := Title;
FItems.Sort(CompareItems);
FixLines;
CalculateHeight(ACanvas);
RestoreFontPenBrush(ACanvas);
end;
procedure TBCEditorSection.SaveFontPenBrush(ACanvas: TCanvas);
begin
FOldFont.Assign(ACanvas.Font);
FOldBrush.Assign(ACanvas.Brush);
FOldPen.Assign(ACanvas.Pen);
end;
procedure TBCEditorSection.RestoreFontPenBrush(ACanvas: TCanvas);
begin
ACanvas.Font.Assign(FOldFont);
ACanvas.Brush.Assign(FOldBrush);
ACanvas.Pen.Assign(FOldPen);
end;
procedure TBCEditorSection.DrawFrame(ACanvas: TCanvas);
begin
if FrameTypes = [] then
Exit;
with ACanvas, FMargins do
begin
Pen.Color := LineColor;
Brush.Color := ShadedColor;
if ftShaded in FrameTypes then
Brush.Style := bsSolid
else
Brush.Style := bsClear;
if ftBox in FrameTypes then
Pen.Style := psSolid
else
Pen.Style := psClear;
if FrameTypes * [ftBox, ftShaded] <> [] then
begin
if FSectionType = stHeader then
Rectangle(PixelLeft, PixelHeader - FFrameHeight, PixelRight, PixelHeader)
else
Rectangle(PixelLeft, PixelFooter, PixelRight, PixelFooter + FFrameHeight);
end;
if ftLine in FrameTypes then
begin
Pen.Style := psSolid;
if FSectionType = stHeader then
begin
MoveTo(PixelLeft, PixelHeader);
LineTo(PixelRight, PixelHeader);
end
else
begin
MoveTo(PixelLeft, PixelFooter);
LineTo(PixelRight, PixelFooter);
end
end;
end;
end;
procedure TBCEditorSection.Print(ACanvas: TCanvas; PageNum: Integer);
var
i, X, Y, CurrentLine: Integer;
S: string;
SectionItem: TBCEditorSectionItem;
OldAlign: UINT;
LAlignment: TAlignment;
begin
if FFrameHeight <= 0 then
Exit;
SaveFontPenBrush(ACanvas);
DrawFrame(ACanvas);
ACanvas.Brush.Style := bsClear;
if FSectionType = stHeader then
Y := FMargins.PixelHeader - FFrameHeight
else
Y := FMargins.PixelFooter;
Y := Y + FMargins.PixelInternalMargin;
CurrentLine := 1;
for i := 0 to FItems.Count - 1 do
begin
SectionItem := TBCEditorSectionItem(FItems[i]);
ACanvas.Font := SectionItem.Font;
if SectionItem.LineNumber <> CurrentLine then
begin
Y := Y + TBCEditorLineInfo(FLineInfo[CurrentLine - 1]).LineHeight;
CurrentLine := SectionItem.LineNumber;
end;
S := SectionItem.GetText(FNumberOfPages, PageNum, FRomanNumbers, FTitle, FTime, FDate);
LAlignment := SectionItem.Alignment;
if MirrorPosition and ((PageNum mod 2) = 0) then
begin
case SectionItem.Alignment of
taRightJustify:
LAlignment := taLeftJustify;
taLeftJustify:
LAlignment := taRightJustify;
end;
end;
with FMargins do
begin
X := PixelLeftTextIndent;
case LAlignment of
taRightJustify:
X := PixelRightTextIndent - TextWidth(ACanvas, S);
taCenter:
X := (PixelLeftTextIndent + PixelRightTextIndent - TextWidth(ACanvas, S)) div 2;
end;
end;
OldAlign := SetTextAlign(ACanvas.Handle, TA_BASELINE);
ExtTextOut(ACanvas.Handle, X, Y + TBCEditorLineInfo(FLineInfo[CurrentLine - 1]).MaxBaseDist, 0, nil, PChar(S),
Length(S), nil);
SetTextAlign(ACanvas.Handle, OldAlign);
end;
RestoreFontPenBrush(ACanvas);
end;
procedure TBCEditorSection.Assign(Source: TPersistent);
var
i: Integer;
begin
if Assigned(Source) and (Source is TBCEditorSection) then
with Source as TBCEditorSection do
begin
Clear;
Self.FSectionType := FSectionType;
Self.FFrameTypes := FFrameTypes;
Self.FShadedColor := FShadedColor;
Self.FLineColor := FLineColor;
for i := 0 to FItems.Count - 1 do
with TBCEditorSectionItem(FItems[i]) do
Self.Add(Text, Font, Alignment, LineNumber);
Self.FDefaultFont.Assign(FDefaultFont);
Self.FRomanNumbers := FRomanNumbers;
Self.FMirrorPosition := FMirrorPosition;
end
else
inherited Assign(Source);
end;
function TBCEditorSection.Count: Integer;
begin
Result := FItems.Count;
end;
function TBCEditorSection.Get(Index: Integer): TBCEditorSectionItem;
begin
Result := TBCEditorSectionItem(FItems[index]);
end;
procedure TBCEditorSection.LoadFromStream(AStream: TStream);
var
LCount, i: Integer;
LCharset: TFontCharset;
LColor: TColor;
LHeight: Integer;
LName: TFontName;
LPitch: TFontPitch;
LSize: Integer;
LStyle: TFontStyles;
LBufferSize: Integer;
LBuffer: PAnsiChar;
begin
with AStream do
begin
Read(FFrameTypes, SizeOf(FFrameTypes));
Read(FShadedColor, SizeOf(FShadedColor));
Read(FLineColor, SizeOf(FLineColor));
Read(FRomanNumbers, SizeOf(FRomanNumbers));
Read(FMirrorPosition, SizeOf(FMirrorPosition));
Read(LCharset, SizeOf(LCharset));
Read(LColor, SizeOf(LColor));
Read(LHeight, SizeOf(LHeight));
Read(LBufferSize, SizeOf(LBufferSize));
GetMem(LBuffer, LBufferSize + 1);
try
Read(LBuffer^, LBufferSize);
LBuffer[LBufferSize] := BCEDITOR_NONE_CHAR;
LName := string(LBuffer);
finally
FreeMem(LBuffer);
end;
Read(LPitch, SizeOf(LPitch));
Read(LSize, SizeOf(LSize));
Read(LStyle, SizeOf(LStyle));
FDefaultFont.Charset := LCharset;
FDefaultFont.Color := LColor;
FDefaultFont.Height := LHeight;
FDefaultFont.Name := LName;
FDefaultFont.Pitch := LPitch;
FDefaultFont.Size := LSize;
FDefaultFont.Style := LStyle;
Read(LCount, SizeOf(LCount));
while LCount > 0 do
begin
i := Add('', nil, taLeftJustify, 1);
Get(i).LoadFromStream(AStream);
Dec(LCount);
end;
end;
end;
procedure TBCEditorSection.SaveToStream(AStream: TStream);
var
i, LCount: Integer;
LCharset: TFontCharset;
LColor: TColor;
LHeight: Integer;
LName: TFontName;
LPitch: TFontPitch;
LSize: Integer;
LStyle: TFontStyles;
LLength: Integer;
begin
with AStream do
begin
Write(FFrameTypes, SizeOf(FFrameTypes));
Write(FShadedColor, SizeOf(FShadedColor));
Write(FLineColor, SizeOf(FLineColor));
Write(FRomanNumbers, SizeOf(FRomanNumbers));
Write(FMirrorPosition, SizeOf(FMirrorPosition));
LCharset := FDefaultFont.Charset;
LColor := FDefaultFont.Color;
LHeight := FDefaultFont.Height;
LName := FDefaultFont.Name;
LPitch := FDefaultFont.Pitch;
LSize := FDefaultFont.Size;
LStyle := FDefaultFont.Style;
Write(LCharset, SizeOf(LCharset));
Write(LColor, SizeOf(LColor));
Write(LHeight, SizeOf(LHeight));
LLength := Length(LName);
Write(LLength, SizeOf(LLength));
Write(PAnsiChar(AnsiString(LName))^, Length(LName));
Write(LPitch, SizeOf(LPitch));
Write(LSize, SizeOf(LSize));
Write(LStyle, SizeOf(LStyle));
LCount := Count;
Write(LCount, SizeOf(LCount));
for i := 0 to LCount - 1 do
Get(i).SaveToStream(AStream);
end;
end;
{ TBCEditorPrintHeader }
constructor TBCEditorPrintHeader.Create;
begin
inherited;
SectionType := stHeader;
end;
{ TBCEditorPrintFooter }
constructor TBCEditorPrintFooter.Create;
begin
inherited;
SectionType := stFooter;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSAzDlgPage;
interface
uses Vcl.Buttons, System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Forms, Vcl.Graphics, Vcl.StdCtrls, System.SysUtils;
type
TAzPage = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
Bevel1: TBevel;
lbStartByte: TLabel;
edtStartByte: TEdit;
Label1: TLabel;
Label2: TLabel;
edtPageCount: TEdit;
rgOperation: TRadioGroup;
gbCriteria: TGroupBox;
lblMD5: TLabeledEdit;
lblLease: TLabeledEdit;
lblSequence: TLabel;
cbSequenceOp: TComboBox;
edtSequence: TEdit;
Label3: TLabel;
cbSince: TComboBox;
edtSince: TEdit;
lblIf: TLabel;
cbMatch: TComboBox;
edtMatch: TEdit;
lblContentLocation: TLabeledEdit;
btnExplorer: TButton;
procedure btnExplorerClick(Sender: TObject);
private
{ Private declarations }
public
function GetContentMD5: String;
function GetPageWrite: String;
function GetLeaseID: String;
procedure SetLeaseID(LeaseId: String);
function GetSequenceNumberLte: String;
function GetSequenceNumberLt: String;
function GetSequenceNumberEq: String;
function GetModifiedSince: String;
function GetUnmodifiedSince: String;
function IfMatch: String;
function IfNoneMatch: String;
function FirstByte: Int64;
function EndByte: Int64;
function Content: TBytes;
end;
implementation
uses Vcl.Dialogs;
{$R *.dfm}
procedure TAzPage.btnExplorerClick(Sender: TObject);
var
foDlg: TOpenDialog;
fs: TFileStream;
begin
foDlg := TOpenDialog.Create(self);
if foDlg.Execute(Handle) then
begin
lblContentLocation.Text := foDlg.FileName;
fs := TFileStream.Create(foDlg.FileName, fmOpenRead);
edtPageCount.Text := IntToStr((fs.Size div 512)+ 1);
fs.Free;
end;
foDlg.Free;
end;
function TAzPage.Content: TBytes;
var
fs: TFileStream;
begin
if Length(lblContentLocation.Text) > 0 then
begin
fs := TFileStream.Create(lblContentLocation.Text, fmOpenRead);
try
SetLength(Result, ((fs.Size div 512) + 1) * 512);
fs.ReadBuffer(Result[0], fs.Size);
finally
fs.Free;
end
end;
end;
function TAzPage.EndByte: Int64;
begin
Result := (StrToInt64(edtStartByte.Text) + StrToInt64(edtPageCount.Text)) * 512 - 1;
end;
function TAzPage.FirstByte: Int64;
begin
Result := StrToInt64(edtStartByte.Text) * 512;
end;
function TAzPage.GetContentMD5: String;
begin
Result := lblMD5.Text;
end;
function TAzPage.GetLeaseID: String;
begin
Result := lblLease.Text;
end;
procedure TAzPage.SetLeaseID(LeaseId: String);
begin
lblLease.Text := LeaseId;
end;
function TAzPage.GetModifiedSince: String;
begin
Result := '';
if cbSince.ItemIndex = 0 then
Result := edtSince.Text;
end;
function TAzPage.GetPageWrite: String;
begin
if rgOperation.ItemIndex = 0 then
Result := 'update'
else
Result := 'clear';
end;
function TAzPage.GetSequenceNumberEq: String;
begin
Result := '';
if cbSequenceOp.ItemIndex = 2 then
Result := edtSequence.Text
end;
function TAzPage.GetSequenceNumberLt: String;
begin
Result := '';
if cbSequenceOp.ItemIndex = 1 then
Result := edtSequence.Text
end;
function TAzPage.GetSequenceNumberLte: String;
begin
Result := '';
if cbSequenceOp.ItemIndex = 0 then
Result := edtSequence.Text
end;
function TAzPage.GetUnmodifiedSince: String;
begin
Result := '';
if cbSince.ItemIndex = 1 then
Result := edtSince.Text;
end;
function TAzPage.IfMatch: String;
begin
Result := '';
if cbMatch.ItemIndex = 0 then
Result := edtMatch.Text
end;
function TAzPage.IfNoneMatch: String;
begin
Result := '';
if cbMatch.ItemIndex = 1 then
Result := edtMatch.Text
end;
end.
|
unit PRODUTO;
interface
uses
Classes,
DB,
SysUtils,
Generics.Collections,
ormbr.mapping.attributes,
ormbr.types.mapping,
ormbr.types.lazy,
ormbr.types.nullable,
ormbr.mapping.register;
type
[Entity]
[Table('SABORES', '')]
[PrimaryKey('ID', NotInc, NoSort, True, 'Chave primária')]
TSABORES = Class
Strict private
FDescricao: String;
FID: Integer;
fUsar: Boolean;
public
[Column('ID_SABOR', ftInteger)]
property id: Integer read FID write FID;
[Column('DESCRICAO', ftString)]
property Descricao: String read FDescricao write FDescricao;
[Restrictions([NoValidate])]
property Usar: Boolean read fUsar write fUsar;
End;
[Entity]
[Table('PRODUTO', '')]
[PrimaryKey('ID', AutoInc, NoSort, True, 'Chave primária')]
TPRODUTO = class
Strict private
FID: Integer;
fQTD: nullable<Integer>;
FGRUPA60DESCR: String;
fGRUPICOD: Integer;
fPRODN3VLRVENDA: Double;
fIMPRESSO: String;
fSabores: TObjectList<TSABORES>;
fListaSabores: String;
{ Private declarations }
public
constructor create;
destructor destroy; override;
{ Public declarations }
[Restrictions([NoUpdate, NotNull])]
[Column('PRODICOD', ftInteger)]
property id: Integer read FID write FID;
[Column('PRODA60DESCR', ftString)]
property PRODA60DESCR: String read FGRUPA60DESCR write FGRUPA60DESCR;
[Column('GRUPICOD', ftInteger)]
property GRUPICOD: Integer read fGRUPICOD write fGRUPICOD;
[Column('PRODN3VLRVENDA', ftInteger)]
property PRODN3VLRVENDA: Double read fPRODN3VLRVENDA write fPRODN3VLRVENDA;
[Restrictions([NoValidate])]
property IMPRESSO: String read fIMPRESSO write fIMPRESSO;
[Restrictions([NoValidate])]
property QTD: nullable<Integer> read fQTD write fQTD;
property Sabores: TObjectList<TSABORES> read fSabores write fSabores;
property ListaSabores:String read fListaSabores write fListaSabores;
end;
implementation
{ TPRODUTO }
constructor TPRODUTO.create;
begin
fSabores := TObjectList<TSABORES>.create;
end;
destructor TPRODUTO.destroy;
begin
fSabores.Free;
inherited;
end;
initialization
TRegisterClass.RegisterEntity(TPRODUTO);
end.
|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit RouteCollectionImpl;
interface
{$MODE OBJFPC}
uses
RouteCollectionIntf,
RouterImpl;
type
(*!------------------------------------------------
* basic class that can manage and retrieve routes
*
* This class will be deprecated. You should use IRouter
*
* @author Zamrony P. Juhara <zamronypj@yahoo.com>
* -----------------------------------------------*)
TRouteCollection = class(TRouter, IRouteCollection)
end;
implementation
end.
|
{
Definition of library events.
LICENSE:
Copyright 2015-2021 Michal Petrilak, Jan Horacek
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit LibraryEvents;
interface
type
TStdNotifyEvent = procedure(Sender: TObject; data: Pointer); stdcall;
TStdLogEvent = procedure(Sender: TObject; data: Pointer; logLevel: Integer; msg: PChar); stdcall;
TStdErrorEvent = procedure(Sender: TObject; data: Pointer; errValue: word; errAddr: Cardinal; errMsg: PChar); stdcall;
TStdModuleChangeEvent = procedure(Sender: TObject; data: Pointer; module: Cardinal); stdcall;
TMyErrorEvent = record
event: TStdErrorEvent;
data: Pointer;
end;
TMyNotifyEvent = record
event: TStdNotifyEvent;
data: Pointer;
end;
TMyModuleChangeEvent = record
event: TStdModuleChangeEvent;
data: Pointer end;
TLibEvents = record BeforeOpen: TMyNotifyEvent;
AfterOpen: TMyNotifyEvent;
BeforeClose: TMyNotifyEvent;
AfterClose: TMyNotifyEvent;
BeforeStart: TMyNotifyEvent;
AfterStart: TMyNotifyEvent;
BeforeStop: TMyNotifyEvent;
AfterStop: TMyNotifyEvent;
OnError: TMyErrorEvent;
OnInputChanged: TMyModuleChangeEvent;
OnOutputChanged: TMyModuleChangeEvent;
OnModuleChanged: TMyModuleChangeEvent;
OnScanned: TMyNotifyEvent;
end;
var
LibEvents: TLibEvents;
implementation
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC MongoDB driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$SCOPEDENUMS ON}
{$HPPEMIT LINKUNIT}
unit FireDAC.Phys.MongoDB;
interface
uses
System.Classes,
FireDAC.Phys;
type
/// <summary> Use the TFDPhysMongoDriverLink component to link the MongoDB driver
/// to an application and to set it up. Generally, it is enough to include the
/// FireDAC.Phys.MongoDB unit in your application uses clause. </summary>
[ComponentPlatformsAttribute(pfidWindows or pfidOSX or pfidLinux)]
TFDPhysMongoDriverLink = class(TFDPhysDriverLink)
protected
function GetBaseDriverID: String; override;
end;
{-------------------------------------------------------------------------------}
implementation
uses
System.Variants, System.SysUtils, System.SyncObjs, System.JSON.Types,
System.JSON.Builders, System.JSON.Readers, System.Rtti,
FireDAC.Stan.Consts, FireDAC.Stan.Intf, FireDAC.Stan.Util, FireDAC.Stan.Error,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys.SQLGenerator,
FireDAC.Phys.MongoDBCli, FireDAC.Phys.MongoDBWrapper, FireDAC.Phys.MongoDBDef,
FireDAC.Phys.MongoDBMeta;
const
S_TZLocal = 'Local';
S_TZUTC = 'UTC';
type
TFDPhysMongoDriver = class;
TFDPhysMongoConnection = class;
TFDPhysMongoEventAlerter = class;
TFDPhysMongoTransaction = class;
TFDPhysMongoDriver = class(TFDPhysDriver)
private
FCLib: TMongoClientLib;
FBLib: TMongoBSONLib;
protected
class function GetBaseDriverID: String; override;
class function GetBaseDriverDesc: String; override;
class function GetRDBMSKind: TFDRDBMSKind; override;
class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override;
procedure InternalLoad; override;
procedure InternalUnload; override;
function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override;
function GetCliObj: Pointer; override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
public
constructor Create(AManager: TFDPhysManager; const ADriverDef: IFDStanDefinition); override;
destructor Destroy; override;
end;
TFDPhysMongoConnection = class(TFDPhysConnection)
private
FEnv: TMongoEnv;
FConnection: TMongoConnection;
FServerVersion: TFDVersion;
function BuildMongoConnectString(const AConnectionDef: IFDStanConnectionDef): String;
protected
procedure InternalConnect; override;
procedure InternalSetMeta; override;
procedure InternalDisconnect; override;
procedure InternalPing; override;
function InternalCreateTransaction: TFDPhysTransaction; override;
function InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter; override;
function InternalCreateCommand: TFDPhysCommand; override;
function InternalCreateMetadata: TObject; override;
function InternalCreateCommandGenerator(const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; override;
{$IFDEF FireDAC_MONITOR}
procedure InternalTracingChanged; override;
{$ENDIF}
procedure GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind); override;
function GetItemCount: Integer; override;
procedure InternalExecuteDirect(const ASQL: String; ATransaction: TFDPhysTransaction); override;
function GetCliObj: Pointer; override;
function InternalGetCliHandle: Pointer; override;
public
constructor Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost); override;
property MongoConnection: TMongoConnection read FConnection;
end;
TFDPhysMongoEventAlerter = class(TFDPhysEventAlerter)
private
FTailThread: TThread;
FEventsConnection: IFDPhysConnection;
FColl: String;
FDB: String;
FSize: Integer;
procedure DoFired(ADoc: TMongoDocument);
protected
// TFDPhysEventAlerter
procedure InternalAllocHandle; override;
procedure InternalRegister; override;
procedure InternalHandle(AEventMessage: TFDPhysEventMessage); override;
procedure InternalAbortJob; override;
procedure InternalReleaseHandle; override;
procedure InternalSignal(const AEvent: String; const AArgument: Variant); override;
end;
TFDPhysMongoTransaction = class(TFDPhysTransaction)
protected
procedure InternalStartTransaction(ATxID: LongWord); override;
procedure InternalCommit(ATxID: LongWord); override;
procedure InternalRollback(ATxID: LongWord); override;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMongoDriverLink }
{-------------------------------------------------------------------------------}
function TFDPhysMongoDriverLink.GetBaseDriverID: String;
begin
Result := S_FD_MongoId;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMongoDriver }
{-------------------------------------------------------------------------------}
constructor TFDPhysMongoDriver.Create(AManager: TFDPhysManager;
const ADriverDef: IFDStanDefinition);
begin
inherited Create(AManager, ADriverDef);
FCLib := TMongoClientLib.Create(FDPhysManagerObj);
FBLib := TMongoBSONLib.Create(FCLib);
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysMongoDriver.Destroy;
begin
inherited Destroy;
FDFreeAndNil(FBLib);
FDFreeAndNil(FCLib);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoDriver.InternalLoad;
var
sHome, sLib: String;
begin
sHome := '';
sLib := '';
GetVendorParams(sHome, sLib);
FCLib.Load(sHome, sLib);
FBLib.Load;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoDriver.InternalUnload;
begin
FBLib.Unload;
FCLib.Unload;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoDriver.InternalCreateConnection(
AConnHost: TFDPhysConnectionHost): TFDPhysConnection;
begin
Result := TFDPhysMongoConnection.Create(Self, AConnHost);
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMongoDriver.GetBaseDriverID: String;
begin
Result := S_FD_MongoId;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMongoDriver.GetBaseDriverDesc: String;
begin
Result := 'MongoDB';
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMongoDriver.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.MongoDB;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysMongoDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass;
begin
Result := TFDPhysMongoConnectionDefParams;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoDriver.GetCliObj: Pointer;
begin
Result := FBLib;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
var
oView: TFDDatSView;
begin
Result := inherited GetConnParams(AKeys, AParams);
oView := Result.Select('Name=''' + S_FD_ConnParam_Common_Database + '''');
if oView.Rows.Count = 1 then begin
oView.Rows[0].BeginEdit;
oView.Rows[0].SetValues('LoginIndex', 4);
oView.Rows[0].EndEdit;
end;
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Server, S_FD_Local, S_FD_Local, S_FD_ConnParam_Common_Server, 2]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_Port, '@I', '27017', S_FD_ConnParam_Common_Port, 3]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Mongo_MoreHosts, '@S', '', S_FD_ConnParam_Mongo_MoreHosts, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Mongo_UseSSL, '@L', S_FD_False, S_FD_ConnParam_Mongo_UseSSL, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_LoginTimeout, '@I', '0', S_FD_ConnParam_Common_LoginTimeout, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Mongo_ReadTimeout, '@I', '300', S_FD_ConnParam_Mongo_ReadTimeout, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Mongo_TimeZone, S_TZLocal + ';' + S_TZUTC, S_TZLocal, S_FD_ConnParam_Mongo_TimeZone, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Mongo_MongoAdvanced, '@S', '', S_FD_ConnParam_Mongo_MongoAdvanced, -1]);
// Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefCatalog, '@S', 'test', S_FD_ConnParam_Common_MetaDefCatalog, -1]);
// Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurCatalog, '@S', '', S_FD_ConnParam_Common_MetaCurCatalog, -1]);
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMongoConnection }
{-------------------------------------------------------------------------------}
constructor TFDPhysMongoConnection.Create(ADriverObj: TFDPhysDriver;
AConnHost: TFDPhysConnectionHost);
begin
inherited Create(ADriverObj, AConnHost);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnection.InternalCreateTransaction: TFDPhysTransaction;
begin
Result := TFDPhysMongoTransaction.Create(Self);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnection.InternalCreateEvent(const AEventKind: String): TFDPhysEventAlerter;
begin
if CompareText(AEventKind, S_FD_EventKind_Mongo_Tail) = 0 then
Result := TFDPhysMongoEventAlerter.Create(Self, S_FD_EventKind_Mongo_Tail)
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnection.InternalCreateCommand: TFDPhysCommand;
begin
Result := nil;
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverObj.DriverID]);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnection.InternalCreateMetadata: TObject;
begin
Result := TFDPhysMongoMetadata.Create(Self, FServerVersion,
TFDPhysMongoDriver(DriverObj).FCLib.Version, True);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnection.InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator;
begin
Result := nil;
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverObj.DriverID]);
end;
{$IFDEF FireDAC_MONITOR}
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnection.InternalTracingChanged;
begin
if FEnv <> nil then begin
FEnv.Monitor := FMonitor;
FEnv.Tracing := FTracing;
end;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnection.BuildMongoConnectString(
const AConnectionDef: IFDStanConnectionDef): String;
var
oParams: TFDPhysMongoConnectionDefParams;
lWasOpt: Boolean;
i: Integer;
s: String;
procedure AddOpt(const AOpt: String);
begin
if not lWasOpt then
Result := Result + '?'
else
Result := Result + '&';
lWasOpt := True;
Result := Result + AOpt;
end;
begin
oParams := AConnectionDef.Params as TFDPhysMongoConnectionDefParams;
Result := 'mongodb://';
if AConnectionDef.HasValue(S_FD_ConnParam_Common_UserName) or
AConnectionDef.HasValue(S_FD_ConnParam_Common_Password) then
Result := Result + oParams.UserName + ':' + oParams.Password + '@';
if AConnectionDef.HasValue(S_FD_ConnParam_Common_Server) then
Result := Result + oParams.Server
else
Result := Result + '127.0.0.1';
if AConnectionDef.HasValue(S_FD_ConnParam_Common_Port) then
Result := Result + ':' + IntToStr(oParams.Port);
if AConnectionDef.HasValue(S_FD_ConnParam_Mongo_MoreHosts) then begin
i := 1;
s := oParams.MoreHosts;
while i <= Length(s) do
Result := Result + ',' + FDExtractFieldName(s, i);
end;
Result := Result + '/';
if AConnectionDef.HasValue(S_FD_ConnParam_Mongo_UseSSL) or
AConnectionDef.HasValue(S_FD_ConnParam_Common_LoginTimeout) or
AConnectionDef.HasValue(S_FD_ConnParam_Mongo_ReadTimeout) or
AConnectionDef.HasValue(S_FD_ConnParam_Mongo_MongoAdvanced) or
AConnectionDef.HasValue(S_FD_ConnParam_Common_Database) then begin
if AConnectionDef.HasValue(S_FD_ConnParam_Common_Database) then
Result := Result + oParams.Database;
lWasOpt := False;
if AConnectionDef.HasValue(S_FD_ConnParam_Mongo_UseSSL) then
AddOpt('ssl=' + LowerCase(BoolToStr(oParams.UseSSL, True)));
if AConnectionDef.HasValue(S_FD_ConnParam_Common_LoginTimeout) then
AddOpt('connectTimeoutMS=' + IntToStr(oParams.LoginTimeout * 1000));
if AConnectionDef.HasValue(S_FD_ConnParam_Mongo_ReadTimeout) then
AddOpt('socketTimeoutMS=' + IntToStr(oParams.ReadTimeout * 1000));
if AConnectionDef.HasValue(S_FD_ConnParam_Mongo_MongoAdvanced) then begin
i := 1;
s := oParams.MongoAdvanced;
while i <= Length(s) do
AddOpt(FDExtractFieldName(s, i));
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnection.InternalConnect;
begin
// TMongoEnv creation moved to InternalConnect from Create, because on ARC
// platforms destruction of FEnv in Destroy leaded to Self->FEnv->FError->Self
// circular destruction sequence
FEnv := TMongoEnv.Create(TFDPhysMongoDriver(DriverObj).FCLib,
TFDPhysMongoDriver(DriverObj).FBLib, Self);
FEnv.DateTimeZoneHandling := (ConnectionDef.Params as TFDPhysMongoConnectionDefParams).TimeZone;
if InternalGetSharedCliHandle() <> nil then
FConnection := TMongoConnection.CreateUsingHandle(FEnv,
Pmongoc_handle_t(InternalGetSharedCliHandle()), Self)
else
FConnection := TMongoConnection.Create(FEnv, Self);
{$IFDEF FireDAC_MONITOR}
InternalTracingChanged;
{$ENDIF}
if InternalGetSharedCliHandle() = nil then begin
FConnection.Open(BuildMongoConnectString(ConnectionDef));
// Open only initializes connection parameters. The connection will be
// really open on first command (communication) to the server. To handle
// incorrect credentials, server inavailability, etc perform Ping command.
FConnection.Ping;
end;
FServerVersion := FConnection.ServerVersion;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnection.InternalSetMeta;
begin
inherited InternalSetMeta;
if FDefaultCatalog = '' then
FDefaultCatalog := 'test';
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnection.InternalDisconnect;
begin
FDFreeAndNil(FConnection);
FDFreeAndNil(FEnv);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnection.InternalPing;
begin
FConnection.Ping;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnection.InternalExecuteDirect(const ASQL: String;
ATransaction: TFDPhysTransaction);
begin
FDCapabilityNotSupported(Self, [S_FD_LPhys, DriverObj.DriverID]);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnection.GetItemCount: Integer;
begin
Result := inherited GetItemCount;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoConnection.GetItem(AIndex: Integer; out AName: String;
out AValue: Variant; out AKind: TFDMoniAdapterItemKind);
begin
inherited GetItem(AIndex, AName, AValue, AKind);
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnection.GetCliObj: Pointer;
begin
Result := FConnection;
end;
{-------------------------------------------------------------------------------}
function TFDPhysMongoConnection.InternalGetCliHandle: Pointer;
begin
if FConnection <> nil then
Result := FConnection.Handle
else
Result := nil;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMongoTailThread }
{-------------------------------------------------------------------------------}
type
TFDPhysMongoTailThread = class(TThread)
private
[weak] FAlerter: TFDPhysMongoEventAlerter;
protected
procedure Execute; override;
public
constructor Create(AAlerter: TFDPhysMongoEventAlerter);
destructor Destroy; override;
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysMongoTailThread.Create(AAlerter: TFDPhysMongoEventAlerter);
begin
inherited Create;
FAlerter := AAlerter;
FreeOnTerminate := True;
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysMongoTailThread.Destroy;
begin
FAlerter.FTailThread := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoTailThread.Execute;
var
oConn: TMongoConnection;
oCrs: IMongoCursor;
rLastId: TJsonOid;
oIter: TJSONIterator;
oDoc: TMongoDocument;
begin
oConn := TMongoConnection(FAlerter.FEventsConnection.CliObj);
oDoc := nil;
try
try
oCrs := oConn[FAlerter.FDB][FAlerter.FColl].Aggregate([])
.Group()
.Add('_id', '1')
.BeginObject('lastId')
.Add('$max', '$_id')
.EndObject
.&End;
if oCrs.Next then begin
oIter := oCrs.Doc.Iterator;
try
oIter.Next('lastId');
rLastId := oIter.AsOid;
finally
FDFree(oIter);
end;
end;
while not Terminated and FAlerter.IsRunning do begin
oCrs := oConn[FAlerter.FDB][FAlerter.FColl]
.Find([TMongoQueryFlag.TailableCursors, TMongoQueryFlag.AwaitData])
.Match()
.BeginObject('_id')
.Add('$gt', rLastId)
.EndObject
.&End
.Sort()
.Ascending(['$natural'])
.&End;
while not Terminated and FAlerter.IsRunning do begin
if oDoc = nil then
oDoc := oConn.Env.NewDoc;
if not oCrs.Next(oDoc) then begin
if not oCrs.IsAlive then begin
Sleep(100);
Break;
end;
Continue;
end;
oIter := oDoc.Iterator;
try
oIter.Next('_id');
rLastId := oIter.AsOid;
finally
FDFree(oIter);
end;
FAlerter.DoFired(oDoc);
oDoc := nil;
end;
end;
except
on E: EFDDBEngineException do
if E.Kind <> ekCmdAborted then begin
Terminate;
FAlerter.AbortJob;
end;
end;
finally
if oDoc <> nil then
FDFree(oDoc);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMongoEventMessage }
{-------------------------------------------------------------------------------}
type
TFDPhysMongoEventMessage = class(TFDPhysEventMessage)
private
FName: String;
FDoc: TMongoDocument;
public
constructor Create(const AName: String; ADoc: TMongoDocument);
destructor Destroy; override;
end;
{-------------------------------------------------------------------------------}
constructor TFDPhysMongoEventMessage.Create(const AName: String; ADoc: TMongoDocument);
begin
inherited Create;
FName := AName;
FDoc := ADoc;
end;
{-------------------------------------------------------------------------------}
destructor TFDPhysMongoEventMessage.Destroy;
begin
FDFreeAndNil(FDoc);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMongoEventAlerter }
{-------------------------------------------------------------------------------}
const
C_WakeUpEvent = C_FD_SysNamePrefix + 'WAKEUP';
C_DefDBName = 'test';
C_DefCollSize = 10000;
procedure TFDPhysMongoEventAlerter.InternalAllocHandle;
var
i: Integer;
begin
if GetNames().Count <> 1 then
FDException(Self, [S_FD_LPhys, S_FD_MongoId], er_FD_MongoAlertToMany, []);
FColl := GetNames()[0];
i := Pos('=', FColl);
if i > 0 then begin
FSize := StrToIntDef(Copy(FColl, i + 1, MaxInt), C_DefCollSize);
FColl := Copy(FColl, 1, i - 1);
end
else
FSize := C_DefCollSize;
i := Pos('.', FColl);
if i > 0 then begin
FDB := Copy(FColl, 1, i - 1);
FColl := Copy(FColl, i + 1, MaxInt);
end
else begin
FDB := GetConnection.ConnectionDef.Params.Database;
if FDB = '' then
FDB := C_DefDBName;
end;
FEventsConnection := GetConnection.Clone;
if FEventsConnection.State = csDisconnected then
FEventsConnection.Open;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoEventAlerter.InternalRegister;
var
oConn: TMongoConnection;
oOpts: TMongoDocument;
begin
oConn := TMongoConnection(FEventsConnection.CliObj);
if not oConn[FDB].HasCollection(FColl) then begin
oOpts := oConn.Env.NewDoc;
try
oOpts.Add('capped', True);
oOpts.Add('size', FSize);
oConn[FDB].CreateCollection(FColl, oOpts);
oConn[FDB][FColl]
.Insert()
.Values()
.Add('name', C_WakeUpEvent)
.&End
.Exec;
finally
FDFree(oOpts);
end;
end;
FTailThread := TFDPhysMongoTailThread.Create(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoEventAlerter.DoFired(ADoc: TMongoDocument);
var
oIter: TJSONIterator;
lEnqueue: Boolean;
sName: String;
begin
lEnqueue := True;
sName := '';
oIter := ADoc.Iterator;
try
if oIter.Find('name') then begin
sName := oIter.AsString;
lEnqueue := CompareText(sName, C_WakeUpEvent) <> 0;
end;
finally
FDFree(oIter);
end;
if lEnqueue then
FMsgThread.EnqueueMsg(TFDPhysMongoEventMessage.Create(sName, ADoc))
else
FDFree(ADoc);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoEventAlerter.InternalHandle(AEventMessage: TFDPhysEventMessage);
var
oMsg: TFDPhysMongoEventMessage;
begin
oMsg := TFDPhysMongoEventMessage(AEventMessage);
InternalHandleEvent(oMsg.FName, oMsg.FDoc.AsJSON);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoEventAlerter.InternalAbortJob;
begin
if FTailThread <> nil then begin
FTailThread.Terminate;
InternalSignal(C_WakeUpEvent, Null);
while (FTailThread <> nil) and (FTailThread.ThreadID <> TThread.Current.ThreadID) do
Sleep(1);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoEventAlerter.InternalReleaseHandle;
begin
FTailThread := nil;
FEventsConnection := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoEventAlerter.InternalSignal(const AEvent: String;
const AArgument: Variant);
var
oConn: TMongoConnection;
oIns: TMongoInsert;
s: String;
begin
oConn := TMongoConnection(GetConnection.CliObj);
oIns := TMongoInsert.Create(oConn.Env);
try
oIns.Values().Add('name', AEvent);
if not (VarIsNull(AArgument) or VarIsEmpty(AArgument)) then begin
s := VarToStr(AArgument);
if (Length(s) > 0) and (s[1] = '{') and (s[Length(s)] = '}') then
oIns.Values().Append(s)
else
oIns.Values().Add('arg', AArgument);
end;
oConn[FDB][FColl].Insert(oIns);
finally
FDFree(oIns);
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysMongoTransaction }
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoTransaction.InternalCommit(ATxID: LongWord);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoTransaction.InternalRollback(ATxID: LongWord);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysMongoTransaction.InternalStartTransaction(ATxID: LongWord);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
initialization
FDRegisterDriverClass(TFDPhysMongoDriver);
finalization
FDUnregisterDriverClass(TFDPhysMongoDriver);
end.
|
{===============================================================================
Copyright(c) 2007-2009, 北京北研兴电力仪表有限责任公司
All rights reserved.
错误接线,公式计算单元
+ TWE_EQUATION 公式计算
===============================================================================}
unit U_WE_EQUATION;
interface
uses SysUtils, Classes, math, U_WIRING_ERROR, U_WE_EQUATION_MATH,
U_WE_EXPRESSION, Dialogs, U_POWER_LIST_INFO;
const
C_WE_POWER_RIGHT_3 = '#UIcos\o';
C_WE_POWER_RIGHT_4 = '3UIcos\o';
C_WE_POWER_RIGHT_SINGLE = 'UIcos\o';
type
/// <summary>
/// 错误接线公式
/// </summary>
TWE_EQUATION = class( TPersistent )
private
FExpression : TWE_EXPRESSION;
FEquationP : TStrings;
FEquationK : TStrings;
FAnalysisK : TStrings;
FPhaseEquations : TList;
FKValue : Double;
function GetWiringError : TWIRING_ERROR;
procedure SetWiringError(const Value: TWIRING_ERROR);
function GetUIAngle : Double;
procedure SetUIAngle(const Value: Double);
private
FRunTpye: Integer;
FFourPower: TFourPower;
FThreePower: TThreePower;
/// <summary>计算 三线公式 /// </summary>
procedure CalEquationP3;
/// <summary>计算 四线公式 /// </summary>
procedure CalEquationP4;
/// <summary>计算 四线PT公式 /// </summary>
procedure CalEquationP4PT;
/// <summary>计算 单相公式 /// </summary>
procedure CalEquationSingle;
/// <summary>计算 更正系数 /// </summary>
procedure CalEquationK;
/// <summary>分析更正系数 /// </summary>
procedure CalAnalysisK( ACoefs : array of string; AIntCoefs : array of Integer );
/// <summary>
/// 最终的计算结果
/// </summary>
function FinalEquation : string;
/// <summary>
/// 分析公式
/// </summary>
procedure AnalysisExpression( APhaseEquation : TWE_PHASE_EXPRESSION );
/// <summary>
/// 清空公式
/// </summary>
procedure CleanEquation;
/// <summary>
/// 生成三线表达式
/// </summary>
procedure CreateExpression3;
/// <summary>
/// 生成四线表达式
/// </summary>
procedure CreateExpression4;
/// <summary>
/// 生成四线PT表达式
/// </summary>
procedure CreateExpression4PT;
public
/// <summary>
/// 生成单相表达式
/// </summary>
procedure CreateExpressionSingle;
/// <summary>
/// 功率公式
/// </summary>
property EquationP : TStrings read FEquationP;
/// <summary>
/// 更正系数公式
/// </summary>
property EquationK : TStrings read FEquationK;
/// <summary>
/// 更正系数解析
/// </summary>
property AnalysisK : TStrings read FAnalysisK;
/// <summary>
/// UI夹角
/// </summary>
property UIAngle : Double read GetUIAngle write SetUIAngle;
/// <summary>
/// 错误接线
/// </summary>
property WiringError : TWIRING_ERROR read GetWiringError write SetWiringError;
/// <summary>
/// 运行类型 0正转, 1反转, 2不转
/// </summary>
property RunTpye : Integer read FRunTpye write FRunTpye;
/// <summary>
/// 当前更正系数K值
/// </summary>
property KValue : Double read FKValue write FKValue;
/// <summary>
/// 三相四线功率对象
/// </summary>
property FourPower : TFourPower read FFourPower write FFourPower;
/// <summary>
/// 三相三线功率对象
/// </summary>
property ThreePower : TThreePower read FThreePower write FThreePower;
public
constructor Create();
destructor Destroy; override;
/// <summary>
/// 获取相公式
/// </summary>
function GetPhaseEquation( const AIndex : Integer ) : TWE_PHASE_EXPRESSION;
/// <summary>
/// 生成计算公式
/// </summary>
procedure GenerateEquations( AWE : TWIRING_ERROR; AUIAngle : Double ); overload;
/// <summary>
/// 生成公式
/// </summary>
procedure GenerateEquations; overload;
/// <summary>
/// 显示分析
/// </summary>
procedure ShowAnalysis( AText : TStrings; AMaxSize : Integer );
end;
implementation
{ TWE_EQUATION }
procedure TWE_EQUATION.AnalysisExpression(APhaseEquation : TWE_PHASE_EXPRESSION);
var
sCoUI, sCoI : string; // U, I 系数
begin
if not Assigned( APhaseEquation ) then
Exit;
with APhaseEquation do // 初始化数据
begin
Result1 := '';
Result2 := '';
CoCos := '';
CoSin := '';
end;
sCoUI := '';
sCoI := '';
// 如果该式结果为0
if APhaseEquation.Expression = '0' then
Exit;
with APhaseEquation do
begin
//------------------------------------------------------------------------
// 计算UI的系数, 同时生成结果公式
//------------------------------------------------------------------------
// 取U的系数
if ExpressU[ 1 ] <> 'U' then
begin
sCoUI := Copy( ExpressU, 1, Pos( 'U', ExpressU ) - 1 );
sCoUI := StringReplace( sCoUI, '-', '', [] );
end;
// 取I的系数
if ( Pos( '_a_c', ExpressI ) > 0 ) or
( Pos( '_c_a', ExpressI ) > 0 ) then
sCoI := C_EQ_SIGN_SQRT3;
if ExpressI[ 1 ] <> 'I' then
begin
sCoI := Copy( ExpressI, 1, Pos( 'I', ExpressI ) - 1 ) + sCoI;
sCoI := StringReplace( sCoI, '-', '', [] );
CleanSigns( sCoI );
end;
// 生成UI公式
Result1 := sCoUI + 'U' + sCoI + 'I';
// 化简系数
sCoUI := sCoUI + sCoI;
CleanSigns( sCoUI );
Result2 := sCoUI + 'UI';
//------------------------------------------------------------------------
// 计算Cos/Sin的系数, 同时生成结果公式
//------------------------------------------------------------------------
if AngleO = 0 then
begin
// cos(0+O) = -cosO
// cos(0-O) = -cosO
Result1 := Result1 + 'cos\o';
Result2 := Result2 + 'cos\o';
// 最终系数
CoCos := '1'; // 如果为空,则系数为 +
end
else if AngleO = 90 then
begin
if SignO then // cos(90+O) = -sinO
begin
Result1 := Result1 + '(-sin\o)';
sCoUI := '-' + sCoUI;
Result2 := '-' + Result2 + 'sin\o';
end
else
begin
Result1 := Result1 + 'sin\o';
Result2 := Result2 + 'sin\o';
end;
// 去掉可能出现的 --
Result1 := StringReplace( Result1, '--', '', [] );
Result2 := StringReplace( Result2, '--', '', [] );
// 最终系数
CoSin := sCoUI + CoSin;
CoSin := StringReplace( CoSin, '--', '', [] );
if CoSin = '' then // 如果为空,则系数为 @
CoSin := '1';
end
else if AngleO = 180 then
begin
// cos(180+O) = -cosO
// cos(180-O) = -cosO
Result1 := Result1 + '(-cos\o)';
sCoUI := '-' + sCoUI;
Result2 := '-' + Result2 + 'cos\o';
// 去掉可能出现的 --
Result1 := StringReplace( Result1, '--', '', [] );
Result2 := StringReplace( Result2, '--', '', [] );
// 最终系数
CoCos := sCoUI + CoCos;
CoCos := StringReplace( CoCos, '--', '', [] );
if CoCos = '' then // 如果为空,则系数为 +
CoCos := '1';
end
else
begin
// 进行三角公式计算
// cos(@+O) = cos@cosO-sin@sinO
// cos(@-O) = cos@cosO+sin@sinO
CoCos := 'cos' + IntToStr( AngleO ) + '`';
CoSin := 'sin' + IntToStr( AngleO ) + '`';
if SignO then
CoSin := '-' + CoSin;
// 生成公式1
Result1 := Result1 + '(' + CoCos + 'cos\o' + '+' + CoSin + 'sin\o)';
CleanSigns( Result1 );
// 转化为分数
ReplaceCosSinWithFrac( CoCos );
ReplaceCosSinWithFrac( CoSin );
// 生成结果2
Result2 := Result2 + '(' + CoCos + 'cos\o' + '+' + CoSin + 'sin\o)';
CleanSigns( Result2 );
// 最终 UIcos, UIsin 系数
CoCos := sCoUI + CoCos;
CoSin := sCoUI + CoSin;
end;
end;
end;
procedure TWE_EQUATION.CalAnalysisK(ACoefs: array of string;
AIntCoefs: array of Integer);
var
sCoR, sCoWcos, sCoWsin : string;
nR, nR3, nWCos, nW3Cos, nWSin, nW3Sin : Integer;
d : Double;
dtg : Double;
dCos : Double;
sCos : string;
s : string;
X, Y1, Y2 : Double;
dTemp : Double;
dAngle : Double;
begin
sCoR := ACoefs[ 0 ];
sCoWcos := ACoefs[ 1 ];
sCoWsin := ACoefs[ 2 ];
nR := AIntCoefs[ 0 ];
nR3 := AIntCoefs[ 1 ];
nWCos := AIntCoefs[ 2 ];
nW3Cos := AIntCoefs[ 3 ];
nWSin := AIntCoefs[ 4 ];
nW3Sin := AIntCoefs[ 5 ];
X := nR + nR3 * Sqrt( 3 );
Y1 := nWCos + nW3Cos * Sqrt( 3 );
Y2 := nWSin + nW3Sin * Sqrt( 3 );
dAngle := DegToRad(UIAngle);
dTemp := Cos(dAngle);
// Xcoso / Y1coso = X/Y1
if (sCoWcos <> '') and (sCoWsin = '') then
begin
try
d := X / Y1;
FKValue := d;
// d = 0 的可能不存在, 分子不为 0
if d < 0 then
FAnalysisK.Add('表反转。')
else if IsZero( d - 1 ) then // dK = 1 可能存在,不确定
FAnalysisK.Add('计量正确。')
else if d < 1 then
FAnalysisK.Add('表快。')
else if d > 1 then
FAnalysisK.Add('表慢。');
if d < 0 then
FRunTpye := 1
else
FRunTpye := 0;
except
FAnalysisK.Add('表不转。'); // 分母为 0, 不应该存在
FRunTpye := 2;
end;
end
// Xcoso / Y2Sino = 1 -> tg = X/Y2
else if (sCoWcos = '') and (sCoWsin <> '') then
begin
try
dtg := X / Y2;
if (y2* Sin(dAngle)) <> 0 then
FKValue := (X * Cos(dAngle))/(y2* Sin(dAngle))
else
FKValue := 0;
// cosO^2 = 1 / ( 1 + tgO^2 )
dCos := Sqrt(1 / ( 1 + Power( dtg, 2 )));
sCos := FloatToStr( Round( dCos * 1000 ) / 1000 );
FAnalysisK.Add('当 cosφ= 1 时,表不转。');
if dtg < 0 then
begin
FAnalysisK.Add('当负载为感性,0 < cosφ < 1 时,表反转。');
FAnalysisK.Add('当负载为容性,0 < cosφ < 1 时,表正转。');
end
else
begin
FAnalysisK.Add('当负载为感性,0 < cosφ < 1 时,表正转。');
FAnalysisK.Add('当负载为容性,0 < cosφ < 1 时,表反转。');
end;
FAnalysisK.Add( Format( '当 cosφ < %s 时, 表快。', [ sCos ] ) );
FAnalysisK.Add( Format( '当 cosφ > %s 时, 表慢。', [ sCos ] ) );
if Cos(DegToRad(UIAngle))= 1 then
begin
FRunTpye := 2;
end;
if dtg < 0 then
begin
if UIAngle > 0 then
FRunTpye := 0
else
FRunTpye := 1;
end
else
begin
if UIAngle > 0 then
FRunTpye := 1
else
FRunTpye := 0;
end;
except
end;
end
else
// K = Xcos / ( Y1Cos + Y2Sin ) 包含 sin cos
begin
try
FKValue := (X * Cos(dAngle))/(y1 * Cos(dAngle) + y2* Sin(dAngle));
// 计算临界值,即分母为0 的情况
// Y1cos + Y2sin = 0 -> tg = - Y1/Y2
dtg := - Y1 / Y2;
dCos := Sqrt(1 / ( 1 + Power( dtg, 2 )));
sCos := FloatToStr( Round( dCos * 1000 ) / 1000 );
// 判断 K 正负, 计算K值
// tg变大时,cos变小
// K = X / ( Y1 + Y2tg ), X > 0, 只需判断分母即可
d := Y1 + ( dtg + 0.1 ) * Y2;
if Abs(d) > 0 then
s := '当负载为感性,cosφ = %s 时,表不转;cosφ > %s 时,表反转;cosφ < %s 时,表正转。'
else
s := '当负载为容性,cosφ = %s 时,表不转;cosφ > %s 时,表正转;cosφ < %s 时,表反转。';
FAnalysisK.Add( Format( s, [ sCos, sCos, sCos ] ) );
if Abs(d) > 0 then
begin
if dTemp < dCos then
FRunTpye := 1
else if dTemp = dCos then
FRunTpye := 2
else
FRunTpye := 0;
end
else
begin
if dTemp < dCos then
FRunTpye := 0
else if dTemp = dCos then
FRunTpye := 2
else
FRunTpye := 1;
end;
except
end;
try
// 计算正确时
// K = Xcos / ( Y1Cos + Y2Sin ) = 1 -> tg = (X-Y1)/Y2 包含 sin cos
dtg := ( X - Y1 ) / Y2;
// coso的值
dCos := Sqrt(1 / ( 1 + Power( dtg, 2 )));
sCos := FloatToStr( Round( dCos * 1000 ) / 1000 );
// 计算cosO变小时的K值, dtg变大,cos变小
// K = X / ( Y1 + Y2tg )
if dtg < 0 then
dtg := dtg - 0.1
else
dtg := dtg + 0.1;
d := X / ( Y1 + ( dtg ) * Y2 );
if Abs(dtg) > 0 then
s := '当负载为容性,'
else
s := '当负载为感性,';
if d > 1 then
s := s + 'cosφ = %s 时,计量正确;cosφ > %s 时,表快;cosφ < %s 时,表慢。'
else
s := s + 'cosφ = %s 时,计量正确;cosφ > %s 时,表慢;cosφ < %s 时,表快。';
FAnalysisK.Add( Format( s, [ sCos, sCos, sCos ] ) );
except
end;
try
// 计算反转时计量正确
// K = Xcos / ( Y1Cos + Y2Sin ) = -1 -> tg = -(X+Y1)/Y2
dtg := -( X + Y1 ) / Y2;
// coso的值
dCos := Sqrt(1 / ( 1 + Power( dtg, 2 )));
sCos := FloatToStr( Round( dCos * 1000 ) / 1000 );
if Abs(dtg) > 0 then
s := '当负载为容性,cosφ = %s 时,计量正确但表反转。'
else
s := '当负载为感性,cosφ = %s 时,计量正确但表反转。';
if Abs(dtg) > 0 then
begin
if dTemp = dCos then
FRunTpye := 1
end;
FAnalysisK.Add( Format( s, [ sCos ] ) );
except
end;
end;
FAnalysisK.Add( '更正系数K为' + FormatFloat('0.000', FKValue));
end;
procedure TWE_EQUATION.CalEquationK;
var
sEquation : string;
sRightE : string;
sWrongE : string;
// 系数
sCoR, sCoW, sCoWcos, sCoWsin : string;
s : string;
sTemp : string;
FracR, FracR3 : TWE_FRAC;
FracWCos, FracW3Cos : TWE_FRAC;
FracWSin, FracW3Sin : TWE_FRAC;
nFactor, nCommonDen : Integer;
begin
if FEquationP.Count = 0 then
Exit;
if GetWiringError.PhaseType = ptThree then
sRightE := C_WE_POWER_RIGHT_3
else if GetWiringError.PhaseType = ptSingle then
sRightE := C_WE_POWER_RIGHT_SINGLE
else
sRightE := C_WE_POWER_RIGHT_4;
sWrongE := FEquationP[FEquationP.Count -1];
FEquationK.Add('P/P''');
FEquationK.Add(sRightE + '/' + sWrongE);
if sWrongE = '0' then
begin
FEquationK.Add('\q'); // 无穷大
FAnalysisK.Add('表不转。');
FRunTpye := 2;
FKValue := -1;
FAnalysisK.Add( '更正系数K为 无穷大');
end
else if sWrongE = sRightE then
begin
FEquationK.Add('1');
FAnalysisK.Add('计量正确。');
FRunTpye := 0;
FKValue := 1;
FAnalysisK.Add( '更正系数K为' + FormatFloat('0.000', FKValue));
end
else // 计算
begin
// 1. 提取系数
DivStr( sRightE, 'U', sCoR, s ); // 正确公式
DivStr( sWrongE, 'U', sCoW, s ); // 错误公式
if sCoW = '' then sCoW := '1';
sCoWsin := '';
sCoWcos := '';
s := Copy( s, 3, Length( s ) - 2 ); // 去掉UI
if Pos('(', s ) > 0 then
begin
// 获取 cos, sin 的系数
s := Copy( s, 2, Length( s ) - 2 ); // 如果有括号, 去掉括号
DivStr( s, 'cos\o', sCoWcos, sTemp );
s := Copy( sTemp, 6, Length( sTemp ) - 5 ); // 去掉 cos\o
DivStr( s, 'sin\o', sCoWsin, sTemp );
sCoWcos := sCoW + sCoWcos;
sCoWsin := sCoW + sCoWsin;
end
else
begin
if Pos('cos', sWrongE) > 0 then
sCoWcos := sCoW
else
sCoWsin := sCoW;
end;
// 提取系数
PlusCoefs( [ sCoR ], FracR, FracR3 );
PlusCoefs( [ sCoWcos ], FracWCos, FracW3Cos );
PlusCoefs( [ sCoWsin ], FracWSin, FracW3Sin );
// 2. 系数化简
// 提取公分母, K公式上下同时乘以公分母,消除分数
nCommonDen := GetCommonDen( [ FracR, FracR3, FracWCos, FracW3Cos, FracWSin,
FracW3Sin ] );
FracR := MultiplyFrac( FracR, nCommonDen );
FracR3 := MultiplyFrac( FracR3, nCommonDen );
FracWCos := MultiplyFrac( FracWCos, nCommonDen );
FracW3Cos := MultiplyFrac( FracW3Cos, nCommonDen );
FracWSin := MultiplyFrac( FracWSin, nCommonDen );
FracW3Sin := MultiplyFrac( FracW3Sin, nCommonDen );
// K公式上下用因数化简
nFactor := GetFactor( [ FracR.n, FracR3.n, FracWCos.n, FracW3Cos.n,
FracWSin.n, FracW3Sin.n ] );
if ( nFactor > 1 ) or ( nFactor < 0 ) then
begin
FracR.n := FracR.n div nFactor;
FracR3.n := FracR3.n div nFactor;
FracWCos.n := FracWCos.n div nFactor;
FracW3Cos.n := FracW3Cos.n div nFactor;
FracWSin.n := FracWSin.n div nFactor;
FracW3Sin.n := FracW3Sin.n div nFactor;
end;
// 如果分母为负数,则翻到分子
nFactor := GetFactor( [ FracWCos.n, FracW3Cos.n, FracWSin.n, FracW3Sin.n ] );
if nFactor < 0 then
begin
FracR.n := FracR.n * -1;
FracR3.n := FracR3.n * -1;
FracWCos.n := FracWCos.n * -1;
FracW3Cos.n := FracW3Cos.n * -1;
FracWSin.n := FracWSin.n * -1;
FracW3Sin.n := FracW3Sin.n * -1;
end;
// 如果可以是sqrt3的倍数, 例如 3/4 + sqrt3/4 -> sqrt3( 1/4, sqrt3/4 )
if HasSqrt3Factor( FracR.n, FracR3.n ) and
HasSqrt3Factor( FracWCos.n, FracW3Cos.n ) and
HasSqrt3Factor( FracWSin.n, FracW3Sin.n ) then
begin
DivSqrt3( FracR, FracR3 );
DivSqrt3( FracWCos, FracW3Cos );
DivSqrt3( FracWSin, FracW3Sin );
end;
// 3. 显示化简结果
sCoR := PlusExpressions( GenCoef( FracR.n, False ), GenCoef( FracR3.n, True ) );
if sCoR = '' then
sCoR := '1';
sCoWcos := PlusExpressions( GenCoef( FracWCos.n, False ), GenCoef( FracW3Cos.n, True ) );
sCoWsin := PlusExpressions( GenCoef( FracWSin.n, False ), GenCoef( FracW3Sin.n, True ) );
if sCoWsin = '' then // *coso/*coso
sEquation := RefinedCoef( Format( C_FMT_FRAC, [ sCoR, sCoWcos ] ) )
else if sCoWcos = '' then
sEquation := MultiplyExpressions(
RefinedCoef( Format( C_FMT_FRAC, [ sCoR, sCoWsin ] ) ), 'ctg\o' )
else
sEquation := sCoR + '/' + PlusExpressions( sCoWcos,
MultiplyExpressions( sCoWsin, 'tg\o' ) );
FEquationK.Add(sEquation);
if GetWiringError.PhaseType <> ptSingle then
begin
// 解析K
CalAnalysisK( [ sCoR, sCoWcos, sCoWsin ], [ FracR.n, FracR3.n, FracWCos.n,
FracW3Cos.n, FracWSin.n, FracW3Sin.n ] );
end;
end;
end;
procedure TWE_EQUATION.CalEquationP3;
var
sEquation : string;
begin
// 公式2
FEquationP.Add('P_1''+P_2''');
sEquation := GetPhaseEquation(0).Expression + '+' + GetPhaseEquation(1).Expression;
CleanSigns( sEquation );
FEquationP.Add( sEquation );
if sEquation = '0' then
Exit;
// 结果公式1
sEquation := CombineExpressions( [ GetPhaseEquation(0).Result1,
GetPhaseEquation(1).Result1 ] );
FEquationP.Add( sEquation );
// 结果公式2
sEquation := CombineExpressions( [ GetPhaseEquation(0).Result2,
GetPhaseEquation(1).Result2 ] );
if sEquation <> FEquationP[ FEquationP.Count - 1 ] then
FEquationP.Add( sEquation );
// 计算最终结果
sEquation := FinalEquation;
if sEquation <> FEquationP[ FEquationP.Count - 1 ] then
begin
FEquationP.Add( sEquation );
end;
end;
procedure TWE_EQUATION.CalEquationP4;
var
sEquation : string;
begin
// 公式2
FEquationP.Add( 'P_1''+P_2''+P_3''' );
sEquation := GetPhaseEquation(0).Expression + '+' +
GetPhaseEquation(1).Expression + '+' + GetPhaseEquation(2).Expression;
CleanSigns( sEquation );
FEquationP.Add( sEquation );
if sEquation = '0' then
Exit;
// 结果公式1
sEquation := CombineExpressions( [ GetPhaseEquation(0).Result1,
GetPhaseEquation(1).Result1, GetPhaseEquation(2).Result1 ] );
FEquationP.Add( sEquation );
// 结果公式2
sEquation := CombineExpressions( [ GetPhaseEquation(0).Result2,
GetPhaseEquation(1).Result2, GetPhaseEquation(2).Result2 ] );
if sEquation <> FEquationP[ FEquationP.Count - 1 ] then
FEquationP.Add( sEquation );
// 计算最终结果
if sEquation <> FinalEquation then
begin
sEquation := FinalEquation;
FEquationP.Add( sEquation );
end;
end;
procedure TWE_EQUATION.CalEquationP4PT;
var
sEquation : string;
begin
// 公式2
FEquationP.Add( 'P_1''+P_2''+P_3''' );
sEquation := GetPhaseEquation(0).Expression + '+' +
GetPhaseEquation(1).Expression + '+' + GetPhaseEquation(2).Expression;
CleanSigns( sEquation );
FEquationP.Add( sEquation );
if sEquation = '0' then
Exit;
// 结果公式1
sEquation := CombineExpressions( [ GetPhaseEquation(0).Result1,
GetPhaseEquation(1).Result1, GetPhaseEquation(2).Result1 ] );
FEquationP.Add( sEquation );
// 结果公式2
sEquation := CombineExpressions( [ GetPhaseEquation(0).Result2,
GetPhaseEquation(1).Result2, GetPhaseEquation(2).Result2 ] );
if sEquation <> FEquationP[ FEquationP.Count - 1 ] then
FEquationP.Add( sEquation );
// 计算最终结果
if sEquation <> FinalEquation then
begin
sEquation := FinalEquation;
FEquationP.Add( sEquation );
end;
end;
procedure TWE_EQUATION.CalEquationSingle;
var
sEquation : string;
begin
// 公式2
FEquationP.Add( 'P_1' );
sEquation := GetPhaseEquation(0).Expression;
CleanSigns( sEquation );
FEquationP.Add( sEquation );
if sEquation = '0' then
Exit;
// 结果公式1
sEquation := CombineExpressions( [ GetPhaseEquation(0).Result1 ] );
FEquationP.Add( sEquation );
// 结果公式2
sEquation := CombineExpressions( [ GetPhaseEquation(0).Result2] );
if sEquation <> FEquationP[ FEquationP.Count - 1 ] then
FEquationP.Add( sEquation );
// 计算最终结果
if sEquation <> FinalEquation then
begin
sEquation := FinalEquation;
FEquationP.Add( sEquation );
end;
end;
procedure TWE_EQUATION.CleanEquation;
var
i: Integer;
begin
for i := 0 to FPhaseEquations.Count - 1 do
GetPhaseEquation( i ).Clear;
FEquationP.Clear;
FEquationK.Clear;
FAnalysisK.Clear;
end;
constructor TWE_EQUATION.Create;
var
i: Integer;
begin
FExpression := TWE_EXPRESSION.Create;
FEquationP := TStringList.Create;
FEquationK := TStringList.Create;
FAnalysisK := TStringList.Create;
FPhaseEquations := TList.create;
FFourPower:= TFourPower.create;
FThreePower:= TThreePower.create;
for i := 0 to 3 - 1 do
FPhaseEquations.Add( TWE_PHASE_EXPRESSION.Create );
FRunTpye := 0;
end;
procedure TWE_EQUATION.CreateExpression3;
function GetUValue(sValue : string):Double;
begin
if sValue = '' then
Result := -1
else if Pos(C_EQ_SIGN_1_2, sValue) > 0 then
Result := 0.5
else if Pos(C_EQ_SIGN_SQRT3_2, sValue) > 0 then
Result := 0.866
else if Pos(C_EQ_SIGN_SQRT3, sValue) > 0 then
Result := 1.732
else
Result := 1;
end;
function GetIValue(sValue : string):Double;
begin
if sValue = '' then
Result := -1
else
Result := 1;
end;
function GetAngle(dA1,dA2 : Double):Double;
begin
Result := dA1 - dA2;
if Result > 360 then
Result := Result - 360;
if Result < 0 then
Result := Result + 360;
end;
var
i: Integer;
AEXPRESSION : TWE_PHASE_EXPRESSION;
dU1, dU2 : Double;
begin
FExpression.GetExpressions3( [ GetPhaseEquation( 0 ), GetPhaseEquation( 1 ) ] );
for i := 0 to 2 - 1 do
AnalysisExpression( GetPhaseEquation( i ) );
dU1 := 0;
dU2 := 0;
for i := 0 to 3 - 1 do
begin
AEXPRESSION := GetPhaseEquation( i );
FThreePower.Errorcode := WiringError.IDInStr;
FThreePower.Errorcount := WiringError.ErrorCount;
FThreePower.Angle := FExpression.UIAngle;
case i of
0:
begin
FThreePower.U12 := GetUValue(AEXPRESSION.ExpressU);
FThreePower.I1 := GetIValue(AEXPRESSION.ExpressI);
if (FThreePower.U12 <> -1) and (FThreePower.I1 <> -1) then
FThreePower.U12i1 := GetAngle(AEXPRESSION.AngleU, AEXPRESSION.AngleI)
else
FThreePower.U12i1 := -1;
dU1 := AEXPRESSION.AngleU;
end;
1:
begin
FThreePower.U32 := GetUValue(AEXPRESSION.ExpressU);
FThreePower.I3 := GetIValue(AEXPRESSION.ExpressI);
if (FThreePower.U32 <> -1) and (FThreePower.I3 <> -1) then
FThreePower.U32i3 := GetAngle(AEXPRESSION.AngleU, AEXPRESSION.AngleI)
else
FThreePower.U32i3 := -1;
dU2 := AEXPRESSION.AngleU;
end;
end;
end;
if (FThreePower.U12 <> -1) and (FThreePower.U32 <> -1) then
FThreePower.U12u32 := GetAngle(dU1, dU2)
else
FThreePower.U12u32 := -1;
end;
procedure TWE_EQUATION.CreateExpression4;
function GetUIValue(sValue : string):Double;
begin
if sValue = '' then
Result := -1
else
Result := 1;
end;
function GetAngle(dA1,dA2 : Double):Double;
begin
Result := dA1 - dA2;
if Result > 360 then
Result := Result - 360;
if Result < 0 then
Result := Result + 360;
end;
var
i: Integer;
AEXPRESSION : TWE_PHASE_EXPRESSION;
dU1, dU2, dU3 : Double;
begin
FExpression.GetExpressions4( [ GetPhaseEquation( 0 ), GetPhaseEquation( 1 ),
GetPhaseEquation( 2 ) ] );
for i := 0 to 3 - 1 do
AnalysisExpression( GetPhaseEquation( i ) );
dU1 := 0;
dU2 := 0;
dU3 := 0;
for i := 0 to 3 - 1 do
begin
AEXPRESSION := GetPhaseEquation( i );
FFourPower.Errorcode := WiringError.IDInStr;
FFourPower.Errorcount := WiringError.ErrorCount;
FFourPower.Angle := FExpression.UIAngle;
case i of
0:
begin
FFourPower.U1 := GetUIValue(AEXPRESSION.ExpressU);
FFourPower.I1 := GetUIValue(AEXPRESSION.ExpressI);
if (FFourPower.U1 <> -1) and (FFourPower.I1 <> -1) then
FFourPower.U1i1 := GetAngle(AEXPRESSION.AngleU, AEXPRESSION.AngleI)
else
FFourPower.U1i1 := -1;
dU1 := AEXPRESSION.AngleU;
end;
1:
begin
FFourPower.U2 := GetUIValue(AEXPRESSION.ExpressU);
FFourPower.I2 := GetUIValue(AEXPRESSION.ExpressI);
if (FFourPower.U2 <> -1) and (FFourPower.I2 <> -1) then
FFourPower.U2i2 := GetAngle(AEXPRESSION.AngleU, AEXPRESSION.AngleI)
else
FFourPower.U2i2 := -1;
dU2 := AEXPRESSION.AngleU;
end;
2:
begin
FFourPower.U3 := GetUIValue(AEXPRESSION.ExpressU);
FFourPower.I3 := GetUIValue(AEXPRESSION.ExpressI);
if (FFourPower.U3 <> -1) and (FFourPower.I3 <> -1) then
FFourPower.U3i3 := GetAngle(AEXPRESSION.AngleU, AEXPRESSION.AngleI)
else
FFourPower.U3i3 := -1;
dU3 := AEXPRESSION.AngleU;
end;
end;
end;
if (dU1 <> -1) and (dU2 <> -1) then
FFourPower.U1u2 := GetAngle(dU1, dU2)
else
FFourPower.U1u2 := -1;
if (dU2 <> -1) and (dU3 <> -1) then
FFourPower.U2u3 := GetAngle(dU2, dU3)
else
FFourPower.U2u3 := -1;
if (dU1 <> -1) and (dU3 <> -1) then
FFourPower.U1u3 := GetAngle(dU1, dU3)
else
FFourPower.U1u3 := -1;
end;
procedure TWE_EQUATION.CreateExpression4PT;
var
i: Integer;
begin
FExpression.GetExpressions4PT( [ GetPhaseEquation( 0 ), GetPhaseEquation( 1 ),
GetPhaseEquation( 2 ) ] );
for i := 0 to 3 - 1 do
AnalysisExpression( GetPhaseEquation( i ) );
end;
procedure TWE_EQUATION.CreateExpressionSingle;
begin
FExpression.GetExpressionsSingle( GetPhaseEquation( 0 ));
AnalysisExpression( GetPhaseEquation( 0 ) );
end;
destructor TWE_EQUATION.Destroy;
var
i: Integer;
begin
for i := 0 to 3 - 1 do
GetPhaseEquation( i ).Free;
FPhaseEquations.Free;
FEquationP.Free;
FEquationK.Free;
FAnalysisK.Free;
FExpression.Free;
FFourPower.Free;
FThreePower.Free;
inherited;
end;
function TWE_EQUATION.FinalEquation : string;
var
anCos, anSin : array of string;
sCoCos, sCoSin : string;
sCoUI : string;
i: Integer;
FracCos, FracR3Cos : TWE_FRAC;
FracSin, FracR3Sin : TWE_FRAC;
nUIFactor : Integer;
begin
Result := '';
SetLength( anCos, 3 );
SetLength( anSin, 3 );
for i := 0 to 3 - 1 do
begin
anCos[ i ] := GetPhaseEquation( i ).CoCos;
anSin[ i ] := GetPhaseEquation( i ).CoSin;
end;
// 数据相加
PlusCoefs( anCos, FracCos, FracR3Cos );
PlusCoefs( anSin, FracSin, FracR3Sin );
// 提取UI的系数
nUIFactor := GetFactor( [ FracCos.n, FracR3Cos.n, FracSin.n, FracR3Sin.n ] );
if Abs( nUIFactor ) = 1 then
begin
if nUIFactor < 0 then
sCoUI := '-'
else
sCoUI := '';
end
else
sCoUI := IntToStr( nUIFactor );
// 获取完整的系数
if ( nUIFactor > 1 ) or ( nUIFactor < 0 ) then
begin
FracCos.n := FracCos.n div nUIFactor;
FracR3Cos.n := FracR3Cos.n div nUIFactor;
FracSin.n := FracSin.n div nUIFactor;
FracR3Sin.n := FracR3Sin.n div nUIFactor;
end;
sCoCos := PlusExpressions( GenCoef( FracCos, False ),
GenCoef( FracR3Cos, True ) );
sCoSin := PlusExpressions( GenCoef( FracSin, False ),
GenCoef( FracR3Sin, True ) );
if ( sCoCos = EmptyStr ) and ( sCoSin <> EmptyStr ) then
begin
Result := sCoSin + 'UIsin\o';
end
else if ( sCoCos <> EmptyStr ) and ( sCoSin = EmptyStr ) then
begin
Result := sCoCos + 'UIcos\o';
end
else if ( sCoCos <> EmptyStr ) and ( sCoSin <> EmptyStr ) then
begin
Result := Format( '%sUI(%s)', [ scoUI, PlusExpressions(
MultiplyExpressions( sCoCos, 'cos\o' ),
MultiplyExpressions( sCoSin, 'sin\o' ) ) ] );
end
else
begin
Result := '0';
end;
Result := StringReplace( Result, '1U', 'U', [rfIgnoreCase] );
end;
procedure TWE_EQUATION.GenerateEquations( AWE : TWIRING_ERROR; AUIAngle : Double );
begin
FExpression.UIAngle := AUIAngle;
FExpression.WiringError := AWE;
GenerateEquations;
end;
procedure TWE_EQUATION.GenerateEquations;
var
WErr : TWIRING_ERROR;
begin
CleanEquation;
WErr := GetWiringError;
if Assigned( WErr ) then
if WErr.PhaseType = ptThree then
begin
CreateExpression3;
CalEquationP3;
end
else if WErr.PhaseType = ptFour then
begin
CreateExpression4;
CalEquationP4;
end
else if WErr.PhaseType = ptFourPT then
begin
CreateExpression4PT;
CalEquationP4PT;
end
else if WErr.PhaseType = ptSingle then
begin
CreateExpression4;
CalEquationSingle;
end;
CalEquationK;
end;
function TWE_EQUATION.GetPhaseEquation(
const AIndex: Integer): TWE_PHASE_EXPRESSION;
begin
if AIndex in [ 0.. FPhaseEquations.Count - 1 ]then
Result := TWE_PHASE_EXPRESSION( FPhaseEquations.Items[ AIndex ] )
else
Result := nil;
end;
function TWE_EQUATION.GetUIAngle: Double;
begin
Result := FExpression.UIAngle;
end;
function TWE_EQUATION.GetWiringError: TWIRING_ERROR;
begin
Result := FExpression.WiringError;
end;
procedure TWE_EQUATION.SetUIAngle(const Value: Double);
begin
FExpression.UIAngle := Value;
GenerateEquations;
end;
procedure TWE_EQUATION.SetWiringError(const Value: TWIRING_ERROR);
begin
FExpression.WiringError := Value;
GenerateEquations;
end;
procedure TWE_EQUATION.ShowAnalysis(AText: TStrings; AMaxSize: Integer);
procedure AddString( AStr : string; AIndex : Integer = -1 );
var
nPosComma : Integer; // 逗号位置
sFirstStr : string;
begin
if AIndex = -1 then
sFirstStr := ' '
else
sFirstStr := IntToStr( AIndex + 1 )+ '. ';
// 字符串长度过长,需要拆分
if Length( AStr ) > AMaxSize then
begin
nPosComma := AnsiPos( ',', AStr );
AText.Add( sFirstStr + Copy( AStr, 1, nPosComma + 1 ));
AddString( Copy( AStr, nPosComma + 2, Length( AStr ) - nPosComma - 1 ) );
end
else
AText.Add( sFirstStr + AStr );
end;
var
i : Integer;
nPosSemi : Integer; // 分号位置
sTemp : string;
begin
AText.Clear;
if FAnalysisK.Count = 0 then
Exit
else if FAnalysisK.Count = 1 then
AText.Add( FAnalysisK[ 0 ] )
else
for i := 0 to FAnalysisK.Count - 1 do
begin
if Pos( ';', FAnalysisK[ i ] ) > 0 then // 包含;号的 拆分
begin
nPosSemi := Pos(';', FAnalysisK[ i ] );
AddString( Copy( FAnalysisK[ i ], 1, nPosSemi + 1), i );
sTemp := Copy( FAnalysisK[ i ], nPosSemi + 2, Length( FAnalysisK[ i ] ) - nPosSemi );
while sTemp <> '' do
begin
if Pos( ';', sTemp ) > 0 then // 包含;号的 拆分
begin
nPosSemi := Pos(';', sTemp);
AddString( Copy( sTemp, 1, nPosSemi + 1) );
sTemp := Copy( sTemp, nPosSemi + 2, Length(sTemp) - nPosSemi);
end
else
begin
AddString( sTemp );
sTemp := '';
end;
end;
end
else
AddString( FAnalysisK[ i ], i );
AText.Add( EmptyStr );
end;
end;
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Специальный клас-переходник, позволяющий представить значения индикатора как
коллецию данных (ISCInputDataCollection)
History:
-----------------------------------------------------------------------------}
unit FC.StockData.IndicatorToInputDataCollectionMediator;
{$I Compiler.inc}
interface
uses BaseUtils,SysUtils, Classes, Controls, Serialization,
StockChart.Definitions,StockChart.Definitions.Units, FC.Definitions, StockChart.Obj;
type
//----------------------------------------------------------------------------
TEventMediator = class;
IStockIndicatorToInputDataCollectionMediator = interface
['{70CD9A6D-3682-4552-BD9B-F5A3FA30AE90}']
function GetDataSource: ISCIndicator;
end;
TStockIndicatorToInputDataCollectionMediator = class (TSCInputDataCollection_B,IStockIndicatorToInputDataCollectionMediator,ISCInputDataCollectionCustomDataSupport)
private
FIndicator_ : ISCIndicator;
FIndicator : ISCIndicatorValueSupport;
FEventMediator : TEventMediator;
procedure CheckMutualdependence(const aIndicator: ISCIndicator);
public
constructor Create(const aDS:ISCIndicator; AOwner: ISCChangeNotifier);
destructor Destroy; override;
function ISCInputDataCollection_GetItem(Index: Integer): ISCInputData; override;
function DirectGetItem_DataDateTime(index: integer):TDateTime; override;
function DirectGetItem_DataClose(index: integer): TStockRealNumber; override;
function DirectGetItem_DataHigh(index: integer): TStockRealNumber; override;
function DirectGetItem_DataLow(index: integer): TStockRealNumber; override;
function DirectGetItem_DataOpen(index: integer): TStockRealNumber; override;
function DirectGetItem_DataVolume(index: integer): integer; override;
function Count: integer; override;
procedure SetDataSource(const aDS: ISCIndicator);
//from IStockIndicatorToInputDataCollectionMediator
function GetDataSource: ISCIndicator;
//from ISCInputDataCollectionCustomDataSupport
function Caption: string;
end;
TEventMediator = class (TInterfacedObject,ISCInputDataCollectionEventHandler)
private
FEventHandlers:TInterfaceList; //ISCInputDataCollectionEventHandler
FOwner : TStockIndicatorToInputDataCollectionMediator;
public
procedure OnChangeItem(const aSender: ISCInputDataCollection; aIndex: integer; aType: TSCInputDataCollectionChangeType);
constructor Create(aOwner: TStockIndicatorToInputDataCollectionMediator);
destructor Destroy; override;
end;
implementation
uses Math;
type
//----------------------------------------------------------------------------
//Класс для описания одного элемента входных данных
TDataMediator = class (TInterfacedObjectEx,ISCInputData)
private
FValue : TStockRealNumber;
FDateTime: TDateTime;
FVolume : integer;
protected
function _Release: Integer; override; stdcall;
public
//from ISCInputData
function GetDataClose: TStockRealNumber;
function GetDataHigh: TStockRealNumber;
function GetDataLow: TStockRealNumber;
function GetDataOpen: TStockRealNumber;
function GetDataVolume: integer;
function GetDataDateTime: TDateTime;
function IsBullish: boolean;
function IsBearish: boolean;
end;
const
gReserveInputDataObjectsSize = 1024;
var
gReserveInputDataObjects : array [0..gReserveInputDataObjectsSize-1] of TDataMediator;
gReserveInputDataObjectsCounter: integer;
{ TSCInputDataMediator }
function TDataMediator.GetDataOpen: TStockRealNumber;
begin
result:=FValue;
end;
function TDataMediator.GetDataHigh: TStockRealNumber;
begin
result:=FValue;
end;
function TDataMediator.GetDataDateTime: TDateTime;
begin
result:=FDateTime;
end;
function TDataMediator.GetDataVolume: integer;
begin
result:=FVolume;
end;
function TDataMediator.GetDataClose: TStockRealNumber;
begin
result:=FValue;
end;
function TDataMediator.GetDataLow: TStockRealNumber;
begin
result:=FValue;
end;
function TDataMediator._Release: Integer;
begin
Dec(FRefCount);
Result:=FRefCount;
ASSERT(Result >= 0);
if (Result=0) then
begin
if gReserveInputDataObjectsCounter<gReserveInputDataObjectsSize then
begin
gReserveInputDataObjects[gReserveInputDataObjectsCounter]:=self;
inc(gReserveInputDataObjectsCounter);
end
else
self.free;
end;
end;
function TDataMediator.IsBullish: boolean;
begin
result:=GetDataOpen<GetDataClose;
end;
function TDataMediator.IsBearish: boolean;
begin
result:=GetDataOpen>GetDataClose;
end;
{ TStockIndicatorToInputDataCollectionMediator }
constructor TStockIndicatorToInputDataCollectionMediator.Create(const aDS:ISCIndicator; AOwner: ISCChangeNotifier);
begin
inherited Create(AOwner,0.0);
FEventMediator:=TEventMediator.Create(self);
IInterface(FEventMediator)._AddRef;
SetDataSource(aDS);
end;
destructor TStockIndicatorToInputDataCollectionMediator.Destroy;
begin
inherited;
FEventMediator.FOwner:=nil;
IInterface(FEventMediator)._Release;
FEventMediator:=nil;
end;
function TStockIndicatorToInputDataCollectionMediator.Caption: string;
begin
if FIndicator_=nil then
result:=''
else
result:=FIndicator_.Caption;
end;
procedure TStockIndicatorToInputDataCollectionMediator.CheckMutualdependence(const aIndicator: ISCIndicator);
var
aMediator: IStockIndicatorToInputDataCollectionMediator;
begin
if aIndicator.GetInputData=nil then
exit;
if not Supports(aIndicator.GetInputData,IStockIndicatorToInputDataCollectionMediator,aMediator) then
exit;
if aMediator=IStockIndicatorToInputDataCollectionMediator(self) then
raise EStockError.Create('Mutual dependence detected');
CheckMutualdependence(aMediator.GetDataSource);
end;
function TStockIndicatorToInputDataCollectionMediator.Count: integer;
begin
if (FIndicator=nil) or (FIndicator_.GetInputData=nil) then
result:=0
else
result:=FIndicator_.GetInputData.Count;
end;
function TStockIndicatorToInputDataCollectionMediator.ISCInputDataCollection_GetItem(Index: Integer): ISCInputData;
var
aDataItem: TDataMediator;
begin
if gReserveInputDataObjectsCounter>0 then
begin
dec(gReserveInputDataObjectsCounter);
aDataItem:=gReserveInputDataObjects[gReserveInputDataObjectsCounter];
gReserveInputDataObjects[gReserveInputDataObjectsCounter+1]:=nil;
end
else begin
aDataItem:=TDataMediator.Create;
end;
aDataItem.FValue:=FIndicator.GetValue(index);
with FIndicator_.GetInputData do
begin
aDataItem.FDateTime:=DirectGetItem_DataDateTime(index);
aDataItem.FVolume:=DirectGetItem_DataVolume(index);
end;
result:=aDataItem;
end;
procedure TStockIndicatorToInputDataCollectionMediator.SetDataSource(const aDS: ISCIndicator);
begin
if FIndicator_<>aDS then
begin
CheckMutualdependence(aDS);
if FIndicator_<>nil then
FIndicator_.GetInputData.RemoveEventHandler(FEventMediator);
FIndicator_:=aDS;
FIndicator:=aDS as ISCIndicatorValueSupport;
if FIndicator_<>nil then
begin
FIndicator_.GetInputData.AddEventHandler(FEventMediator);
SetGradation(FIndicator_.GetInputData.GetGradation);
end;
OnItemsChanged;
end;
end;
function TStockIndicatorToInputDataCollectionMediator.GetDataSource: ISCIndicator;
begin
result:=FIndicator_;
end;
function TStockIndicatorToInputDataCollectionMediator.DirectGetItem_DataOpen(index: integer): TStockRealNumber;
begin
result:=FIndicator.GetValue(index);
end;
function TStockIndicatorToInputDataCollectionMediator.DirectGetItem_DataHigh(index: integer): TStockRealNumber;
begin
result:=FIndicator.GetValue(index);
end;
function TStockIndicatorToInputDataCollectionMediator.DirectGetItem_DataDateTime(index: integer): TDateTime;
begin
result:=FIndicator_.GetInputData.DirectGetItem_DataDateTime(index)
end;
function TStockIndicatorToInputDataCollectionMediator.DirectGetItem_DataVolume(index: integer): integer;
begin
result:=FIndicator_.GetInputData.DirectGetItem_DataVolume(index)
end;
function TStockIndicatorToInputDataCollectionMediator.DirectGetItem_DataClose(index: integer): TStockRealNumber;
begin
result:=FIndicator.GetValue(index);
end;
function TStockIndicatorToInputDataCollectionMediator.DirectGetItem_DataLow(index: integer): TStockRealNumber;
begin
result:=FIndicator.GetValue(index);
end;
procedure CleanupInputDataObjects;
var
i: integer;
begin
for i:=0 to gReserveInputDataObjectsSize-1 do
FreeAndNil(gReserveInputDataObjects[i]);
end;
{ TEventMediator }
constructor TEventMediator.Create(aOwner: TStockIndicatorToInputDataCollectionMediator);
begin
FEventHandlers := TInterfaceList.Create;
FOwner:=aOwner;
end;
destructor TEventMediator.Destroy;
begin
FreeAndNil(FEventHandlers);
FOwner:=nil;
inherited;
end;
procedure TEventMediator.OnChangeItem(const aSender: ISCInputDataCollection; aIndex: integer; aType: TSCInputDataCollectionChangeType);
begin
if FOwner<>nil then
FOwner.OnItemChanged(aIndex,aType);
end;
initialization
finalization
CleanupInputDataObjects;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Grids, IniFiles, ShellApi,
// XLSReadWriteII units.
XLSReadWriteII5, XLSHyperlinks5, Xc12Utils5, Xc12DataStylesheet5, XLSSheetData5,
XPMan;
type TDoubleArray = array of double;
type
TfrmMain = class(TForm)
Panel1: TPanel;
btnRead: TButton;
btnWrite: TButton;
edReadFilename: TEdit;
edWriteFilename: TEdit;
btnDlgOpen: TButton;
btnDlgSave: TButton;
dlgSave: TSaveDialog;
dlgOpen: TOpenDialog;
Button1: TButton;
Grid: TStringGrid;
btnAddCells: TButton;
XLS: TXLSReadWriteII5;
Button2: TButton;
XPManifest1: TXPManifest;
procedure btnCloseClick(Sender: TObject);
procedure btnReadClick(Sender: TObject);
procedure btnWriteClick(Sender: TObject);
procedure btnDlgOpenClick(Sender: TObject);
procedure btnDlgSaveClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnAddCellsClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
procedure AddHyperlinks;
procedure ReadHyperlinks;
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
procedure TfrmMain.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfrmMain.btnReadClick(Sender: TObject);
begin
XLS.Filename := edReadFilename.Text;
XLS.Read;
ReadHyperlinks;
end;
procedure TfrmMain.btnWriteClick(Sender: TObject);
begin
XLS.Filename := edWriteFilename.Text;
XLS.Write;
end;
procedure TfrmMain.btnDlgOpenClick(Sender: TObject);
begin
dlgOpen.InitialDir := ExtractFilePath(Application.ExeName);
dlgOpen.FileName := edReadFilename.Text;
if dlgOpen.Execute then
edReadFilename.Text := dlgOpen.FileName;
end;
procedure TfrmMain.btnDlgSaveClick(Sender: TObject);
begin
dlgSave.InitialDir := ExtractFilePath(Application.ExeName);
dlgSave.FileName := edWriteFilename.Text;
if dlgSave.Execute then
edWriteFilename.Text := dlgSave.FileName;
end;
procedure TfrmMain.Button1Click(Sender: TObject);
begin
Close;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
var
S: string;
Ini: TIniFile;
begin
S := ChangeFileExt(Application.ExeName,'.ini');
Ini := TIniFile.Create(S);
try
edReadFilename.Text := Ini.ReadString('Files','Read','');
edWriteFilename.Text := Ini.ReadString('Files','Write','');
finally
Ini.Free;
end;
Grid.Cells[0,0] := 'Cell';
Grid.Cells[1,0] := 'Address';
Grid.Cells[2,0] := 'Type';
Grid.Cells[3,0] := 'Description';
Grid.Cells[4,0] := 'Tooltip';
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
var
S: string;
Ini: TIniFile;
begin
S := ChangeFileExt(Application.ExeName,'.ini');
Ini := TIniFile.Create(S);
try
Ini.WriteString('Files','Read',edReadFilename.Text);
Ini.WriteString('Files','Write',edWriteFilename.Text);
finally
Ini.Free;
end;
end;
procedure TfrmMain.btnAddCellsClick(Sender: TObject);
begin
AddHyperlinks;
ReadHyperlinks;
end;
procedure TfrmMain.AddHyperlinks;
var
HLink: TXLSHyperlink;
begin
// There can be four types of hyperlinks:
// 1. URL, an internet address (http://, ftp:// , mailto:).
// 2. UNC, a network file address (\\MyServer\ ...).
// 3. The current workbook (Sheet1!B2).
// 4. A local file.
// The hyperlink type is detected automatically. If it don't matches any of the
// first three, it is assumed to be a local file. This can be changed with the
// HyperlinkType property.
// Hyperlinks are in the Hyperlink property of the worksheet. This property
// contains the address settings for the hyperlink, but not the cell text.
// That is stored as a normal cell value.
// There are several options for creating hyperlinks:
// *****************************************************************************
// 1. Add a Hyperlink object.
HLink := XLS[0].Hyperlinks.Add;
// The cell of the hyperlink.
HLink.Col1 := 1;
HLink.Row1 := 4;
HLink.Col2 := 1;
HLink.Row2 := 4;
// The URL must start with http:// otherwhise will Excel think the address is a file.
HLink.Address := 'http://www.embarcadero.com';
// Optional tooltip.
HLink.Tooltip := 'Embarcadero sells Delphi and burning monkeys';
// Description is not used by Excel.
HLink.Description := '???';
// Set cell value and standard hyperlink formatting (blue text and underline).
XLS[0].AsString[1,4] := 'Embarcadero';
XLS[0].Cell[1,4].FontColor := $000000FF;
XLS[0].Cell[1,4].FontUnderline := xulSingle;
// *****************************************************************************
// 2. Use the AsHyperlink property. This will set the address options.
// AsHyperlink will add http:// to the address if it starts with www
XLS[0].AsHyperlink[1,5] := 'http://www.embarcadero.com';
// Set cell value
XLS[0].AsString[1,5] := 'Embarcadero';
XLS[0].Cell[1,5].FontColor := $000000FF;
XLS[0].Cell[1,5].FontUnderline := xulSingle;
// *****************************************************************************
// 3. Use the MakeHyperlink method. Parameters are: Col,Row,Address,[Tooltip]
// MakeHyperlink will add http:// to the address if it starts with www
XLS[0].MakeHyperlink(1,6,'www.borland.com','Borland');
XLS[0].MakeHyperlink(1,7,'www.borland.com','Borland','Borland do not sell Delphi anymore.');
// Add a mail address
XLS[0].MakeHyperlink(1,8,'mailto:monkeys@embarcadero.com','Embarcadero');
// Add a cell reference in the workbook.
XLS[0].MakeHyperlink(1,8,'Sheet1!E10','Cell E10');
// Add a disk file.
XLS[0].MakeHyperlink(1,9,'c:\temp\text.txt','Text file');
end;
procedure TfrmMain.ReadHyperlinks;
var
i: integer;
HLink: TXLSHyperlink;
begin
for i := 0 to XLS[0].Hyperlinks.Count - 1 do begin
if i >= Grid.RowCount then
Exit;
HLink := XLS[0].Hyperlinks[i];
Grid.Cells[0,i + 1] := ColRowToRefStr(HLink.Col1,HLink.Row1);
Grid.Cells[1,i + 1] := HLink.Address;
case HLink.HyperlinkType of
xhltUnknown : Grid.Cells[2,i + 1] := '[Unknown]';
xhltURL : Grid.Cells[2,i + 1] := 'URL';
xhltFile : Grid.Cells[2,i + 1] := 'File';
xhltUNC : Grid.Cells[2,i + 1] := 'UNC';
xhltWorkbook: Grid.Cells[2,i + 1] := 'Workbook';
end;
Grid.Cells[3,i + 1] := HLink.Description;
Grid.Cells[4,i + 1] := HLink.Tooltip;
end;
end;
procedure TfrmMain.Button2Click(Sender: TObject);
begin
ShellExecute(Handle,'open', 'excel.exe',PWideChar(edWriteFilename.Text), nil, SW_SHOWNORMAL);
end;
end.
|
unit ncaFrmAlertaPIN;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, Vcl.Menus, Vcl.StdCtrls,
cxButtons, LMDControl, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel,
LMDSimplePanel, cxLabel, cxCheckBox;
type
TFrmAlertaPIN = class(TForm)
cxLabel1: TcxLabel;
LMDSimplePanel4: TLMDSimplePanel;
btnSalvar: TcxButton;
lbPINBranco: TcxLabel;
cbCiente: TcxCheckBox;
cxLabel3: TcxLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnSalvarClick(Sender: TObject);
private
{ Private declarations }
public
function Ciente(aMostrarPINBranco: Boolean): Boolean;
{ Public declarations }
end;
var
FrmAlertaPIN: TFrmAlertaPIN;
implementation
{$R *.dfm}
procedure TFrmAlertaPIN.btnSalvarClick(Sender: TObject);
begin
if not cbCiente.Checked then
raise Exception.Create('É necessário marcar a opção que você está ciente sobre perder o certificado caso informe um PIN errado');
ModalResult := mrOk;
end;
function TFrmAlertaPIN.Ciente(aMostrarPINBranco: Boolean): Boolean;
begin
lbPINBranco.Visible := aMostrarPINBranco;
ShowModal;
Result := (ModalResult=mrOk);
end;
procedure TFrmAlertaPIN.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
end.
|
unit WasmTest_ShareMemory;
interface
uses
System.SysUtils
, Wasm
{$ifndef USE_WASMER}
, Wasmtime
{$else}
, Wasmer
{$ifend}
;
function ShareMemory() : Boolean;
implementation
// A function to be called from Wasm code.
function callback(const args : PWasmValVec; results : PWasmValVec) : PWasmTrap; cdecl;
begin
writeln('Calling back...');
write('> ');
writeln( Format('> %x %x %x %x', [
args.Items[0].i32, args.Items[1].i32,
args.Items[2].i32, args.Items[3].i32]));
writeln('');
TWasm.val_copy(results.Items.Pointers[0], args.Items.Pointers[3]);
TWasm.val_copy(results.Items.Pointers[1], args.Items.Pointers[2]);
TWasm.val_copy(results.Items.Pointers[2], args.Items.Pointers[1]);
TWasm.val_copy(results.Items.Pointers[3], args.Items.Pointers[0]);
result := nil;
end;
function ShareMemory() : Boolean;
begin
// Initialize.
writeln('Initializing...');
var engine := TWasmEngine.New();
var store := TWasmStore.New(+engine);
// Load binary.
writeln('Loading binary (import memory)...');
var binary := TWasmByteVec.NewEmpty;
var wat :=
'(module'+
' (memory (import "" "memory") 1)'+
' (func $f (import "" "f") (param i32 i32 i32 i32) (result i32 i32 i32 i32))'+
''+
' (func $g (export "g") (result i32 i32 i32 i32)'+
' (i32.load (i32.const 0x0000))'+
' (i32.load (i32.const 0x1004))'+
' (i32.load (i32.const 0x1008))'+
' (i32.load (i32.const 0x100C))'+
' (call $f)'+
' )'+
' (data (i32.const 0x0) "\55\AA\55\AA")'+
')';
binary.Unwrap.Wat2Wasm(wat);
// Compile.
writeln('Compiling import memory module...');
var module := TWasmModule.New(+store, +binary);
if module.IsNone then
begin
writeln('> Error compiling import memory module!');
exit(false)
end;
writeln('Loading binary (export memory)...');
var wat2 :=
'(module'+
' (memory (export "memory") 1)'+
''+
' (func (export "size") (result i32) (memory.size))'+
' (func (export "load") (param i32) (result i32) (i32.load8_s (local.get 0)))'+
' (func (export "store") (param i32 i32)'+
' (i32.store8 (local.get 0) (local.get 1))'+
' )'+
''+
' (data (i32.const 0x1000) "\01\00\01\00\02\00\02\00\03\00\03\00\04\05\06\07")'+
')';
binary.Unwrap.Wat2Wasm(wat2);
writeln('Compiling export memory module...');
var module2 := TWasmModule.New(+store, +binary);
if module2.IsNone then
begin
writeln('> Error compiling export module!');
exit(false)
end;
writeln('Instantiating export memory module...');
var imports2 := TWasmExternVec.Create([]);
var instance2 := TWasmInstance.New(+store, +module2, @imports2);
if instance2.IsNone then
begin
writeln('> Error instantiating export module!');
exit(false);
end;
var export_s2 := (+instance2).GetExports;
// Create external print functions.
writeln('Creating callback...');
var callback_func := TWasmFunc.New(+store, +TWasmFunctype.New([WASM_I32, WASM_I32, WASM_I32, WASM_I32], [WASM_I32, WASM_I32, WASM_I32, WASM_I32]), callback);
Assert(export_s2.Unwrap.Items[0].AsMemory <> nil);
// Instantiate.
writeln('Instantiating import memory module...');
var imports := TWasmExternVec.Create([ export_s2.Unwrap.Items[0], (+callback_func).AsExtern ]);
var instance := TWasmInstance.New(+store, +module, @imports);
if instance.IsNone then
begin
writeln('> Error instantiating import memory module!');
exit(false);
end;
// TWasm.func_delete(callback_func);
// Extract export.
writeln('Extracting export...');
var export_s := (+instance).GetExports;
if export_s.Unwrap.size = 0 then
begin
writeln('> Error accessing exports!');
exit(false);
end;
var run_func := export_s.Unwrap.Items[0].AsFunc;
if run_func = nil then
begin
writeln('> Error accessing export!');
exit(false);
end;
// Call.
writeln('Calling import memory func...');
var res := [
WASM_INIT_VAL, WASM_INIT_VAL, WASM_INIT_VAL, WASM_INIT_VAL
];
var args := TWasmValVec.Create([]);
var results := TWasmValVec.Create(res);
if run_func.Call( @args, @results).IsError then
begin
writeln('> Error calling function!');
exit(false);
end;
// Print result.
writeln('Printing result...');
writeln( Format('> %x %x %x %x', [
res[0].i32, res[1].i32, res[2].i32, res[3].i32]));
assert(res[0].i32 = $07060504);
assert(res[1].i32 = $030003);
assert(res[2].i32 = $020002);
assert(UInt32(res[3].i32) = $AA55AA55);
// Shut down.
writeln('Shutting down...');
// All done.
writeln('Done.');
result := true;
end;
end.
|
unit CSTokens;
interface
uses
SysUtils, Classes;
resourcestring
// Erros léxicos
sStringIncomplete = 'Texto incompleto';
sUnexpectedEndOfSourceInComment = 'Fim de arquivo inesperado em um comentário';
sPushBackError = 'Erro interno em PushBack';
sInvalidRealNumber = 'Número real inválido';
sInvalidIntNumber = 'Número inteiro inválido';
sInvalidHexNumber = 'Número hexadecimal inválido';
sInvalidControlString = 'Texto de controle inválido';
sInvalidOperator = 'Operador inválido';
const
STRQUOTE = '"';
type
{ TToken }
TToken = (
// palavras reservadas
tkRWand,
tkRWarray,
tkRWbegin,
tkRWboolean,
tkRWcase,
tkRWchar,
tkRWconst,
tkRWdispose,
tkRWdiv,
tkRWdo,
tkRWdownto,
tkRWelse,
tkRWend,
tkRWfalse,
tkRWfile,
tkRWfor,
tkRWforward,
tkRWfunction,
tkRWif,
tkRWin,
tkRWinclude,
tkRWinteger,
tkRWmod,
tkRWnew,
tkRWnil,
tkRWnot,
tkRWof,
tkRWor,
tkRWprocedure,
tkRWprogram,
tkRWread,
tkRWreal,
tkRWrecord,
tkRWrepeat,
tkRWreturn,
tkRWset,
tkRWshl,
tkRWshr,
tkRWstring,
tkRWthen,
tkRWto,
tkRWtrue,
tkRWtype,
tkRWuntil,
tkRWvar,
tkRWwhile,
tkRWwith,
tkRWwrite,
tkRWwriteln,
tkRWxor,
tkRWyes,
tkRWyesOrNo,
tkRWpointer,
tkRWchoose,
// especiais
tkAny, tkUnknown, tkUnaryMinus, tkEndOfSource, tkComment, tkBlank,
// símbolos
tkId, tkIntNumber, tkFloatNumber, tkHexNumber, tkString, tkChar,
// tokens de 1 caracter
tkPlus, tkMinus, tkTimes, tkSlash, tkEqual, tkLT, tkGT, tkLBracket,
tkRBracket, tkPeriod, tkComma, tkLParen, tkRParen, tkColon, tkSemiColon,
tkCaret, tkAt, tkDollar, tkFence,
// pares de caracteres
tkLE, tkGE, tkNE, tkAssign, tkDotDot
);
{ TTokens }
TTokens = set of TToken;
{ TTokenValue }
TTokenValue = class
private
FInteger: Integer;
FChar: Char;
FExtended: Extended;
FString: String;
public
property AsInteger: Integer read FInteger;
property AsChar: Char read FChar;
property AsExtended: Extended read FExtended;
property AsString: String read FString;
end;
{ CSTokenizer - C# Tokenizer}
CSTokenizer = class
private
FStream: TStream;
FBuffer: PChar;
FBufEnd: PChar;
FBufPos: PChar;
FDotDot: Boolean;
FNewLine: Boolean;
FPosition: Integer;
FSourceLine: Integer;
FSourceCol: Integer;
FTokenLine: Integer;
FTokenCol: Integer;
FTokenPosition: Integer;
FTokenStr: String;
FTokenValue: TTokenValue;
FCurrentToken: TToken;
CurrentChar: Char;
FName: String;
function CheckHexNumber(S: String): Integer;
function CheckRealNumber(S: String): Extended;
function CheckIntNumber(S: String): Integer;
function CheckReservedWord(S: String): TToken;
function GetChar: Char;
procedure GetQuotedString;
procedure GetControlString;
procedure Error(S: String);
procedure PushBack(Current: Char);
protected
procedure SkipBlanks; virtual;
public
constructor Create(Stream: TStream); overload;
constructor Create(Stream: TStream; Name: String); overload;
destructor Destroy; override;
function GetNextToken: TToken; virtual;
function GetTokenName(Token: TToken): String;
property Stream: TStream read FStream;
property CurrentToken: TToken read FCurrentToken;
property TokenLine: Integer read FTokenLine;
property TokenCol: Integer read FTokenCol;
property TokenPosition: Integer read FTokenPosition;
property TokenString: String read FTokenStr;
property TokenValue: TTokenValue read FTokenValue;
property Name: String read FName write FName;
end;
{ Exception: EInterpreterException }
EInterpreterException = class(Exception)
private
FLine: Integer;
FCol: Integer;
FParser: TPascalTokenizer;
public
constructor Create(S: String; Line, Col: Integer; Parser: TPascalTokenizer);
property Line: Integer read FLine;
property Col: Integer read FCol;
property Parser: TPascalTokenizer read FParser write FParser;
end;
{ TSimplePascalTokenizer }
TSimplePascalTokenizer = class(TPascalTokenizer)
private
FTokenPositionDotDot: Integer;
FTokenLineDotDot: Integer;
FTokenColDotDot: Integer;
public
function GetNextToken: TToken; override;
end;
implementation
{ TPascalTokenizer }
const
BUFSIZE = 80000;
var
// one character tokens (see initialization section)
TokChar: array [Char] of TToken;
// palavras reservadas
ReservedWords: TStrings;
constructor CSTokenizer.Create(Stream: TStream);
begin
inherited Create;
FStream := Stream;
GetMem(FBuffer, BUFSIZE);
FTokenValue := TTokenValue.Create;
FBufPos := FBuffer;
FBufEnd := FBuffer;
FPosition := -1;
FNewLine := True;
GetChar;
GetNextToken;
end;
constructor CSTokenizer.Create(Stream: TStream; Name: String);
begin
Create(Stream);
FName := Name;
end;
destructor CSTokenizer.Destroy;
begin
if FBuffer <> nil then
FreeMem(FBuffer);
FTokenValue.Free;
inherited Destroy;
end;
procedure CSTokenizer.Error(S: String);
begin
raise EInterpreterException.Create(S, FSourceLine, FSourceCol, Self);
end;
function CSTokenizer.CheckReservedWord(S: String): TToken;
var
Ind: Integer;
Aux: String;
// esta funçao resolve o uso opcional de acentos, tils e
// cedilhas.
function port_Equivalent(S: String): String;
begin
Result := S;
if (Result = 'até') then
Result := 'ate'
else if (Result = 'então') then
Result := 'entao'
else if (Result = 'faça') then
Result := 'faca'
else if (Result = 'funçao') then
Result := 'funcao'
else if (Result = 'funcão') then
Result := 'funcao'
else if (Result = 'função') then
Result := 'funcao'
else if (Result = 'início') then
Result := 'inicio'
else if (Result = 'lógico') then
Result := 'logico'
else if (Result = 'não') then
Result := 'nao'
else if (Result = 'senão') then
Result := 'senao'
else if (Result = 'simounão') then
Result := 'simounao';
end;
begin
// Aux := LowerCase(S);
Aux := S;
Aux := port_Equivalent(Aux);
Ind := ReservedWords.IndexOf(Aux);
if Ind >= 0 then
Result := TToken(ReservedWords.Objects[Ind])
else
Result := tkId;
end;
function CSTokenizer.GetChar: Char;
begin
if FBufPos >= FBufEnd then
begin
// fill the buffer
FBufEnd := FBuffer + FStream.Read(FBuffer^, BUFSIZE);
FBufPos := FBuffer;
end;
if FBufPos >= FBufEnd then
Result := #0
else
begin
Result := FBufPos^;
Inc(FBufPos);
Inc(FPosition);
if FNewLine then
begin
Inc(FSourceLine);
FSourceCol := 0;
FNewLine := False;
end;
Inc(FSourceCol);
if Result = #10 then
FNewLine := True;
end;
CurrentChar := Result;
end;
procedure CSTokenizer.PushBack(Current: Char);
begin
if FBufPos = FBuffer then
Exit; // Error(sPushBackError);
Dec(FBufPos);
Dec(FPosition);
Dec(FSourceCol);
CurrentChar := Current;
end;
procedure CSTokenizer.GetQuotedString;
var
P: PChar;
begin
FTokenStr := '';
while CurrentChar = STRQUOTE do
begin
repeat
FTokenStr := FTokenStr + CurrentChar;
until GetChar in [STRQUOTE, #13, #0];
if CurrentChar in [#13, #0] then
Error(sStringIncomplete);
FTokenStr := FTokenStr + CurrentChar;
GetChar;
end;
P := PChar(FTokenStr);
TokenValue.FString := TokenValue.FString + AnsiExtractQuotedStr(P, STRQUOTE);
end;
procedure CSTokenizer.GetControlString;
var
Value: Integer;
begin
Value := 0;
FTokenStr := '';
if GetChar = '$' then
begin
repeat
FTokenStr := FTokenStr + CurrentChar;
until not (GetChar in ['0'..'9', 'A'..'F', 'a'..'f']);
try
Value := CheckHexNumber(FTokenStr);
except
Error(sInvalidControlString);
end;
if (Value < 0) or (Value > 255) then
Error(sInvalidControlString);
TokenValue.FString := TokenValue.FString + Chr(Value);
end
else
begin
while CurrentChar in ['0'..'9'] do
begin
FTokenStr := FTokenStr + CurrentChar;
GetChar;
end;
try
Value := CheckIntNumber(FTokenStr);
except
Error(sInvalidControlString);
end;
if (Value < 0) or (Value > 255) then
Error(sInvalidControlString);
TokenValue.FString := TokenValue.FString + Chr(Value);
end;
end;
procedure CSTokenizer.SkipBlanks;
begin
while True do
begin
case CurrentChar of
#0:
Exit;
#1..' ':
GetChar;
// '{':
// begin
// repeat
// GetChar;
// until CurrentChar in [#0, '}'];
// if CurrentChar = #0 then
// Error(sUnexpectedEndOfSourceInComment);
// GetChar;
// end;
'/':
if GetChar = '/' then
begin
repeat
GetChar;
until CurrentChar in [#0, #10];
if CurrentChar = #0 then
Exit;
GetChar;
end
else if CurrentChar = '*' then
begin
while True do
begin
repeat
GetChar;
until CurrentChar in [#0, '*'];
if CurrentChar = #0 then
Error(sUnexpectedEndOfSourceInComment);
if GetChar = '/' then
begin
GetChar;
Break;
end
else
PushBack('*');
end;
end
else
begin
PushBack('/');
Exit;
end;
// '(':
// if GetChar = '*' then
// begin
// while True do
// begin
// repeat
// GetChar;
// until CurrentChar in [#0, '*'];
// if CurrentChar = #0 then
// Error(sUnexpectedEndOfSourceInComment);
// if GetChar = ')' then
// begin
// GetChar;
// Break;
// end
// else
// PushBack('*');
// end;
// end
// else
// begin
// PushBack('(');
// Exit;
// end;
else // default case
Break;
end;
end;
end;
function CSTokenizer.CheckHexNumber(S: String): Integer;
var
I, Len: Integer;
C: Char;
V: Byte;
begin
Result := 0;
Len := Length(S);
if (Len <= 1) or (Len > 9) then Error(sInvalidHexNumber);
try
for I := 2 to Len do
begin
C := S[I];
if C in ['0'..'9'] then
V := Ord(C) - Ord('0')
else if C in ['A'..'F'] then
V := Ord(C) - Ord('A') + 10
else { C in ['a'..'f'] }
V := Ord(C) - Ord('a') + 10;
Result := (Result shl 4) or V;
end;
except
Error(sInvalidHexNumber);
end;
end;
function CSTokenizer.CheckRealNumber(S: String): Extended;
var
SaveDecSep: Char;
begin
Result := 0.0;
try
SaveDecSep := DecimalSeparator;
DecimalSeparator := '.';
Result := StrToFloat(S);
DecimalSeparator := SaveDecSep;
except
Error(sInvalidRealNumber);
end;
end;
function CSTokenizer.CheckIntNumber(S: String): Integer;
begin
Result := 0;
if Length(S) = 0 then
Error(sInvalidIntNumber);
try
Result := StrToInt(S);
except
Error(sInvalidIntNumber);
end;
end;
function CSTokenizer.GetNextToken: TToken;
begin
// the dotdot special case (see case '0'..'9' below)
if FDotDot then
begin
Result := tkDotDot;
FTokenStr := '..';
FDotDot := False;
FCurrentToken := Result;
Exit;
end;
SkipBlanks;
FTokenPosition := FPosition;
FTokenLine := FSourceLine;
FTokenCol := FSourceCol;
FTokenStr := '';
case CurrentChar of
#0:
Result := tkEndOfSource;
':':
begin
Result := tkColon;
FTokenStr := ':';
if GetChar = '=' then
begin
Result := tkAssign;
FTokenStr := ':=';
GetChar;
end;
end;
'<':
begin
Result := tkLT;
FTokenStr := '<';
if GetChar = '=' then
begin
Result := tkLE;
FTokenStr := '<=';
GetChar;
end
else if CurrentChar = '>' then
begin
Result := tkNE;
FTokenStr := '<>';
GetChar;
end;
end;
'>':
begin
Result := tkGT;
FTokenStr := '>';
if GetChar = '=' then
begin
Result := tkGE;
FTokenStr := '>=';
GetChar;
end;
end;
'&':
begin
if GetChar <> '&' then
Error(sInvalidOperator);
Result := tkRWand;
FTokenStr := '&&';
GetChar;
end;
'|':
begin
if GetChar <> '|' then
Error(sInvalidOperator);
Result := tkRWor;
FTokenStr := '||';
GetChar;
end;
'.':
begin
Result := tkPeriod;
FTokenStr := '.';
if GetChar = '.' then
begin
Result := tkDotDot;
FTokenStr := '..';
GetChar;
end;
end;
'A'..'Z', 'a'..'z', '_', #192..#255:
begin
repeat
FTokenStr := FTokenStr + CurrentChar;
until not (GetChar in ['A'..'Z', 'a'..'z', '0'..'9', '_', #192..#255]);
Result := CheckReservedWord(FTokenStr);
end;
'$':
begin
repeat
FTokenStr := FTokenStr + CurrentChar;
until not (GetChar in ['0'..'9', 'A'..'F', 'a'..'f']);
if FTokenStr = '$' then
Result := tkDollar
else
begin
Result := tkIntNumber;
TokenValue.FInteger := CheckHexNumber(FTokenStr);
end;
end;
'0'..'9':
begin
Result := tkIntNumber;
repeat
FTokenStr := FTokenStr + CurrentChar;
until not (GetChar in ['0'..'9']);
if CurrentChar = '.' then
begin
// the dotdot special case
if GetChar = '.' then
begin
FDotDot := True;
FCurrentToken := Result; // tkIntNumber
TokenValue.FInteger := CheckIntNumber(FTokenStr);
GetChar;
Exit;
end;
FTokenStr := FTokenStr + '.' + CurrentChar;
Result := tkFloatNumber;
while GetChar in ['0'..'9'] do
FTokenStr := FTokenStr + CurrentChar;
end;
if CurrentChar in ['E', 'e'] then
begin
Result := tkFloatNumber;
FTokenStr := FTokenStr + CurrentChar;
if GetChar in ['+', '-'] then
begin
FTokenStr := FTokenStr + CurrentChar;
GetChar;
end;
if not (CurrentChar in ['0'..'9']) then
Error(sInvalidRealNumber);
repeat
FTokenStr := FTokenStr + CurrentChar;
until not (GetChar in ['0'..'9']);
end;
if Result = tkFloatNumber then
TokenValue.FExtended := CheckRealNumber(FTokenStr)
else
TokenValue.FInteger := CheckIntNumber(FTokenStr);
end;
STRQUOTE, '#':
begin
Result := tkString;
TokenValue.FString := '';
while CurrentChar in [STRQUOTE, '#'] do
begin
if CurrentChar = STRQUOTE then
begin
GetQuotedString;
if CurrentChar <> '#' then
Break;
end;
if CurrentChar = '#' then
GetControlString;
end;
if Length(TokenValue.FString) = 1 then
begin
Result := tkChar;
TokenValue.FChar := TokenValue.FString[1];
end;
end;
'+', '-', '*', '/', '=', '[', ']', ',', '(', ')', ';', '^', '@':
begin
Result := TokChar[CurrentChar];
FTokenStr := CurrentChar;
GetChar;
end;
else
Result := tkUnknown;
GetChar;
end;
FCurrentToken := Result;
end;
function CSTokenizer.GetTokenName(Token: TToken): String;
var
Ind: Integer;
begin
Ind := ReservedWords.IndexOfObject(TObject(Token));
if Ind >= 0 then
Result := ReservedWords[Ind]
else
Result := '???';
end;
{ EInterpreterException }
constructor EInterpreterException.Create(S: String; Line, Col: Integer;
Parser: TPascalTokenizer);
begin
inherited Create(S);
FLine := Line;
FCol := Col;
FParser := Parser;
end;
{ TSimplePascalTokenizer }
function TSimplePascalTokenizer.GetNextToken: TToken;
begin
// the dotdot special case (see case '0'..'9' below)
if FDotDot then
begin
Result := tkDotDot;
FTokenStr := '..';
FTokenPosition := FTokenPositionDotDot;
FTokenLine := FTokenLineDotDot;
FTokenCol := FTokenColDotDot;
FDotDot := False;
FCurrentToken := Result;
Exit;
end;
FTokenPosition := FPosition;
FTokenLine := FSourceLine;
FTokenCol := FSourceCol;
FTokenStr := '';
case CurrentChar of
#0:
Result := tkEndOfSource;
#1..' ':
begin
repeat
FTokenStr := FTokenStr + CurrentChar;
until not (GetChar in [#1..' ']);
Result := tkBlank;
end;
':':
begin
Result := tkColon;
FTokenStr := ':';
if GetChar = '=' then
begin
Result := tkAssign;
FTokenStr := ':=';
GetChar;
end;
end;
'<':
begin
Result := tkLT;
FTokenStr := '<';
if GetChar = '=' then
begin
Result := tkLE;
FTokenStr := '<=';
GetChar;
end
else if CurrentChar = '>' then
begin
Result := tkNE;
FTokenStr := '<>';
GetChar;
end;
end;
'>':
begin
Result := tkGT;
FTokenStr := '>';
if GetChar = '=' then
begin
Result := tkGE;
FTokenStr := '>=';
GetChar;
end;
end;
'.':
begin
Result := tkPeriod;
FTokenStr := '.';
if GetChar = '.' then
begin
Result := tkDotDot;
FTokenStr := '..';
GetChar;
end;
end;
'{':
begin
repeat
FTokenStr := FTokenStr + CurrentChar;
until GetChar in [#0, '}'];
if CurrentChar = '}' then
begin
FTokenStr := FTokenStr + CurrentChar;
GetChar;
end;
Result := tkComment;
end;
'/':
begin
Result := tkSlash;
FTokenStr := '/';
if GetChar = '/' then
begin
Result := tkComment;
repeat
FTokenStr := FTokenStr + CurrentChar;
until GetChar in [#0, #10];
if CurrentChar = #0 then
Exit;
FTokenStr := FTokenStr + CurrentChar;
GetChar;
end;
end;
'(':
begin
Result := tkLParen;
FTokenStr := '(';
if GetChar = '*' then
begin
Result := tkComment;
while True do
begin
repeat
FTokenStr := FTokenStr + CurrentChar;
until GetChar in [#0, '*'];
if CurrentChar = #0 then
Break;
FTokenStr := FTokenStr + CurrentChar;
if GetChar = ')' then
begin
FTokenStr := FTokenStr + CurrentChar;
GetChar;
Break;
end;
end;
end;
end;
'A'..'Z', 'a'..'z', '_', #192..#255:
begin
repeat
FTokenStr := FTokenStr + CurrentChar;
until not (GetChar in ['A'..'Z', 'a'..'z', '0'..'9', '_', #192..#255]);
Result := CheckReservedWord(FTokenStr);
end;
'$':
begin
repeat
FTokenStr := FTokenStr + CurrentChar;
until not (GetChar in ['0'..'9', 'A'..'F', 'a'..'f']);
if FTokenStr = '$' then
Result := tkDollar
else
begin
Result := tkIntNumber;
TokenValue.FInteger := 0; // não importa o valor
end;
end;
'0'..'9':
begin
Result := tkIntNumber;
repeat
FTokenStr := FTokenStr + CurrentChar;
until not (GetChar in ['0'..'9']);
if CurrentChar = '.' then
begin
// the dotdot special case
if GetChar = '.' then
begin
FDotDot := True;
FTokenPositionDotDot := FPosition - 1;
FTokenLineDotDot := FTokenLine;
FTokenColDotDot := FSourceCol - 1;
FCurrentToken := Result; // tkIntNumber
TokenValue.FInteger := 0; // não importa o valor
GetChar;
Exit;
end;
FTokenStr := FTokenStr + '.' + CurrentChar;
Result := tkFloatNumber;
while GetChar in ['0'..'9'] do
FTokenStr := FTokenStr + CurrentChar;
end;
if CurrentChar in ['E', 'e'] then
begin
Result := tkFloatNumber;
FTokenStr := FTokenStr + CurrentChar;
if GetChar in ['+', '-'] then
begin
FTokenStr := FTokenStr + CurrentChar;
GetChar;
end;
if not (CurrentChar in ['0'..'9']) then
begin
FCurrentToken := Result; // tkFloatNumber
Exit;
end;
repeat
FTokenStr := FTokenStr + CurrentChar;
until not (GetChar in ['0'..'9']);
end;
if Result = tkFloatNumber then
TokenValue.FExtended := 0.0
else
TokenValue.FInteger := 0;
end;
STRQUOTE:
begin
Result := tkString;
repeat
FTokenStr := FTokenStr + CurrentChar;
until GetChar in [#0, #10, STRQUOTE];
if CurrentChar = STRQUOTE then
begin
FTokenStr := FTokenStr + CurrentChar;
GetChar;
end;
end;
'#':
begin
Result := tkString;
repeat
FTokenStr := FTokenStr + CurrentChar;
until not (GetChar in ['0'..'9']);
end;
'+', '-', '*', '=', '[', ']', ',', ')', ';', '^', '@':
begin
Result := TokChar[CurrentChar];
FTokenStr := CurrentChar;
GetChar;
end;
else
Result := tkUnknown;
FTokenStr := CurrentChar;
GetChar;
end;
FCurrentToken := Result;
end;
initialization
// one character tokens
TokChar['+'] := tkPlus;
TokChar['-'] := tkMinus;
TokChar['*'] := tkTimes;
TokChar['/'] := tkSlash;
TokChar['='] := tkEqual;
TokChar['['] := tkLBracket;
TokChar[']'] := tkRBracket;
TokChar[','] := tkComma;
TokChar['('] := tkLParen;
TokChar[')'] := tkRParen;
TokChar[';'] := tkSemiColon;
TokChar['^'] := tkCaret;
TokChar['@'] := tkAt;
// registra palavras reservadas
ReservedWords := TStringList.Create;
(ReservedWords as TStringList).CaseSensitive := True;
ReservedWords.AddObject('adiante', TObject(tkRWforward));
// ReservedWords.AddObject('arquivo', TObject(tkRWfile));
ReservedWords.AddObject('arranjo', TObject(tkRWarray));
ReservedWords.AddObject('ate', TObject(tkRWuntil));
ReservedWords.AddObject('caso', TObject(tkRWcase));
ReservedWords.AddObject('caractere', TObject(tkRWchar));
// ReservedWords.AddObject('com', TObject(tkRWwith));
// ReservedWords.AddObject('conjunto', TObject(tkRWset));
ReservedWords.AddObject('const', TObject(tkRWconst));
ReservedWords.AddObject('de', TObject(tkRWof));
// ReservedWords.AddObject('decr', TObject(tkRWdownto));
ReservedWords.AddObject('desld', TObject(tkRWshr));
ReservedWords.AddObject('desle', TObject(tkRWshl));
ReservedWords.AddObject('div', TObject(tkRWdiv));
// ReservedWords.AddObject('e', TObject(tkRWand));
ReservedWords.AddObject('em', TObject(tkRWin));
ReservedWords.AddObject('enquanto', TObject(tkRWwhile));
ReservedWords.AddObject('entao', TObject(tkRWthen));
ReservedWords.AddObject('escolha', TObject(tkRWchoose));
ReservedWords.AddObject('escreva', TObject(tkRWwrite));
ReservedWords.AddObject('escrevaLn', TObject(tkRWwriteln));
ReservedWords.AddObject('faca', TObject(tkRWdo));
ReservedWords.AddObject('falso', TObject(tkRWfalse));
ReservedWords.AddObject('fim', TObject(tkRWend));
ReservedWords.AddObject('funcao', TObject(tkRWfunction));
ReservedWords.AddObject('inclui', TObject(tkRWinclude));
ReservedWords.AddObject('inicio', TObject(tkRWbegin));
ReservedWords.AddObject('inteiro', TObject(tkRWinteger));
ReservedWords.AddObject('leia', TObject(tkRWread));
ReservedWords.AddObject('logico', TObject(tkRWboolean));
ReservedWords.AddObject('libere', TObject(tkRWdispose));
ReservedWords.AddObject('mod', TObject(tkRWmod));
ReservedWords.AddObject('nao', TObject(tkRWnot));
ReservedWords.AddObject('novo', TObject(tkRWnew));
ReservedWords.AddObject('nulo', TObject(tkRWnil));
// ReservedWords.AddObject('ou', TObject(tkRWor));
ReservedWords.AddObject('oux', TObject(tkRWxor));
ReservedWords.AddObject('para', TObject(tkRWfor));
ReservedWords.AddObject('procedimento', TObject(tkRWprocedure));
ReservedWords.AddObject('programa', TObject(tkRWprogram));
ReservedWords.AddObject('real', TObject(tkRWreal));
ReservedWords.AddObject('registro', TObject(tkRWrecord));
ReservedWords.AddObject('repita', TObject(tkRWrepeat));
ReservedWords.AddObject('retorne', TObject(tkRWreturn));
ReservedWords.AddObject('se', TObject(tkRWif));
ReservedWords.AddObject('senao', TObject(tkRWelse));
ReservedWords.AddObject('sim', TObject(tkRWyes));
ReservedWords.AddObject('simOuNao', TObject(tkRWyesOrNo));
ReservedWords.AddObject('texto', TObject(tkRWstring));
ReservedWords.AddObject('tipo', TObject(tkRWtype));
ReservedWords.AddObject('var', TObject(tkRWvar));
ReservedWords.AddObject('verdadeiro', TObject(tkRWtrue));
ReservedWords.AddObject('ponteiro', TObject(tkRWpointer));
// os tokens seguintes estão incluídos apenas para o eventual
// uso da propriedade TokName; eles iniciam com branco, o que
// garante que eles não seráo encontrados na pesquisa normal
// por palavra reservada
ReservedWords.AddObject(' Qualquer ', TObject(tkAny));
ReservedWords.AddObject(' Desconhecido ', TObject(tkUnknown));
ReservedWords.AddObject(' - ', TObject(tkUnaryMinus));
ReservedWords.AddObject(' FimDoFonte ', TObject(tkEndOfSource));
ReservedWords.AddObject(' Id ', TObject(tkId));
ReservedWords.AddObject(' NumInteiro ', TObject(tkIntNumber));
ReservedWords.AddObject(' NumReal ', TObject(tkFloatNumber));
ReservedWords.AddObject(' NumHexa ', TObject(tkHexNumber));
ReservedWords.AddObject(' Texto ', TObject(tkString));
ReservedWords.AddObject(' Caractere ', TObject(tkChar));
ReservedWords.AddObject(' + ', TObject(tkPlus));
ReservedWords.AddObject(' - ', TObject(tkMinus));
ReservedWords.AddObject(' * ', TObject(tkTimes));
ReservedWords.AddObject(' / ', TObject(tkSlash));
ReservedWords.AddObject(' = ', TObject(tkEqual));
ReservedWords.AddObject(' < ', TObject(tkLT));
ReservedWords.AddObject(' > ', TObject(tkGT));
ReservedWords.AddObject(' [ ', TObject(tkLBracket));
ReservedWords.AddObject(' ] ', TObject(tkRBracket));
ReservedWords.AddObject(' . ', TObject(tkPeriod));
ReservedWords.AddObject(' , ', TObject(tkComma));
ReservedWords.AddObject(' ( ', TObject(tkLParen));
ReservedWords.AddObject(' ) ', TObject(tkRParen));
ReservedWords.AddObject(' : ', TObject(tkColon));
ReservedWords.AddObject(' ; ', TObject(tkSemiColon));
ReservedWords.AddObject(' ^ ', TObject(tkCaret));
ReservedWords.AddObject(' @ ', TObject(tkAt));
ReservedWords.AddObject(' $ ', TObject(tkDollar));
ReservedWords.AddObject(' # ', TObject(tkFence));
ReservedWords.AddObject(' <= ', TObject(tkLE));
ReservedWords.AddObject(' >= ', TObject(tkGE));
ReservedWords.AddObject(' <> ', TObject(tkNE));
ReservedWords.AddObject(' := ', TObject(tkAssign));
ReservedWords.AddObject(' .. ', TObject(tkDotDot));
finalization
ReservedWords.Free;
end.
|
unit u_ICBCRec;
interface
type
//公共头
TPubRec = packed record
TransCode: string[10]; // 交易代码 必输项 字符 10 PAYENT
CIS: string[60]; // 集团CIS号 必输项 字符 60 客户注册时的归属编码
BankCode: string[3]; // 归属银行编号 必输项 字符 3 客户注册时的归属单位
ID: string[40]; // 证书ID 必输项 字符 40 无证书客户可上送空
TranDate: string[8]; // 交易日期 必输项 字符 8 ERP系统产生的交易日期,格式是yyyyMMdd
TranTime: string[12]; // 交易时间 必输项 字符 12 ERP系统产生的交易时间,格式如hhmmssaaabbb,精确到微秒;
fSeqno: string[35]; // 指令包序列号 必输项 字符 35 ERP系统产生的指令包序列号,一个集团永远不能重复;
//返回专用..................................................................
//支付指令、批扣个人返回专用...........................
SerialNo: string[15]; // 平台交易流水号 否 字符 15 银行产生的银行批次号
//...........................................
RetCode: string[5]; // 交易返回码 否 字符 5
RetMsg: string[100]; // 交易返回描述 否 字符 100
//..........................................................................
end;
//查询当日明细
TQueryCurDayDetailsRec = packed record
AccNo: string[19]; // 查询账号 必输项 数字 19
//返回专用..................................................................
AccName: string[80]; // 户名 否 字符 80
CurrType: string[3]; // 币种 否 字符 3
//..........................................................................
AreaCode: string[4]; // 地区代码 选输项 数字 4 4位工行地区代码
MinAmt: string[17]; // 发生额下限 选输项 数字 17 若输入则必须为大于或等于零的整数,单位为分
MaxAmt: string[17]; // 发生额上限 选输项 数字 17 若输入则必须为大于或等于零的整数,单位为分.发生额上下限都有值时则下限必须小于等于上限
BeginTime: string[8]; // 预留,目前无意义
EndTime: string[8]; // 预留,目前无意义
NextTag: string[60]; // 查询下页标识 选输项 字符 60 查询首页上送空;其他页需与银行返回包提供的一致
//返回专用..................................................................
TotalNum: string[6]; // 交易条数 否 数字 6
//..........................................................................
_Reserved1: string[3]; // 请求包备用字段1 选输项 数字 3 行别,集团有他行帐号时为必输
_Reserved2: string[100]; // 请求包备用字段2 选输项 字符 100 备用,目前无意义
//返回专用..................................................................
rd: array of packed record
Drcrf: string[1]; // 借贷标志 否 数字 1 1:借 2:贷
VouhNo: string[9]; // 凭证号 否 字符 9
Amount: string[17]; // 发生额 否 数字 17 无正负号,不带小数点,以币种的最小单位为单位
RecipBkNo: string[13]; // 对方行号 否 字符 13
RecipAccNo: string[34]; // 对方账号 否 数字 34
RecipName: string[60]; // 对方户名 否 字符 60
Summary: string[20]; // 摘要 否 字符 20
UseCN: string[20]; // 用途 否 字符 20
PostScript: string[100]; // 附言 否 字符 100
Ref: string[20]; // 业务编号 否 字符 20
BusCode: string[5]; // 业务代码 否 字符 5
Oref: string[20]; // 相关业务编号 否 字符 20
EnSummary: string[40]; // 英文备注 否 字符 40
BusType: string[3]; // 业务种类 否 字符 3
CvouhType: string[3]; // 凭证种类 否 字符 3
AddInfo: string[210]; // 附加信息 否 字符 210
TimeStamp: string[26]; // 时间戳 否 字符 26
_Reserved3: string[100]; // 响应备用字段3 否 字符 100 集团如果开通了“电子回单”的高级功能,则返回"地区号|网点号|柜员号|主机交易流水号"
_Reserved4: string[100]; // 响应备用字段4 否 字符 100 备用,目前无意义
end;
//..........................................................................
end;
//查询历史明细
TQueryHistoryDetailsRec = packed record
AccNo: string[19]; // 查询账号 必输项 数字 19
//返回专用..................................................................
AccName: string[80]; // 户名 否 字符 80
CurrType: string[3]; // 币种 否 字符 3
//..........................................................................
BeginDate: string[8]; // 起始日期 必输项 数字 8 起始日期必须小于等于截止日期;
EndDate: string[8]; // 截止日期 必输项 数字 8 格式是yyyyMMdd
MinAmt: string[17]; // 发生额下限 选输项 数字 17 若输入则必须为大于或等于零的整数,单位为分
MaxAmt: string[17]; // 发生额上限 选输项 数字 17 若输入则必须为大于或等于零的整数,单位为分.发生额上下限都有值时则下限必须小于等于上限
NextTag: string[60]; // 查询下页标识 选输项 字符 60 查询首页上送空;其他页需与银行返回包提供的一致
//返回专用..................................................................
TotalNum: string[6]; // 交易条数 否 数字 6
//..........................................................................
_Reserved1: string[3]; // 请求包备用字段1 选输项 数字 3 行别,集团有他行帐号时为必输
_Reserved2: string[100]; // 请求包备用字段2 选输项 字符 100 备用,目前无意义
//返回专用..................................................................
rd: array of packed record
Drcrf: string[1]; // 借贷标志 否 数字 1 1:借 2:贷
VouhNo: string[9]; // 凭证号 否 字符 9
DebitAmount: string[18]; // 借方发生额 否 数字 18 以币种的最小单位为单位
CreditAmount: string[18]; // 贷方发生额 否 数字 18 以币种的最小单位为单位
Balance: string[18]; // 余额 否 数字 18 以币种的最小单位为单位
RecipBkNo: string[12]; // 对方行号 否 字符 12
RecipBkName: string[140]; // 对方行名 否 字符 140
RecipAccNo: string[34]; // 对方账号 否 字符 34
RecipName: string[140]; // 对方户名 否 字符 140
Summary: string[20]; // 摘要 否 字符 20
UseCN: string[20]; // 用途 否 字符 20
PostScript: string[100]; // 附言 否 字符 100
BusCode: string[5]; // 业务代码 否 字符 5
Date: string[8]; // 交易日期 否 字符 8 yyyyMMdd
Time: string[26]; // 时间戳 否 字符 26
Ref: string[20]; // 业务编号 否 字符 20
Oref: string[20]; // 相关业务编号 否 字符 20
EnSummary: string[40]; // 英文备注 否 字符 40
BusType: string[3]; // 业务种类 否 字符 3
VouhType: string[3]; // 凭证种类 否 字符 3
AddInfo: string[210]; // 附加信息 否 字符 210
_Reserved3: string[100]; // 响应备用字段3 否 字符 100 集团如果开通了“电子回单”的高级功能,则返回"地区号|网点号|柜员号|主机交易流水号"
_Reserved4: string[100]; // 响应备用字段4 否 字符 100 备用,目前无意义
end;
//..........................................................................
end;
//多账户余额查询
TQueryAccValueRec = packed record
//发送专用..................................................................
TotalNum: string[6]; // 总笔数 必输项 数字 6 需要查询明细的笔数
_Reserved1: string[100]; // 请求包备用字段1 选输项 字符 100 备用,目前无意义
_Reserved2: string[100]; // 请求包备用字段2 选输项 字符 100 备用,目前无意义
//..........................................................................
rd: array of packed record
iSeqno: string[35]; // 指令顺序号 必输项 字符 35 不能为空,并且不能重复
AccNo: string[19]; // 帐号 必输项 数字 19
CurrType: string[3]; // 币种 选输项 字符 3 工行币种代码,不输入则自动取帐号币种
//返回专用................................................................
CashExf: string[1]; // 钞汇标志 否 数字 1 0:钞 1:汇
AcctProperty: string[1]; // 账户属性 否 数字 1 1:基本户 2:一般结算户 3:临时户 4:专用户 6:集团二级户 7:协定存款户 8:保证金户
AccBalance: string[20]; // 昨日余额 否 数字 20 以币种的最小单位为单位
Balance: string[20]; // 当前余额 否 数字 20 以币种的最小单位为单位
UsableBalance: string[20]; // 可用余额 否 数字 20 以币种的最小单位为单位
FrzAmt: string[20]; // 冻结额度合计 否 数字 20 以币种的最小单位为单位
QueryTime: string[20]; // 查询时间 否 数字 20
iRetCode: string[5]; // 返回码 否 字符 5
iRetMsg: string[100]; // 返回描述 否 字符 100
//........................................................................
_Reserved3: string[3]; // 请求包备用字段3 选输项 数字 3 行别,集团有他行帐号时为必输项
_Reserved4: string[100]; // 请求包备用字段4 选输项 字符 100 备用,目前无意义
end;
end;
//支付指令提交
TPayEntRec = packed record
OnlBatF: string[1]; // 联机批量标志 选输项 数字 1 1:联机
SettleMode: string[1]; // 入账方式 必输项 数字 1 2:并笔入账 0:逐笔记账
TotalNum: string[6]; // 总笔数 必输项 数字 6 指令包内的指令笔数
TotalAmt: string[20]; // 总金额 必输项 数字 20 无正负号,不带小数点,以分作单位
//发送专用..................................................................
SignTime: string[17]; // 签名时间 必输项 字符 17 格式是yyyyMMddhhmmssSSS
//..........................................................................
_Reserved1: string[100]; // 请求备用字段1 选输项 字符 100 备用,目前无意义
_Reserved2: string[100]; // 请求备用字段2 选输项 字符 100 备用,目前无意义
rd: array of packed record
iSeqno: string[35]; // 指令顺序号 必输项 字符 35 每笔指令的序号,本包内不重复。(工行只检查包内不重复,不同的包,工行不做指令顺序号重复性的检查。)
//返回专用................................................................
OrderNo: string[6]; // 平台交易序号 否 字符 6 银行产生的批次内的小序号
//........................................................................
ReimburseNo: string[40]; // 自定义序号 选输项 字符 40
ReimburseNum: string[10]; // 单据张数 选输项 字符 10
StartDate: string[8]; // 定时启动日期 选输项 字符 8 格式是yyyyMMdd
StartTime: string[6]; // 定时启动时间 选输项 字符 6 格式是hhmmss
PayType: string[1]; // 记账处理方式 必输项 数字 1 1:加急 2:普通
PayAccNo: string[34]; // 本方账号 必输项 数字 34
PayAccNameCN: string[100]; // 本方账户名称 选输项 字符 100 根据人行标准,人民币账户的户名不应超过60字节,否则该字段可能被截取
PayAccNameEN: string[100]; // 本方账户英文名称 选输项 字符 100 中文名称、英文名称二者必输其一。
RecAccNo: string[34]; // 对方账号 必输项 字符 34
RecAccNameCN: string[100]; // 对方账户名称 选输项 字符 100 根据人行标准,人民币账户的户名不应超过60字节,否则该字段可能被截取
RecAccNameEN: string[100]; // 对方账户英文名称 选输项 字符 100 中文名称、英文名称二者必输其一。
SysIOFlg: string[1]; // 系统内外标志 必输项 数字 1 "1:系统内 2:系统外"
IsSameCity: string[1]; // 同城异地标志 选输项 数字 1 "1:同城 2:异地"
Prop: string[1]; // 对公对私标志 选输项 数字 1 "跨行必输 0:对公账户 1:个人账户"
RecICBCCode: string[5]; // 交易对方工行地区号 选输项 数字 5 4位工行地区号
RecCityName: string[40]; // 收款方所在城市名称 选输项 字符 40 跨行指令此项必输
RecBankNo: string[13]; // 对方行行号 选输项 字符 13
RecBankName: string[60]; // 交易对方银行名称 必输项 字符 60 跨行指令此项必输,中文,60位字符。
CurrType: string[3]; // 币种 必输项 字符 3
PayAmt: string[17]; // 金额 必输项 数字 17 无正负号,不带小数点,以分作单位
UseCode: string[3]; // 用途代码 选输项 字符 3
UseCN: string[20]; // 用途中文描述 选输项 字符 20 "用途代码和用途中文描述必输其一;如需跨行实时到帐此项最多10个字符.超长则落地处理."
EnSummary: string[40]; // 英文备注 选输项 字符 40 必须ASCII字符
PostScript: string[100]; // 附言 选输项 字符 100
Summary: string[20]; // 摘要 选输项 字符 20
Ref: string[20]; // 业务编号(业务参考号) 选输项 字符 20 必须ASCII字符
Oref: string[20]; // 相关业务编号 选输项 字符 20 必须ASCII字符
ERPSqn: string[20]; // ERP流水号 选输项 字符 20 必须ASCII字符
BusCode: string[5]; // 业务代码 选输项 字符 5 必须ASCII字符
ERPcheckno: string[8]; // ERP支票号 选输项 字符 8 必须ASCII字符
CrvouhType: string[3]; // 原始凭证种类 选输项 字符 3 必须ASCII字符
CrvouhName: string[30]; // 原始凭证名称 选输项 字符 30
CrvouhNo: string[20]; // 原始凭证号 选输项 字符 20 必须ASCII字符
//返回专用................................................................
Result: string[2]; {指令状态 否 字符 2 "0:提交成功,等待银行处理
1:授权成功, 等待银行处理
2:等待授权
3:等待二次授权
4:等待银行答复
5:主机返回待处理
6:被银行拒绝
7:处理成功
8:指令被拒绝授权
9:银行正在处理
10:预约指令
11:预约取消"
}
iRetCode: string[5]; // 返回码 否 字符 5
iRetMsg: string[100]; // 交易返回描述 否 字符 100
//........................................................................
_Reserved3: string[3]; // 请求备用字段3 选输项 字符 3 付款账号行别,不输或输入102代表工行
_Reserved4: string[100]; // 请求备用字段4 选输项 字符 100 备用,目前无意义
end;
end;
//支付指令提交查询
TQueryPayEntRec = packed record
QryfSeqno: string[35]; // 待查指令包序列号 选输项 字符 35 判断待查指令包序列号和待查平台交易序列号必须至少有一项有值,如同时有则以后者为准
QrySerialNo: string[15]; // 待查平台交易序列号 选输项 字符 15
//返回专用................................................................
OnlBatF: string[1]; // 联机批量标志 选输项 数字 1 1:联机
SettleMode: string[1]; // 入账方式 必输项 数字 1 2:并笔入账 0:逐笔记账
BusType: string[2]; // 业务种类 否 字符 2 1-15的数字
//..........................................................................
_Reserved1: string[100]; // 请求备用字段1 选输项 字符 100 备用,目前无意义
_Reserved2: string[100]; // 请求备用字段2 选输项 字符 100 备用,目前无意义
rd: array of packed record
iSeqno: string[35]; // 指令顺序号 必输项 字符 35 每笔指令的序号,本包内不重复。(工行只检查包内不重复,不同的包,工行不做指令顺序号重复性的检查。)
QryiSeqno: string[35]; // 待查指令包顺序号 否 字符 35
QryOrderNo: string[6]; // 待查平台交易顺序号 否 字符 6 银行产生的批次内的小序号
//返回专用................................................................
ReimburseNo: string[40]; // 自定义序号 选输项 字符 40
ReimburseNum: string[10]; // 单据张数 选输项 字符 10
StartDate: string[8]; // 定时启动日期 选输项 字符 8 格式是yyyyMMdd
StartTime: string[6]; // 定时启动时间 选输项 字符 6 格式是hhmmss
PayType: string[1]; // 记账处理方式 必输项 数字 1 1:加急 2:普通
PayAccNo: string[34]; // 本方账号 必输项 数字 34
PayAccNameCN: string[100]; // 本方账户名称 选输项 字符 100 根据人行标准,人民币账户的户名不应超过60字节,否则该字段可能被截取
PayAccNameEN: string[100]; // 本方账户英文名称 选输项 字符 100 中文名称、英文名称二者必输其一。
RecAccNo: string[34]; // 对方账号 必输项 字符 34
RecAccNameCN: string[100]; // 对方账户名称 选输项 字符 100 根据人行标准,人民币账户的户名不应超过60字节,否则该字段可能被截取
RecAccNameEN: string[100]; // 对方账户英文名称 选输项 字符 100 中文名称、英文名称二者必输其一。
SysIOFlg: string[1]; // 系统内外标志 必输项 数字 1 "1:系统内 2:系统外"
IsSameCity: string[1]; // 同城异地标志 选输项 数字 1 "1:同城 2:异地"
RecICBCCode: string[5]; // 交易对方工行地区号 选输项 数字 5 4位工行地区号
RecCityName: string[40]; // 收款方所在城市名称 选输项 字符 40 跨行指令此项必输
RecBankNo: string[13]; // 对方行行号 选输项 字符 13
RecBankName: string[60]; // 交易对方银行名称 必输项 字符 60 跨行指令此项必输,中文,60位字符。
CurrType: string[3]; // 币种 必输项 字符 3
PayAmt: string[17]; // 金额 必输项 数字 17 无正负号,不带小数点,以分作单位
UseCode: string[3]; // 用途代码 选输项 字符 3
UseCN: string[20]; // 用途中文描述 选输项 字符 20 "用途代码和用途中文描述必输其一;如需跨行实时到帐此项最多10个字符.超长则落地处理."
EnSummary: string[40]; // 英文备注 选输项 字符 40 必须ASCII字符
PostScript: string[100]; // 附言 选输项 字符 100
Summary: string[20]; // 摘要 选输项 字符 20
Ref: string[20]; // 业务编号(业务参考号) 选输项 字符 20 必须ASCII字符
Oref: string[20]; // 相关业务编号 选输项 字符 20 必须ASCII字符
ERPSqn: string[20]; // ERP流水号 选输项 字符 20 必须ASCII字符
BusCode: string[5]; // 业务代码 选输项 字符 5 必须ASCII字符
ERPcheckno: string[8]; // ERP支票号 选输项 字符 8 必须ASCII字符
CrvouhType: string[3]; // 原始凭证种类 选输项 字符 3 必须ASCII字符
CrvouhName: string[30]; // 原始凭证名称 选输项 字符 30
CrvouhNo: string[20]; // 原始凭证号 否 字符 20
//文档中无,测试环境有.....................................................s
iRetCode: string[5]; // 返回码 否 字符 5
iRetMsg: string[100]; // 交易返回描述 否 字符 100
//........................................................................
Result: string[2]; {指令状态 否 字符 2 "0:提交成功,等待银行处理
1:授权成功, 等待银行处理
2:等待授权
3:等待二次授权
4:等待银行答复
5:主机返回待处理
6:被银行拒绝
7:处理成功
8:指令被拒绝授权
9:银行正在处理
10:预约指令
11:预约取消"
}
instrRetCode: string[5]; // 返回码 否 字符 5
instrRetMsg: string[100]; // 交易返回描述 否 字符 100
BankRetTime: string[14]; // 银行反馈时间 否 字符 14
//........................................................................
_Reserved3: string[3]; // 请求备用字段3 选输项 字符 3 付款账号行别,不输或输入102代表工行
_Reserved4: string[100]; // 请求备用字段4 选输项 字符 100 备用,目前无意义
end;
end;
//批扣个人指令提交
TPerDisRec = packed record
OnlBatF: string[1]; // 联机批量标志 选输项 数字 1 1:联机
//批扣个人指令提交 专用.....................................................
SettleMode: string[1]; // 入账方式 必输项 数字 1 2:并笔入账 0:逐笔记账
//..........................................................................
//批扣个人指令提交汇总记帐 专用 PerDiscol...................................
BusType: string[2]; // 业务种类编号 必输项 数字 2 1-15的数字
//..........................................................................
RecAccNo: string[19]; // 收方账号 必输项 数字 19
RecAccNameCN: string[60]; // 收方账户名称 选输项 字符 60 中文名称、英文名称二者必输其一。
RecAccNameEN: string[60]; // 收方账户英文名称 选输项 字符 60 中文名称、英文名称二者必输其一。
TotalNum: string[6]; // 总笔数 必输项 数字 6 指令包内的指令笔数
TotalAmt: string[20]; // 总金额 必输项 数字 20 无正负号,不带小数点,以分作单位
//发送专用..................................................................
SignTime: string[17]; // 签名时间 必输项 字符 17 格式是yyyyMMddhhmmssSSS
//..........................................................................
_Reserved1: string[100]; // 请求备用字段1 选输项 字符 100 备用,目前无意义
_Reserved2: string[100]; // 请求备用字段2 选输项 字符 100 备用,目前无意义
rd: array of packed record
iSeqno: string[35]; // 指令顺序号 必输项 字符 35 每笔指令的序号,本包内不重复。(工行只检查包内不重复,不同的包,工行不做指令顺序号重复性的检查。)
//返回专用................................................................
OrderNo: string[6]; // 平台交易序号 否 字符 6 银行产生的批次内的小序号
//........................................................................
PayAccNo: string[34]; // 本方账号 必输项 数字 34
PayAccNameCN: string[100]; // 本方账户名称 选输项 字符 100 根据人行标准,人民币账户的户名不应超过60字节,否则该字段可能被截取
PayAccNameEN: string[100]; // 本方账户英文名称 选输项 字符 100 中文名称、英文名称二者必输其一。
PayBranch: string[60]; // 付款账号开户行 必输项 字符 60
Portno: string[30]; // 缴费编号 必输项 字符 30
ContractNo: string[15]; // 协议编号 必输项 字符 15
CurrType: string[3]; // 币种 必输项 字符 3
PayAmt: string[17]; // 金额 必输项 数字 17 无正负号,不带小数点,以分作单位
UseCode: string[3]; // 用途代码 选输项 字符 3
UseCN: string[20]; // 用途中文描述 选输项 字符 20 "用途代码和用途中文描述必输其一;如需跨行实时到帐此项最多10个字符.超长则落地处理."
EnSummary: string[40]; // 英文备注 选输项 字符 40 必须ASCII字符
PostScript: string[100]; // 附言 选输项 字符 100
Summary: string[20]; // 摘要 选输项 字符 20
Ref: string[20]; // 业务编号(业务参考号) 选输项 字符 20 必须ASCII字符
Oref: string[20]; // 相关业务编号 选输项 字符 20 必须ASCII字符
ERPSqn: string[20]; // ERP流水号 选输项 字符 20 必须ASCII字符
BusCode: string[5]; // 业务代码 选输项 字符 5 必须ASCII字符
ERPcheckno: string[8]; // ERP支票号 选输项 字符 8 必须ASCII字符
CrvouhType: string[3]; // 原始凭证种类 选输项 字符 3 必须ASCII字符
CrvouhName: string[30]; // 原始凭证名称 选输项 字符 30
CrvouhNo: string[20]; // 原始凭证号 选输项 字符 20 必须ASCII字符
//返回专用................................................................
Result: string[2]; {指令状态 否 字符 2 "0:提交成功,等待银行处理
1:授权成功, 等待银行处理
2:等待授权
3:等待二次授权
4:等待银行答复
5:主机返回待处理
6:被银行拒绝
7:处理成功
8:指令被拒绝授权
9:银行正在处理
10:预约指令
11:预约取消"
}
iRetCode: string[5]; // 返回码 否 字符 5
iRetMsg: string[100]; // 交易返回描述 否 字符 100
//........................................................................
_Reserved3: string[3]; // 请求备用字段3 选输项 字符 3 付款账号行别,不输或输入102代表工行
_Reserved4: string[100]; // 请求备用字段4 选输项 字符 100 备用,目前无意义
end;
end;
//批量扣个人指令查询
TQueryPerDisRec = packed record
QryfSeqno: string[35]; // 待查指令包序列号 可选项 字符 35
QrySerialNo: string[15]; // 待查平台交易流水号 可选项 字符 15
//返回专用..................................................................
OnlBatF: string[1]; // 联机批量标志 选输项 数字 1 1:联机
SettleMode: string[1]; // 入账方式 必输项 数字 1 2:并笔入账 0:逐笔记账
RecAccNo: string[19]; // 收方账号 必输项 数字 19
RecAccNameCN: string[60]; // 收方账户名称 选输项 字符 60 中文名称、英文名称二者必输其一。
RecAccNameEN: string[60]; // 收方账户英文名称 选输项 字符 60 中文名称、英文名称二者必输其一。
RetTotalNum: string[6]; // 总笔数 必输项 数字 6 指令包内的指令笔数
RetTotalAmt: string[20]; // 总金额 必输项 数字 20 无正负号,不带小数点,以分作单位
CurrType: string[3]; // 币种 否 字符 3
BusType: string[2]; // 业务种类编号 否 字符 2 1-15的数字
//..........................................................................
_Reserved1: string[100]; // 请求备用字段1 选输项 字符 100 备用,目前无意义
_Reserved2: string[100]; // 请求备用字段2 选输项 字符 100 备用,目前无意义
rd: array of packed record
iSeqno: string[35]; // 指令顺序号 必输项 字符 35 每笔指令的序号,本包内不重复。(工行只检查包内不重复,不同的包,工行不做指令顺序号重复性的检查。)
QryiSeqno: string[35]; // 待查指令顺序号 可选项 字符 35
QryOrderNo: string[6]; // 待查平台交易序号 可选项 字符 6
//返回专用................................................................
Portno: string[30]; // 缴费编号 否 字符 30
//XML 返回 <OpType>资金汇划普通</OpType>
OpType: string[20]; { 缴费类型 否 数字 1 "0:同城转账
1:资金汇划普通
2:资金汇划加急" }
ContractNo: string[15]; // 协议编号 否 字符 15
PayAccNo: string[34]; // 本方账号 必输项 数字 34
PayAccNameCN: string[100]; // 本方账户名称 选输项 字符 100 根据人行标准,人民币账户的户名不应超过60字节,否则该字段可能被截取
PayAccNameEN: string[100]; // 本方账户英文名称 选输项 字符 100 中文名称、英文名称二者必输其一。
PayBranch: string[60]; // 付款账号开户行 必输项 字符 60
//CurrType: string[3]; // 币种 必输项 字符 3
PayAmt: string[17]; // 金额 必输项 数字 17 无正负号,不带小数点,以分作单位
UseCode: string[3]; // 用途代码 选输项 字符 3
UseCN: string[20]; // 用途中文描述 选输项 字符 20 "用途代码和用途中文描述必输其一;如需跨行实时到帐此项最多10个字符.超长则落地处理."
UserRem: string[40]; // 备注信息 否 字符 40
PostScript: string[100]; // 附言 选输项 字符 100
Summary: string[20]; // 摘要 选输项 字符 20
Ref: string[20]; // 业务编号(业务参考号) 选输项 字符 20 必须ASCII字符
Oref: string[20]; // 相关业务编号 选输项 字符 20 必须ASCII字符
ERPSqn: string[20]; // ERP流水号 选输项 字符 20 必须ASCII字符
BusCode: string[5]; // 业务代码 选输项 字符 5 必须ASCII字符
ERPcheckno: string[8]; // ERP支票号 选输项 字符 8 必须ASCII字符
CrvouhType: string[3]; // 原始凭证种类 选输项 字符 3 必须ASCII字符
CrvouhName: string[30]; // 原始凭证名称 选输项 字符 30
CrvouhNo: string[20]; // 原始凭证号 选输项 字符 20 必须ASCII字符
Result: string[2]; {指令状态 否 字符 2 "0:提交成功,等待银行处理
1:授权成功, 等待银行处理
2:等待授权
3:等待二次授权
4:等待银行答复
5:主机返回待处理
6:被银行拒绝
7:处理成功
8:指令被拒绝授权
9:银行正在处理
10:预约指令
11:预约取消"
}
BankRem: string[100]; // 银行备注 否 字符 100
BankRetime: string[14]; // 银行批复时间 否 字符 14 yyyymmddhhmmss
iRetCode: string[5]; // 返回码 否 字符 5
iRetMsg: string[100]; // 交易返回描述 否 字符 100
//........................................................................
_Reserved3: string[3]; // 请求备用字段3 选输项 字符 3 付款账号行别,不输或输入102代表工行
_Reserved4: string[100]; // 请求备用字段4 选输项 字符 100 备用,目前无意义
end;
end;
//网点信息下载
TQueryNetNodeRec = packed record
NextTag: string[60]; // 查询下页标识 选输项 字符 60 查询首页上送空;其他页需与银行返回包提供的一致
_Reserved1: string[100]; // 请求备用字段1 选输项 字符 100 备用,目前无意义
_Reserved2: string[100]; // 请求备用字段2 选输项 字符 100 备用,目前无意义
//返回专用..................................................................
rd: array of packed record
AreaCode: string[4]; // 地区号 否 字符 4
NetName: string[40]; // 网点名称 否 字符 40
_Reserved3: string[100]; // 响应备用字段3 否 字符 100 备用,目前无意义
_Reserved4: string[100]; // 响应备用字段4 否 字符 100 备用,目前无意义
end;
//..........................................................................
end;
//缴费个人信息查询
TQueryPerInf = packed record
//发送专用..................................................................
BeginDate: string[8]; // 起始日期 必输项 字符 8 起始日期不能晚于终止日期;格式为YYYYMMDD
EndDate: string[8]; // 终止日期 必输项 字符 8 终止日期不能早于起始日期 格式为YYYYMMDD
BeginTime: string[6]; // 开始时间 选输项 字符 6 同一天的情况下,开始时间不能晚于终止时间 格式为hhmmss(暂时不起作用)
EndTime: string[6]; // 终止时间 选输项 字符 6 同一天的情况下,开始时间不能晚于终止时间 格式为hhmmss(暂时不起作用)
PayAccNo: string[19]; // 付款账号 选输项 字符 19
Portno: string[30]; // 缴费编号 选输项 字符 30
//..........................................................................
RecAccNo: string[19]; // 收费企业账号 必输项 字符 19
QueryTag: string[1]; // 查询协议类型 必输项 字符 1 0:签订协议 1:撤销协议
NextTag: string[60]; // 查询下页标识 选输项 字符 60 查询首页上送空;其他页与银行返回包提供的一致
_Reserved1: string[100]; // 请求备用字段1 选输项 字符 100 备用,目前无意义
_Reserved2: string[100]; // 请求备用字段2 选输项 字符 100 备用,目前无意义
//返回专用..................................................................
rd: array of packed record
ContractNo: string[35]; // 协议编号 否 字符 35
Portno: string[30]; // 缴费编号 否 字符 30
OpType: string[20]; // 缴费种类 否 字符 20
PayAccNo: string[19]; // 付款帐号 否 字符 19
PayAccNameCN: string[60]; // 付款帐号名称 否 字符 60
SignDate: string[14]; // 签定/撤销协议时间 否 字符 14 YYYYMMDDHHMMSS
_Reserved3: string[100]; // 响应备用字段3 否 字符 100 备用,目前无意义
_Reserved4: string[100]; // 响应备用字段4 否 字符 100 备用,目前无意义
end;
//..........................................................................
end;
implementation
end.
|
unit FormMovimentacaoAjusteEstoque;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Vcl.ExtCtrls;
type
TfrmMovimentacaoAjusteEstoque = class(TForm)
painelComandos: TPanel;
btnRetornar: TBitBtn;
btnAlterar: TBitBtn;
btnNovo: TBitBtn;
btnPesquisar: TBitBtn;
btnExcluir: TBitBtn;
btnSalvar: TBitBtn;
btnAvancar: TBitBtn;
btnCancelar: TBitBtn;
btnImprimir: TBitBtn;
btnSair: TBitBtn;
procedure btnSairClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure fecharForm;
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMovimentacaoAjusteEstoque: TfrmMovimentacaoAjusteEstoque;
implementation
{$R *.dfm}
procedure TfrmMovimentacaoAjusteEstoque.btnSairClick(Sender: TObject);
begin
fecharForm;
end;
procedure TfrmMovimentacaoAjusteEstoque.fecharForm;
begin
if (Application.MessageBox('Deseja Realmente Sair ?','Confirmação',MB_YESNO Or MB_ICONQUESTION) = IDYES) then
frmMovimentacaoAjusteEstoque.Close;
end;
procedure TfrmMovimentacaoAjusteEstoque.FormKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key = VK_F11 then
fecharForm;
if Key = VK_ESCAPE then
fecharForm;
end;
end.
|
{
Copyright (c) 2012, Loginov Dmitry Sergeevich
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}
unit MedDBStruct;
interface
uses
ibxFBUtils, fbTypes, MedGlobalUnit, SysUtils, Classes;
procedure BuildDBStructure;
implementation
procedure BuildDBStructure;
var
ATable: TfbTableDesc;
begin
fb.DBStruct.ReCreateDefDataBaseDesc();
try
fb.DBStruct.DefDBDesc.AddDomain('T_YESNO', 'INTEGER', '0', CanNull, '(VALUE IS NULL) OR (VALUE IN (0,1))');
// CONFIGPARAMS - таблица для хранения конфигурационных настроек
ATable := fb.DBStruct.DefDBDesc.AddTable('CONFIGPARAMS');
with ATable do
begin
AddField('FILENAME', 'VARCHAR(100)', '', NotNull);
AddField('COMPUTERNAME', 'VARCHAR(100)', '', NotNull);
AddField('USERNAME', 'VARCHAR(100)', '', NotNull);
AddField('SECTIONNAME', 'VARCHAR(100)', '', NotNull);
AddField('PARAMNAME', 'VARCHAR(100)', '', NotNull);
AddField('PARAMVALUE', 'VARCHAR(10000)', '', CanNull);
AddField('PARAMBLOB', 'BLOB', '', CanNull);
AddField('PARAMBLOBHASH', 'VARCHAR(50)', '', CanNull);
AddField('MODIFYDATE', 'TIMESTAMP', '', CanNull);
AddField('MODIFYUSER', 'VARCHAR(100)', '', CanNull);
SetPrimaryKey('CONFIGPARAMS_PK', 'FILENAME, COMPUTERNAME, USERNAME, SECTIONNAME, PARAMNAME');
end;
// DOCTORS - таблица врачей
ATable := fb.DBStruct.DefDBDesc.AddTable('DOCTORS');
with ATable do
begin
AddField('ID', 'INTEGER', '', NotNull); // Порядковый № записи
AddField('TABNUM', 'VARCHAR(20)', '', CanNull); // Табельный № врача (синхронизация 1)
AddField('NAME', 'VARCHAR(100)', '', CanNull); // ФИО врача (синхронизация 2)
AddField('FULLNAME', 'VARCHAR(200)', '', CanNull); // Полное имя врача
AddField('USERPASSW', 'VARCHAR(20)', '', CanNull); // Пароль врача
AddField('ISBOSS', 'T_YESNO', '', CanNull); // Является ли учетная запись административной
AddField('ADDDATE', 'TIMESTAMP', '', CanNull); // Время добавления записи
AddField('ISDELETE', 'T_YESNO', '', CanNull); // Признак удаления записи
AddField('COMMENT', 'VARCHAR(999)', '', CanNull); // Дополнительная информация
AddField('COMPNAME', 'VARCHAR(100)', '', CanNull); // Имя компьютера, где добавлена запись
// Подключаем триггер для обновления поля MODIFYDATE (поле будет создано автоматически)
UseModifyDateTrigger := trsActive;
SetPrimaryKey('DOCTORS_PK', '"ID"'); // Описание первичного ключа
// Триггер для автоматического заполнения поля ADDDATE
AddTrigger(trBefore, [trInsert], 1, trsActive, 'DOCTORS_ADDDATE_BI', '',
' IF (NEW.ADDDATE IS NULL) THEN NEW.ADDDATE = CURRENT_TIMESTAMP;');
fb.DBStruct.DefDBDesc.AddGenerator('GEN_DOCTORS_ID', 0);
end;
// DESCCATEGS - таблица категорий элементов описания
ATable := fb.DBStruct.DefDBDesc.AddTable('DESCCATEGS');
with ATable do
begin
AddField('ID', 'INTEGER', '', NotNull); // Порядковый номер категории
AddField('ADDDATE', 'TIMESTAMP', '', CanNull); // Время добавления записи
AddField('ADDDOCTOR', 'INTEGER', '', CanNull); // ID доктора, добавившего категорию
AddField('MODIFYDOCTOR', 'INTEGER', '', CanNull); // ID доктора, изменившего категорию
AddField('ISDELETE', 'T_YESNO', '', CanNull); // Признак удаления записи
AddField('CATEGCODE', 'VARCHAR(100)', '', CanNull); // Код категории (синхронизация 1) - должен совпадать на всех раб. местах
AddField('NAME', 'VARCHAR(100)', '', CanNull); // Наименование категории (синхронизация 2)
AddField('CATEGTEXT', 'VARCHAR(500)', '', CanNull); // Текст категории для выписки
AddField('ELEMLISTSTYLE','INTEGER', '', CanNull); // Способ представления элементов: 0 - друг за другом в абзаце, 1 - нумерованный список, 2 - маркированный список
AddField('CATEGDECOR', 'VARCHAR(20)', '', CanNull); // Символы выделения текста категории (B, I, U)
AddField('TEMPLCODE', 'VARCHAR(100)', '', CanNull); // Наименование переменной в шаблоне
AddField('USECATEG', 'T_YESNO', '', CanNull); // TRUE - можно использовать категорию для выписки
AddField('COMMENT', 'VARCHAR(999)', '', CanNull); // Подробное описание категории
AddField('COMPNAME', 'VARCHAR(100)', '', CanNull); // Имя компьютера, где добавлена запись
AddField('ORDERNUM', 'INTEGER', '', CanNull); // Порядок, в котором должны выводиться категории в окне ввода
// Подключаем триггер для обновления поля MODIFYDATE (поле будет создано автоматически)
UseModifyDateTrigger := trsActive;
SetPrimaryKey('DESCCATEGS_PK', '"ID"'); // Описание первичного ключа
// Триггер для автоматического заполнения поля ADDDATE
AddTrigger(trBefore, [trInsert], 1, trsActive, 'DESCCATEGS_ADDDATE_BI', '',
' IF (NEW.ADDDATE IS NULL) THEN NEW.ADDDATE = CURRENT_TIMESTAMP;');
fb.DBStruct.DefDBDesc.AddGenerator('GEN_DESCCATEGS_ID', 0);
end;
// DESCELEMS - таблица элементов описания
ATable := fb.DBStruct.DefDBDesc.AddTable('DESCELEMS');
with ATable do
begin
AddField('ID', 'INTEGER', '', NotNull); // Порядковый номер элемента
AddField('CATEG_ID', 'INTEGER', '', NotNull); // ID категории (ссылка на DESCCATEGS)
AddField('ADDDATE', 'TIMESTAMP', '', CanNull); // Время добавления записи
AddField('ADDDOCTOR', 'INTEGER', '', CanNull); // ID доктора, добавившего элемент описания
AddField('MODIFYDOCTOR', 'INTEGER', '', CanNull); // ID доктора, изменившего элемент
AddField('ISDELETE', 'T_YESNO', '', CanNull); // Признак удаления записи
AddField('ELEMCODE', 'VARCHAR(100)', '', CanNull); // Код элемента (синхронизация 1) - должен совпадать на всех раб. местах
AddField('ELEMNAME', 'VARCHAR(100)', '', CanNull); // Наименование элемента (синхронизация 2)
AddField('ELEMTEXT', 'VARCHAR(500)', '', CanNull); // Текст элемента для выписки
AddField('COMMENT', 'VARCHAR(300)', '', CanNull); // Подробное описание категории
AddField('COMPNAME', 'VARCHAR(100)', '', CanNull); // Имя компьютера, где добавлена запись
AddField('ORDERNUM', 'INTEGER', '', CanNull); // Порядок, в котором должны выводиться элементы в окне ввода
//AddField('PRINTTEXT', 'T_YESNO', '', CanNull); // Должен ли печататься текст категории
AddField('ISREQUIRED', 'T_YESNO', '', CanNull); // Является ли элемент обязательным для заполнения
AddField('VARPOS', 'VARCHAR(1)', '', CanNull); // Расположение вариантов состояния (L-слева, R-справа)
AddField('DELIMAFTER', 'VARCHAR(1)', '', CanNull); // Символ-разделитель после текста элемента (если варианты - справа)
AddField('ELEMDECOR', 'VARCHAR(20)', '', CanNull); // Символы выделения текста элемента (B, I, U)
AddField('CONTINUEPREV', 'T_YESNO', '', CanNull); // Продолжать предыдущий элемент (размещать в одном предложении)
AddField('VARSEPARATOR', 'VARCHAR(1)', '', CanNull); // Символ разделения вариантов
AddField('REQUIREVARS', 'T_YESNO', '', CanNull); // Требовать, чтобы был выбран хотя бы один из вариантов
AddField('CUSTOMVARS', 'T_YESNO', '', CanNull); // Можно ли вводить вместо варианта произвольный текст (при этом)
// Подключаем триггер для обновления поля MODIFYDATE (поле будет создано автоматически)
UseModifyDateTrigger := trsActive;
SetPrimaryKey('DESCELEMS_PK', '"ID"'); // Описание первичного ключа
// Триггер для автоматического заполнения поля ADDDATE
AddTrigger(trBefore, [trInsert], 1, trsActive, 'DESCELEMS_ADDDATE_BI', '',
' IF (NEW.ADDDATE IS NULL) THEN NEW.ADDDATE = CURRENT_TIMESTAMP;');
fb.DBStruct.DefDBDesc.AddGenerator('GEN_DESCELEMS_ID', 0);
end;
// DESCVARS - таблица вариантов описания
ATable := fb.DBStruct.DefDBDesc.AddTable('DESCVARS');
with ATable do
begin
AddField('ID', 'INTEGER', '', NotNull); // Порядковый номер варианта
AddField('ELEM_ID', 'INTEGER', '', NotNull); // ID элемента (ссылка на DESCELEMS)
AddField('ADDDATE', 'TIMESTAMP', '', CanNull); // Время добавления записи
AddField('ADDDOCTOR', 'INTEGER', '', CanNull); // ID доктора, добавившего элемент описания
AddField('MODIFYDOCTOR', 'INTEGER', '', CanNull); // ID доктора, изменившего элемент
AddField('ISDELETE', 'T_YESNO', '', CanNull); // Признак удаления записи
AddField('VARCODE', 'VARCHAR(50)', '', CanNull); // Код варианта (синхронизация 1) - должен совпадать на всех раб. местах
AddField('VARTEXT', 'VARCHAR(500)', '', CanNull); // Текст варианта (синхронизация 2)
AddField('VARTYPES', 'VARCHAR(200)', '', CanNull); // Указание типа для каждой подстановочной строки
AddField('CORRELEM', 'VARCHAR(100)', '', CanNull); // Скорректированный текст элемента
AddField('COMMENT', 'VARCHAR(300)', '', CanNull); // Подробное описание варианта
AddField('COMPNAME', 'VARCHAR(100)', '', CanNull); // Имя компьютера, где добавлена запись
AddField('ORDERNUM', 'INTEGER', '', CanNull); // Порядок расположения относительно других вариантов
AddField('CANOTHERVARS', 'T_YESNO', '', CanNull); // Допускает ли одновременное присутствие других вариантов в выписке
UseModifyDateTrigger := trsActive;
SetPrimaryKey('DESCVARS_PK', '"ID"');
// Триггер для автоматического заполнения поля ADDDATE
AddTrigger(trBefore, [trInsert], 1, trsActive, 'DESCVARS_ADDDATE_BI', '',
' IF (NEW.ADDDATE IS NULL) THEN NEW.ADDDATE = CURRENT_TIMESTAMP;');
fb.DBStruct.DefDBDesc.AddGenerator('GEN_DESCVARS_ID', 0);
end;
// CHECKOUTS - таблица выписок
ATable := fb.DBStruct.DefDBDesc.AddTable('CHECKOUTS');
with ATable do
begin
AddField('ID', 'INTEGER', '', NotNull); // Порядковый номер выписки
AddField('ADDDATE', 'TIMESTAMP', '', CanNull); // Время добавления записи
AddField('ADDDOCTOR', 'INTEGER', '', CanNull); // ID доктора, добавившего выписку
AddField('MODIFYDOCTOR', 'INTEGER', '', CanNull); // ID доктора, изменившего выписку
AddField('ISDELETE', 'T_YESNO', '', CanNull); // Признак удаления записи
AddField('COMPNAME', 'VARCHAR(100)', '', CanNull); // Имя компьютера, где добавлена запись
AddField('ISCLOSED', 'T_YESNO', '', CanNull); // Признак завершенности выписки (ПРОВЕДЕНА)
AddField('DATEIN', 'TIMESTAMP', '', CanNull); // Дата госпитализации пациента
AddField('DATEOUT', 'TIMESTAMP', '', CanNull); // Дата выписки пациента
AddField('NUMBER', 'VARCHAR(100)', '', CanNull); // Номер выписки (вводится вручную)
//AddField('PATNAME1', 'VARCHAR(100)', '', CanNull); // Фамилия пациента
//AddField('PATNAME2', 'VARCHAR(100)', '', CanNull); // Имя пациента
//AddField('PATNAME3', 'VARCHAR(100)', '', CanNull); // Отчество пациента
AddField('PATPRINTNAME', 'VARCHAR(200)', '', CanNull); // ФИО пациента для выписки
AddField('PATSEX', 'VARCHAR(1)', '', CanNull); // Пол пациента (m - мужчина, f - женщина)
AddField('PATBDAY', 'TIMESTAMP', '', CanNull); // Дата рождения пациента
AddField('DIAGNOS', 'VARCHAR(1000)','', CanNull); // Диагноз
AddField('DOCTOR_ID', 'INTEGER', '', CanNull); // ID лечащего врача
UseModifyDateTrigger := trsActive;
SetPrimaryKey('CHECKOUTS_PK', '"ID"');
// Триггер для автоматического заполнения поля ADDDATE
AddTrigger(trBefore, [trInsert], 1, trsActive, 'CHECKOUTS_ADDDATE_BI', '',
' IF (NEW.ADDDATE IS NULL) THEN NEW.ADDDATE = CURRENT_TIMESTAMP;');
fb.DBStruct.DefDBDesc.AddGenerator('GEN_CHECKOUTS_ID', 0);
end;
// COCATEGS - катерогии формируемых выписок
ATable := fb.DBStruct.DefDBDesc.AddTable('COCATEGS');
with ATable do
begin
AddField('ID', 'INTEGER', '', NotNull); // Порядковый номер записи
AddField('ADDDATE', 'TIMESTAMP', '', CanNull); // Время добавления записи
AddField('ADDDOCTOR', 'INTEGER', '', CanNull); // ID доктора, добавившего запись
AddField('MODIFYDOCTOR', 'INTEGER', '', CanNull); // ID доктора, изменившего запись
//AddField('ISDELETE', 'T_YESNO', '', CanNull); // Признак удаления записи
AddField('COMPNAME', 'VARCHAR(100)', '', CanNull); // Имя компьютера, где добавлена запись
AddField('CHECKOUT_ID', 'INTEGER', '', CanNull); // Ссылка на выписку CHECKOUTS.ID
AddField('CATEG_ID', 'INTEGER', '', CanNull); // Ссылка на категорию описания DESCCATEGS
AddField('FULLTEXT', 'BLOB', '', CanNull); // Полный текст категории (доступен после проведения выписки)
AddField('ORDERNUM', 'INTEGER', '', CanNull); // Порядковый № категории (копируется из таблицы DESCCATEGS)
UseModifyDateTrigger := trsActive;
SetPrimaryKey('COCATEGS_PK', '"ID"');
// Триггер для автоматического заполнения поля ADDDATE
AddTrigger(trBefore, [trInsert], 1, trsActive, 'COCATEGS_ADDDATE_BI', '',
' IF (NEW.ADDDATE IS NULL) THEN NEW.ADDDATE = CURRENT_TIMESTAMP;');
fb.DBStruct.DefDBDesc.AddGenerator('GEN_COCATEGS_ID', 0);
end;
// COELEMS - элементы формируемых выписок
ATable := fb.DBStruct.DefDBDesc.AddTable('COELEMS');
with ATable do
begin
AddField('ID', 'INTEGER', '', NotNull); // Порядковый номер записи
AddField('ADDDATE', 'TIMESTAMP', '', CanNull); // Время добавления записи
AddField('ADDDOCTOR', 'INTEGER', '', CanNull); // ID доктора, добавившего запись
AddField('MODIFYDOCTOR', 'INTEGER', '', CanNull); // ID доктора, изменившего запись
//AddField('ISDELETE', 'T_YESNO', '', CanNull); // Признак удаления записи
AddField('COMPNAME', 'VARCHAR(100)', '', CanNull); // Имя компьютера, где добавлена запись
AddField('COCATEGS_ID', 'INTEGER', '', CanNull); // Ссылка на категорию COCATEGS.ID
AddField('ELEM_ID', 'INTEGER', '', CanNull); // Ссылка на элемент описания DESCELEMS.ID
AddField('ELEMTEXT', 'VARCHAR(100)', '', CanNull); // Текст элемента описания (в том числе если он введен вручную)
AddField('ORDERNUM', 'INTEGER', '', CanNull); // Порядковый № элемента (копируется из таблицы DESCELEMS)
UseModifyDateTrigger := trsActive;
SetPrimaryKey('COELEMS_PK', '"ID"');
// Триггер для автоматического заполнения поля ADDDATE
AddTrigger(trBefore, [trInsert], 1, trsActive, 'COELEMS_ADDDATE_BI', '',
' IF (NEW.ADDDATE IS NULL) THEN NEW.ADDDATE = CURRENT_TIMESTAMP;');
fb.DBStruct.DefDBDesc.AddGenerator('GEN_COELEMS_ID', 0);
end;
// COVARS - варианты элементов описания формируемых выписок
ATable := fb.DBStruct.DefDBDesc.AddTable('COVARS');
with ATable do
begin
AddField('ID', 'INTEGER', '', NotNull); // Порядковый номер записи
AddField('ADDDATE', 'TIMESTAMP', '', CanNull); // Время добавления записи
AddField('ADDDOCTOR', 'INTEGER', '', CanNull); // ID доктора, добавившего запись
AddField('MODIFYDOCTOR', 'INTEGER', '', CanNull); // ID доктора, изменившего запись
//AddField('ISDELETE', 'T_YESNO', '', CanNull); // Признак удаления записи
AddField('COMPNAME', 'VARCHAR(100)', '', CanNull); // Имя компьютера, где добавлена запись
AddField('COELEM_ID', 'INTEGER', '', CanNull); // Ссылка на элемент описания COELEMS.ID
AddField('VAR_ID', 'INTEGER', '', CanNull); // Ссылка на вариант элемента описания DESCVARS.ID
AddField('VARTEXT', 'VARCHAR(100)', '', CanNull); // Окончательный текст варианта описания (в том числе если он введен вручную)
AddField('ORDERNUM', 'INTEGER', '', CanNull); // Порядковый № варианта (копируется из таблицы DESCVARS)
UseModifyDateTrigger := trsActive;
SetPrimaryKey('COVARS_PK', '"ID"');
// Триггер для автоматического заполнения поля ADDDATE
AddTrigger(trBefore, [trInsert], 1, trsActive, 'COVARS_ADDDATE_BI', '',
' IF (NEW.ADDDATE IS NULL) THEN NEW.ADDDATE = CURRENT_TIMESTAMP;');
fb.DBStruct.DefDBDesc.AddGenerator('GEN_COVARS_ID', 0);
end;
//exit;
finally
fb.DBStruct.CheckDefDataBaseStruct(FBServer, FBPort, FBFile,
FBUser, FBPassword, FBRusCharSet, LogEventsProc);
end;
end;
end.
|
unit adot.Variants;
{ Definition of classes/record types:
TUnifiedVarAccess = record
Unified access to content of variable of any type:
- array of byte/integer/extended/... type can be accessed as array of "double".
- operations on variant array of any type can be done in unified style.
TVar = class
Utils/helpers for variant type (set of functions ToType/ToTypeDef/TryToType etc)
TVarArray = record
Helper for variant array (unified access to numeric values as "double" etc).
TVarArrayTypified<ElementType> = record
Typed access to elements of variant array (should be instantiated with correct type).
}
interface
uses
adot.Types,
System.Variants,
System.Math,
System.SysUtils,
System.Classes;
type
{ Utils/helpers for variant type (set of functions ToType/ToTypeDef/TryToType etc) }
TVar = class
public
class function IsArray(const v: variant): boolean; static;
class function IsRef(const v: variant): boolean;
class function IsArrayOrRef(const v: variant): boolean;
class function IsStr(const v: variant): boolean;
class function IsDateTime(const v: variant): boolean;
class function IsNumeric(const v: variant): boolean;
class function IsInteger(const v: variant): boolean;
class function IsBoolean(const v: variant): boolean;
class function IsNull(const V: variant): Boolean; overload;
class function IsNull(const V: array of variant): Boolean; overload;
class function IsEmpty(const V: variant): Boolean; { Null, Unassigned }
{ simple conversion (raises exception in case of errors) }
class function ToInteger(const Src: variant): int64; static;
class function ToFloat(const Src: variant): double; static;
class function ToCurrency(const Src: variant): Currency; static;
class function ToChar(const Src: variant): char; static;
class function ToGUID(const Src: variant): TGUID; overload; static;
class function ToBoolean(const Src: variant): boolean; static;
class function ToString(const Src: variant): string; reintroduce; static;
class function ToDateTime(const Src: variant): TDateTime; static;
{ same conversion but returns boolean instead of exceptions }
class function TryToInteger(const Src: variant; out Dst: integer): boolean; overload; static;
class function TryToInteger(const Src: variant; out Dst: int64): boolean; overload; static;
class function TryToFloat(const Src: variant; out Dst: double): boolean; static;
class function TryToCurrency(const Src: variant; out Dst: currency): boolean; static;
class function TryToChar(const Src: variant; out Dst: char): boolean; static;
class function TryToGUID(const Src: variant; out Dst: TGUID): boolean; static;
class function TryToBoolean(const Src: variant; out Dst: boolean): boolean; static;
class function TryToString(const Src: variant; out Dst: string): boolean; static;
class function TryToDateTime(const Src: variant; out Dst: TDateTime): boolean; static;
{ same conversion with default value instead of exception }
class function ToIntegerDef(const Src: variant; const Default: int64 = 0): int64; static;
class function ToFloatDef(const Src: variant; const Default: double = 0): double; static;
class function ToCurrencyDef(const Src: variant; const Default: currency = 0): currency; static;
class function ToCharDef(const Src: variant; const Default: char = #0): char; static;
class function ToGUIDDef(const Src: variant; const Default: TGUID): TGUID; overload; static;
class function ToGUIDDef(const Src: variant): TGUID; overload; static;
class function ToBooleanDef(const Src: variant; const Default: boolean = False): boolean; static;
class function ToStringDef(const Src: variant; const Default: string = ''): string; reintroduce; static;
class function ToDateTimeDef(const Src: variant; const Default: TDateTime = 0): TDateTime; static;
class function VarOrArrayToStr(const V: variant; const ArrElemDelimeter: string = #13#10): string; static;
class function GetArrayBounds(const DataArray: Variant; var ALow, AHigh: Integer): boolean; overload;
class function GetArrayBounds(const DataArray: Variant; var ALow1,AHigh1,ALow2,AHigh2: Integer): boolean; overload;
class function VarRecAsVariant(Value: TVarRec): Variant; static;
class function VarRecAsString(Value: TVarRec): String; static;
end;
TEnumFloatProc = reference to procedure(var AValue: Double; const ADim: TArray<integer>);
{ Helper for variant array (unified access to numeric values as "double" etc). }
TVarArray = record
public
type
TDimEnumerator = record
private
FDimCount: integer;
FDimCurrent: TArray<integer>;
FDimInc: TArray<integer>;
FDimLow: TArray<integer>;
FDimHigh: TArray<integer>;
public
constructor Create(const Arr: TVarArray);
procedure Next;
property Current: TArray<integer> read FDimCurrent;
end;
private
FVArray: variant;
function GetDimCount: integer;
function GetDimHighBound(ADim: integer): integer;
function GetDimLowBound(ADim: integer): integer;
function GetCount: integer;
public
constructor Create(VArray: variant);
function Lock: pointer;
procedure Unlock;
procedure Clear;
{ default enumerator for indices of all elements }
function GetEnumerator: TDimEnumerator;
{ Enumerates all compatible types (array of integer/string/...) as "float" for unified access.
If type of array elements is not compatible, then returns False. }
function EnumElementsAsFloat(const ACurProc: TEnumFloatProc): boolean;
property Count: integer read GetCount; { Total number of elements (in all dimensions) }
property DimCount: integer read GetDimCount;
property DimLowBound[ADim: integer]: integer read GetDimLowBound; { Indexing starts from 0 }
property DimHighBound[ADim: integer]: integer read GetDimHighBound; { Indexing starts from 0 }
property VArray: variant read FVArray;
end;
{ Typed access to elements of variant array (should be instantiated with correct type). }
TVarArrayTypified<ElementType> = record
private
type
TVarArrayEnumerator = record
private
FVarArray: variant;
FTotalItemsLeft: integer;
FCurrentPtr: ^ElementType;
function GetCurrent: ElementType;
public
constructor Create(const Arr: TVarArrayTypified<ElementType>);
function MoveNext: Boolean;
property Current: ElementType read GetCurrent;
end;
var
FVarArray: TVarArray;
function GetDimCount: integer;
function GetDimHighBound(ADim: integer): integer;
function GetDimLowBound(ADim: integer): integer;
function GetCount: integer;
function GetVArray: variant;
public
type
TEnumProc = reference to procedure(var AValue: ElementType);
TEnumProcDim = reference to procedure(var AValue: ElementType; const ADim: TArray<integer>);
constructor Create(const VArray: variant);
{ Default enumerator for all elements of the array:
arr := TVarArray<variant>.Create(v);
for i in arr do
<...> }
function GetEnumerator: TVarArrayEnumerator;
function GetDimEnumerator: TVarArray.TDimEnumerator;
{ Enumerate all items for all dimensions (there is overloaded function
without "indices" parameter):
arr := TVarArray<variant>.Create(Value);
arr.Enumerate(
procedure(var Value: variant; const indices: TArray<integer>)
begin
value := -value;
end); }
procedure Enumerate(const AProc: TEnumProc); overload;
procedure Enumerate(const AProc: TEnumProcDim); overload;
function Lock: pointer;
procedure Unlock;
{ Total number of elements (in all dimensions) }
property Count: integer read GetCount;
{ Dimensions info }
property DimCount: integer read GetDimCount;
property DimLowBound[ADim: integer]: integer read GetDimLowBound; { Indexing starts from 0 }
property DimHighBound[ADim: integer]: integer read GetDimHighBound; { Indexing starts from 0 }
property VArray: variant read GetVArray;
end;
{ Access variant array of bytes as read/write stream (resize operation is not allowed) }
TVarArrayStream = class(TCustomMemoryStream)
protected
FValue: Variant;
procedure SetValue(AValue: Variant);
procedure SetSize(NewSize: Longint); override;
public
constructor Create(AValue: Variant);
destructor Destroy; override;
function Write(const Buffer; Count: Longint): Longint; override;
function ExtractValue: variant;
class function IsAcceptable(const AValue: Variant):Boolean; static;
property Value: Variant read FValue write SetValue;
end;
implementation
uses
adot.Tools;
type
{ Unified access to content of variable of any type:
- array of byte/integer/extended/... type can be accessed as array of "double".
- operations on variant array of any type can be done in unified style. }
TUnifiedVarAccess = record
private
type
TFloatReader = function(var Src): Double;
TFloatSetter = procedure(const Src: Double; var Dst);
var
Reader: TFloatReader;
Setter: TFloatSetter;
ElementSizeInArray: integer;
function GetAsFloat(var Src): Double;
procedure SetAsFloat(var Dst; const Value: Double);
procedure SetAccessProc(const AReader: TFloatReader; const ASetter: TFloatSetter;
AElementSize: integer);
class function GetByteAsFloat(var Value): Double; static;
class function GetWordAsFloat(var Value): Double; static;
class function GetLongwordAsFloat(var Value): Double; static;
class function GetShortIntAsFloat(var Value): Double; static;
class function GetSmallIntAsFloat(var Value): Double; static;
class function GetIntegerAsFloat(var Value): Double; static;
class function GetInt64AsFloat(var Value): Double; static;
class function GetUInt64AsFloat(var Value): Double; static;
// class function GetNativeIntAsFloat(var Value): Double; static;
// class function GetNativeUIntAsFloat(var Value): Double; static;
class function GetSingleAsFloat(var Value): Double; static;
class function GetDoubleAsFloat(var Value): Double; static;
// class function GetExtendedAsFloat(var Value): Double; static;
class function GetCurrencyAsFloat(var Value): Double; static;
class function GetStringAsFloat(var Value): Double; static;
// class function GetUnicodeStringAsFloat(var Value): Double; static;
{$IF Defined(MSWindows)}
class function GetWideStringAsFloat(var Value): Double; static;
{$EndIf}
class function GetVariantAsFloat(var Value): Double; static;
class procedure SetByteAsFloat(const Src: Double; var Value); static;
class procedure SetWordAsFloat(const Src: Double; var Value); static;
class procedure SetLongwordAsFloat(const Src: Double; var Value); static;
class procedure SetShortIntAsFloat(const Src: Double; var Value); static;
class procedure SetSmallIntAsFloat(const Src: Double; var Value); static;
class procedure SetIntegerAsFloat(const Src: Double; var Value); static;
class procedure SetInt64AsFloat(const Src: Double; var Value); static;
class procedure SetUInt64AsFloat(const Src: Double; var Value); static;
// class procedure SetNativeIntAsFloat(const Src: Double; var Value); static;
// class procedure SetNativeUIntAsFloat(const Src: Double; var Value); static;
class procedure SetSingleAsFloat(const Src: Double; var Value); static;
class procedure SetDoubleAsFloat(const Src: Double; var Value); static;
// class procedure SetExtendedAsFloat(const Src: Double; var Value); static;
class procedure SetCurrencyAsFloat(const Src: Double; var Value); static;
class procedure SetStringAsFloat(const Src: Double; var Value); static;
// class procedure SetUnicodeStringAsFloat(const Src: Double; var Value); static;
{$IF Defined(MSWindows)}
class procedure SetWideStringAsFloat(const Src: Double; var Value); static;
{$EndIf}
class procedure SetVariantAsFloat(const Src: Double; var Value); static;
public
class function Init(VarType: integer; var AHelper: TUnifiedVarAccess): boolean; static;
property AsFloat[var Src]: double read GetAsFloat write SetAsFloat;
property ElementSize: integer read ElementSizeInArray;
end;
{ TUnifiedVarAccess }
class function TUnifiedVarAccess.Init(VarType: integer; var AHelper: TUnifiedVarAccess): boolean;
begin
AHelper.Reader := nil;
AHelper.Setter := nil;
{ constants from System.Variants.pas }
case VarType of
// varEmpty = $0000; { vt_empty 0 }
// varNull = $0001; { vt_null 1 }
varSmallint : AHelper.SetAccessProc(GetSmallintAsFloat, SetSmallintAsFloat, SizeOf(SmallInt));
varInteger : AHelper.SetAccessProc(GetIntegerAsFloat, SetIntegerAsFloat, SizeOf(Integer));
varSingle : AHelper.SetAccessProc(GetSingleAsFloat, SetSingleAsFloat, SizeOf(Single));
varDouble : AHelper.SetAccessProc(GetDoubleAsFloat, SetDoubleAsFloat, SizeOf(Double));
varCurrency : AHelper.SetAccessProc(GetCurrencyAsFloat, SetCurrencyAsFloat, SizeOf(Currency));
// varDate = $0007; { vt_date 7 }
{$IF Defined(MSWindows)}
varOleStr : AHelper.SetAccessProc(GetWideStringAsFloat, SetWideStringAsFloat, SizeOf(WideString));
{$EndIf}
// varDispatch = $0009; { vt_dispatch 9 }
// varError = $000A; { vt_error 10 }
// varBoolean = $000B; { vt_bool 11 }
varVariant : AHelper.SetAccessProc(GetVariantAsFloat, SetVariantAsFloat, SizeOf(Variant));
// varUnknown = $000D; { vt_unknown 13 }
// //varDecimal = $000E; { vt_decimal 14 } {UNSUPPORTED as of v6.x code base}
// //varUndef0F = $000F; { undefined 15 } {UNSUPPORTED per Microsoft}
varShortInt : AHelper.SetAccessProc(GetShortIntAsFloat, SetShortIntAsFloat, SizeOf(ShortInt));
varByte : AHelper.SetAccessProc(GetByteAsFloat, SetByteAsFloat, SizeOf(Byte));
varWord : AHelper.SetAccessProc(GetWordAsFloat, SetWordAsFloat, SizeOf(Word));
varLongWord : AHelper.SetAccessProc(GetLongWordAsFloat, SetLongWordAsFloat, SizeOf(LongWord));
varInt64 : AHelper.SetAccessProc(GetInt64AsFloat, SetInt64AsFloat, SizeOf(Int64));
varUInt64 : AHelper.SetAccessProc(GetUInt64AsFloat, SetUInt64AsFloat, SizeOf(UInt64));
// varRecord = $0024; { VT_RECORD 36 }
{ if adding new items, update Variants' varLast, BaseTypeMap and OpTypeMap }
// varStrArg = $0048; { vt_clsid 72 }
// varObject = $0049; { 73 }
// varUStrArg = $004A; { 74 }
varString : AHelper.SetAccessProc(GetStringAsFloat, SetStringAsFloat, SizeOf(String));
// varAny = $0101; { Corba any 257 } {not OLE compatible }
//varUString : AHelper.SetAccessProc(GetUnicodeStringAsFloat, SetUnicodeStringAsFloat, SizeOf(UnicodeString));
end;
result := Assigned(AHelper.Reader) and Assigned(AHelper.Setter);
end;
procedure TUnifiedVarAccess.SetAccessProc(const AReader: TFloatReader; const ASetter: TFloatSetter;
AElementSize: integer);
begin
Reader := AReader;
Setter := ASetter;
ElementSizeInArray := AElementSize;
end;
function TUnifiedVarAccess.GetAsFloat(var Src): Double;
begin
result := Reader(Src);
end;
procedure TUnifiedVarAccess.SetAsFloat(var Dst; const Value: Double);
begin
Setter(Value, Dst);
end;
class function TUnifiedVarAccess.GetByteAsFloat(var Value): Double;
begin
result := Byte(Value);
end;
class function TUnifiedVarAccess.GetCurrencyAsFloat(var Value): Double;
begin
result := Currency(Value);
end;
class function TUnifiedVarAccess.GetDoubleAsFloat(var Value): Double;
begin
result := Double(Value);
end;
//class function TUnifiedVarAccess.GetExtendedAsFloat(var Value): Double;
//begin
// result := Extended(Value);
//end;
class function TUnifiedVarAccess.GetInt64AsFloat(var Value): Double;
begin
result := Int64(Value);
end;
class function TUnifiedVarAccess.GetIntegerAsFloat(var Value): Double;
begin
result := Integer(Value);
end;
class function TUnifiedVarAccess.GetLongwordAsFloat(var Value): Double;
begin
result := Longword(Value);
end;
//class function TUnifiedVarAccess.GetNativeIntAsFloat(var Value): Double;
//begin
// result := NativeInt(Value);
//end;
class function TUnifiedVarAccess.GetShortIntAsFloat(var Value): Double;
begin
result := ShortInt(Value);
end;
class function TUnifiedVarAccess.GetSingleAsFloat(var Value): Double;
begin
result := Single(Value);
end;
class function TUnifiedVarAccess.GetSmallIntAsFloat(var Value): Double;
begin
result := SmallInt(Value);
end;
class function TUnifiedVarAccess.GetStringAsFloat(var Value): Double;
begin
if not TryStrToFloat(String(Value), result) then
result := 0;
end;
class function TUnifiedVarAccess.GetUInt64AsFloat(var Value): Double;
begin
result := UInt64(Value);
end;
//class function TUnifiedVarAccess.GetNativeUIntAsFloat(var Value): Double;
//begin
// result := NativeUInt(Value);
//end;
//class function TUnifiedVarAccess.GetUnicodeStringAsFloat(var Value): Double;
//begin
// if not TryStrToFloat(UnicodeString(Value), result) then
// result := 0;
//end;
class function TUnifiedVarAccess.GetVariantAsFloat(var Value): Double;
begin
result := TVar.ToFloatDef(Variant(Value), 0);
end;
{$IF Defined(MSWindows)}
class function TUnifiedVarAccess.GetWideStringAsFloat(var Value): Double;
begin
if not TryStrToFloat(WideString(Value), result) then
result := 0;
end;
{$EndIf}
class function TUnifiedVarAccess.GetWordAsFloat(var Value): Double;
begin
result := Word(Value);
end;
class procedure TUnifiedVarAccess.SetByteAsFloat(const Src: Double; var Value);
begin
Byte(Value) := Round(Src);
end;
class procedure TUnifiedVarAccess.SetCurrencyAsFloat(const Src: Double; var Value);
begin
Currency(Value) := Src;
end;
class procedure TUnifiedVarAccess.SetDoubleAsFloat(const Src: Double; var Value);
begin
Double(Value) := Src;
end;
//class procedure TUnifiedVarAccess.SetExtendedAsFloat(const Src: Double; var Value);
//begin
// Extended(Value) := Src;
//end;
class procedure TUnifiedVarAccess.SetInt64AsFloat(const Src: Double; var Value);
begin
Int64(Value) := Round(Src);
end;
class procedure TUnifiedVarAccess.SetIntegerAsFloat(const Src: Double; var Value);
begin
Integer(Value) := Round(Src);
end;
class procedure TUnifiedVarAccess.SetLongwordAsFloat(const Src: Double; var Value);
begin
LongWord(Value) := Round(Src);
end;
//class procedure TUnifiedVarAccess.SetNativeIntAsFloat(const Src: Double; var Value);
//begin
// NativeInt(Value) := Round(Src);
//end;
class procedure TUnifiedVarAccess.SetShortIntAsFloat(const Src: Double; var Value);
begin
ShortInt(Value) := Round(Src);
end;
class procedure TUnifiedVarAccess.SetSingleAsFloat(const Src: Double; var Value);
begin
NativeInt(Value) := Round(Src);
end;
class procedure TUnifiedVarAccess.SetSmallIntAsFloat(const Src: Double; var Value);
begin
SmallInt(Value) := Round(Src);
end;
class procedure TUnifiedVarAccess.SetStringAsFloat(const Src: Double; var Value);
begin
String(Value) := FloatToStr(Src);
end;
class procedure TUnifiedVarAccess.SetUInt64AsFloat(const Src: Double; var Value);
begin
UInt64(Value) := Round(Src);
end;
//class procedure TUnifiedVarAccess.SetNativeUIntAsFloat(const Src: Double; var Value);
//begin
// NativeUInt(Value) := Round(Src);
//end;
//
//class procedure TUnifiedVarAccess.SetUnicodeStringAsFloat(const Src: Double; var Value);
//begin
// UnicodeString(Value) := FloatToStr(Src);
//end;
class procedure TUnifiedVarAccess.SetVariantAsFloat(const Src: Double; var Value);
begin
Variant(Value) := Src;
end;
{$IF Defined(MSWindows)}
class procedure TUnifiedVarAccess.SetWideStringAsFloat(const Src: Double; var Value);
begin
WideString(Value) := FloatToStr(Src);
end;
{$EndIf}
class procedure TUnifiedVarAccess.SetWordAsFloat(const Src: Double; var Value);
begin
Word(Value) := Round(Src);
end;
{ TVarArray<ElementType>.TVarArrayEnumerator<ElementType> }
constructor TVarArrayTypified<ElementType>.TVarArrayEnumerator.Create(const Arr: TVarArrayTypified<ElementType>);
begin
FVarArray := Arr.VArray;
FTotalItemsLeft := Arr.Count;
if FTotalItemsLeft<=0 then
FCurrentPtr := nil
else
begin
FCurrentPtr := VarArrayLock(FVarArray);
dec(FCurrentPtr);
end;
end;
function TVarArrayTypified<ElementType>.TVarArrayEnumerator.MoveNext: Boolean;
begin
result := FTotalItemsLeft>0;
if result then
begin
dec(FTotalItemsLeft);
inc(FCurrentPtr);
end
else
if FCurrentPtr<>nil then
begin
FCurrentPtr := nil;
VarArrayUnlock(FVarArray);
end;
end;
function TVarArrayTypified<ElementType>.TVarArrayEnumerator.GetCurrent: ElementType;
begin
result := FCurrentPtr^;
end;
{ TVarArrayTypified<ElementType> }
constructor TVarArrayTypified<ElementType>.Create(const VArray: variant);
begin
FVarArray := TVarArray.Create(VArray);
end;
function TVarArrayTypified<ElementType>.GetDimEnumerator: TVarArray.TDimEnumerator;
begin
result := FVarArray.GetEnumerator;
end;
function TVarArrayTypified<ElementType>.Lock: pointer;
begin
result := FVarArray.Lock;
end;
procedure TVarArrayTypified<ElementType>.Unlock;
begin
FVarArray.UnLock;
end;
function TVarArrayTypified<ElementType>.GetCount: integer;
begin
result := FVarArray.Count;
end;
function TVarArrayTypified<ElementType>.GetVArray: variant;
begin
result := FVarArray.VArray;
end;
function TVarArrayTypified<ElementType>.GetDimCount: integer;
begin
result := FVarArray.DimCount;
end;
function TVarArrayTypified<ElementType>.GetDimHighBound(ADim: integer): integer;
begin
result := FVarArray.DimHighBound[ADim];
end;
function TVarArrayTypified<ElementType>.GetDimLowBound(ADim: integer): integer;
begin
result := FVarArray.DimLowBound[ADim];
end;
function TVarArrayTypified<ElementType>.GetEnumerator: TVarArrayEnumerator;
begin
result := TVarArrayEnumerator.Create(Self);
end;
procedure TVarArrayTypified<ElementType>.Enumerate(const AProc: TEnumProc);
var
p: ^ElementType;
i: Integer;
begin
p := Lock;
try
for i := 0 to Count-1 do
begin
AProc(p^);
inc(p);
end;
finally
Unlock;
end;
end;
procedure TVarArrayTypified<ElementType>.Enumerate(const AProc: TEnumProcDim);
var
p: ^ElementType;
i: Integer;
DimEnum: TVarArray.TDimEnumerator;
begin
DimEnum := GetDimEnumerator;
p := Lock;
try
for i := 0 to Count-1 do
begin
AProc(p^, DimEnum.Current);
inc(p);
DimEnum.Next;
end;
finally
Unlock;
end;
end;
{ TVar }
class function TVar.ToBoolean(const Src: variant): boolean;
var
S: string;
begin
if IsBoolean(Src) then { VarIsNumeric returns True for varBoolean type, so we check it first }
result := Src
else
if VarIsStr(Src) then
begin
S := Src;
result := AnsiSameText(S, 'True') or AnsiSameText(S, 'Ja') or AnsiSameText(S, '1');
end
else
if VarIsNumeric(Src) then
result := Integer(Src)=1
else
result := Src; { give a try }
end;
class function TVar.ToBooleanDef(const Src: variant; const Default: boolean): boolean;
begin
if not TryToBoolean(Src, result) then
result := Default;
end;
class function TVar.ToChar(const Src: variant): char;
var
S: string;
begin
S := Src;
if Length(S)>0 then
result := S[Low(S)]
else
raise Exception.Create('Error');
end;
class function TVar.ToCharDef(const Src: variant; const Default: char): char;
begin
if not TryToChar(Src, result) then
result := Default;
end;
class function TVar.ToDateTime(const Src: variant): TDateTime;
begin
result := VarToDateTime(Src); { Supports string/DateTime etc }
end;
class function TVar.ToDateTimeDef(const Src: variant; const Default: TDateTime): TDateTime;
begin
if not TryToDateTime(Src, result) then
result := Default;
end;
class function TVar.ToFloat(const Src: variant): double;
begin
result := Src;
end;
class function TVar.ToCurrency(const Src: variant): currency;
begin
result := Src;
end;
class function TVar.ToFloatDef(const Src: variant; const Default: double): double;
begin
if not TryToFloat(Src, result) then
result := Default;
end;
class function TVar.ToCurrencyDef(const Src: variant; const Default: currency): currency;
begin
if not TryToCurrency(Src, result) then
result := Default;
end;
class function TVar.ToGUIDDef(const Src: variant; const Default: TGUID): TGUID;
begin
if not TryToGUID(Src, result) then
result := Default;
end;
class function TVar.ToGUID(const Src: variant): TGUID;
begin
result := StringToGUID(Src);
end;
class function TVar.ToGUIDDef(const Src: variant): TGUID;
begin
if not TryToGUID(Src, result) then
result := NullGUID;
end;
class function TVar.ToInteger(const Src: variant): int64;
begin
Result := Src;
end;
class function TVar.ToIntegerDef(const Src: variant; const Default: int64): int64;
begin
if not TryToInteger(Src, result) then
result := Default;
end;
class function TVar.ToString(const Src: variant): string;
begin
result := Src;
end;
class function TVar.ToStringDef(const Src: variant; const Default: string): string;
begin
if not TryToString(Src, result) then
result := Default;
end;
class function TVar.IsBoolean(const v: variant): boolean;
begin
result := (VarType(v) and varTypeMask)=varBoolean;
end;
class function TVar.TryToBoolean(const Src: variant; out Dst: boolean): boolean;
var
S: string;
begin
try
result := not IsEmpty(Src);
if result then
if IsBoolean(Src) then { VarIsNumeric returns True for varBoolean type, so we check it first }
Dst := Src
else
if VarIsStr(Src) then
begin
S := Src;
Dst := AnsiSameText(S, 'True') or AnsiSameText(S, 'Ja') or AnsiSameText(S, '1');
end
else
if VarIsNumeric(Src) then
Dst := Integer(Src)=1
else
Dst := Src; { give a try }
except
result := False; { type conversion to integer/boolean may raise exceptions }
end;
end;
class function TVar.TryToChar(const Src: variant; out Dst: char): boolean;
var
S: string;
begin
result := IsStr(Src);
if result then
begin
S := Src;
if Length(S)>0 then
Dst := S[Low(S)]
else
result := False;
end;
end;
class function TVar.TryToDateTime(const Src: variant; out Dst: TDateTime): boolean;
begin
result := not IsEmpty(Src); { To avoid of exceptions in simple situations }
if result then
try
Dst := VarToDateTime(Src); { Supports string/DateTime etc }
except
result := False;
end;
end;
class function TVar.TryToFloat(const Src: variant; out Dst: double): boolean;
begin
Result := not IsEmpty(Src); { To avoid of exceptions in simple situations }
if Result then
try
{ "Dst := Src" does same job, but we use extra check for
regular strings to avoid of exceptions (annoying in debug) }
if VarIsStr(Src) then
result := TryStrToFloat(Src, Dst)
else
Dst := Src; { Supports numeric/str/datetime etc }
except
result := False;
end;
end;
class function TVar.TryToCurrency(const Src: variant; out Dst: currency): boolean;
begin
Result := not IsEmpty(Src); { To avoid of exceptions in simple situations }
if Result then
try
{ "Dst := Src" does same job, but we use extra check for
regular strings to avoid of exceptions (annoying in debug) }
if VarIsStr(Src) then
result := TryStrToCurr(Src, Dst)
else
Dst := Src; { Supports numeric/str/datetime etc }
except
result := False;
end;
end;
class function TVar.TryToGUID(const Src: variant; out Dst: TGUID): boolean;
var
S: string;
begin
result := VarIsStr(Src); { To avoid of exceptions in simple situations }
if result then
begin
S := Src;
{ Simple check (copy-pasted from StringToGUID) helps to avoid of exceptions in many cases }
if ((Length(S) <> 38) or (S[Low(string)] <> '{')) then
result := False
else
try
Dst := StringToGUID(Src);
except
result := False;
end;
end;
end;
class function TVar.TryToInteger(const Src: variant; out Dst: integer): boolean;
begin
Result := not IsEmpty(Src); { to avoid of exceptions in simple situations }
if Result then
try
Dst := Src; { Supports numeric/str/datetime etc, no need for manual check }
except
result := False;
end;
end;
class function TVar.TryToInteger(const Src: variant; out Dst: int64): boolean;
begin
Result := not IsEmpty(Src); { to avoid of exceptions in simple situations }
if Result then
try
Dst := Src; { Supports numeric/str/datetime etc, no need for manual check }
except
result := False;
end;
end;
class function TVar.TryToString(const Src: variant; out Dst: string): boolean;
begin
result := not IsEmpty(Src); { to avoid of exceptions in simple situations }
if result then
try
Dst := Src; { supports all string-compatible formats }
except
result := False;
end;
end;
class function TVar.VarOrArrayToStr(const V: variant; const ArrElemDelimeter: string): string;
var
i,l,r: Integer;
Arr: TVarArray;
begin
if not IsArray(v) then
if IsEmpty(v) then
result := ''
else
result := v
else
begin
Arr := TVarArray.Create(v);
Assert(Arr.DimCount=1);
l := Arr.DimLowBound[0];
r := Arr.DimHighBound[0];
result := VarOrArrayToStr(v[l], ArrElemDelimeter);
for i := l+1 to r do
result := result + ArrElemDelimeter + VarOrArrayToStr(v[i], ArrElemDelimeter);
end;
end;
class function TVar.VarRecAsString(Value: TVarRec): String;
begin
case Value.VType of
vtInteger : result := Value.VInteger.ToString;
vtBoolean : result := Value.VBoolean.ToString;
vtChar : result := Char(Value.VChar);
vtExtended : result := Value.VExtended^.ToString;
{$IFNDEF NEXTGEN}
vtString : result := String(Value.VString^);
{$ENDIF NEXTGEN}
vtPointer : result := '$' + THex.PointerToHex(Value.VPointer);
vtPChar : result := Char(Value.VPChar^);
vtObject :
if Value.VObject = nil
then result := 'TObject(nil)'
else result := TObject(Value.VObject).ClassName + '($' + THex.PointerToHex(Value.VObject) + ')';
vtClass : result := Value.VClass.ClassName;
vtWideChar : result := Value.VWideChar;
vtPWideChar : result := Value.VPWideChar^;
{$IF Defined(MSWindows)}
vtAnsiString : result := UnicodeString(AnsiString(Value.VAnsiString));
{$EndIf}
vtCurrency : result := CurrToStr(Value.VCurrency^);
vtVariant : result := TVar.ToStringDef(Value.VVariant^);
vtInterface : result := 'Interface($' + THex.PointerToHex(Value.VInterface) + ')';
{$IF Defined(MSWindows)}
vtWideString : result := WideString(Value.VWideString);
{$EndIf}
vtInt64 : result := Value.VInt64^.ToString;
vtUnicodeString : result := String(Value.VUnicodeString);
end;
end;
class function TVar.VarRecAsVariant(Value: TVarRec): Variant;
begin
case Value.VType of
vtInteger : result := Value.VInteger;
vtBoolean : result := Value.VBoolean;
vtChar : result := Char(Value.VChar);
vtExtended : result := Value.VExtended^;
{$IFNDEF NEXTGEN}
vtString : result := String(Value.VString^);
{$ENDIF NEXTGEN}
vtPointer : result := VarRecAsString(Value);
vtPChar : result := Char(Value.VPChar^);
vtObject : result := VarRecAsString(Value);
vtClass : result := VarRecAsString(Value);
vtWideChar : result := Value.VWideChar;
vtPWideChar : result := Value.VPWideChar^;
{$IF Defined(MSWindows)}
vtAnsiString : result := UnicodeString(AnsiString(Value.VAnsiString));
{$EndIf}
vtCurrency : result := Value.VCurrency^;
vtVariant : result := Value.VVariant^;
vtInterface : result := VarRecAsString(Value);
{$IF Defined(MSWindows)}
vtWideString : result := WideString(Value.VWideString);
{$EndIf}
vtInt64 : result := Value.VInt64^;
vtUnicodeString : result := String(Value.VUnicodeString);
end;
end;
function VarTypeIsStr(const AVarType: TVarType): Boolean;
begin
Result := (AVarType = varOleStr) or (AVarType = varString) or (AVarType = varUString);
end;
class function TVar.IsStr(const v: variant): boolean;
begin
Result := VarTypeIsStr(FindVarData(V)^.VType);
end;
{ TIntegerTypesHelper<T> }
class function TVar.IsArray(const v: variant): boolean;
begin
result := VarType(v) and varArray<>0;
end;
class function TVar.IsRef(const v: variant): boolean;
begin
result := VarType(v) and varByRef<>0;
end;
class function TVar.IsArrayOrRef(const v: variant): boolean;
begin
result := VarType(v) and (varArray or varByRef)<>0;
end;
class function TVar.IsDateTime(const v: variant): boolean;
begin
result := VarType(v) and varTypeMask = varDate;
end;
class function TVar.IsNull(const V: variant): Boolean;
begin
result := VarIsNull(v);
end;
class function TVar.IsEmpty(const V: variant): Boolean;
begin
result := VarIsNull(v) or VarIsEmpty(v);
end;
class function TVar.IsNull(const V: array of variant): Boolean;
var
I: Integer;
begin
for I := Low(V) to High(V) do
if not VarIsNull(v[I]) then
Exit(False);
Result := True;
end;
class function TVar.IsNumeric(const v: variant): boolean;
var
vt: Word;
begin
vt := VarType(v) and varTypeMask;
result := (vt=varSmallint) or (vt=varInteger) or (vt=varSingle) or (vt=varDouble) or (vt=varCurrency) or
(vt=varShortInt) or (vt=varByte) or (vt=varWord) or (vt=varLongWord) or (vt=varInt64) or (vt=varUInt64);
end;
class function TVar.IsInteger(const v: variant): boolean;
var
vt: Word;
begin
vt := VarType(v) and varTypeMask;
result := (vt=varSmallint) or (vt=varInteger) or (vt=varShortInt) or (vt=varByte) or
(vt=varWord) or (vt=varLongWord) or (vt=varInt64) or (vt=varUInt64);
end;
class function TVar.GetArrayBounds(const DataArray: Variant; var ALow, AHigh: Integer): boolean;
begin
result := IsArray(DataArray);
if result then
try
ALow := VarArrayLowBound (DataArray, 1);
AHigh := VarArrayHighBound(DataArray, 1);
except
result := false;
ALow := 0;
AHigh := -1;
end;
end;
class function TVar.GetArrayBounds(const DataArray: Variant; var ALow1, AHigh1, ALow2, AHigh2: Integer): boolean;
begin
result := IsArray(DataArray);
if result then
try
ALow1 := VarArrayLowBound (DataArray, 1);
AHigh1 := VarArrayHighBound(DataArray, 1);
ALow2 := VarArrayLowBound (DataArray, 2);
AHigh2 := VarArrayHighBound(DataArray, 2);
except
result := false;
ALow1 := 0;
AHigh1 := -1;
ALow2 := 0;
AHigh2 := -1;
end;
end;
{ TVarArray.TDimEnumerator }
constructor TVarArray.TDimEnumerator.Create(const Arr: TVarArray);
var
i: Integer;
begin
FDimCount := Arr.DimCount;
SetLength(FDimLow, FDimCount);
SetLength(FDimHigh, FDimCount);
SetLength(FDimInc, FDimCount);
SetLength(FDimCurrent, FDimCount);
for i := 0 to FDimCount-1 do
begin
FDimLow[i] := Arr.DimLowBound[i];
FDimHigh[i] := Arr.DimHighBound[i];
FDimInc[i] := Sign(FDimHigh[i]-FDimLow[i]);
FDimCurrent[i] := FDimLow[i];
end;
end;
procedure TVarArray.TDimEnumerator.Next;
var
i: Integer;
begin
for i := 0 to FDimCount-1 do
if FDimCurrent[i]=FDimHigh[i] then
FDimCurrent[i] := FDimLow[i]
else
begin
inc(FDimCurrent[i], FDimInc[i]);
Break;
end;
end;
{ TVarArray }
constructor TVarArray.Create(VArray: variant);
begin
Assert(TVar.IsArray(VArray));
FVArray := VArray;
end;
procedure TVarArray.Clear;
begin
Self := Default(TVarArray);
end;
function TVarArray.EnumElementsAsFloat(const ACurProc: TEnumFloatProc): boolean;
var
Dim: TDimEnumerator; { item indices }
Value: TUnifiedVarAccess; { access to value }
p: PByte; { pointer to current element of the array }
i,j,n: integer;
a,b: double;
begin
result := False;
if not TVar.IsArray(FVArray) or TVar.IsRef(FVArray) or not TUnifiedVarAccess.Init(VarType(FVArray) and varTypeMask, Value) then
Exit;
Dim := GetEnumerator;
p := Lock;
if p<>nil then
try
j := Count;
n := Value.ElementSize;
for i := 0 to j-1 do
begin
a := Value.AsFloat[p^];
b := a;
ACurProc(a, Dim.Current);
if a<>b then
Value.AsFloat[p^] := a;
inc(p, n);
Dim.Next;
end;
finally
Unlock;
end;
end;
function TVarArray.GetCount: integer;
var
d,i: Integer;
begin
result := 0;
d := DimCount;
if d>0 then
begin
result := Abs(DimLowBound[0]-DimHighBound[0]) + 1;
for i := 1 to d-1 do
result := result * (Abs(DimLowBound[i]-DimHighBound[i]) + 1);
end;
end;
function TVarArray.GetDimCount: integer;
begin
result := VarArrayDimCount(FVArray);
end;
function TVarArray.GetDimHighBound(ADim: integer): integer;
begin
result := VarArrayHighBound(FVArray, ADim + 1); { VarArrayHighBound has 1-based index }
end;
function TVarArray.GetDimLowBound(ADim: integer): integer;
begin
result := VarArrayLowBound(FVArray, ADim + 1); { VarArrayLowBound has 1-based index }
end;
function TVarArray.GetEnumerator: TDimEnumerator;
begin
result := TDimEnumerator.Create(Self);
end;
function TVarArray.Lock: pointer;
begin
result := VarArrayLock(FVArray);
end;
procedure TVarArray.Unlock;
begin
VarArrayUnLock(FVArray)
end;
{ TVarArrayStream }
constructor TVarArrayStream.Create(AValue: Variant);
begin
Value := AValue;
end;
destructor TVarArrayStream.Destroy;
begin
Value := Null;
inherited;
end;
procedure TVarArrayStream.SetSize(NewSize: Longint);
begin
raise Exception.Create('Error');
end;
procedure TVarArrayStream.SetValue(AValue: Variant);
begin
{ release old value }
if Memory<>nil then
begin
VarArrayUnLock(FValue);
SetPointer(nil, 0);
end;
{ assign new one }
Assert(IsAcceptable(AValue));
FValue := AValue;
Position := 0;
if VarIsNull(AValue) or VarIsClear(AValue) then
Exit;
{ FValue is 1-dimensional array with ElementSize=1 }
SetPointer(VarArrayLock(FValue), VarArrayHighBound(FValue, 1) - VarArrayLowBound(FValue, 1) + 1);
end;
function TVarArrayStream.Write(const Buffer; Count: Longint): Longint;
begin
Result := Min(Count, Size-Position);
if Result > 0 then
begin
System.Move(Buffer, (PByte(Memory) + Position)^, Result);
Position := Position + Result;
end;
end;
function TVarArrayStream.ExtractValue: variant;
begin
if Memory<>nil then
begin
VarArrayUnLock(FValue);
SetPointer(nil, 0);
end;
result := FValue;
FValue := null;
end;
class function TVarArrayStream.IsAcceptable(const AValue: Variant): Boolean;
begin
Result :=
VarIsNull(AValue) or
VarIsClear(AValue) or
VarIsArray(AValue) and (VarArrayDimCount(AValue)=1) and (TVarData(AValue).VArray.ElementSize=1);
end;
end.
|
unit UL.TUFlowGridLayout;
interface
uses
System.Classes, System.Types,
VCL.Controls, VCL.Graphics, VCL.ExtCtrls;
type
TUFlowGridLayout = class(TPanel)
private
FMaxColumns: Integer;
FAlignSpace: Integer;
FOneCol2List: Boolean;
FItemWidth: Integer;
FItemHeight: Integer;
FListItemHeight: Integer;
protected
procedure Resize; override;
public
constructor Create(aOwner: TComponent); override;
function GetColumnCount: Integer;
published
property MaxColumns: Integer read FMaxColumns write FMaxColumns default 5;
property AlignSpace: Integer read FAlignSpace write FAlignSpace default 20;
property OneCol2List: Boolean read FOneCol2List write FOneCol2List default true;
property ItemWidth: Integer read FItemWidth write FItemWidth default 250;
property ItemHeight: Integer read FItemHeight write FItemHeight default 80;
property ListItemHeight: Integer read FListItemHeight write FListItemHeight default 60;
end;
implementation
{ TUFlowGridLayout }
constructor TUFlowGridLayout.Create(aOwner: TComponent);
begin
inherited;
BevelOuter := bvNone;
Color := $E6E6E6;
ShowCaption := false;
FMaxColumns := 5;
FAlignSpace := 20;
FOneCol2List := true;
FItemWidth := 250;
FItemHeight := 80;
FListItemHeight := 60;
end;
procedure TUFlowGridLayout.Resize;
var
ColCount: Integer;
FrameWidth: Integer;
LeftSide: Integer;
i, Col, Row, ItemLeft, ItemTop: Integer;
Item: TControl;
begin
inherited;
ColCount := GetColumnCount;
FrameWidth := ColCount * ItemWidth + (ColCount + 1) * AlignSpace;
LeftSide := (Width - FrameWidth) div 2;
for i := 0 to ControlCount - 1 do
begin
Item := Controls[i];
Col := i mod ColCount;
Row := i div ColCount;
if (ColCount = 1) and (OneCol2List) then
begin
ItemLeft := 0;
ItemTop := Row * ListItemHeight;
Item.Width := Width;
Item.Height := ListItemHeight;
end
else
begin
ItemLeft := LeftSide + Col * ItemWidth + (Col + 1) * AlignSpace;
ItemTop := 0 + Row * ItemHeight + (Row + 1) * AlignSpace;
Item.Width := ItemWidth;
Item.Height := ItemHeight;
end;
Item.Top := ItemTop;
Item.Left := ItemLeft;
end;
end;
function TUFlowGridLayout.GetColumnCount: Integer;
var
NeededWidth: Integer;
begin
Result := MaxColumns + 1;
repeat
Result := Result - 1;
NeededWidth :=
Result * ItemWidth + // Items width on row
(Result + 1) * AlignSpace; // Space between items
until Width > NeededWidth;
if Result = 0 then
Result := 1;
end;
end.
|
unit SendMail;
interface
uses
{$IFDEF IOS}
Macapi.ObjectiveC, Macapi.CoreFoundation, Macapi.Dispatch,
iOSApi.CocoaTypes, iOSApi.Foundation, Posix.SysSocket;
{$ENDIF}
{$IFDEF ANDROID}
FMX.Helpers.Android, Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.Net,
Androidapi.JNI.Os, Androidapi.Helpers;
{$ENDIF}
procedure CreateEmail(const Recipient, Subject, Content, FileToAttach: string);
implementation
procedure CreateEmail(const Recipient, Subject, Content, FileToAttach: string);
{$IFDEF ANDROID}
var
Uri: Jnet_Uri;
Intent: JIntent;
Recipients: TJavaObjectArray<JString>;
{$ENDIF}
begin
{$IFDEF ANDROID}
Intent := TJIntent.JavaClass.init(TJIntent.JavaClass.ACTION_SEND);
Recipients := TJavaObjectArray<JString>.Create(1);
Recipients.Items[0] := StringToJString(Recipient);
Intent.putExtra(TJIntent.JavaClass.EXTRA_EMAIL, Recipients);
Intent.putExtra(TJIntent.JavaClass.EXTRA_SUBJECT, StringToJString(Subject));
Intent.putExtra(TJIntent.JavaClass.EXTRA_TEXT, StringToJString(Content));
Intent.setType(StringToJString('plain/text'));
SharedActivity.startActivity(TJIntent.JavaClass.createChooser(Intent,
StrToJCharSequence('Which email app?')));
if FileToAttach <> '' then
begin
Uri := TJnet_Uri.JavaClass.parse(StringToJString(FileToAttach));
Intent.putExtra(TJIntent.JavaClass.EXTRA_STREAM,
TJParcelable.Wrap((Uri as ILocalObject).GetObjectID));
end;
{$ENDIF}
end;
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, SharedMemoryName_TLB;
type
TUniqueNameForm = class(TForm)
labelUniqueName: TLabel;
editUniqueName: TEdit;
btnClose: TButton;
procedure FormCreate(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
UniqueNameForm: TUniqueNameForm;
implementation
{$R *.dfm}
uses System.UITypes;
procedure TUniqueNameForm.FormCreate(Sender: TObject);
var
UniqueName: IUniqueName;
begin
try
UniqueName := CoUniqueName.Create();
editUniqueName.Text := UniqueName.GetSharedMemoryName();
except
on E: Exception do
begin
MessageDlg(E.Message, mtError, [mbOk], 0);
Application.Terminate();
end;
end;
end;
procedure TUniqueNameForm.btnCloseClick(Sender: TObject);
begin
Close();
end;
end.
|
unit SimpleSofaFile;
interface
uses
ECMA.TypedArray, ECMA.Map, WHATWG.Encoding;
type
EHdfInvalidFormat = class(Exception);
TVector3 = array [0..2] of Float;
THdfSignature = String;
JZlibInflate = class external 'Zlib.Inflate'
constructor Create(compressed: JUint8Array);
function decompress: Variant;
end;
TStream = class
private
FPosition: Integer;
FDataView: JDataView;
public
constructor Create(Buffer: JArrayBuffer);
function ReadInteger(const Count: Integer): Integer; overload;
function ReadFloat(const Count: Integer): Float; overload;
function ReadString(const Count: Integer): String; overload;
function ReadBuffer(const Count: Integer): JUint8Array; overload;
procedure WriteInteger(const Count: Integer; const Value: Integer);
procedure WriteString(const Value: String);
procedure WriteBuffer(Buffer: JUInt8Array);
procedure Clear;
function Seek(Position: Integer; IsRelative: Boolean = False): Integer;
property DataView: JDataView read FDataView;
property Size: Integer read (FDataView.buffer.byteLength);
property Position: Integer read FPosition write FPosition;
end;
THdfSuperBlock = class
private
FOffsetSize: Integer;
FLengthsSize: Integer;
FEndOfFileAddress: Integer;
public
procedure LoadFromStream(Stream: TStream);
property OffsetSize: Integer read FOffsetSize;
property LengthsSize: Integer read FLengthsSize;
property EndOfFileAddress: Integer read FEndOfFileAddress;
end;
THdfDataObject = class;
THdfDataObjectMessage = class
private
FSuperBlock: THdfSuperBlock;
protected
FVersion: Integer;
FDataObject: THdfDataObject;
property Superblock: THdfSuperBlock read FSuperBlock;
property DataObject: THdfDataObject read FDataObject;
public
constructor Create(SuperBlock: THdfSuperBlock; DataObject: THdfDataObject);
procedure LoadFromStream(Stream: TStream); virtual;
property Version: Integer read FVersion;
end;
THdfMessageDataSpace = class(THdfDataObjectMessage)
private
FDimensionality: Integer;
FFlags: Integer;
FType: Integer;
FDimensionSize: array of Integer;
FDimensionMaxSize: array of Integer;
function GetDimension(Index: Integer): Integer;
public
procedure LoadFromStream(Stream: TStream); override;
property Dimensionality: Integer read FDimensionality;
property Dimension[Index: Integer]: Integer read GetDimension;
end;
THdfMessageLinkInfo = class(THdfDataObjectMessage)
private
FFractalHeapAddress: Integer;
public
procedure LoadFromStream(Stream: TStream); override;
property FractalHeapAddress: Integer read FFractalHeapAddress;
end;
THdfMessageDataType = class;
THdfBaseDataType = class
protected
FDataTypeMessage: THdfMessageDataType;
public
constructor Create(DatatypeMessage: THdfMessageDataType); virtual;
procedure LoadFromStream(Stream: TStream); virtual;
end;
THdfDataTypeFixedPoint = class(THdfBaseDataType)
public
procedure LoadFromStream(Stream: TStream); override;
end;
THdfDataTypeFloatingPoint = class(THdfBaseDataType)
public
procedure LoadFromStream(Stream: TStream); override;
end;
THdfDataTypeTime = class(THdfBaseDataType)
public
procedure LoadFromStream(Stream: TStream); override;
end;
THdfDataTypeString = class(THdfBaseDataType);
THdfDataTypeBitfield = class(THdfBaseDataType)
public
procedure LoadFromStream(Stream: TStream); override;
end;
THdfDataTypeOpaque = class(THdfBaseDataType);
THdfDataTypeCompoundPart = class
private
FName: String;
FByteOffset: Integer;
FSize: Integer;
FDataType: THdfMessageDataType;
public
constructor Create(DatatypeMessage: THdfMessageDataType); virtual;
procedure ReadFromStream(Stream: TStream);
end;
THdfDataTypeCompound = class(THdfBaseDataType)
private
FDataTypes: array of THdfDataTypeCompoundPart;
public
constructor Create(DatatypeMessage: THdfMessageDataType); override;
procedure LoadFromStream(Stream: TStream); override;
end;
THdfDataTypeReference = class(THdfBaseDataType);
THdfDataTypeEnumerated = class(THdfBaseDataType);
THdfDataTypeVariableLength = class(THdfBaseDataType)
private
FDataType: THdfMessageDataType;
public
constructor Create(DatatypeMessage: THdfMessageDataType); override;
procedure LoadFromStream(Stream: TStream); override;
end;
THdfDataTypeArray = class(THdfBaseDataType);
THdfMessageDataType = class(THdfDataObjectMessage)
private
FDataClass: Integer;
FClassBitField: array [0..2] of Integer;
FSize: Integer;
FDataType: THdfBaseDataType;
public
procedure LoadFromStream(Stream: TStream); override;
property Size: Integer read FSize;
property DataClass: Integer read FDataClass;
end;
THdfMessageDataFill = class(THdfDataObjectMessage)
public
procedure LoadFromStream(Stream: TStream); override;
end;
THdfMessageDataLayout = class(THdfDataObjectMessage)
private
FLayoutClass: Integer;
FDataAddress: Integer;
FDataSize: Integer;
FDimensionality: Integer;
procedure ReadTree(Stream: TStream; Size: Integer);
public
procedure LoadFromStream(Stream: TStream); override;
end;
THdfMessageGroupInfo = class(THdfDataObjectMessage)
public
procedure LoadFromStream(Stream: TStream); override;
end;
THdfMessageFilterPipeline = class(THdfDataObjectMessage)
public
procedure LoadFromStream(Stream: TStream); override;
end;
THdfAttribute = class
private
FName: String;
FStream: TStream;
function GetValueAsString: String;
procedure SetValueAsString(const Value: String);
function GetValueAsInteger: Integer;
procedure SetValueAsInteger(const Value: Integer);
public
constructor Create(Name: String);
property Name: String read FName;
property ValueAsString: String read GetValueAsString write SetValueAsString;
property ValueAsInteger: Integer read GetValueAsInteger write SetValueAsInteger;
end;
THdfMessageAttribute = class(THdfDataObjectMessage)
private
FName: String;
FDatatypeMessage: THdfMessageDataType;
FDataspaceMessage: THdfMessageDataSpace;
procedure ReadData(Stream: TStream; Attribute: THdfAttribute);
procedure ReadDataDimension(Stream: TStream; Attribute: THdfAttribute;
Dimension: Integer);
public
procedure LoadFromStream(Stream: TStream); override;
end;
THdfMessageHeaderContinuation = class(THdfDataObjectMessage)
public
procedure LoadFromStream(Stream: TStream); override;
end;
THdfMessageAttributeInfo = class(THdfDataObjectMessage)
private
FFractalHeapAddress: Integer;
public
procedure LoadFromStream(Stream: TStream); override;
property FractalHeapAddress: Integer read FFractalHeapAddress;
end;
THdfFractalHeap = class
private
FSuperBlock: THdfSuperBlock;
FDataObject: THdfDataObject;
FSignature: String;
FVersion: Integer;
FHeapIdLength: Integer;
FEncodedLength: Integer;
FFlags: Integer;
FMaximumSize: Integer;
FNextHugeID: Integer;
FBtreeAddresses: Integer;
FAmountFreeSpace: Integer;
FAddressManagedBlock: Integer;
FAmountManagedSpace: Integer;
FAmountAllocatedManagedSpace: Integer;
FOffsetDirectBlockAllocation: Integer;
FNumberOfManagedObjects: Integer;
FSizeOfHugeObjects: Integer;
FNumberOfHugeObjects: Integer;
FSizeOfTinyObjects: Integer;
FNumberOfTinyObjects: Integer;
FTableWidth: Integer;
FStartingBlockSize: Integer;
FMaximumDirectBlockSize: Integer;
FMaximumHeapSize: Integer;
protected
property SuperBlock: THdfSuperBlock read FSuperBlock;
public
constructor Create(SuperBlock: THdfSuperBlock; DataObject: THdfDataObject);
procedure LoadFromStream(Stream: TStream);
property MaximumSize: Integer read FMaximumSize;
property MaximumDirectBlockSize: Integer read FMaximumDirectBlockSize;
property MaximumHeapSize: Integer read FMaximumHeapSize;
property StartingBlockSize: Integer read FStartingBlockSize;
property Flags: Integer read FFlags;
property TableWidth: Integer read FTableWidth;
property EncodedLength: Integer read FEncodedLength;
end;
THdfCustomBlock = class
private
FSuperBlock: THdfSuperBlock;
protected
FFractalHeap: THdfFractalHeap;
FChecksum: Integer;
FBlockOffset: Integer;
FDataObject: THdfDataObject;
class function GetSignature: THdfSignature; virtual; abstract;
property SuperBlock: THdfSuperBlock read FSuperBlock;
public
constructor Create(SuperBlock: THdfSuperBlock;
FractalHeap: THdfFractalHeap; DataObject: THdfDataObject); virtual;
procedure LoadFromStream(Stream: TStream); virtual;
end;
THdfDirectBlock = class(THdfCustomBlock)
protected
class function GetSignature: THdfSignature; override;
public
procedure LoadFromStream(Stream: TStream); override;
end;
THdfIndirectBlock = class(THdfCustomBlock)
private
FInitialBlockSize: Integer;
protected
class function GetSignature: THdfSignature; override;
public
constructor Create(SuperBlock: THdfSuperBlock; FractalHeap: THdfFractalHeap;
DataObject: THdfDataObject); override;
procedure LoadFromStream(Stream: TStream); override;
end;
THdfDataObject = class
private
FName: String;
FSuperBlock: THdfSuperBlock;
FChunkSize: Integer;
FFlags: Integer;
FDataLayoutChunk: array of Integer;
FData: TStream;
FAttributeList: array of THdfAttribute;
FDataType: THdfMessageDataType;
FDataSpace: THdfMessageDataSpace;
FLinkInfo: THdfMessageLinkInfo;
FGroupInfo: THdfMessageGroupInfo;
FAttributeInfo: THdfMessageAttributeInfo;
FDataObjects: array of THdfDataObject;
FAttributesHeap: THdfFractalHeap;
FObjectsHeap: THdfFractalHeap;
function GetDataObjectCount: Integer;
function GetDataObject(Index: Integer): THdfDataObject;
function GetDataLayoutChunk(Index: Integer): Integer;
function GetDataLayoutChunkCount: Integer;
function GetAttributeListCount: Integer;
function GetAttributeListItem(Index: Integer): THdfAttribute;
protected
procedure ReadObjectHeaderMessages(Stream: TStream; EndOfStream: Integer);
property Superblock: THdfSuperBlock read FSuperBlock;
property AttributesHeap: THdfFractalHeap read FAttributesHeap;
property ObjectsHeap: THdfFractalHeap read FObjectsHeap;
public
constructor Create(SuperBlock: THdfSuperBlock); overload;
constructor Create(SuperBlock: THdfSuperBlock; Name: String); overload;
procedure AddDataObject(DataObject: THdfDataObject);
procedure AddAttribute(Attribute: THdfAttribute);
procedure LoadFromStream(Stream: TStream);
function HasAttribute(Name: string): Boolean;
function GetAttribute(Name: string): String;
property Name: String read FName;
property Data: TStream read FData write FData;
property DataType: THdfMessageDataType read FDataType;
property DataSpace: THdfMessageDataSpace read FDataSpace;
property LinkInfo: THdfMessageLinkInfo read FLinkInfo;
property GroupInfo: THdfMessageGroupInfo read FGroupInfo;
property AttributeInfo: THdfMessageAttributeInfo read FAttributeInfo;
property AttributeListCount: Integer read GetAttributeListCount;
property AttributeListItem[Index: Integer]: THdfAttribute read GetAttributeListItem;
property DataObjectCount: Integer read GetDataObjectCount;
property DataObject[Index: Integer]: THdfDataObject read GetDataObject;
property DataLayoutChunkCount: Integer read GetDataLayoutChunkCount;
property DataLayoutChunk[Index: Integer]: Integer read GetDataLayoutChunk;
end;
THdfFile = class
private
FSuperBlock: THdfSuperBlock;
FDataObject: THdfDataObject;
public
constructor Create;
procedure LoadFromStream(Stream: TStream);
procedure LoadFromBuffer(Buffer: JArrayBuffer);
function HasAttribute(Name: string): Boolean;
function GetAttribute(Name: string): string;
property SuperBlock: THdfSuperBlock read FSuperBlock;
property DataObject: THdfDataObject read FDataObject;
end;
TSofaPositions = class
private
FPositions: array of TVector3;
FIsSpherical: Boolean;
public
constructor Create(IsSpherical: Boolean);
procedure LoadFromStream(Stream: TStream; const DataSize: Integer);
function GetPosition(const Index: Integer): TVector3; overload;
function GetPosition(const Index: Integer; Spherical: Boolean): TVector3; overload;
property IsSpherical: Boolean read FIsSpherical;
property Count: Integer read (Length(FPositions));
end;
JSofaFilter = class external
SampleRate: Float;
Left, Right: JFloat64Array;
LeftDelay, RightDelay: Float;
end;
TSofaFile = class
private
FNumberOfMeasurements: Integer;
FNumberOfDataSamples: Integer;
FNumberOfEmitters: Integer;
FNumberOfReceivers: Integer;
FNumberOfSources: Integer;
FNumberOfListeners: Integer;
FListenerPositions: TSofaPositions;
FReceiverPositions: TSofaPositions;
FSourcePositions: TSofaPositions;
FEmitterPositions: TSofaPositions;
FListenerUp: TVector3;
FListenerView: TVector3;
FSampleRate: array of Float;
FImpulseResponses: array of array of JFloat64Array;
FDelay: array of Float;
FAttributes: JMap;
procedure ReadDataObject(DataObject: THdfDataObject);
function GetSampleRate(Index: Integer): Float;
function GetDelay(Index: Integer): Float;
function GetDelayCount: Integer;
function GetSampleRateCount: Integer;
function GetImpulseResponse(MeasurementIndex, ReceiverIndex: Integer): JFloat64Array;
public
procedure LoadFromBuffer(Buffer: JArrayBuffer);
function GetClosestIndexCartesian(X, Y, Z: Float): Integer;
function GetClosestIndexSpherical(Phi, Theta, Radius: Float): Integer;
property Attributes: JMap read FAttributes;
property NumberOfMeasurements: Integer read FNumberOfMeasurements;
property NumberOfListeners: Integer read FNumberOfListeners;
property NumberOfReceivers: Integer read FNumberOfReceivers;
property NumberOfEmitters: Integer read FNumberOfEmitters;
property NumberOfDataSamples: Integer read FNumberOfDataSamples;
property NumberOfSources: Integer read FNumberOfSources;
property ListenerPositions: TSofaPositions read FListenerPositions;
property ReceiverPositions: TSofaPositions read FReceiverPositions;
property SourcePositions: TSofaPositions read FSourcePositions;
property EmitterPositions: TSofaPositions read FEmitterPositions;
property ListenerUp: TVector3 read FListenerUp;
property ListenerView: TVector3 read FListenerView;
property ImpulseResponse[MeasurementIndex, ReceiverIndex: Integer]: JFloat64Array read GetImpulseResponse;
property SampleRate[Index: Integer]: Float read GetSampleRate;
property SampleRateCount: Integer read GetSampleRateCount;
property Delay[Index: Integer]: Float read GetDelay;
property DelayCount: Integer read GetDelayCount;
end;
TGetPositionCallback = procedure(Position: array [0..2] of Float);
function sofaLoadFile(Buffer: JArrayBuffer): TSofaFile; export;
function sofaGetAttribute(SofaFile: TSofaFile; const AttributeName: String): String; export;
procedure sofaGetListenerPosition(SofaFile: TSofaFile; Callback: TGetPositionCallback; Spherical: Boolean = False); export;
procedure sofaGetReceiverPosition(SofaFile: TSofaFile; Callback: TGetPositionCallback; Spherical: Boolean = False); export;
procedure sofaGetSourcePosition(SofaFile: TSofaFile; Callback: TGetPositionCallback; Spherical: Boolean = False); export;
procedure sofaGetEmitterPosition(SofaFile: TSofaFile; Callback: TGetPositionCallback; Spherical: Boolean = False); export;
function sofaGetListenerPositionList(SofaFile: TSofaFile; Spherical: Boolean = False): array of TVector3; export;
function sofaGetReceiverPositionList(SofaFile: TSofaFile; Spherical: Boolean = False): array of TVector3; export;
function sofaGetSourcePositionList(SofaFile: TSofaFile; Spherical: Boolean = False): array of TVector3; export;
function sofaGetEmitterPositionList(SofaFile: TSofaFile; Spherical: Boolean = False): array of TVector3; export;
function sofaGetSampleRates(SofaFile: TSofaFile): array of Float; export;
function sofaGetSofaDelays(SofaFile: TSofaFile): array of Float; export;
function sofaGetImpulseResponses(SofaFile: TSofaFile): array of array of JFloat64Array; export;
function sofaGetFilterCartesian(SofaFile: TSofaFile; X, Y, Z: Float): JSofaFilter; export;
function sofaGetFilterSpherical(SofaFile: TSofaFile; Phi, Theta, Radius: Float): JSofaFilter; export;
function SphericalToCartesian(Position: TVector3): TVector3; export;
function CartesianToSpherical(Position: TVector3): TVector3; export;
implementation
uses
WHATWG.Console;
resourcestring
RStrIndexOutOfBounds = 'Index out of bounds (%d)';
RStrSofaConventionMissing = 'File does not contain the SOFA convention';
RStrAllFiltersMustBeEnabled = 'All filters must be enabled';
RStrErrorReadingDimensions = 'Error reading dimensions';
RStrErrorSeekingFirstObject = 'Error seeking first object';
RStrErrorUnknownDataClass = 'Error: unknown data class';
RStrErrorUnsupportedCompoundVersion = 'Error unsupported compound version (%d)';
RStrFHDBType1UnsupportedValues = 'FHDB type 1 unsupported values';
RStrInvalidBaseAddress = 'The base address should be zero';
RStrInvalidCount = 'Invalid count';
RStrInvalidHDF = 'The file is not a valid HDF';
RStrInvalidPosition = 'Invalid Position';
RStrInvalidVersion = 'Invalid version';
RStrNoHugeObjects = 'Cannot handle huge objects';
RStrNoTinyObjects = 'Cannot handle tiny objects';
RStrPositionExceedsByteLength = 'Position exceeds byte length';
RStrSizeMismatch = 'Size mismatch';
RStrTooManyFilters = 'The filter pipeline message has too many filters';
RStrUnknownBitWidth = 'Unknown bit width';
RStrUnknownDatatype = 'Unknown datatype (%d)';
RStrUnsupportedBitPrecision = 'Unsupported bit precision';
RStrUnsupportedFilter = 'Unsupported filter';
RStrUnsupportedOHDRMessageFlag = 'Unsupported OHDR message flag';
RStrUnsupportedValues = 'Unsupported values';
RStrUnsupportedVersion = 'Unsupported version';
RStrUnsupportedVersionOfAttributeInfoMessage = 'Unsupported version of attribute info message';
RStrUnsupportedVersionOfDataFillMessage = 'Unsupported version of data fill message';
RStrUnsupportedVersionOfDataLayoutMessage = 'Unsupported version of data layout message';
RStrUnsupportedVersionOfDataspaceMessage = 'Unsupported version of dataspace message';
RStrUnsupportedVersionOfDataTypeMessage = 'Unsupported version of data type message';
RStrUnsupportedVersionOfFractalHeap = 'Unsupported version of fractal heap';
RStrUnsupportedVersionOfGroupInfoMessage = 'Unsupported version of group info message';
RStrUnsupportedVersionOfLinkInfoMessage = 'Unsupported version of link info message';
RStrUnsupportedVersionOfCustomBlock = 'Unsupported version of custom block';
RStrUnsupportedVersionOfMessageAttribute = 'Unsupported version of message attribute';
RStrUnsupportedVersionOfTheFilterPipelineMessage = 'Unsupported version of the filter pipeline message';
RStrWrongSignature = 'Wrong signature (%s)';
RStrZeroBlockOffset = 'Only a block offset of 0 is supported so far';
uses
WHATWG.Console;
{ TStream }
constructor TStream.Create(Buffer: JArrayBuffer);
begin
FPosition := 0;
FDataView := JDataView.Create(Buffer);
end;
function TStream.ReadInteger(const Count: Integer): Integer;
begin
if FPosition + Count > FDataView.byteLength then
raise Exception.Create(RStrPositionExceedsByteLength);
case Count of
1:
Result := FDataView.getUint8(FPosition);
2:
Result := FDataView.getUint16(FPosition, True);
3:
Result := FDataView.getUint16(FPosition, True) + FDataView.getUint8(FPosition + 2) shl 16;
4:
Result := FDataView.getUint32(FPosition, True);
5:
Result := FDataView.getUint32(FPosition, True) or (FDataView.getUint8(FPosition + 4) shl 32);
6:
Result := FDataView.getUint32(FPosition, True) or (FDataView.getUint16(FPosition + 4, True) shl 32);
8:
Result := FDataView.getUint32(FPosition, True) or (FDataView.getUint32(FPosition + 4, True) shl 32);
else
raise Exception.Create(RStrUnknownBitWidth);
end;
Inc(FPosition, Count);
end;
function TStream.ReadFloat(const Count: Integer): Float;
begin
if FPosition + Count > FDataView.byteLength then
raise Exception.Create(RStrPositionExceedsByteLength);
case Count of
4:
Result := FDataView.getFloat32(FPosition, True);
8:
Result := FDataView.getFloat64(FPosition, True);
else
raise Exception.Create(RStrUnknownBitWidth);
end;
Inc(FPosition, Count);
end;
function TStream.ReadString(const Count: Integer): String;
begin
if FPosition + Count > FDataView.byteLength then
raise Exception.Create(RStrPositionExceedsByteLength);
var Decoder := JTextDecoder.Create;
Result := Decoder.decode(FDataView.buffer.slice(FPosition, FPosition + Count));
// eventually strip #0 character at the end
if Ord(Result[High(Result)]) = 0 then
Result := Result.DeleteRight(1);
Inc(FPosition, Count);
end;
function TStream.ReadBuffer(const Count: Integer): JUint8Array;
begin
if FPosition + Count > FDataView.byteLength then
raise Exception.Create(RStrPositionExceedsByteLength);
Result := JUint8Array.Create(FDataView.buffer.slice(FPosition, FPosition + Count));
Inc(FPosition, Count);
end;
function TStream.Seek(Position: Integer; IsRelative: Boolean = False): Integer;
begin
FPosition := Position + if IsRelative then FPosition;
if FPosition > FDataView.byteLength then
FPosition := FDataView.byteLength;
if FPosition > FDataView.byteLength then
raise Exception.Create(RStrInvalidPosition);
Result := FPosition;
end;
procedure TStream.WriteInteger(const Count: Integer; const Value: Integer);
begin
case Count of
1:
FDataView.setUint8(FPosition, Value);
2:
FDataView.setUint16(FPosition, Value);
4:
FDataView.setUint32(FPosition, Value);
else
raise Exception.Create(RStrInvalidCount);
end;
Inc(FPosition, Count);
end;
procedure TStream.WriteString(const Value: String);
begin
var Encoder := JTextEncoder.Create;
WriteBuffer(Encoder.Encode(Value));
end;
procedure TStream.Clear;
begin
FPosition := 0;
end;
procedure TStream.WriteBuffer(Buffer: JUint8Array);
begin
var OldBuffer := JUint8Array(FDataView.buffer);
var NewBuffer := JUint8Array.Create(OldBuffer.byteLength + Buffer.byteLength);
NewBuffer.set(OldBuffer, 0);
NewBuffer.set(Buffer, OldBuffer.byteLength);
FDataView := JDataView.Create(NewBuffer.buffer);
FPosition := NewBuffer.byteLength;
end;
{ THdfSuperBlock }
procedure THdfSuperBlock.LoadFromStream(Stream: TStream);
begin
var Identifier := Stream.ReadInteger(1);
if Identifier <> 137 then
raise Exception.Create(RStrInvalidHDF);
var FormatSignature := Stream.ReadString(3);
if FormatSignature <> 'HDF' then
raise Exception.Create(RStrInvalidHDF);
var FormatSignatureVersion := Stream.ReadInteger(4);
if FormatSignatureVersion <> 169478669 then
raise Exception.Create(RStrInvalidHDF);
// read version
var Version := Stream.ReadInteger(1);
if not (Version in [2, 3]) then
raise Exception.Create(RStrUnsupportedVersion);
// read offset & length size
FOffsetSize := Stream.ReadInteger(1);
FLengthsSize := Stream.ReadInteger(1);
// read consistency flag
var ConsistencyFlag := Stream.ReadInteger(1);
// read base address
var BaseAddress := Stream.ReadInteger(FOffsetSize);
if BaseAddress <> 0 then
raise Exception.Create(RStrInvalidBaseAddress);
// read superblock extension address
var SuperBlockExtensionAddress := Stream.ReadInteger(FOffsetSize);
// read end of file address
FEndOfFileAddress := Stream.ReadInteger(FOffsetSize);
// read group object header address
var RootGroupObjectHeaderAddress := Stream.ReadInteger(FOffsetSize);
if FEndOfFileAddress <> Stream.Size then
raise Exception.Create(RStrSizeMismatch);
// read checksum
var Checksum := Stream.ReadInteger(4);
// read checksum
if Stream.Seek(RootGroupObjectHeaderAddress) <> RootGroupObjectHeaderAddress then
raise Exception.Create(RStrErrorSeekingFirstObject);
end;
{ THdfDataObjectMessage }
constructor THdfDataObjectMessage.Create(SuperBlock: THdfSuperBlock; DataObject: THdfDataObject);
begin
FSuperBlock := SuperBlock;
FDataObject := DataObject;
end;
procedure THdfDataObjectMessage.LoadFromStream(Stream: TStream);
begin
// read version
FVersion := Stream.ReadInteger(1);
end;
{ THdfMessageDataSpace }
procedure THdfMessageDataSpace.LoadFromStream(Stream: TStream);
var
Index: Integer;
begin
inherited LoadFromStream(Stream);
if not (FVersion in [1, 2]) then
raise Exception.Create(RStrUnsupportedVersionOfDataspaceMessage);
// read dimensionality
FDimensionality := Stream.ReadInteger(1);
// read flags
FFlags := Stream.ReadInteger(1);
// eventually skip reserved
if FVersion = 1 then
begin
Stream.Seek(5, True);
raise Exception.Create(RStrUnsupportedVersionOfDataspaceMessage);
end;
// read type
FType := Stream.ReadInteger(1);
// read dimension size
for Index := 0 to FDimensionality - 1 do
begin
var Size := Stream.ReadInteger(Superblock.LengthsSize);
FDimensionSize.Add(Size);
end;
// eventually read dimension max size
if (FFlags and 1) <> 0 then
begin
for Index := 0 to FDimensionality - 1 do
begin
var MaxSize := Stream.ReadInteger(Superblock.LengthsSize);
FDimensionMaxSize.Add(MaxSize);
end
end;
end;
function THdfMessageDataSpace.GetDimension(Index: Integer): Integer;
begin
if (Index < 0) or (Index >= Length(FDimensionSize)) then
raise Exception.Create(Format(RStrIndexOutOfBounds, [Index]));
Result := FDimensionSize[Index];
end;
{ THdfBaseDataType }
constructor THdfBaseDataType.Create(DatatypeMessage: THdfMessageDataType);
begin
FDataTypeMessage := DataTypeMessage;
end;
procedure THdfBaseDataType.LoadFromStream(Stream: TStream);
begin
// do nothing by default
end;
{ THdfDataTypeFixedPoint }
procedure THdfDataTypeFixedPoint.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
var BitOffset := Stream.ReadInteger(2);
var BitPrecision := Stream.ReadInteger(2);
end;
{ THdfDataTypeFloatingPoint }
procedure THdfDataTypeFloatingPoint.LoadFromStream(Stream: TStream);
begin
var BitOffset := Stream.ReadInteger(2);
var BitPrecision := Stream.ReadInteger(2);
var ExponentLocation := Stream.ReadInteger(1);
var ExponentSize := Stream.ReadInteger(1);
var MantissaLocation := Stream.ReadInteger(1);
var MantissaSize := Stream.ReadInteger(1);
var ExponentBias := Stream.ReadInteger(4);
Assert(BitOffset = 0);
Assert(MantissaLocation = 0);
if (BitPrecision = 32) then
begin
Assert(ExponentLocation = 23);
Assert(ExponentSize = 8);
Assert(MantissaSize = 23);
Assert(ExponentBias = 127);
end else
if (BitPrecision = 64) then
begin
Assert(ExponentLocation = 52);
Assert(ExponentSize = 11);
Assert(MantissaSize = 52);
Assert(ExponentBias = 1023);
end
else
raise Exception.Create(RStrUnsupportedBitPrecision);
end;
{ THdfDataTypeTime }
procedure THdfDataTypeTime.LoadFromStream(Stream: TStream);
begin
var BitPrecision := Stream.ReadInteger(2);
end;
{ THdfDataTypeBitfield }
procedure THdfDataTypeBitfield.LoadFromStream(Stream: TStream);
begin
var BitOffset := Stream.ReadInteger(2);
var BitPrecision := Stream.ReadInteger(2);
end;
{ THdfDataTypeCompoundPart }
constructor THdfDataTypeCompoundPart.Create(DatatypeMessage: THdfMessageDataType);
begin
FDataType := THdfMessageDataType.Create(DatatypeMessage.Superblock, DatatypeMessage.DataObject);
FSize := DatatypeMessage.Size;
end;
procedure THdfDataTypeCompoundPart.ReadFromStream(Stream: TStream);
var
ByteIndex: Integer;
ByteValue: Integer;
Temp: Integer;
begin
FName := '';
repeat
ByteValue := Stream.ReadInteger(1);
FName := FName + Chr(ByteValue);
until ByteValue = 0;
ByteIndex := 0;
repeat
Temp := Stream.ReadInteger(1);
FByteOffset := FByteOffset + Temp shl (8 * ByteIndex);
Inc(ByteIndex);
until 1 shl (8 * ByteIndex) > FSize;
FDataType.LoadFromStream(Stream);
end;
{ THdfDataTypeCompound }
constructor THdfDataTypeCompound.Create(DatatypeMessage: THdfMessageDataType);
begin
inherited Create(DatatypeMessage);
end;
procedure THdfDataTypeCompound.LoadFromStream(Stream: TStream);
var
Index: Integer;
Count: Integer;
Part: THdfDataTypeCompoundPart;
begin
if (FDataTypeMessage.Version <> 3) then
raise Exception.Create(Format(RStrErrorUnsupportedCompoundVersion, [FDataTypeMessage.Version]));
Count := FDataTypeMessage.FClassBitField[1] shl 8 + FDataTypeMessage.FClassBitField[0];
for Index := 0 to Count - 1 do
begin
Part := THdfDataTypeCompoundPart.Create(FDataTypeMessage);
Part.ReadFromStream(Stream);
FDataTypes.Add(Part);
end;
end;
{ THdfDataTypeVariableLength }
constructor THdfDataTypeVariableLength.Create(
DatatypeMessage: THdfMessageDataType);
begin
inherited Create(DatatypeMessage);
FDataType := THdfMessageDataType.Create(FDataTypeMessage.Superblock, FDataTypeMessage.DataObject);
end;
procedure THdfDataTypeVariableLength.LoadFromStream(Stream: TStream);
begin
FDataType.LoadFromStream(Stream);
end;
{ THdfMessageDataType }
procedure THdfMessageDataType.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
// expand class and version
FDataClass := FVersion and $F;
FVersion := FVersion shr 4;
// check version
if not (FVersion in [1, 3]) then
raise Exception.Create(RStrUnsupportedVersionOfDataTypeMessage);
FClassBitField[0] := Stream.ReadInteger(1);
FClassBitField[1] := Stream.ReadInteger(1);
FClassBitField[2] := Stream.ReadInteger(1);
FSize := Stream.ReadInteger(4);
case FDataClass of
0:
FDataType := THdfDataTypeFixedPoint.Create(Self);
1:
FDataType := THdfDataTypeFloatingPoint.Create(Self);
2:
FDataType := THdfDataTypeTime.Create(Self);
3:
FDataType := THdfDataTypeString.Create(Self);
4:
FDataType := THdfDataTypeBitfield.Create(Self);
5:
FDataType := THdfDataTypeOpaque.Create(Self);
6:
FDataType := THdfDataTypeCompound.Create(Self);
7:
FDataType := THdfDataTypeReference.Create(Self);
8:
FDataType := THdfDataTypeEnumerated.Create(Self);
9:
FDataType := THdfDataTypeVariableLength.Create(Self);
10:
FDataType := THdfDataTypeArray.Create(Self);
else
raise Exception.Create(Format(RStrUnknownDatatype, [FDataClass]));
end;
if Assigned(FDataType) then
FDataType.LoadFromStream(Stream);
end;
{ THdfMessageDataFill }
procedure THdfMessageDataFill.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
// check version
if FVersion <> 3 then
raise Exception.Create(RStrUnsupportedVersionOfDataFillMessage);
// read flags
var Flags := Stream.ReadInteger(1);
if (Flags and (1 shl 5)) <> 0 then
begin
var Size := Stream.ReadInteger(4);
Stream.Seek(Size, True);
end;
end;
{ THdfMessageDataLayout }
procedure THdfMessageDataLayout.LoadFromStream(Stream: TStream);
var
Index: Integer;
StreamPos: Integer;
Size: Integer;
begin
inherited LoadFromStream(Stream);
// check version
if FVersion <> 3 then
raise Exception.Create(RStrUnsupportedVersionOfDataLayoutMessage);
FLayoutClass := Stream.ReadInteger(1);
case FLayoutClass of
0: // compact storage
begin
// read data size
FDataSize := Stream.ReadInteger(2);
// read raw data
DataObject.Data.WriteBuffer(Stream.ReadBuffer(FDataSize));
end;
1: // continous storage
begin
// compact storage
FDataAddress := Stream.ReadInteger(Superblock.OffsetSize);
FDataSize := Stream.ReadInteger(Superblock.LengthsSize);
if FDataAddress > 0 then
begin
StreamPos := Stream.Position;
Stream.Position := FDataAddress;
DataObject.Data.WriteBuffer(Stream.ReadBuffer(FDataSize));
Stream.Position := StreamPos;
end;
end;
2:
begin
FDimensionality := Stream.ReadInteger(1);
FDataAddress := Stream.ReadInteger(Superblock.OffsetSize);
for Index := 0 to FDimensionality - 1 do
begin
var DataLayoutChunk := Stream.ReadInteger(4);
FDataObject.FDataLayoutChunk.Add(DataLayoutChunk);
end;
Size := DataObject.FDataLayoutChunk[FDimensionality - 1];
for Index := 0 to DataObject.DataSpace.Dimensionality - 1 do
Size := Size * DataObject.DataSpace.FDimensionSize[Index];
if (FDataAddress > 0) and (FDataAddress < Superblock.EndOfFileAddress) then
begin
StreamPos := Stream.Position;
Stream.Position := FDataAddress;
ReadTree(Stream, Size);
Stream.Position := StreamPos;
end;
end;
end;
end;
procedure THdfMessageDataLayout.ReadTree(Stream: TStream; Size: Integer);
var
Key: Integer;
Start: array of Integer;
begin
if DataObject.DataSpace.Dimensionality > 3 then
raise EHdfInvalidFormat.Create(RStrErrorReadingDimensions);
// read signature
var Signature := Stream.ReadString(4);
if Signature <> 'TREE' then
raise Exception.Create(Format(RStrWrongSignature, [Signature]));
var NodeType := Stream.ReadInteger(1);
var NodeLevel := Stream.ReadInteger(1);
var EntriesUsed := Stream.ReadInteger(2);
var AddressLeftSibling := Stream.ReadInteger(Superblock.OffsetSize);
var AddressRightSibling := Stream.ReadInteger(Superblock.OffsetSize);
var Elements := 1;
for var DimensionIndex := 0 to FDataObject.DataSpace.Dimensionality - 1 do
Elements := Elements * FDataObject.DatalayoutChunk[DimensionIndex];
var ElementSize := FDataObject.DatalayoutChunk[FDataObject.DataSpace.Dimensionality];
var Output := JUint8Array.Create(Size);
for var ElementIndex := 0 to 2 * EntriesUsed - 1 do
begin
if NodeType = 0 then
Key := Stream.ReadInteger(Superblock.LengthsSize)
else
begin
var ChunkSize := Stream.ReadInteger(4);
var FilterMask := Stream.ReadInteger(4);
if FilterMask <> 0 then
raise Exception.Create(RStrAllFiltersMustBeEnabled);
Start.Clear;
for var DimensionIndex := 0 to DataObject.DataSpace.Dimensionality - 1 do
begin
var StartPos := Stream.ReadInteger(8);
Start.Add(StartPos);
end;
var BreakCondition := Stream.ReadInteger(8);
if BreakCondition <> 0 then
Break;
var ChildPointer := Stream.ReadInteger(Superblock.OffsetSize);
// read data
var StreamPos := Stream.Position;
Stream.Position := ChildPointer;
// read data from stream
var ByteData := Stream.ReadBuffer(ChunkSize);
var Inflate := JZlibInflate.Create(ByteData);
var Input := JUint8Array(Inflate.decompress);
Assert(Input.byteLength = Elements * ElementSize);
case DataObject.DataSpace.Dimensionality of
1:
begin
var sx := DataObject.DataSpace.FDimensionSize[0];
for var ByteIndex := 0 to Elements * ElementSize - 1 do
begin
var b := ByteIndex div Elements;
var x := ByteIndex mod Elements + Start[0];
if (x < sx) then
Output[x * ElementSize + b] := Input[ByteIndex];
end;
end;
2:
begin
var sx := DataObject.DataSpace.FDimensionSize[0];
var sy := DataObject.DataSpace.FDimensionSize[1];
var dy := DataObject.DataLayoutChunk[1];
for var ByteIndex := 0 to Elements * ElementSize - 1 do
begin
var b := ByteIndex div Elements;
var x := ByteIndex mod Elements;
var y := x mod dy + Start[1];
x := x div dy + Start[0];
if (y < sy) and (x < sx) then
Output[(x * sy + y) * ElementSize + b] := Input[ByteIndex];
end;
end;
3:
begin
var sx := DataObject.DataSpace.FDimensionSize[0];
var sy := DataObject.DataSpace.FDimensionSize[1];
var sz := DataObject.DataSpace.FDimensionSize[2];
var dy := DataObject.DataLayoutChunk[1];
var dz := DataObject.DataLayoutChunk[2];
for var ByteIndex := 0 to Elements * ElementSize - 1 do
begin
var b := ByteIndex div Elements;
var x := ByteIndex mod Elements;
var z := (x mod dz) + Start[2];
var y := (x div dz) mod dy + Start[1];
x := (x div (dy * dz)) + Start[0];
if (z < sz) and (y < sy) and (x < sx) then
Output[(x * sz * sy + y * sz + z) * ElementSize + b] := Input[ByteIndex];
end;
end;
end;
Stream.Position := StreamPos;
end;
end;
DataObject.Data.WriteBuffer(Output);
var CheckSum := Stream.ReadInteger(4);
end;
{ THdfMessageLinkInfo }
procedure THdfMessageLinkInfo.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
// check version
if FVersion <> 0 then
raise Exception.Create(RStrUnsupportedVersionOfLinkInfoMessage);
// read flags
var Flags := Stream.ReadInteger(1);
if (Flags and 1) <> 0 then
Stream.ReadInteger(8);
FFractalHeapAddress := Stream.ReadInteger(SuperBlock.OffsetSize);
var AddressBTreeIndex := Stream.ReadInteger(SuperBlock.OffsetSize);
if (Flags and 2) <> 0 then
Stream.ReadInteger(SuperBlock.OffsetSize);
end;
{ THdfMessageGroupInfo }
procedure THdfMessageGroupInfo.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
// check version
if FVersion <> 0 then
raise Exception.Create(RStrUnsupportedVersionOfGroupInfoMessage);
// read flags
var Flags := Stream.ReadInteger(1);
if (Flags and 1) <> 0 then
begin
var MaximumCompact := Stream.ReadInteger(2);
var MinimumDense := Stream.ReadInteger(2);
end;
if (Flags and 2) <> 0 then
begin
var EstimatedNumberOfEntries := Stream.ReadInteger(2);
var EstimatedLinkNameLength := Stream.ReadInteger(2);
end;
end;
{ THdfMessageFilterPipeline }
procedure THdfMessageFilterPipeline.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
// check version
if FVersion <> 2 then
raise Exception.Create(RStrUnsupportedVersionOfTheFilterPipelineMessage);
var Filters := Stream.ReadInteger(1);
if Filters > 32 then
raise Exception.Create(RStrTooManyFilters);
for var Index := 0 to Filters - 1 do
begin
var FilterIdentificationValue := Stream.ReadInteger(2);
if not FilterIdentificationValue in [1, 2] then
raise Exception.Create(RStrUnsupportedFilter);
var Flags := Stream.ReadInteger(2);
var NumberClientDataValues := Stream.ReadInteger(2);
Stream.Seek(4 * NumberClientDataValues, True);
end;
end;
{ THdfAttribute }
constructor THdfAttribute.Create(Name: String);
begin
FName := Name;
FStream := TStream.Create(JArrayBuffer.Create(0));
end;
function THdfAttribute.GetValueAsString: String;
begin
if FStream.Size = 0 then
begin
Result := '';
Exit;
end;
FStream.Position := 0;
Result := FStream.ReadString(FStream.Size);
end;
procedure THdfAttribute.SetValueAsInteger(const Value: Integer);
begin
FStream.Clear;
FStream.WriteInteger(4, Value);
end;
function THdfAttribute.GetValueAsInteger: Integer;
begin
FStream.Position := 0;
Result := FStream.ReadInteger(4);
end;
procedure THdfAttribute.SetValueAsString(const Value: String);
begin
FStream.Clear;
FStream.WriteString(Value);
end;
{ THdfMessageAttribute }
procedure THdfMessageAttribute.ReadData(Stream: TStream; Attribute: THdfAttribute);
begin
case FDatatypeMessage.DataClass of
3:
Attribute.ValueAsString := Stream.ReadString(FDatatypeMessage.Size);
6:
Stream.Seek(FDatatypeMessage.Size, True);
7:
Attribute.ValueAsInteger := Stream.ReadInteger(4);
9:
Stream.Seek(16, True);
else
raise Exception.Create(RStrErrorUnknownDataClass);
end;
end;
procedure THdfMessageAttribute.ReadDataDimension(Stream: TStream;
Attribute: THdfAttribute; Dimension: Integer);
var
Index: Integer;
begin
if Length(FDataspaceMessage.FDimensionSize) > 0 then
for Index := 0 to FDataspaceMessage.FDimensionSize[0] - 1 do
begin
if (1 < FDataspaceMessage.Dimensionality) then
ReadDataDimension(Stream, Attribute, Dimension + 1)
else
ReadData(Stream, Attribute);
end;
end;
procedure THdfMessageAttribute.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
// check version
if FVersion <> 3 then
raise Exception.Create(RStrUnsupportedVersionOfMessageAttribute);
// read flags
var Flags := Stream.ReadInteger(1);
var NameSize := Stream.ReadInteger(2);
var DatatypeSize := Stream.ReadInteger(2);
var DataspaceSize := Stream.ReadInteger(2);
var Encoding := Stream.ReadInteger(1);
FName := Stream.ReadString(NameSize);
FDatatypeMessage := THdfMessageDataType.Create(Superblock, DataObject);
FDatatypeMessage.LoadFromStream(Stream);
FDataspaceMessage := THdfMessageDataSpace.Create(Superblock, DataObject);
FDataspaceMessage.LoadFromStream(Stream);
var Attribute := THdfAttribute.Create(FName);
DataObject.AddAttribute(Attribute);
if FDataspaceMessage.Dimensionality = 0 then
ReadData(Stream, Attribute)
else
ReadDataDimension(Stream, Attribute, 0);
end;
{ THdfMessageHeaderContinuation }
procedure THdfMessageHeaderContinuation.LoadFromStream(Stream: TStream);
begin
var Offset := Stream.ReadInteger(Superblock.OffsetSize);
var LengthX := Stream.ReadInteger(Superblock.LengthsSize);
var StreamPos := Stream.Position;
Stream.Position := Offset;
// read signature
var Signature := Stream.ReadString(4);
if Signature <> 'OCHK' then
raise Exception.Create(Format(RStrWrongSignature, [Signature]));
DataObject.ReadObjectHeaderMessages(Stream, Offset + LengthX);
Stream.Position := StreamPos;
end;
{ THdfMessageAttributeInfo }
procedure THdfMessageAttributeInfo.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
// check version
if FVersion <> 0 then
raise Exception.Create(RStrUnsupportedVersionOfAttributeInfoMessage);
// read flags
var Flags := Stream.ReadInteger(1);
if (Flags and 1) <> 0 then
Stream.ReadInteger(2);
FFractalHeapAddress := Stream.ReadInteger(SuperBlock.OffsetSize);
var AttributeNameBTreeAddress := Stream.ReadInteger(SuperBlock.OffsetSize);
if (Flags and 2) <> 0 then
Stream.ReadInteger(SuperBlock.OffsetSize);
end;
{ THdfCustomBlock }
constructor THdfCustomBlock.Create(SuperBlock: THdfSuperBlock;
FractalHeap: THdfFractalHeap; DataObject: THdfDataObject);
begin
FSuperBlock := SuperBlock;
FFractalHeap := FractalHeap;
FDataObject := DataObject;
end;
procedure THdfCustomBlock.LoadFromStream(Stream: TStream);
begin
// read signature
var Signature := Stream.ReadString(4);
if Signature <> GetSignature then
raise Exception.Create(Format(RStrWrongSignature, [Signature]));
// read version
var Version := Stream.ReadInteger(1);
if Version <> 0 then
raise Exception.Create(RStrUnsupportedVersionOfCustomBlock);
// read heap header address
var HeapHeaderAddress := Stream.ReadInteger(SuperBlock.OffsetSize);
// read block offset
FBlockOffset := 0;
FBlockOffset := Stream.ReadInteger((FFractalHeap.MaximumHeapSize + 7) div 8);
end;
{ THdfDirectBlock }
class function THdfDirectBlock.GetSignature: THdfSignature;
begin
Result := 'FHDB';
end;
procedure THdfDirectBlock.LoadFromStream(Stream: TStream);
var
OffsetSize, LengthSize: Integer;
TypeAndVersion: Integer;
HeapHeaderAddress: Integer;
StreamPos: Integer;
SubDataObject: THdfDataObject;
begin
inherited LoadFromStream(Stream);
if (FFractalHeap.Flags and 2) <> 0 then
FChecksum := Stream.ReadInteger(4);
OffsetSize := Ceil(log2(FFractalHeap.MaximumHeapSize) / 8);
if (FFractalHeap.MaximumDirectBlockSize < FFractalHeap.MaximumSize) then
LengthSize := Ceil(log2(FFractalHeap.MaximumDirectBlockSize) / 8)
else
LengthSize := Ceil(log2(FFractalHeap.MaximumSize) / 8);
repeat
TypeAndVersion := Stream.ReadInteger(1);
var OffsetX := Stream.ReadInteger(OffsetSize);
var LengthX := Stream.ReadInteger(LengthSize);
if (TypeAndVersion = 3) then
begin
var Temp := Stream.ReadInteger(5);
if Temp <> $40008 then
raise Exception.Create(RStrUnsupportedValues);
var Name := Stream.ReadString(LengthX);
Temp := Stream.ReadInteger(4);
if (Temp <> $13) then
raise Exception.Create(RStrUnsupportedValues);
LengthX := Stream.ReadInteger(2);
var ValueType := Stream.ReadInteger(4);
var TypeExtend := Stream.ReadInteger(2);
var Value := '';
if (ValueType = $20000) and (TypeExtend = 0) then
Value := Stream.ReadString(LengthX);
var Attribute := THdfAttribute.Create(Name);
Attribute.ValueAsString := Value;
FDataObject.AddAttribute(Attribute);
end
else
if (TypeAndVersion = 1) then
begin
var Temp := Stream.ReadInteger(6);
if Temp <> 0 then
raise Exception.Create(RStrFHDBType1UnsupportedValues);
// read name
LengthX := Stream.ReadInteger(1);
var Name := Stream.ReadString(LengthX);
// read heap header address
HeapHeaderAddress := Stream.ReadInteger(SuperBlock.OffsetSize);
StreamPos := Stream.Position;
Stream.Position := HeapHeaderAddress;
SubDataObject := THdfDataObject.Create(SuperBlock, Name);
SubDataObject.LoadFromStream(Stream);
FDataObject.AddDataObject(SubDataObject);
Stream.Position := StreamPos;
end;
until TypeAndVersion = 0;
end;
{ THdfIndirectBlock }
constructor THdfIndirectBlock.Create(SuperBlock: THdfSuperBlock;
FractalHeap: THdfFractalHeap; DataObject: THdfDataObject);
begin
inherited Create(SuperBlock, FractalHeap, DataObject);
FInitialBlockSize := FractalHeap.StartingBlockSize;
end;
class function THdfIndirectBlock.GetSignature: THdfSignature;
begin
Result := 'FHIB';
end;
procedure THdfIndirectBlock.LoadFromStream(Stream: TStream);
var
RowsCount: Integer;
k, n: Integer;
ChildBlockAddress: Integer;
SizeOfFilteredDirectBlock: Integer;
FilterMaskForDirectBlock: Integer;
StreamPosition: Integer;
Block: THdfCustomBlock;
begin
inherited LoadFromStream(Stream);
if FBlockOffset <> 0 then
raise Exception.Create(RStrZeroBlockOffset);
// The number of rows of blocks, nrows, in an indirect block of size iblock_size is given by the following expression:
RowsCount := Round(log2(FInitialBlockSize) - log2(FFractalHeap.StartingBlockSize)) + 1;
// The maximum number of rows of direct blocks, max_dblock_rows, in any indirect block of a fractal heap is given by the following expression: */
var MaximumNumberOfDirectBlockRows := Round(log2(FFractalHeap.MaximumDirectBlockSize)
- log2(FFractalHeap.StartingBlockSize)) + 2;
// Using the computed values for nrows and max_dblock_rows, along with the Width of the doubling table, the number of direct and indirect block entries (K and N in the indirect block description, below) in an indirect block can be computed:
if (RowsCount < MaximumNumberOfDirectBlockRows) then
k := RowsCount * FFractalHeap.TableWidth
else
k := MaximumNumberOfDirectBlockRows * FFractalHeap.TableWidth;
// If nrows is less than or equal to max_dblock_rows, N is 0. Otherwise, N is simply computed:
n := k - (MaximumNumberOfDirectBlockRows * FFractalHeap.TableWidth);
while (k > 0) do
begin
ChildBlockAddress := 0;
ChildBlockAddress := Stream.ReadInteger(SuperBlock.OffsetSize);
if (FFractalHeap.EncodedLength > 0) then
begin
SizeOfFilteredDirectBlock := Stream.ReadInteger(SuperBlock.LengthsSize);
FilterMaskForDirectBlock := Stream.ReadInteger(4);
end;
if (ChildBlockAddress > 0) and (ChildBlockAddress < SuperBlock.EndOfFileAddress) then
begin
StreamPosition := Stream.Position;
Stream.Position := ChildBlockAddress;
Block := THdfDirectBlock.Create(SuperBlock, FFractalHeap, FDataObject);
Block.LoadFromStream(Stream);
Stream.Position := StreamPosition;
end;
Dec(k);
end;
while (n > 0) do
begin
ChildBlockAddress := 0;
ChildBlockAddress := Stream.ReadInteger(SuperBlock.OffsetSize);
if (ChildBlockAddress > 0) and (ChildBlockAddress < SuperBlock.EndOfFileAddress) then
begin
StreamPosition := Stream.Position;
Stream.Position := ChildBlockAddress;
Block := THdfInDirectBlock.Create(SuperBlock, FFractalHeap, FDataObject);
Block.LoadFromStream(Stream);
Stream.Position := StreamPosition;
end;
Dec(n);
end;
end;
{ THdfFractalHeap }
constructor THdfFractalHeap.Create(SuperBlock: THdfSuperBlock; DataObject: THdfDataObject);
begin
FSuperBlock := SuperBlock;
FDataObject := DataObject;
end;
procedure THdfFractalHeap.LoadFromStream(Stream: TStream);
var
Block: THdfCustomBlock;
begin
// read signature
FSignature := Stream.ReadString(4);
if FSignature <> 'FRHP' then
raise Exception.Create(Format(RStrWrongSignature, [FSignature]));
// read version
FVersion := Stream.ReadInteger(1);
if FVersion <> 0 then
raise Exception.Create(RStrUnsupportedVersionOfFractalHeap);
FHeapIdLength := Stream.ReadInteger(2);
FEncodedLength := Stream.ReadInteger(2);
FFlags := Stream.ReadInteger(1);
FMaximumSize := Stream.ReadInteger(4);
FNextHugeID := Stream.ReadInteger(SuperBlock.LengthsSize);
FBtreeAddresses := Stream.ReadInteger(SuperBlock.OffsetSize);
FAmountFreeSpace := Stream.ReadInteger(SuperBlock.LengthsSize);
FAddressManagedBlock := Stream.ReadInteger(SuperBlock.OffsetSize);
FAmountManagedSpace := Stream.ReadInteger(SuperBlock.LengthsSize);
FAmountAllocatedManagedSpace := Stream.ReadInteger(SuperBlock.LengthsSize);
FOffsetDirectBlockAllocation := Stream.ReadInteger(SuperBlock.LengthsSize);
FNumberOfManagedObjects := Stream.ReadInteger(SuperBlock.LengthsSize);
FSizeOfHugeObjects := Stream.ReadInteger(SuperBlock.LengthsSize);
FNumberOfHugeObjects := Stream.ReadInteger(SuperBlock.LengthsSize);
FSizeOfTinyObjects := Stream.ReadInteger(SuperBlock.LengthsSize);
FNumberOfTinyObjects := Stream.ReadInteger(SuperBlock.LengthsSize);
FTableWidth := Stream.ReadInteger(2);
FStartingBlockSize := Stream.ReadInteger(SuperBlock.LengthsSize);
FMaximumDirectBlockSize := Stream.ReadInteger(SuperBlock.LengthsSize);
FMaximumHeapSize := Stream.ReadInteger(2);
var StartingNumber := Stream.ReadInteger(2);
var AddressOfRootBlock := Stream.ReadInteger(SuperBlock.OffsetSize);
var CurrentNumberOfRows := Stream.ReadInteger(2);
if FEncodedLength > 0 then
Stream.Seek(SuperBlock.LengthsSize + 4, True);
if (FNumberOfHugeObjects > 0) then
raise Exception.Create(RStrNoHugeObjects);
if (FNumberOfTinyObjects > 0) then
raise Exception.Create(RStrNoTinyObjects);
if (AddressOfRootBlock > 0) and (AddressOfRootBlock < Superblock.EndOfFileAddress) then
begin
Stream.Position := AddressOfRootBlock;
if CurrentNumberOfRows <> 0 then
Block := THdfIndirectBlock.Create(SuperBlock, Self, FDataObject)
else
Block := THdfDirectBlock.Create(SuperBlock, Self, FDataObject);
Block.LoadFromStream(Stream);
end;
end;
{ THdfDataObject }
constructor THdfDataObject.Create(SuperBlock: THdfSuperBlock);
begin
FSuperblock := SuperBlock;
FName := '';
// create a few default messages
FDataType := THdfMessageDataType.Create(FSuperBlock, Self);
FDataSpace := THdfMessageDataSpace.Create(FSuperBlock, Self);
FLinkInfo := THdfMessageLinkInfo.Create(FSuperBlock, Self);
FGroupInfo := THdfMessageGroupInfo.Create(FSuperBlock, Self);
FAttributeInfo := THdfMessageAttributeInfo.Create(FSuperBlock, Self);
FAttributesHeap := THdfFractalHeap.Create(FSuperBlock, Self);
FObjectsHeap := THdfFractalHeap.Create(FSuperBlock, Self);
FData := TStream.Create(JArrayBuffer.Create(0));
end;
procedure THdfDataObject.AddAttribute(Attribute: THdfAttribute);
begin
FAttributeList.Add(Attribute);
end;
procedure THdfDataObject.AddDataObject(DataObject: THdfDataObject);
begin
FDataObjects.Add(DataObject);
end;
constructor THdfDataObject.Create(SuperBlock: THdfSuperBlock; Name: String);
begin
Create(SuperBlock);
FName := Name;
end;
function THdfDataObject.GetAttributeListCount: Integer;
begin
Result := FAttributeList.Count;
end;
function THdfDataObject.GetAttributeListItem(Index: Integer): THdfAttribute;
begin
if (Index < 0) or (Index >= FAttributeList.Count) then
raise Exception.Create(Format(RStrIndexOutOfBounds, [Index]));
Result := THdfAttribute(FAttributeList[Index]);
end;
function THdfDataObject.GetDataLayoutChunk(Index: Integer): Integer;
begin
if (Index < 0) or (Index >= Length(FDataLayoutChunk)) then
raise Exception.Create(Format(RStrIndexOutOfBounds, [Index]));
Result := FDataLayoutChunk[Index];
end;
function THdfDataObject.GetDataLayoutChunkCount: Integer;
begin
Result := Length(FDataLayoutChunk);
end;
function THdfDataObject.GetDataObject(Index: Integer): THdfDataObject;
begin
if (Index < 0) or (Index >= FDataObjects.Count) then
raise Exception.Create(Format(RStrIndexOutOfBounds, [Index]));
Result := THdfDataObject(FDataObjects[Index]);
end;
function THdfDataObject.GetDataObjectCount: Integer;
begin
Result := FDataObjects.Count;
end;
function THdfDataObject.HasAttribute(Name: string): Boolean;
var
Index: Integer;
begin
Result := False;
for Index := 0 to AttributeListCount - 1 do
if AttributeListItem[Index].Name = Name then
exit(True);
end;
function THdfDataObject.GetAttribute(Name: string): string;
var
Index: Integer;
begin
Result := '';
for Index := 0 to AttributeListCount - 1 do
if AttributeListItem[Index].Name = Name then
exit(AttributeListItem[Index].ValueAsString);
end;
procedure THdfDataObject.LoadFromStream(Stream: TStream);
begin
var Signature := Stream.ReadString(4);
if Signature <> 'OHDR' then
raise Exception.Create(Format(RStrWrongSignature, [Signature]));
// read version
var Version := Stream.ReadInteger(1);
if Version <> 2 then
raise Exception.Create(RStrInvalidVersion);
FFlags := Stream.ReadInteger(1);
// eventually skip time stamps
if (FFlags and (1 shl 5)) <> 0 then
Stream.Seek(16, True);
// eventually skip number of attributes
if (FFlags and (1 shl 4)) <> 0 then
begin
var MaximumCompact := Stream.ReadInteger(2);
var MinimumDense := Stream.ReadInteger(2);
end;
FChunkSize := Stream.ReadInteger(1 shl (FFlags and 3));
ReadObjectHeaderMessages(Stream, Stream.Position + FChunkSize);
// parse message attribute info
if (AttributeInfo.FractalHeapAddress > 0) and
(AttributeInfo.FractalHeapAddress < FSuperblock.EndOfFileAddress) then
begin
Stream.Position := AttributeInfo.FractalHeapAddress;
FAttributesHeap.LoadFromStream(Stream);
end;
// parse message link info
if (LinkInfo.FractalHeapAddress > 0) and
(LinkInfo.FractalHeapAddress < FSuperblock.EndOfFileAddress) then
begin
Stream.Position := LinkInfo.FractalHeapAddress;
FObjectsHeap.LoadFromStream(Stream);
end;
end;
procedure THdfDataObject.ReadObjectHeaderMessages(Stream: TStream; EndOfStream: Integer);
var
MessageType: Integer;
MessageSize: Integer;
MessageFlags: Integer;
EndPos: Integer;
DataObjectMessage: THdfDataObjectMessage;
begin
while Stream.Position < EndOfStream - 4 do
begin
MessageType := Stream.ReadInteger(1);
MessageSize := Stream.ReadInteger(2);
MessageFlags := Stream.ReadInteger(1);
if (MessageFlags and not 5) <> 0 then
raise Exception.Create(RStrUnsupportedOHDRMessageFlag);
// eventually skip creation order
if FFlags and (1 shl 2) <> 0 then
Stream.Seek(2, True);
EndPos := Stream.Position + MessageSize;
DataObjectMessage := nil;
case MessageType of
0:
Stream.Seek(MessageSize, True);
1:
DataObjectMessage := FDataSpace;
2:
DataObjectMessage := FLinkInfo;
3:
DataObjectMessage := FDataType;
5:
DataObjectMessage := THdfMessageDataFill.Create(FSuperBlock, Self);
8:
DataObjectMessage := THdfMessageDataLayout.Create(FSuperBlock, Self);
10:
DataObjectMessage := FGroupInfo;
11:
DataObjectMessage := THdfMessageFilterPipeline.Create(FSuperBlock, Self);
12:
DataObjectMessage := THdfMessageAttribute.Create(FSuperBlock, Self);
16:
DataObjectMessage := THdfMessageHeaderContinuation.Create(FSuperBlock, Self);
21:
DataObjectMessage := FAttributeInfo;
else
raise Exception.Create(Format('Unknown header message (%d)', [MessageType]));
end;
// now eventally load data object message
if Assigned(DataObjectMessage) then
DataObjectMessage.LoadFromStream(Stream);
{$IFDEF IgnoreWrongPosition}
Stream.Position := EndPos;
{$ELSE}
if Stream.Position <> EndPos then
Assert(Stream.Position = EndPos);
{$ENDIF}
end;
end;
{ THdfFile }
constructor THdfFile.Create;
begin
inherited Create;
FSuperBlock := THdfSuperBlock.Create;
FDataObject := THdfDataObject.Create(FSuperblock);
end;
function THdfFile.GetAttribute(Name: string): string;
begin
Result := FDataObject.GetAttribute(Name);
end;
function THdfFile.HasAttribute(Name: string): Boolean;
begin
Result := FDataObject.HasAttribute(Name);
end;
procedure THdfFile.LoadFromStream(Stream: TStream);
begin
FSuperblock.LoadFromStream(Stream);
FDataObject.LoadFromStream(Stream);
end;
procedure THdfFile.LoadFromBuffer(Buffer: JArrayBuffer);
begin
LoadFromStream(TStream.Create(Buffer));
end;
{ TSofaFile }
function TSofaFile.GetDelay(Index: Integer): Float;
begin
if (Index < 0) or (Index >= Length(FDelay)) then
raise Exception.Create(Format(RStrIndexOutOfBounds, [Index]));
Result := FDelay[Index];
end;
function TSofaFile.GetDelayCount: Integer;
begin
Result := Length(FDelay);
end;
function TSofaFile.GetImpulseResponse(MeasurementIndex,
ReceiverIndex: Integer): JFloat64Array;
begin
Result := FImpulseResponses[MeasurementIndex, ReceiverIndex];
end;
function TSofaFile.GetSampleRate(Index: Integer): Float;
begin
if (Index < 0) or (Index >= Length(FSampleRate)) then
raise Exception.Create(Format(RStrIndexOutOfBounds, [Index]));
Result := FSampleRate[Index];
end;
function TSofaFile.GetSampleRateCount: Integer;
begin
Result := Length(FSampleRate);
end;
procedure TSofaFile.LoadFromBuffer(Buffer: JArrayBuffer);
var
HdfFile: THdfFile;
begin
HdfFile := THdfFile.Create;
try
HdfFile.LoadFromBuffer(Buffer);
if HdfFile.GetAttribute('Conventions') <> 'SOFA' then
raise Exception.Create(RStrSofaConventionMissing);
for var Index := 0 to HdfFile.DataObject.DataObjectCount - 1 do
ReadDataObject(HdfFile.DataObject.DataObject[Index]);
FAttributes := JMap.Create;
for var Index := 0 to HdfFile.DataObject.AttributeListCount - 1 do
begin
var Attribute := HdfFile.DataObject.AttributeListItem[Index];
FAttributes.set(Attribute.Name, Attribute.ValueAsString);
end;
finally
HdfFile.Free;
end;
end;
procedure TSofaFile.ReadDataObject(DataObject: THdfDataObject);
function GetDimension(Text: String): Integer;
var
TextPos: Integer;
const
CNetCdfDim = 'This is a netCDF dimension but not a netCDF variable.';
begin
Result := 0;
TextPos := Pos(CNetCdfDim, Text);
if TextPos > 0 then
begin
Delete(Text, TextPos, 53);
Result := StrToInt(Trim(Text));
end;
end;
const
CClassIdentifier = 'CLASS';
CDimensionScaleIdentifier = 'DIMENSION_SCALE';
CNameIdentifier = 'NAME';
CTypeIdentifier = 'Type';
CSphericalIdentifier = 'spherical';
begin
DataObject.Data.Position := 0;
if DataObject.Name = 'M' then
begin
Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier);
FNumberOfMeasurements := GetDimension(DataObject.GetAttribute(CNameIdentifier));
end
else if DataObject.Name = 'R' then
begin
Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier);
FNumberOfReceivers := GetDimension(DataObject.GetAttribute(CNameIdentifier));
end
else if DataObject.Name = 'E' then
begin
Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier);
FNumberOfEmitters := GetDimension(DataObject.GetAttribute(CNameIdentifier));
end
else if DataObject.Name = 'N' then
begin
Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier);
FNumberOfDataSamples := GetDimension(DataObject.GetAttribute(CNameIdentifier));
end
else if DataObject.Name = 'S' then
begin
Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier);
var ItemCount := GetDimension(DataObject.GetAttribute(CNameIdentifier));
end
else if DataObject.Name = 'I' then
begin
Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier);
var ItemCount := GetDimension(DataObject.GetAttribute(CNameIdentifier));
end
else if DataObject.Name = 'C' then
begin
Assert(DataObject.GetAttribute(CClassIdentifier) = CDimensionScaleIdentifier);
var ItemCount := GetDimension(DataObject.GetAttribute(CNameIdentifier));
end
else if DataObject.Name = 'ListenerPosition' then
begin
Assert(DataObject.Data.Size > 0);
Assert(DataObject.DataType.DataClass = 1);
FNumberOfListeners := DataObject.Data.Size div (3 * DataObject.DataType.Size);
var IsSpherical := False;
if DataObject.HasAttribute(CTypeIdentifier) then
IsSpherical := DataObject.GetAttribute(CTypeIdentifier) = CSphericalIdentifier;
FListenerPositions := TSofaPositions.Create(IsSpherical);
FListenerPositions.LoadFromStream(DataObject.Data, DataObject.DataType.Size);
end
else if DataObject.Name = 'ReceiverPosition' then
begin
Assert(DataObject.Data.Size > 0);
Assert(DataObject.DataType.DataClass = 1);
FNumberOfReceivers := DataObject.Data.Size div (3 * DataObject.DataType.Size);
var IsSpherical := False;
if DataObject.HasAttribute(CTypeIdentifier) then
IsSpherical := DataObject.GetAttribute(CTypeIdentifier) = CSphericalIdentifier;
FReceiverPositions := TSofaPositions.Create(IsSpherical);
FReceiverPositions.LoadFromStream(DataObject.Data, DataObject.DataType.Size);
end
else if DataObject.Name = 'SourcePosition' then
begin
Assert(DataObject.Data.Size > 0);
Assert(DataObject.DataType.DataClass = 1);
FNumberOfSources := DataObject.Data.Size div (3 * DataObject.DataType.Size);
var IsSpherical := False;
if DataObject.HasAttribute(CTypeIdentifier) then
IsSpherical := DataObject.GetAttribute(CTypeIdentifier) = CSphericalIdentifier;
FSourcePositions := TSofaPositions.Create(IsSpherical);
FSourcePositions.LoadFromStream(DataObject.Data, DataObject.DataType.Size);
end
else if DataObject.Name = 'EmitterPosition' then
begin
Assert(DataObject.Data.Size > 0);
Assert(DataObject.DataType.DataClass = 1);
FNumberOfEmitters := DataObject.Data.Size div (3 * DataObject.DataType.Size);
var IsSpherical := False;
if DataObject.HasAttribute(CTypeIdentifier) then
IsSpherical := DataObject.GetAttribute(CTypeIdentifier) = CSphericalIdentifier;
FEmitterPositions := TSofaPositions.Create(IsSpherical);
FEmitterPositions.LoadFromStream(DataObject.Data, DataObject.DataType.Size);
end
else if DataObject.Name = 'ListenerUp' then
begin
Assert(DataObject.Data.Size > 0);
Assert(DataObject.DataType.DataClass = 1);
FListenerUp[0] := DataObject.Data.ReadFloat(8);
FListenerUp[1] := DataObject.Data.ReadFloat(8);
FListenerUp[2] := DataObject.Data.ReadFloat(8);
end
else if DataObject.Name = 'ListenerView' then
begin
Assert(DataObject.Data.Size > 0);
Assert(DataObject.DataType.DataClass = 1);
FListenerView[0] := DataObject.Data.ReadFloat(8);
FListenerView[1] := DataObject.Data.ReadFloat(8);
FListenerView[2] := DataObject.Data.ReadFloat(8);
end
else if DataObject.Name = 'Data.IR' then
begin
Assert(DataObject.Data.Size > 0);
var ItemCount := FNumberOfMeasurements * FNumberOfReceivers * FNumberOfDataSamples * 8;
Assert(DataObject.Data.Size = ItemCount);
FImpulseResponses.SetLength(FNumberOfMeasurements);
for var MeasurementIndex := 0 to FNumberOfMeasurements - 1 do
begin
FImpulseResponses[MeasurementIndex].SetLength(FNumberOfReceivers);
for var ReceiverIndex := 0 to FNumberOfReceivers - 1 do
begin
var ImpulseResponse := JFloat64Array.Create(FNumberOfDataSamples);
for var Index := 0 to FNumberOfDataSamples - 1 do
ImpulseResponse[Index] := DataObject.Data.ReadFloat(8);
FImpulseResponses[MeasurementIndex, ReceiverIndex] := ImpulseResponse;
end;
end;
end
else if DataObject.Name = 'Data.SamplingRate' then
begin
Assert(DataObject.Data.Size > 0);
var ItemCount := DataObject.Data.Size div DataObject.DataType.Size;
for var Index := 0 to ItemCount - 1 do
begin
var SampleRate := DataObject.Data.ReadFloat(8);
FSampleRate.Add(SampleRate);
end;
end
else if DataObject.Name = 'Data.Delay' then
begin
Assert(DataObject.Data.Size > 0);
var ItemCount := DataObject.Data.Size div DataObject.DataType.Size;
for var Index := 0 to ItemCount - 1 do
begin
var Delay := DataObject.Data.ReadFloat(8);
FDelay.Add(Delay);
end;
end;
end;
function TSofaFile.GetClosestIndexSpherical(Phi, Theta, Radius: Float): Integer;
begin
var Position: array [0 .. 2] of Float;
Position[0] := Phi;
Position[1] := Theta;
Position[2] := Radius;
Position := SphericalToCartesian(Position);
Result := GetClosestIndexCartesian(Position[0], Position[1], Position[2]);
end;
function TSofaFile.GetClosestIndexCartesian(X, Y, Z: Float): Integer;
begin
Result := 0;
var CurrentPosition := FListenerPositions.GetPosition(0, False);
var Distance := Sqrt(Sqr(X - CurrentPosition[0]) +
Sqr(Y - CurrentPosition[1]) + Sqr(Z - CurrentPosition[1]));
for var Index := 1 to FListenerPositions.Count - 1 do
begin
CurrentPosition := FListenerPositions.GetPosition(Index, False);
var CurrentDistance := Sqrt(Sqr(X - CurrentPosition[0]) +
Sqr(Y - CurrentPosition[1]) + Sqr(Z - CurrentPosition[1]));
if CurrentDistance < Distance then
begin
Distance := CurrentDistance;
Result := Index;
end;
end;
end;
{ TSofaPositions }
constructor TSofaPositions.Create(IsSpherical: Boolean);
begin
FIsSpherical := IsSpherical;
end;
procedure TSofaPositions.LoadFromStream(Stream: TStream; const DataSize: Integer);
begin
Assert(DataSize = 8);
for var Index := 0 to (Stream.Size div (3 * DataSize)) - 1 do
begin
var Position: TVector3;
Position[0] := Stream.ReadFloat(DataSize);
Position[1] := Stream.ReadFloat(DataSize);
Position[2] := Stream.ReadFloat(DataSize);
FPositions.Add(Position);
end;
end;
function TSofaPositions.GetPosition(const Index: Integer): TVector3;
begin
if (Index < 0) or (Index >= Length(FPositions)) then
raise Exception.Create(Format(RStrIndexOutOfBounds, [Index]));
Result := FPositions[Index];
end;
function TSofaPositions.GetPosition(const Index: Integer; Spherical: Boolean): TVector3;
begin
Result := GetPosition(Index);
// eventually convert position
if Spherical <> IsSpherical then
if Spherical then
Result := CartesianToSpherical(Result)
else
Result := SphericalToCartesian(Result);
end;
{ API }
function sofaLoadFile(Buffer: JArrayBuffer): TSofaFile;
begin
Result := TSofaFile.Create;
Result.LoadFromBuffer(Buffer);
end;
function sofaGetAttribute(SofaFile: TSofaFile; const AttributeName: String): String;
begin
Result := '';
if SofaFile.Attributes.has(AttributeName) then
exit(SofaFile.Attributes.get(AttributeName));
end;
function SphericalToCartesian(Position: TVector3): TVector3;
begin
Result[0] := Position[2] * Cos(DegToRad(Position[1])) * Cos(DegToRad(Position[0]));
Result[1] := Position[2] * Cos(DegToRad(Position[1])) * Sin(DegToRad(Position[0]));
Result[2] := Position[2] * Sin(DegToRad(Position[1]));
end;
function CartesianToSpherical(Position: TVector3): TVector3;
begin
Result[2] := Sqrt(Sqr(Position[0]) + Sqr(Position[1]) + Sqr(Position[2]));
Result[1] := ArcSin(Position[2] / Result[2]);
Result[0] := ArcTan2(Position[1], Position[0]);
end;
procedure sofaGetListenerPosition(SofaFile: TSofaFile; Callback: TGetPositionCallback; Spherical: Boolean = False);
begin
for var Index := 0 to SofaFile.NumberOfListeners - 1 do
Callback(SofaFile.ListenerPositions.GetPosition(Index, Spherical));
end;
procedure sofaGetReceiverPosition(SofaFile: TSofaFile; Callback: TGetPositionCallback; Spherical: Boolean = False);
begin
for var Index := 0 to SofaFile.NumberOfReceivers - 1 do
Callback(SofaFile.ReceiverPositions.GetPosition(Index, Spherical));
end;
procedure sofaGetSourcePosition(SofaFile: TSofaFile; Callback: TGetPositionCallback; Spherical: Boolean = False);
begin
for var Index := 0 to SofaFile.NumberOfSources - 1 do
Callback(SofaFile.SourcePositions.GetPosition(Index, Spherical));
end;
procedure sofaGetEmitterPosition(SofaFile: TSofaFile; Callback: TGetPositionCallback; Spherical: Boolean = False);
begin
for var Index := 0 to SofaFile.NumberOfEmitters - 1 do
Callback(SofaFile.EmitterPositions.GetPosition(Index, Spherical));
end;
function sofaGetListenerPositionList(SofaFile: TSofaFile; Spherical: Boolean = False): array of TVector3;
begin
for var Index := 0 to SofaFile.NumberOfListeners - 1 do
Result.Add(SofaFile.ListenerPositions.GetPosition(Index, Spherical));
end;
function sofaGetReceiverPositionList(SofaFile: TSofaFile; Spherical: Boolean = False): array of TVector3;
begin
for var Index := 0 to SofaFile.NumberOfReceivers - 1 do
Result.Add(SofaFile.ReceiverPositions.GetPosition(Index, Spherical));
end;
function sofaGetSourcePositionList(SofaFile: TSofaFile; Spherical: Boolean = False): array of TVector3;
begin
for var Index := 0 to SofaFile.NumberOfSources - 1 do
Result.Add(SofaFile.SourcePositions.GetPosition(Index, Spherical));
end;
function sofaGetEmitterPositionList(SofaFile: TSofaFile; Spherical: Boolean = False): array of TVector3;
begin
for var Index := 0 to SofaFile.NumberOfEmitters - 1 do
Result.Add(SofaFile.EmitterPositions.GetPosition(Index, Spherical));
end;
function sofaGetSampleRates(SofaFile: TSofaFile): array of Float;
begin
for var Index := 0 to SofaFile.SampleRateCount - 1 do
Result.Add(SofaFile.SampleRate[Index]);
end;
function sofaGetSofaDelays(SofaFile: TSofaFile): array of Float;
begin
for var Index := 0 to SofaFile.DelayCount - 1 do
Result.Add(SofaFile.Delay[Index]);
end;
function sofaGetImpulseResponses(SofaFile: TSofaFile): array of array of JFloat64Array;
begin
Result.SetLength(SofaFile.NumberOfMeasurements);
for var MeasurementIndex := 0 to SofaFile.NumberOfMeasurements - 1 do
begin
Result[MeasurementIndex].SetLength(SofaFile.NumberOfReceivers);
for var ReceiverIndex := 0 to SofaFile.NumberOfReceivers - 1 do
Result[MeasurementIndex, ReceiverIndex] := SofaFile.ImpulseResponse[MeasurementIndex, ReceiverIndex]
end;
end;
function sofaGetFilterCartesian(SofaFile: TSofaFile; X, Y, Z: Float): JSofaFilter;
begin
var Index := SofaFile.GetClosestIndexCartesian(X, Y, Z);
Result := JSofaFilter(class
SampleRate = SofaFile.SampleRate[0];
Left = SofaFile.ImpulseResponse[Index, 0];
Right = SofaFile.ImpulseResponse[Index, 1];
LeftDelay = SofaFile.Delay[0];
RightDelay = SofaFile.Delay[1];
end);
end;
function sofaGetFilterSpherical(SofaFile: TSofaFile; Phi, Theta, Radius: Float): JSofaFilter;
begin
var Index := SofaFile.GetClosestIndexSpherical(Phi, Theta, Radius);
Result := JSofaFilter(class
SampleRate = SofaFile.SampleRate[0];
Left = SofaFile.ImpulseResponse[Index, 0];
Right = SofaFile.ImpulseResponse[Index, 1];
LeftDelay = SofaFile.Delay[0];
RightDelay = SofaFile.Delay[1];
end);
end;
end. |
{$INCLUDE ..\cDefines.inc}
unit cRegistry;
{ }
{ Windows Registry functions v3.01 }
{ }
{ This unit is copyright © 2002-2004 by David J Butler }
{ }
{ This unit is part of Delphi Fundamentals. }
{ Its original file name is cRegistry.pas }
{ The latest version is available from the Fundamentals home page }
{ http://fundementals.sourceforge.net/ }
{ }
{ I invite you to use this unit, free of charge. }
{ I invite you to distibute this unit, but it must be for free. }
{ I also invite you to contribute to its development, }
{ but do not distribute a modified copy of this file. }
{ }
{ A forum is available on SourceForge for general discussion }
{ http://sourceforge.net/forum/forum.php?forum_id=2117 }
{ }
{ Description: }
{ Windows Registry functions. }
{ }
{ Revision history: }
{ 2002/09/22 3.00 Created cRegistry unit from cWindows. }
{ 2002/12/08 3.01 Small revisions. }
{ }
interface
uses
{ Delphi }
Windows,
{ Fundamentals }
cUtils;
{ }
{ Registry functions }
{ }
procedure SplitRegName(const Name: String; var Key, ValueName: String);
{ Exists }
function RegKeyExists(const RootKey: HKEY; const Key: String): Boolean;
function RegValueExists(const RootKey: HKEY; const Key, Name: String): Boolean;
{ Set }
function RegSetValue(const RootKey: HKEY; const Key, Name: String;
const ValueType: Cardinal; const Value: Pointer;
const ValueSize: Integer): Boolean; overload;
function RegSetValue(const RootKey: HKEY; const Name: String;
const ValueType: Cardinal; const Value: Pointer;
const ValueSize: Integer): Boolean; overload;
function SetRegistryString(const RootKey: HKEY; const Key: String;
const Name: String; const Value: String): Boolean; overload;
function SetRegistryString(const RootKey: HKEY; const Name: String;
const Value: String): Boolean; overload;
function SetRegistryDWord(const RootKey: HKEY; const Name: String;
const Value: LongWord): Boolean;
function SetRegistryBinary(const RootKey: HKEY; const Name: String;
const Value; const ValueSize: Integer): Boolean;
{ Get }
function RegGetValue(const RootKey: HKEY; const Key, Name: String;
const ValueType: Cardinal; var RegValueType: Cardinal;
var ValueBuf: Pointer; var ValueSize: Integer): Boolean; overload;
function RegGetValue(const RootKey: HKEY; const Name: String;
const ValueType: Cardinal; var RegValueType: Cardinal;
var ValueBuf: Pointer; var ValueSize: Integer): Boolean; overload;
function GetRegistryString(const RootKey: HKEY; const Key, Name: String): String; overload;
function GetRegistryString(const RootKey: HKEY; const Name: String): String; overload;
function GetRegistryDWord(const RootKey: HKEY; const Key, Name: String): LongWord;
{ Delete }
function DeleteRegistryValue(const RootKey: HKEY; const Key, Name: String): Boolean;
function DeleteRegistryKey(const RootKey: HKEY; const Key: String): Boolean;
{ Remote Registries }
function ConnectRegistry(const MachineName: String; const RootKey: HKEY;
var RemoteKey: HKEY): Boolean;
function DisconnectRegistry(const RemoteKey: HKEY): Boolean;
{ Enumerate }
function EnumRegistryValues(const RootKey: HKEY; const Name: String;
var ValueList: StringArray): Boolean;
function EnumRegistryKeys(const RootKey: HKEY; const Name: String;
var KeyList: StringArray): Boolean;
implementation
uses
{ Delphi }
SysUtils,
{ Fundamentals }
cStrings;
{ }
{ Registry }
{ }
procedure SplitRegName(const Name: String; var Key, ValueName: String);
var S : String;
I : Integer;
begin
S := StrExclSuffix(StrExclPrefix(Name, '\'), '\');
I := PosChar('\', S);
if I <= 0 then
begin
Key := S;
ValueName := '';
exit;
end;
Key := CopyLeft(S, I - 1);
ValueName := CopyFrom(S, I + 1);
end;
{ Exists }
function RegKeyExists(const RootKey: HKEY; const Key: String): Boolean;
var Handle : HKEY;
begin
if RegOpenKeyEx(RootKey, PChar(Key), 0, KEY_READ, Handle) = ERROR_SUCCESS then
begin
Result := True;
RegCloseKey(Handle);
end else
Result := False;
end;
function RegValueExists(const RootKey: HKEY; const Key, Name: String): Boolean;
var Handle : HKEY;
begin
if RegOpenKeyEx(RootKey, PChar(Key), 0, KEY_READ, Handle) = ERROR_SUCCESS then
begin
Result := RegQueryValueEx(Handle, Pointer(Name), nil, nil, nil, nil) = ERROR_SUCCESS;
RegCloseKey(Handle);
end else
Result := False;
end;
{ Set }
function RegSetValue(const RootKey: HKEY; const Key, Name: String;
const ValueType: Cardinal; const Value: Pointer;
const ValueSize: Integer): Boolean;
var D : DWORD;
Handle : HKEY;
begin
Result := False;
if ValueSize < 0 then
exit;
if RegCreateKeyEx(RootKey, PChar(Key), 0, nil, REG_OPTION_NON_VOLATILE,
KEY_WRITE, nil, Handle, @D) <> ERROR_SUCCESS then
exit;
Result := RegSetValueEx(Handle, Pointer(Name), 0, ValueType, Value, ValueSize) = ERROR_SUCCESS;
RegCloseKey(Handle);
end;
function RegSetValue(const RootKey: HKEY; const Name: String;
const ValueType: Cardinal; const Value: Pointer;
const ValueSize: Integer): Boolean;
var K, N : String;
begin
SplitRegName(Name, K, N);
Result := RegSetValue(RootKey, K, N, ValueType, Value, ValueSize);
end;
function SetRegistryString(const RootKey: HKEY; const Key: String;
const Name: String; const Value: String): Boolean;
begin
Result := RegSetValue(RootKey, Key, Name, REG_SZ, PChar(Value), Length(Value) + 1);
end;
function SetRegistryString(const RootKey: HKEY; const Name: String;
const Value: String): Boolean;
begin
Result := RegSetValue(RootKey, Name, REG_SZ, PChar(Value), Length(Value) + 1);
end;
function SetRegistryDWord(const RootKey: HKEY; const Name: String;
const Value: LongWord): Boolean;
begin
Result := RegSetValue(RootKey, Name, REG_DWORD, @Value, Sizeof(LongWord));
end;
function SetRegistryBinary(const RootKey: HKEY; const Name: String; const Value;
const ValueSize: Integer): Boolean;
begin
Result := RegSetValue(RootKey, Name, REG_BINARY, @Value, ValueSize);
end;
{ Get }
function RegGetValue(const RootKey: HKEY; const Key, Name: String;
const ValueType: Cardinal; var RegValueType: Cardinal;
var ValueBuf: Pointer; var ValueSize: Integer): Boolean;
var Handle : HKEY;
Buf : Pointer;
BufSize : Cardinal;
begin
Result := False;
ValueSize := 0;
ValueBuf := nil;
if RegOpenKeyEx(RootKey, PChar(Key), 0, KEY_READ, Handle) <> ERROR_SUCCESS then
exit;
BufSize := 0;
RegQueryValueEx(Handle, Pointer(Name), nil, @RegValueType, nil, @BufSize);
if BufSize <= 0 then
exit;
GetMem(Buf, BufSize);
if RegQueryValueEx(Handle, Pointer(Name), nil, @RegValueType, Buf, @BufSize) = ERROR_SUCCESS then
begin
ValueBuf := Buf;
ValueSize := Integer(BufSize);
Result := True;
end;
if not Result then
FreeMem(Buf);
RegCloseKey(Handle);
end;
function RegGetValue(const RootKey: HKEY; const Name: String;
const ValueType: Cardinal; var RegValueType: Cardinal;
var ValueBuf: Pointer; var ValueSize: Integer): Boolean;
var K, N : String;
begin
SplitRegName(Name, K, N);
Result := RegGetValue(RootKey, K, N, ValueType, RegValueType, ValueBuf, ValueSize);
end;
function GetRegistryString(const RootKey: HKEY; const Key, Name: String): String;
var Buf : Pointer;
Size : Integer;
VType : Cardinal;
begin
Result := '';
if not RegGetValue(RootKey, Key, Name, REG_SZ, VType, Buf, Size) then
exit;
if (VType = REG_DWORD) and (Size >= Sizeof(LongWord)) then
Result := IntToStr(PLongWord(Buf)^) else
if Size > 0 then
begin
SetLength(Result, Size - 1);
MoveMem(Buf^, Pointer(Result)^, Size - 1);
end;
FreeMem(Buf);
end;
function GetRegistryString(const RootKey: HKEY; const Name: String): String;
var K, N : String;
begin
SplitRegName(Name, K, N);
Result := GetRegistryString(RootKey, K, N);
end;
function GetRegistryDWord(const RootKey: HKEY; const Key, Name: String): LongWord;
var Buf : Pointer;
Size : Integer;
VType : Cardinal;
begin
Result := 0;
if not RegGetValue(RootKey, Key, Name, REG_DWORD, VType, Buf, Size) then
exit;
if (VType = REG_DWORD) and (Size >= Sizeof(LongWord)) then
Result := PLongWord(Buf)^;
FreeMem(Buf);
end;
{ Delete }
function DeleteRegistryValue(const RootKey: HKEY; const Key, Name: String): Boolean;
var Handle : HKEY;
begin
if RegOpenKeyEx(RootKey, PChar(Key), 0, KEY_WRITE, Handle) = ERROR_SUCCESS then
begin
Result := RegDeleteValue(Handle, Pointer(Name)) = ERROR_SUCCESS;
RegCloseKey(Handle);
end else
Result := False;
end;
function DeleteRegistryKey(const RootKey: HKEY; const Key: String): Boolean;
var Handle : HKEY;
K, N : String;
begin
SplitRegName(Key, K, N);
if RegOpenKeyEx(RootKey, PChar(K), 0, KEY_WRITE, Handle) = ERROR_SUCCESS then
begin
Result := RegDeleteKey(Handle, Pointer(N)) = ERROR_SUCCESS;
RegCloseKey(Handle);
end else
Result := False;
end;
{ Remote Registries }
function ConnectRegistry(const MachineName: String; const RootKey: HKEY;
var RemoteKey: HKEY): Boolean;
begin
Result := RegConnectRegistry(PChar(MachineName), RootKey, RemoteKey) = ERROR_SUCCESS;
end;
function DisconnectRegistry(const RemoteKey: HKEY): Boolean;
begin
Result := RegCloseKey(RemoteKey) = ERROR_SUCCESS;
end;
{ Enumerate }
function RegEnum(const RootKey: HKEY; const Name: String;
var ResultList: StringArray; const DoKeys: Boolean): Boolean;
var Buf : Array[0..2047] of Char;
BufSize : Cardinal;
I : Integer;
Res : Integer;
S : String;
Handle : HKEY;
begin
ResultList := nil;
Result := RegOpenKeyEx(RootKey, PChar(Name), 0, KEY_READ, Handle) = ERROR_SUCCESS;
if not Result then
exit;
I := 0;
Repeat
BufSize := Sizeof(Buf);
if DoKeys then
Res := RegEnumKeyEx(Handle, I, @Buf[0], BufSize, nil, nil, nil, nil)
else
Res := RegEnumValue(Handle, I, @Buf[0], BufSize, nil, nil, nil, nil);
if Res = ERROR_SUCCESS then
begin
SetLength(S, BufSize);
if BufSize > 0 then
MoveMem(Buf[0], Pointer(S)^, BufSize);
Append(ResultList, S);
Inc(I);
end;
Until Res <> ERROR_SUCCESS;
RegCloseKey(Handle);
end;
function EnumRegistryValues(const RootKey: HKEY; const Name: String;
var ValueList: StringArray): Boolean;
begin
Result := RegEnum(RootKey, Name, ValueList, False);
end;
function EnumRegistryKeys(const RootKey: HKEY; const Name: String;
var KeyList: StringArray): Boolean;
begin
Result := RegEnum(RootKey, Name, KeyList, True);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXMetaDataWriter;
interface
uses
Data.DBXCommon,
Data.DBXCommonTable,
Data.DBXMetaDataReader,
Data.DBXPlatform,
System.SysUtils;
type
TDBXAlterTableOperation = class
public
const NoSupport = 0;
const RenameTable = 1;
const RenameTableTo = 2;
const DropColumn = 4;
const AddColumn = 8;
const AddColumnWithPosition = 16;
const ChangeDefaultValue = 32;
const DropDefaultValue = 64;
const SetNullable = 128;
const DropNullable = 256;
const ChangeColumnType = 512;
const AddAutoincrement = 1024;
const DropAutoincrement = 2048;
const ChangeColumnPosition = 4096;
const RenameColumn = 8192;
const FullAlterSupport = 16383;
end;
TDBXMetaDataWriter = class abstract
public
procedure Open; virtual; abstract;
procedure MakeSqlCreate(const Buffer: TStringBuilder; const Item: TDBXTableRow; const Parts: TDBXTable); overload; virtual; abstract;
procedure MakeSqlCreate(const Buffer: TStringBuilder;
const TableItem: TDBXTableRow; const TableParts: TDBXTable;
const ViewItem: TDBXTableRow; const ViewParts: TDBXTable;
const SynonymItem: TDBXTableRow; const SynonymParts: TDBXTable;
const IndexesItem: TDBXTableRow; const IndexesParts: TDBXTable;
const ForeignKeysItem: TDBXTableRow; const ForeignKeysParts: TDBXTable); overload; virtual; abstract;
procedure MakeSqlAlter(const Buffer: TStringBuilder; const Item: TDBXTableRow; const Parts: TDBXTable); virtual; abstract;
procedure MakeSqlDrop(const Buffer: TStringBuilder; const Item: TDBXTableRow); virtual; abstract;
procedure MakeSqlIdentifier(const Buffer: TStringBuilder; const Identifier: string); virtual; abstract;
function CheckColumnSupported(const Column: TDBXTableRow): Boolean; virtual; abstract;
function GetSqlQuotedIdentifier(const UnquotedIdentifier: string): string; virtual; abstract;
function GetSqlUnQuotedIdentifier(const QuotedIdentifier: string): string; virtual; abstract;
protected
procedure SetContext(const Context: TDBXProviderContext); virtual; abstract;
function GetContext: TDBXProviderContext; virtual; abstract;
function GetMetaDataReader: TDBXMetaDataReader; virtual; abstract;
function GetSqlRenameTable: string; virtual; abstract;
function GetSqlAutoIncrementInserts: string; virtual; abstract;
function GetSqlAutoIncrementKeyword: string; virtual; abstract;
function GetSqlKeyGeneratedIndexName: string; virtual; abstract;
function GetAlterTableSupport: Integer; virtual; abstract;
function IsCatalogsSupported: Boolean; virtual; abstract;
function IsSchemasSupported: Boolean; virtual; abstract;
function IsMultipleStatementsSupported: Boolean; virtual; abstract;
function IsIndexNamesGlobal: Boolean; virtual; abstract;
function IsDescendingIndexConstraintsSupported: Boolean; virtual; abstract;
function IsSerializedIsolationSupported: Boolean; virtual; abstract;
function IsDDLTransactionsSupported: Boolean; virtual; abstract;
function IsMixed_DDL_DML_Supported: Boolean; virtual; abstract;
public
property Context: TDBXProviderContext read GetContext write SetContext;
property MetaDataReader: TDBXMetaDataReader read GetMetaDataReader;
property SqlRenameTable: string read GetSqlRenameTable;
property SqlAutoIncrementInserts: string read GetSqlAutoIncrementInserts;
property SqlAutoIncrementKeyword: string read GetSqlAutoIncrementKeyword;
property SqlKeyGeneratedIndexName: string read GetSqlKeyGeneratedIndexName;
property AlterTableSupport: Integer read GetAlterTableSupport;
property CatalogsSupported: Boolean read IsCatalogsSupported;
property SchemasSupported: Boolean read IsSchemasSupported;
property MultipleStatementsSupported: Boolean read IsMultipleStatementsSupported;
property IndexNamesGlobal: Boolean read IsIndexNamesGlobal;
property DescendingIndexConstraintsSupported: Boolean read IsDescendingIndexConstraintsSupported;
property SerializedIsolationSupported: Boolean read IsSerializedIsolationSupported;
property DDLTransactionsSupported: Boolean read IsDDLTransactionsSupported;
property Mixed_DDL_DML_Supported: Boolean read IsMixed_DDL_DML_Supported;
end;
TDBXBaseMetaDataWriter = class(TDBXMetaDataWriter)
public
procedure Open; override;
destructor Destroy; override;
procedure MakeSqlCreate(const Buffer: TStringBuilder; const Item: TDBXTableRow; const Parts: TDBXTable); overload; override;
procedure MakeSqlCreate(const Buffer: TStringBuilder;
const TableItem: TDBXTableRow; const TableParts: TDBXTable;
const ViewItem: TDBXTableRow; const ViewParts: TDBXTable;
const SynonymItem: TDBXTableRow; const SynonymParts: TDBXTable;
const IndexesItem: TDBXTableRow; const IndexesParts: TDBXTable;
const ForeignKeysItem: TDBXTableRow; const ForeignKeysParts: TDBXTable); overload; override;
procedure MakeSqlAlter(const Buffer: TStringBuilder; const Item: TDBXTableRow; const Parts: TDBXTable); override;
procedure MakeSqlDrop(const Buffer: TStringBuilder; const Item: TDBXTableRow); override;
function CheckColumnSupported(const Column: TDBXTableRow): Boolean; override;
function GetSqlQuotedIdentifier(const UnquotedIdentifier: string): string; override;
function GetSqlUnQuotedIdentifier(const QuotedIdentifier: string): string; override;
procedure MakeSqlIdentifier(const Buffer: TStringBuilder; const Identifier: string); override;
protected
procedure SetContext(const Context: TDBXProviderContext); override;
function GetContext: TDBXProviderContext; override;
function GetMetaDataReader: TDBXMetaDataReader; override;
function IsCatalogsSupported: Boolean; override;
function IsSchemasSupported: Boolean; override;
function IsMultipleStatementsSupported: Boolean; override;
function IsIndexNamesGlobal: Boolean; override;
function IsDescendingIndexConstraintsSupported: Boolean; override;
function IsSerializedIsolationSupported: Boolean; override;
function IsDDLTransactionsSupported: Boolean; override;
function IsMixed_DDL_DML_Supported: Boolean; override;
function GetAlterTableSupport: Integer; override;
function GetSqlAutoIncrementKeyword: string; override;
function GetSqlKeyGeneratedIndexName: string; override;
function GetSqlAutoIncrementInserts: string; override;
function GetSqlRenameTable: string; override;
procedure MakeSqlObjectName(const Buffer: TStringBuilder; const CatalogName: string; const SchemaName: string; const ObjectName: string); virtual;
procedure MakeSqlNullable(const Buffer: TStringBuilder; const Column: TDBXTableRow); virtual;
procedure MakeSqlDataType(const Buffer: TStringBuilder; const TypeName: string; const ColumnRow: TDBXTableRow); overload; virtual;
procedure MakeSqlDataType(const Buffer: TStringBuilder; const DataType: TDBXDataTypeDescription; const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s); overload; virtual;
function FindDataType(const InTypeName: string; const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s): TDBXDataTypeDescription; virtual;
function FindTypeName(const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s; const FailIfNotFound: Boolean): string; virtual;
function FindSimpleColumnTypeMatch(const ColumnRow: TDBXTableRow; const FailIfNotFound: Boolean): string; virtual;
function FindBooleanTypeName(const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s; const FailIfNotFound: Boolean): string; virtual;
function FindStringOrBinaryTypeName(const ColumnRow: TDBXTableRow; const FailIfNotFound: Boolean): string; virtual;
function FindIntegerTypeName(const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s; const FailIfNotFound: Boolean): string; virtual;
function FindDecimalTypeName(const ColumnRow: TDBXTableRow; const FailIfNotFound: Boolean): string; virtual;
function FindFloatTypeName(const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s; const FailIfNotFound: Boolean): string; virtual;
function FindDateTimeTypeName(const ColumnRow: TDBXTableRow; const FailIfNotFound: Boolean): string; virtual;
procedure MakeSqlColumnTypeCast(const Buffer: TStringBuilder; const Column: TDBXTable); virtual;
function CanCreateIndexAsKey(const Index: TDBXTableRow; const IndexColumns: TDBXTable): Boolean; virtual;
procedure MakeSqlCreateIndex(const Buffer: TStringBuilder; const Index: TDBXTableRow; const IndexColumns: TDBXTable); virtual;
procedure MakeSqlDropIndex(const Buffer: TStringBuilder; const Index: TDBXTableRow); virtual;
procedure MakeSqlCreateKey(const Buffer: TStringBuilder; const Index: TDBXTableRow; const IndexColumns: TDBXTable); virtual;
procedure MakeSqlConstraintName(const Buffer: TStringBuilder; const Constraint: TDBXTableRow);
procedure MakeSqlAlterTablePrefix(const Buffer: TStringBuilder; const Item: TDBXTableRow); virtual;
procedure MakeSqlCreateIndexColumnList(const Buffer: TStringBuilder; const IndexColumns: TDBXTable); virtual;
procedure MakeSqlDropSecondaryIndex(const Buffer: TStringBuilder; const Index: TDBXTableRow); virtual;
procedure MakeSqlForeignKeySyntax(const Buffer: TStringBuilder; const ForeignKey: TDBXTableRow; const ForeignKeyColumns: TDBXTable);
procedure MakeSqlCreateForeignKey(const Buffer: TStringBuilder; const ForeignKey: TDBXTableRow; const ForeignKeyColumns: TDBXTable); virtual;
procedure MakeSqlDropForeignKey(const Buffer: TStringBuilder; const ForeignKey: TDBXTableRow); virtual;
private
procedure MakeSqlCreateTable(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Columns: TDBXTable);
procedure MakeSqlCreateTableWithIndex(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Columns: TDBXTable; const Index: TDBXTableRow; const IndexColumns: TDBXTable);
procedure MakeSqlAlterTable(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Columns: TDBXTable);
function SupportedTableAlteration(const Operation: Integer): Boolean;
function MakeSqlFullAlterTable(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Columns: TDBXTable): Boolean;
function MakeSqlTableRename(const Buffer: TStringBuilder; const CatalogName: string; const SchemaName: string; const TableName: string; const OldCatalogName: string; const OldSchemaName: string; const OldTableName: string): Boolean; overload;
function MakeSqlColumnRename(const Buffer: TStringBuilder; const ColumnName: string; const CatalogName: string; const SchemaName: string; const TableName: string; const OldColumnName: string): Boolean;
procedure MakeSqlColumnDefinition(const Buffer: TStringBuilder; const Column: TDBXTableRow);
procedure MakeSqlDefaultValue(const Buffer: TStringBuilder; const DefaultValue: string; const TypeName: string);
function RemoveMarkersForNullValues(const InFormat: string; const Values: TDBXStringArray): string;
function ErrorTypeNameNotFound(const ColumnRow: TDBXTableRow): Exception;
function CalcPrecisionColumnType(const ColumnType: Integer; const UnsignedOption: Boolean): Integer;
function CalcDecimalPrecision(const ColumnType: Integer): Integer;
function CalcBinaryPrecision(const ColumnType: Integer): Integer;
function IsSignedInteger(const ColumnType: Integer): Boolean;
function GetDefaultFloatPrecision(const ColumnType: Integer): Integer;
function AddToExternalStatements(const InExternalStatements: TStringBuilder; const Buffer: TStringBuilder; const StartPosition: Integer): TStringBuilder;
function IsValidSqlIdentifier(const Identifier: string): Boolean;
function IsReservedWord(const Identifier: string): Boolean;
function IsLetter(const Ch: WideChar; const UpperOK: Boolean; const LowerOK: Boolean): Boolean;
function IsDigit(const Ch: WideChar): Boolean;
procedure MakeSqlTableReplacement(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Columns: TDBXTable);
function CopyColumns(const ColumnTable: TDBXTable): TDBXTable;
function CopyTable(const Table: TDBXTableRow; const TempTableName: string): TDBXTable;
function ComputeColumnMap(const Columns: TDBXTable): TDBXProperties;
function GetDefaults(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable;
function GetIndexes(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable;
function GetIndexColumns(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable;
function GetForeignKeyColumns(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable;
procedure RemoveForeignKeyGeneratedIndexes(const Table: TDBXTableRow; const Indexes: TDBXTable; const IndexColumns: TDBXTable; const ForeignKeyColumns: TDBXTable);
procedure DropAllConstraints(const Buffer: TStringBuilder; const Defaults: TDBXTable; const Indexes: TDBXTable; const ForeignKeys: TDBXTable);
procedure CreateTempOutputTable(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Columns: TDBXTable; const TempTableName: string);
procedure SetIdentityInsert(const Buffer: TStringBuilder; const CatalogName: string; const SchemaName: string; const TableName: string; const bOn: Boolean);
function CheckForAutoIncrement(const Columns: TDBXTable): Boolean;
procedure InsertValuesFromOldTable(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Columns: TDBXTable; const TempTableName: string);
procedure MakeSqlDropTable(const Buffer: TStringBuilder; const Table: TDBXTableRow);
procedure ReplaceParameter(const Buffer: TStringBuilder; const Start: Integer; const InParameter: string; const Replacement: string);
procedure MakeSqlTableRename(const Buffer: TStringBuilder; const CatalogName: string; const SchemaName: string; const TableName: string; const NewTableName: string); overload;
procedure CopyRow(const Source: TDBXTableRow; const Target: TDBXTable; const Columns: Integer);
function Compare(const Table: TDBXTable; const InStart: Integer; const Row: TDBXTableRow; const InRowStart: Integer; const Columns: Integer): Boolean;
function SameConstraint(const Table: TDBXTable; const Row: TDBXTableRow; const Columns: Integer): Boolean;
procedure MapTable(const Item: TDBXTable; const Table: TDBXTableRow);
function MapColumn(const Parts: TDBXTable; const Table: TDBXTableRow; const ColumnMap: TDBXProperties; const ColIndex: Integer; const IdColumns: Integer; const DroppedColumn: string): string;
procedure CreateConstraints(const Buffer: TStringBuilder; const Columns: TDBXValueTypeArray; const Constraints: TDBXTable; const ConstraintColumns: TDBXTable; const CollectionName: string; const IdColumns: Integer; const ItemColumns: Integer; const PartColumns: Integer; const Table: TDBXTableRow; const ColumnMap: TDBXProperties; const ColIndex1: Integer; const ColIndex2: Integer);
procedure CreateIndices(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Indexes: TDBXTable; const IndexColumns: TDBXTable; const ColumnMap: TDBXProperties);
procedure CreateForeignKeys(const Buffer: TStringBuilder; const Table: TDBXTableRow; const ForeignKeyColumns: TDBXTable; const ColumnMap: TDBXProperties);
procedure MakeSqlCreateSecondaryIndex(const Buffer: TStringBuilder; const Index: TDBXTableRow; const IndexColumns: TDBXTable);
procedure MakeSqlCreateConstraint(const Buffer: TStringBuilder; const Constraint: TDBXTableRow);
procedure MakeSqlDropConstraint(const Buffer: TStringBuilder; const Constraint: TDBXTableRow);
procedure MakeSqlCreateView(const Buffer: TStringBuilder; const View: TDBXTableRow; const Columns: TDBXTable);
procedure MakeSqlAlterView(const Buffer: TStringBuilder; const View: TDBXTableRow; const Columns: TDBXTable);
procedure MakeSqlDropView(const Buffer: TStringBuilder; const View: TDBXTableRow);
procedure MakeSqlCreateSynonym(const Buffer: TStringBuilder; const Synonym: TDBXTableRow; const Columns: TDBXTable);
procedure MakeSqlAlterSynonym(const Buffer: TStringBuilder; const Synonym: TDBXTableRow; const Columns: TDBXTable);
procedure MakeSqlDropSynonym(const Buffer: TStringBuilder; const Synonym: TDBXTableRow);
protected
[Weak]FContext: TDBXProviderContext;
FReader: TDBXBaseMetaDataReader;
FReservedWords: TDBXTable;
private
const Requirement = 1000;
const Desireable = 100;
const TieBreaker1 = 1;
const TieBreaker2 = 2;
const TieBreaker3 = 4;
const TieBreaker4 = 8;
const TieBreaker5 = 16;
const TieBreaker6 = 32;
end;
TDBXSQL = class
public
const Add = 'ADD';
const Alter = 'ALTER';
const cAs = 'AS';
const Binary = 'BINARY';
const Cast = 'CAST';
const Char = 'CHAR';
const CloseBrace = '}';
const CloseParen = ')';
const Colon = ':';
const Column = 'COLUMN';
const Comma = ',';
const Constraint = 'CONSTRAINT';
const Convert = 'CONVERT';
const Create = 'CREATE';
const CurrentTimestamp = 'CURRENT_TIMESTAMP';
const Date = 'DATE';
const Datetime = 'DATETIME';
const Decimal = 'DECIMAL';
const Default = 'DEFAULT';
const Descending = 'DESC';
const Dot = '.';
const DoubleQuote = '"';
const Drop = 'DROP';
const Empty = '';
const cFor = 'FOR';
const Foreign = 'FOREIGN';
const From = 'FROM';
const cFunction = 'FUNCTION';
const Index = 'INDEX';
const Insert = 'INSERT';
const Into = 'INTO';
const Key = 'KEY';
const LineComment = '//';
const Makedate = 'MAKEDATE';
const Nl = #$a;
const cNot = 'NOT';
const Nullable = 'NULL';
const Off = 'OFF';
const cOn = 'ON';
const OpenBrace = '{';
const OpenParen = '(';
const Position = 'POSITION';
const Primary = 'PRIMARY';
const Proc = 'PROCEDURE';
const Quote = '''';
const References = 'REFERENCES';
const Rename = 'RENAME';
const Result = 'RESULT';
const Returns = 'RETURNS';
const Select = 'SELECT';
const Semicolon = ';';
const cSet = 'SET';
const Signed = 'SIGNED';
const Space = ' ';
const Spacing = ' ';
const Synonym = 'SYNONYM';
const Table = 'TABLE';
const Temp = 'TEMP_';
const Time = 'TIME';
const cTo = 'TO';
const cType = 'TYPE';
const FYear = 'year';
const Unique = 'UNIQUE';
const View = 'VIEW';
end;
implementation
uses
Data.DBXMetaDataNames,
Data.DBXMetaDataUtil,
System.StrUtils,
Data.DBXCommonResStrs
{$IFDEF MACOS}
, Macapi.CoreFoundation
{$ENDIF MACOS}
;
procedure TDBXBaseMetaDataWriter.Open;
begin
end;
destructor TDBXBaseMetaDataWriter.Destroy;
begin
FreeAndNil(FReservedWords);
FreeAndNil(FReader);
inherited Destroy;
end;
procedure TDBXBaseMetaDataWriter.SetContext(const Context: TDBXProviderContext);
begin
FContext := Context;
if FReader <> nil then
FReader.Context := Context;
end;
function TDBXBaseMetaDataWriter.GetContext: TDBXProviderContext;
begin
Result := FContext;
end;
function TDBXBaseMetaDataWriter.GetMetaDataReader: TDBXMetaDataReader;
begin
Result := FReader;
end;
procedure TDBXBaseMetaDataWriter.MakeSqlCreate(const Buffer: TStringBuilder; const Item: TDBXTableRow; const Parts: TDBXTable);
var
CollectionName: string;
begin
CollectionName := Item.DBXTableName;
if (CollectionName = TDBXMetaDataCollectionName.Tables) then
MakeSqlCreateTable(Buffer, Item, Parts)
else if (CollectionName = TDBXMetaDataCollectionName.Views) then
MakeSqlCreateView(Buffer, Item, Parts)
else if (CollectionName = TDBXMetaDataCollectionName.Synonyms) then
MakeSqlCreateSynonym(Buffer, Item, Parts)
else if (CollectionName = TDBXMetaDataCollectionName.Indexes) then
MakeSqlCreateIndex(Buffer, Item, Parts)
else if (CollectionName = TDBXMetaDataCollectionName.ForeignKeys) then
MakeSqlCreateForeignKey(Buffer, Item, Parts)
else
raise Exception.Create(SUnsupportedOperation);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlCreate(const Buffer: TStringBuilder;
const TableItem: TDBXTableRow; const TableParts: TDBXTable;
const ViewItem: TDBXTableRow; const ViewParts: TDBXTable;
const SynonymItem: TDBXTableRow; const SynonymParts: TDBXTable;
const IndexesItem: TDBXTableRow; const IndexesParts: TDBXTable;
const ForeignKeysItem: TDBXTableRow; const ForeignKeysParts: TDBXTable);
function CollectionName(Item: TDBXTableRow): string;
begin
Result := Item.DBXTableName;
end;
begin
if (TableItem <> nil) and (CollectionName(TableItem) = TDBXMetaDataCollectionName.Tables) then
begin
if (IndexesItem <> nil) and (CollectionName(IndexesItem) = TDBXMetaDataCollectionName.Indexes) then
MakeSqlCreateTableWithIndex(Buffer, TableItem, TableParts, IndexesItem, IndexesParts)
else
MakeSqlCreate(Buffer, TableItem, TableParts);
end
else if (IndexesItem <> nil) and (CollectionName(IndexesItem) = TDBXMetaDataCollectionName.Indexes) then
MakeSqlCreate(Buffer, IndexesItem, IndexesParts);
if ViewItem <> nil then
MakeSqlCreate(Buffer, ViewItem, ViewParts);
if SynonymItem <> nil then
MakeSqlCreate(Buffer, SynonymItem, SynonymParts);
if ForeignKeysItem <> nil then
MakeSqlCreate(Buffer, ForeignKeysItem, ForeignKeysParts);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlAlter(const Buffer: TStringBuilder; const Item: TDBXTableRow; const Parts: TDBXTable);
var
CollectionName: string;
begin
CollectionName := Item.DBXTableName;
if (CollectionName = TDBXMetaDataCollectionName.Tables) then
MakeSqlAlterTable(Buffer, Item, Parts)
else if (CollectionName = TDBXMetaDataCollectionName.Views) then
MakeSqlAlterView(Buffer, Item, Parts)
else if (CollectionName = TDBXMetaDataCollectionName.Synonyms) then
MakeSqlAlterSynonym(Buffer, Item, Parts)
else if (CollectionName = TDBXMetaDataCollectionName.Indexes) then
begin
MakeSqlDropIndex(Buffer, Item.OriginalRow);
MakeSqlCreateIndex(Buffer, Item, Parts);
end
else if (CollectionName = TDBXMetaDataCollectionName.ForeignKeys) then
begin
MakeSqlDropForeignKey(Buffer, Item.OriginalRow);
MakeSqlCreateForeignKey(Buffer, Item, Parts);
end
else
raise Exception.Create(SUnsupportedOperation);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlDrop(const Buffer: TStringBuilder; const Item: TDBXTableRow);
var
CollectionName: string;
begin
CollectionName := Item.DBXTableName;
if (CollectionName = TDBXMetaDataCollectionName.Tables) then
MakeSqlDropTable(Buffer, Item)
else if (CollectionName = TDBXMetaDataCollectionName.Views) then
MakeSqlDropView(Buffer, Item)
else if (CollectionName = TDBXMetaDataCollectionName.Synonyms) then
MakeSqlDropSynonym(Buffer, Item)
else if (CollectionName = TDBXMetaDataCollectionName.Indexes) then
MakeSqlDropIndex(Buffer, Item)
else if (CollectionName = TDBXMetaDataCollectionName.ForeignKeys) then
MakeSqlDropForeignKey(Buffer, Item)
else
raise Exception.Create(SUnsupportedOperation);
end;
function TDBXBaseMetaDataWriter.CheckColumnSupported(const Column: TDBXTableRow): Boolean;
begin
Result := (not FindTypeName(Column, nil, False).IsEmpty);
end;
function TDBXBaseMetaDataWriter.IsCatalogsSupported: Boolean;
begin
Result := False;
end;
function TDBXBaseMetaDataWriter.IsSchemasSupported: Boolean;
begin
Result := True;
end;
function TDBXBaseMetaDataWriter.IsMultipleStatementsSupported: Boolean;
begin
Result := False;
end;
function TDBXBaseMetaDataWriter.IsIndexNamesGlobal: Boolean;
begin
Result := False;
end;
function TDBXBaseMetaDataWriter.IsDescendingIndexConstraintsSupported: Boolean;
begin
Result := True;
end;
function TDBXBaseMetaDataWriter.IsSerializedIsolationSupported: Boolean;
begin
Result := True;
end;
function TDBXBaseMetaDataWriter.IsDDLTransactionsSupported: Boolean;
begin
Result := True;
end;
function TDBXBaseMetaDataWriter.IsMixed_DDL_DML_Supported: Boolean;
begin
Result := True;
end;
function TDBXBaseMetaDataWriter.GetAlterTableSupport: Integer;
begin
Result := TDBXAlterTableOperation.NoSupport;
end;
function TDBXBaseMetaDataWriter.GetSqlAutoIncrementKeyword: string;
begin
Result := NullString;
end;
function TDBXBaseMetaDataWriter.GetSqlKeyGeneratedIndexName: string;
begin
Result := NullString;
end;
function TDBXBaseMetaDataWriter.GetSqlQuotedIdentifier(const UnquotedIdentifier: string): string;
begin
Result := TDBXMetaDataUtil.QuoteIdentifier(UnquotedIdentifier, FReader.SqlIdentifierQuoteChar, FReader.SqlIdentifierQuotePrefix, FReader.SqlIdentifierQuoteSuffix);
end;
function TDBXBaseMetaDataWriter.GetSqlUnQuotedIdentifier(const QuotedIdentifier: string): string;
begin
Result := TDBXMetaDataUtil.UnquotedIdentifier(QuotedIdentifier, FReader.SqlIdentifierQuoteChar, FReader.SqlIdentifierQuotePrefix, FReader.SqlIdentifierQuoteSuffix);
end;
function TDBXBaseMetaDataWriter.GetSqlAutoIncrementInserts: string;
begin
Result := NullString;
end;
function TDBXBaseMetaDataWriter.GetSqlRenameTable: string;
begin
Result := NullString;
end;
procedure TDBXBaseMetaDataWriter.MakeSqlCreateTable(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Columns: TDBXTable);
var
Separator: string;
SecondSeparator: string;
CurrentColumns: TDBXTable;
begin
Buffer.Append(TDBXSQL.Create);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Table);
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, Table.Value[TDBXTablesIndex.CatalogName].GetWideString(NullString), Table.Value[TDBXTablesIndex.SchemaName].GetWideString(NullString), Table.Value[TDBXTablesIndex.TableName].GetWideString(NullString));
Buffer.Append(TDBXSQL.OpenParen);
Separator := TDBXSQL.Nl + TDBXSQL.Spacing;
SecondSeparator := TDBXSQL.Comma + TDBXSQL.Nl + TDBXSQL.Spacing;
CurrentColumns := Columns.CreateTableView(TDBXColumnsColumns.Ordinal);
CurrentColumns.First;
while CurrentColumns.InBounds do
begin
Buffer.Append(Separator);
MakeSqlColumnDefinition(Buffer, CurrentColumns);
Separator := SecondSeparator;
CurrentColumns.Next;
end;
FreeAndNil(CurrentColumns);
Buffer.Append(TDBXSQL.CloseParen);
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlCreateTableWithIndex(
const Buffer: TStringBuilder; const Table: TDBXTableRow;
const Columns: TDBXTable; const Index: TDBXTableRow;
const IndexColumns: TDBXTable);
var
Separator: string;
SecondSeparator: string;
CurrentColumns: TDBXTable;
LPrimary: Boolean;
LIndexName: string;
begin
LPrimary := Index.Value[TDBXIndexesIndex.IsPrimary].GetBoolean(False);
LIndexName := IndexColumns.Value[TDBXIndexColumnsIndex.ColumnName].GetString;
Buffer.Append(TDBXSQL.Create);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Table);
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, Table.Value[TDBXTablesIndex.CatalogName].GetWideString(NullString), Table.Value[TDBXTablesIndex.SchemaName].GetWideString(NullString), Table.Value[TDBXTablesIndex.TableName].GetWideString(NullString));
Buffer.Append(TDBXSQL.OpenParen);
Separator := TDBXSQL.Nl + TDBXSQL.Spacing;
SecondSeparator := TDBXSQL.Comma + TDBXSQL.Nl + TDBXSQL.Spacing;
CurrentColumns := Columns.CreateTableView(TDBXColumnsColumns.Ordinal);
CurrentColumns.First;
while CurrentColumns.InBounds do
begin
Buffer.Append(Separator);
MakeSqlColumnDefinition(Buffer, CurrentColumns);
if LPrimary and (CurrentColumns.Value[TDBXColumnsIndex.ColumnName].GetString = LIndexName) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Primary);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Key);
end;
Separator := SecondSeparator;
CurrentColumns.Next;
end;
FreeAndNil(CurrentColumns);
Buffer.Append(TDBXSQL.CloseParen);
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlAlterTable(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Columns: TDBXTable);
var
Original: TDBXTableRow;
CatalogName: string;
SchemaName: string;
TableName: string;
ColumnMap: TDBXProperties;
Defaults: TDBXTable;
ForeignKeyColumns: TDBXTable;
Indexes: TDBXTable;
IndexColumns: TDBXTable;
UseTransaction: Boolean;
FullAlterTable: Boolean;
Marker: Integer;
begin
// Blackfish, MSSQL, and ASA.
Original := Table.OriginalRow;
CatalogName := Original.Value[TDBXTablesIndex.CatalogName].GetWideString(NullString);
SchemaName := Original.Value[TDBXTablesIndex.SchemaName].GetWideString(NullString);
TableName := Original.Value[TDBXTablesIndex.TableName].GetWideString(NullString);
ColumnMap := ComputeColumnMap(Columns);
Defaults := GetDefaults(CatalogName, SchemaName, TableName);
ForeignKeyColumns := GetForeignKeyColumns(CatalogName, SchemaName, TableName);
UseTransaction := SerializedIsolationSupported;
if UseTransaction then
FContext.StartSerializedTransaction;
try
Indexes := GetIndexes(CatalogName, SchemaName, TableName);
IndexColumns := GetIndexColumns(CatalogName, SchemaName, TableName);
if UseTransaction then
FContext.Commit;
UseTransaction := False;
finally
if UseTransaction then
FContext.Rollback;
end;
RemoveForeignKeyGeneratedIndexes(Table, Indexes, IndexColumns, ForeignKeyColumns);
DropAllConstraints(Buffer, Defaults, Indexes, ForeignKeyColumns);
Buffer.Append(TDBXSQL.Nl);
FullAlterTable := (AlterTableSupport <> TDBXAlterTableOperation.NoSupport);
if FullAlterTable then
begin
Marker := Buffer.Length;
FullAlterTable := MakeSqlFullAlterTable(Buffer, Table, Columns);
if not FullAlterTable then
Buffer.Length := Marker;
end;
if not FullAlterTable then
MakeSqlTableReplacement(Buffer, Table, Columns);
Buffer.Append(TDBXSQL.Nl);
CreateIndices(Buffer, Table, Indexes, IndexColumns, ColumnMap);
CreateForeignKeys(Buffer, Table, ForeignKeyColumns, ColumnMap);
FreeAndNil(Indexes);
FreeAndNil(IndexColumns);
FreeAndNil(Defaults);
FreeAndNil(ForeignKeyColumns);
FreeAndNil(ColumnMap);
end;
function TDBXBaseMetaDataWriter.SupportedTableAlteration(const Operation: Integer): Boolean;
var
Support: Integer;
begin
Support := AlterTableSupport;
Result := ((Support and Operation) = Operation);
end;
function TDBXBaseMetaDataWriter.MakeSqlFullAlterTable(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Columns: TDBXTable): Boolean;
var
MarkerA, MarkerAlterTableFirst, MarkerAlterTableStart, MarkerB, MarkerChangeColumnFirstChange, MarkerChangeColumnStart: Integer;
LInline: Boolean;
Original, OriginalTable: TDBXTableRow;
ExternalStatements: TStringBuilder;
AutoIncrementWord, DefaultValue, SecondSeparator, Separator: string;
Deleted, Inserted, Modified: TDBXTable;
begin
OriginalTable := Table.OriginalRow;
ExternalStatements := nil;
MarkerAlterTableStart := Buffer.Length;
MakeSqlAlterTablePrefix(Buffer, OriginalTable);
MarkerAlterTableFirst := Buffer.Length;
Separator := TDBXSQL.Nl + TDBXSQL.Spacing;
SecondSeparator := TDBXSQL.Comma + TDBXSQL.Nl + TDBXSQL.Spacing;
Deleted := Columns.DeletedRows;
Deleted.First;
while Deleted.InBounds do
begin
if SupportedTableAlteration(TDBXAlterTableOperation.DropColumn) then
begin
Buffer.Append(Separator);
Buffer.Append(TDBXSQL.Drop);
// buffer.append(SQL.SPACE); Not supported by Interbase
// buffer.append(SQL.COLUMN);
Buffer.Append(TDBXSQL.Space);
MakeSqlIdentifier(Buffer, Deleted.Value[TDBXColumnsIndex.ColumnName].GetWideString(NullString));
Separator := SecondSeparator;
end;
Deleted.Next;
end;
Deleted.Close;
Inserted := Columns.InsertedRows;
Inserted.First;
while Inserted.InBounds do
begin
if SupportedTableAlteration(TDBXAlterTableOperation.AddColumn) then
begin
Buffer.Append(Separator);
Buffer.Append(TDBXSQL.Add);
// buffer.append(SQL.SPACE); Not supported by Interbase
// buffer.append(SQL.COLUMN);
Buffer.Append(TDBXSQL.Space);
MakeSqlColumnDefinition(Buffer, Inserted);
if not Inserted.Value[TDBXColumnsIndex.Ordinal].IsNull then
begin
if SupportedTableAlteration(TDBXAlterTableOperation.AddColumnWithPosition) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Position);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(Inserted.Value[TDBXColumnsIndex.Ordinal].AsInt32);
end;
end;
Separator := SecondSeparator;
end;
Inserted.Next;
end;
Inserted.Close;
Modified := Columns.UpdatedRows;
Modified.First;
while Modified.InBounds do
begin
MarkerChangeColumnStart := Buffer.Length;
Buffer.Append(Separator);
Buffer.Append(TDBXSQL.Alter);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Column);
Buffer.Append(TDBXSQL.Space);
Original := Modified.OriginalRow;
MakeSqlIdentifier(Buffer, Original.Value[TDBXColumnsIndex.ColumnName].AsString);
MarkerChangeColumnFirstChange := Buffer.Length;
if not (Modified.Value[TDBXColumnsIndex.TypeName].EqualsValue(Original.Value[TDBXColumnsIndex.TypeName]) and Modified.Value[TDBXColumnsIndex.Precision].EqualsValue(Original.Value[TDBXColumnsIndex.Precision]) and Modified.Value[TDBXColumnsIndex.Scale].EqualsValue(Original.Value[TDBXColumnsIndex.Scale])) then
begin
if SupportedTableAlteration(TDBXAlterTableOperation.ChangeColumnType) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.cType);
Buffer.Append(TDBXSQL.Space);
MakeSqlDataType(Buffer, Modified.Value[TDBXColumnsIndex.TypeName].AsString, Modified);
end;
end;
if not Modified.Value[TDBXColumnsIndex.DefaultValue].EqualsValue(Original.Value[TDBXColumnsIndex.DefaultValue]) then
begin
DefaultValue := Modified.Value[TDBXColumnsIndex.DefaultValue].GetWideString(NullString);
if (DefaultValue.IsEmpty) or (DefaultValue.Length = 0) then
begin
if SupportedTableAlteration(TDBXAlterTableOperation.DropDefaultValue) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Drop);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Default);
end;
end
else
begin
if SupportedTableAlteration(TDBXAlterTableOperation.ChangeDefaultValue) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.cSet);
Buffer.Append(TDBXSQL.Space);
MakeSqlDefaultValue(Buffer, DefaultValue, Modified.Value[TDBXColumnsIndex.TypeName].GetWideString(NullString));
end;
end;
end;
if not Modified.Value[TDBXColumnsIndex.IsNullable].EqualsValue(Original.Value[TDBXColumnsIndex.IsNullable]) then
begin
if not Modified.Value[TDBXColumnsIndex.IsNullable].GetBoolean(True) then
begin
if SupportedTableAlteration(TDBXAlterTableOperation.DropNullable) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.cNot);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Nullable);
end;
end
else
begin
if SupportedTableAlteration(TDBXAlterTableOperation.SetNullable) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Nullable);
end;
end;
end;
if not Modified.Value[TDBXColumnsIndex.IsAutoIncrement].EqualsValue(Original.Value[TDBXColumnsIndex.IsAutoIncrement]) then
begin
AutoIncrementWord := SqlAutoIncrementKeyword;
if (not AutoIncrementWord.IsEmpty) and (AutoIncrementWord.Length > 0) then
begin
if Modified.Value[TDBXColumnsIndex.IsAutoIncrement].GetBoolean(False) then
begin
if SupportedTableAlteration(TDBXAlterTableOperation.AddAutoincrement) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(AutoIncrementWord);
end;
end
else
begin
if SupportedTableAlteration(TDBXAlterTableOperation.DropAutoincrement) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Drop);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(AutoIncrementWord);
end;
end;
end;
end;
if not Modified.Value[TDBXColumnsIndex.Ordinal].EqualsValue(Original.Value[TDBXColumnsIndex.Ordinal]) then
begin
if SupportedTableAlteration(TDBXAlterTableOperation.ChangeColumnPosition) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Position);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(Modified.Value[TDBXColumnsIndex.Ordinal].AsInt32);
end;
end;
if not Modified.Value[TDBXColumnsIndex.ColumnName].EqualsValue(Original.Value[TDBXColumnsIndex.ColumnName]) then
begin
if SupportedTableAlteration(TDBXAlterTableOperation.RenameColumn) then
begin
MarkerA := Buffer.Length;
Buffer.Append(TDBXSQL.Space);
MarkerB := Buffer.Length;
LInline := MakeSqlColumnRename(Buffer, Modified.Value[TDBXColumnsIndex.ColumnName].GetWideString(NullString), OriginalTable.Value[TDBXTablesIndex.CatalogName].GetWideString(NullString), OriginalTable.Value[TDBXTablesIndex.SchemaName].GetWideString(NullString), OriginalTable.Value[TDBXTablesIndex.TableName].GetWideString(NullString), Original.Value[TDBXColumnsIndex.ColumnName].GetWideString(NullString));
if not LInline then
begin
ExternalStatements := AddToExternalStatements(ExternalStatements, Buffer, MarkerB);
Buffer.Length := MarkerA;
end;
end;
end;
if MarkerChangeColumnFirstChange = Buffer.Length then
Buffer.Length := MarkerChangeColumnStart
else
Separator := SecondSeparator;
Modified.Next;
end;
Modified.Close;
if not (Table.Value[TDBXTablesIndex.CatalogName].EqualsValue(OriginalTable.Value[TDBXTablesIndex.CatalogName]) and Table.Value[TDBXTablesIndex.SchemaName].EqualsValue(OriginalTable.Value[TDBXTablesIndex.SchemaName]) and Table.Value[TDBXTablesIndex.TableName].EqualsValue(OriginalTable.Value[TDBXTablesIndex.TableName])) then
begin
if SupportedTableAlteration(TDBXAlterTableOperation.RenameTable) or SupportedTableAlteration(TDBXAlterTableOperation.RenameTableTo) then
begin
MarkerA := Buffer.Length;
Buffer.Append(Separator);
MarkerB := Buffer.Length;
LInline := MakeSqlTableRename(Buffer, Table.Value[TDBXTablesIndex.CatalogName].GetWideString(NullString), Table.Value[TDBXTablesIndex.SchemaName].GetWideString(NullString), Table.Value[TDBXTablesIndex.TableName].GetWideString(NullString), OriginalTable.Value[TDBXTablesIndex.CatalogName].GetWideString(NullString), OriginalTable.Value[TDBXTablesIndex.SchemaName].GetWideString(NullString), OriginalTable.Value[TDBXTablesIndex.TableName].GetWideString(NullString));
if LInline then
Separator := SecondSeparator
else
begin
ExternalStatements := AddToExternalStatements(ExternalStatements, Buffer, MarkerB);
Buffer.Length := MarkerA;
end;
end;
end;
if MarkerAlterTableFirst = Buffer.Length then
Buffer.Length := MarkerAlterTableStart;
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
if ExternalStatements <> nil then
Buffer.Append(ExternalStatements);
Result := True;
end;
function TDBXBaseMetaDataWriter.MakeSqlTableRename(const Buffer: TStringBuilder; const CatalogName: string; const SchemaName: string; const TableName: string; const OldCatalogName: string; const OldSchemaName: string; const OldTableName: string): Boolean;
begin
Buffer.Append(TDBXSQL.Rename);
if SupportedTableAlteration(TDBXAlterTableOperation.RenameTableTo) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.cTo);
end;
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, CatalogName, SchemaName, TableName);
Result := True;
end;
function TDBXBaseMetaDataWriter.MakeSqlColumnRename(const Buffer: TStringBuilder; const ColumnName: string; const CatalogName: string; const SchemaName: string; const TableName: string; const OldColumnName: string): Boolean;
begin
Buffer.Append(TDBXSQL.cTo);
Buffer.Append(TDBXSQL.Space);
MakeSqlIdentifier(Buffer, ColumnName);
Result := True;
end;
procedure TDBXBaseMetaDataWriter.MakeSqlObjectName(const Buffer: TStringBuilder; const CatalogName: string; const SchemaName: string; const ObjectName: string);
var
Dot: string;
begin
Dot := TDBXSQL.Empty;
if (not CatalogName.IsEmpty) and CatalogsSupported then
begin
MakeSqlIdentifier(Buffer, CatalogName);
Dot := TDBXSQL.Dot;
end;
if (not SchemaName.IsEmpty) and SchemasSupported then
begin
Buffer.Append(Dot);
MakeSqlIdentifier(Buffer, SchemaName);
Dot := TDBXSQL.Dot;
end;
Buffer.Append(Dot);
MakeSqlIdentifier(Buffer, ObjectName);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlIdentifier(const Buffer: TStringBuilder; const Identifier: string);
begin
if FReader.QuotedIdentifiersSupported then
begin
if not IsValidSqlIdentifier(Identifier) or IsReservedWord(Identifier) then
begin
Buffer.Append(GetSqlQuotedIdentifier(Identifier));
Exit;
end;
end;
Buffer.Append(Identifier);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlColumnDefinition(const Buffer: TStringBuilder; const Column: TDBXTableRow);
var
AutoIncrementWord: string;
begin
MakeSqlIdentifier(Buffer, Column.Value[TDBXColumnsIndex.ColumnName].GetWideString(NullString));
Buffer.Append(TDBXSQL.Space);
MakeSqlDataType(Buffer, Column.Value[TDBXColumnsIndex.TypeName].GetWideString(NullString), Column);
MakeSqlDefaultValue(Buffer, Column.Value[TDBXColumnsIndex.DefaultValue].GetWideString(NullString), Column.Value[TDBXColumnsIndex.TypeName].GetWideString(NullString));
if Column.Value[TDBXColumnsIndex.IsAutoIncrement].GetBoolean(False) then
begin
AutoIncrementWord := SqlAutoIncrementKeyword;
if (not AutoIncrementWord.IsEmpty) and (AutoIncrementWord.Length > 0) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(AutoIncrementWord);
end;
end;
MakeSqlNullable(Buffer, Column);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlNullable(const Buffer: TStringBuilder; const Column: TDBXTableRow);
begin
if not Column.Value[TDBXColumnsIndex.IsNullable].GetBoolean(True) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.cNot);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Nullable);
end;
end;
procedure TDBXBaseMetaDataWriter.MakeSqlDefaultValue(const Buffer: TStringBuilder; const DefaultValue: string; const TypeName: string);
begin
if (not DefaultValue.IsEmpty) and (DefaultValue.Length > 0) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Default);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(DefaultValue);
end;
end;
function TDBXBaseMetaDataWriter.RemoveMarkersForNullValues(const InFormat: string; const Values: TDBXStringArray): string;
var
Found, Index: Integer;
Format, SearchFor: string;
begin
SearchFor := NullString;
Format := InFormat;
for Index := Length(Values) - 1 downto 1 do
begin
if Values[Index].IsEmpty then
begin
SearchFor := TDBXSQL.Comma + TDBXSQL.OpenBrace + IntToStr(Index) + TDBXSQL.CloseBrace;
Found := Format.IndexOf(SearchFor);
if Found > 0 then
Format := Format.Substring(0, Found) + Format.Substring(Found + SearchFor.Length, Format.Length - Found - SearchFor.Length);
end;
Break;
end;
if Values[0].IsEmpty then
begin
SearchFor := TDBXSQL.OpenParen + TDBXSQL.OpenBrace + IntToStr(0) + TDBXSQL.CloseBrace + TDBXSQL.CloseParen;
Found := Format.IndexOf(SearchFor);
if Found > 0 then
Format := Format.Substring(0, Found) + Format.Substring(Found + SearchFor.Length, Format.Length - Found - SearchFor.Length);
end;
Result := Format;
end;
procedure TDBXBaseMetaDataWriter.MakeSqlDataType(const Buffer: TStringBuilder; const TypeName: string; const ColumnRow: TDBXTableRow);
var
Overrides: TDBXInt32s;
DataType: TDBXDataTypeDescription;
begin
SetLength(Overrides,2);
Overrides[0] := -1;
Overrides[1] := -1;
DataType := FindDataType(TypeName, ColumnRow, Overrides);
MakeSqlDataType(Buffer, DataType, ColumnRow, Overrides);
Overrides := nil;
end;
procedure TDBXBaseMetaDataWriter.MakeSqlDataType(const Buffer: TStringBuilder; const DataType: TDBXDataTypeDescription; const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s);
var
ColumnName, FormatString, FormattedType, Params: string;
Index, Override, ParameterCount, ParameterIndex: Integer;
Tokenizer: TDBXTokenizer;
Values: TDBXStringArray;
begin
FormattedType := NullString;
Params := DataType.CreateParameters;
FormatString := DataType.CreateFormat;
if (Params.IsEmpty) or (Params.Length = 0) then
FormattedType := FormatString
else
begin
ParameterCount := 0;
Tokenizer := TDBXTokenizer.Create(Params, TDBXSQL.Comma + TDBXSQL.Space);
while Tokenizer.HasMoreTokens do
begin
Tokenizer.NextToken;
Inc(ParameterCount);
end;
SetLength(Values,ParameterCount);
Tokenizer.Free;
Tokenizer := TDBXTokenizer.Create(Params, TDBXSQL.Comma + TDBXSQL.Space);
ParameterIndex := 0;
while Tokenizer.HasMoreTokens do
begin
ColumnName := Tokenizer.NextToken;
Index := ColumnRow.GetOrdinal(ColumnName);
if Index < 0 then
raise TDBXMetaDataError.Create(Format(SUnknownColumnName, [DataType.TypeName,ColumnName]));
Override := -1;
case Index of
TDBXColumnsIndex.Precision:
Override := Overrides[0];
TDBXColumnsIndex.Scale:
Override := Overrides[1];
end;
if Override < 0 then
Values[ParameterIndex] := ColumnRow.Value[Index].AsString
else
Values[ParameterIndex] := IntToStr(Override);
Inc(ParameterIndex);
end;
Tokenizer.Free;
FormatString := RemoveMarkersForNullValues(FormatString, Values);
FormattedType := FormatMessage(FormatString, Values);
end;
Buffer.Append(FormattedType);
end;
function TDBXBaseMetaDataWriter.ErrorTypeNameNotFound(const ColumnRow: TDBXTableRow): Exception;
var
Product: string;
ColumnName: string;
ColumnType: Integer;
IsUnsigned: Boolean;
begin
Product := FReader.ProductName;
ColumnName := ColumnRow.Value[TDBXColumnsIndex.ColumnName].GetWideString('');
ColumnType := ColumnRow.Value[TDBXColumnsIndex.DbxDataType].AsInt32;
IsUnsigned := ColumnRow.Value[TDBXColumnsIndex.IsUnsigned].GetBoolean;
Result := TDBXMetaDataError.Create(Format(STypeNotFound, [Product,ColumnName,FContext.GetPlatformTypeName(ColumnType, IsUnsigned)]));
end;
function TDBXBaseMetaDataWriter.FindDataType(const InTypeName: string; const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s): TDBXDataTypeDescription;
var
TypeName: string;
DataTypes: TDBXObjectStore;
DataType: TDBXDataTypeDescription;
begin
TypeName := InTypeName;
if TypeName.IsEmpty then
TypeName := FindTypeName(ColumnRow, Overrides, True);
if TypeName.IsEmpty then
raise ErrorTypeNameNotFound(ColumnRow);
DataTypes := FReader.DataTypeHash;
DataType := TDBXDataTypeDescription(DataTypes[TypeName]);
if DataType = nil then
raise TDBXMetaDataError.Create(Format(STypeNameNotFound, [TypeName]));
Result := DataType;
end;
function TDBXBaseMetaDataWriter.FindTypeName(const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s; const FailIfNotFound: Boolean): string;
var
ColumnType: Integer;
begin
ColumnType := ColumnRow.Value[TDBXColumnsIndex.DbxDataType].AsInt32;
case ColumnType of
TDBXDataTypes.AnsiStringType,
TDBXDataTypes.WideStringType:
Result := FindStringOrBinaryTypeName(ColumnRow, FailIfNotFound);
TDBXDataTypes.Int8Type,
TDBXDataTypes.Int16Type,
TDBXDataTypes.Int32Type,
TDBXDataTypes.Int64Type,
TDBXDataTypes.UInt8Type,
TDBXDataTypes.UInt16Type,
TDBXDataTypes.UInt32Type,
TDBXDataTypes.UInt64Type:
Result := FindIntegerTypeName(ColumnRow, Overrides, FailIfNotFound);
TDBXDataTypes.BcdType:
Result := FindDecimalTypeName(ColumnRow, FailIfNotFound);
TDBXDataTypes.SingleType,
TDBXDataTypes.DoubleType:
Result := FindFloatTypeName(ColumnRow, Overrides, FailIfNotFound);
TDBXDataTypes.DateType,
TDBXDataTypes.TimeType,
TDBXDataTypes.TimeStampType,
TDBXDataTypes.TimeStampOffsetType:
Result := FindDateTimeTypeName(ColumnRow, FailIfNotFound);
TDBXDataTypes.BlobType,
TDBXDataTypes.BytesType,
TDBXDataTypes.VarBytesType:
Result := FindStringOrBinaryTypeName(ColumnRow, FailIfNotFound);
TDBXDataTypes.BooleanType:
Result := FindBooleanTypeName(ColumnRow, Overrides, FailIfNotFound);
TDBXDataTypes.ObjectType:
Result := FindSimpleColumnTypeMatch(ColumnRow, FailIfNotFound);
else
Result := NullString;
end;
end;
function TDBXBaseMetaDataWriter.FindSimpleColumnTypeMatch(const ColumnRow: TDBXTableRow; const FailIfNotFound: Boolean): string;
var
WantedColumnType: Integer;
BestScore: Integer;
BestTypeName: string;
DataTypes: TDBXArrayList;
Index: Integer;
DataType: TDBXDataTypeDescription;
Score: Integer;
Product: string;
ColumnName: string;
begin
WantedColumnType := ColumnRow.Value[TDBXColumnsIndex.DbxDataType].AsInt32;
BestScore := -1;
BestTypeName := NullString;
DataTypes := FReader.DataTypes;
for index := 0 to DataTypes.Count - 1 do
begin
DataType := TDBXDataTypeDescription(DataTypes[Index]);
Score := 0;
if DataType.DbxDataType = WantedColumnType then
begin
Score := Score + Requirement;
if DataType.BestMatch then
Score := Score + TieBreaker1;
if Score > BestScore then
begin
BestScore := Score;
BestTypeName := DataType.TypeName;
end;
end;
end;
if BestScore >= Requirement then
Exit(BestTypeName)
else if not FailIfNotFound then
Exit(NullString);
Product := FReader.ProductName;
ColumnName := ColumnRow.Value[TDBXColumnsIndex.ColumnName].GetWideString('');
raise TDBXMetaDataError.Create(Format(STypeNotFound, [Product,ColumnName,FContext.GetPlatformTypeName(WantedColumnType, False)]));
end;
function TDBXBaseMetaDataWriter.FindBooleanTypeName(const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s; const FailIfNotFound: Boolean): string;
var
BestScore: Integer;
BestTypeName: string;
DataTypes: TDBXArrayList;
Index: Integer;
DataType: TDBXDataTypeDescription;
ActualColumnType: Integer;
Score: Integer;
Product: string;
ColumnName: string;
begin
BestScore := -1;
BestTypeName := NullString;
DataTypes := FReader.DataTypes;
for index := 0 to DataTypes.Count - 1 do
begin
DataType := TDBXDataTypeDescription(DataTypes[Index]);
ActualColumnType := DataType.DbxDataType;
Score := -1;
case ActualColumnType of
TDBXDataTypes.BooleanType:
Exit(DataType.TypeName);
TDBXDataTypes.AnsiStringType:
Score := 2 * Desireable;
TDBXDataTypes.WideStringType:
Score := Desireable;
end;
if (Score > 0) and ColumnRow.Value[TDBXColumnsIndex.IsFixedLength].GetBoolean then
Score := Score + TieBreaker1;
if Score > BestScore then
begin
BestScore := Score;
BestTypeName := DataType.TypeName;
end;
end;
if BestScore > 0 then
begin
Overrides[0] := 1;
Exit(BestTypeName);
end
else if not FailIfNotFound then
Exit(NullString);
Product := FReader.ProductName;
ColumnName := ColumnRow.Value[TDBXColumnsIndex.ColumnName].GetWideString('');
raise TDBXMetaDataError.Create(Format(STypeNotFound, [Product,ColumnName,FContext.GetPlatformTypeName(TDBXDataTypes.BooleanType, False)]));
end;
function TDBXBaseMetaDataWriter.FindStringOrBinaryTypeName(const ColumnRow: TDBXTableRow; const FailIfNotFound: Boolean): string;
var
WantedColumnType: Integer;
WantedStringType: Boolean;
UnicodeRequired: Boolean;
UnicodeNotDesired: Boolean;
BlobRequired: Boolean;
BlobForbidden: Boolean;
FixedLengthDesired: Boolean;
VariableLengthDesired: Boolean;
PrecisionRequired: Integer;
BestScore: Integer;
BestTypeName: string;
BestColumnSize: Int64;
BestIsUnicode: Boolean;
DataTypes: TDBXArrayList;
Index: Integer;
DataType: TDBXDataTypeDescription;
ActualColumnType: Integer;
ActualStringType: Boolean;
Score: Integer;
Product: string;
ColumnName: string;
begin
WantedColumnType := ColumnRow.Value[TDBXColumnsIndex.DbxDataType].AsInt32;
WantedStringType := ((WantedColumnType = TDBXDataTypes.AnsiStringType) or (WantedColumnType = TDBXDataTypes.WideStringType));
UnicodeRequired := ColumnRow.Value[TDBXColumnsIndex.IsUnicode].GetBoolean(False);
UnicodeNotDesired := not ColumnRow.Value[TDBXColumnsIndex.IsUnicode].GetBoolean(True);
BlobRequired := ColumnRow.Value[TDBXColumnsIndex.IsLong].GetBoolean(False);
BlobForbidden := not ColumnRow.Value[TDBXColumnsIndex.IsLong].GetBoolean(True);
FixedLengthDesired := ColumnRow.Value[TDBXColumnsIndex.IsFixedLength].GetBoolean(False);
VariableLengthDesired := not ColumnRow.Value[TDBXColumnsIndex.IsFixedLength].GetBoolean(True);
PrecisionRequired := ColumnRow.Value[TDBXColumnsIndex.Precision].GetInt64(-1);
if not WantedStringType then
begin
UnicodeRequired := False;
UnicodeNotDesired := False;
end;
BestScore := -1;
BestTypeName := NullString;
BestColumnSize := -1;
BestIsUnicode := False;
DataTypes := FReader.DataTypes;
for index := 0 to DataTypes.Count - 1 do
begin
DataType := TDBXDataTypeDescription(DataTypes[Index]);
ActualColumnType := DataType.DbxDataType;
ActualStringType := ((ActualColumnType = TDBXDataTypes.AnsiStringType) or (ActualColumnType = TDBXDataTypes.WideStringType));
case ActualColumnType of
TDBXDataTypes.BlobType,
TDBXDataTypes.BytesType,
TDBXDataTypes.VarBytesType,
TDBXDataTypes.AnsiStringType,
TDBXDataTypes.WideStringType:
if (WantedStringType = ActualStringType) or (WantedStringType and DataType.StringOptionSupported) then
begin
Score := 0;
if DataType.ColumnSize >= PrecisionRequired then
Score := Score + Requirement;
if DataType.Unicode or DataType.UnicodeOptionSupported or not UnicodeRequired then
Score := Score + Requirement;
if DataType.Long or DataType.LongOptionSupported or not BlobRequired then
Score := Score + Requirement;
if not DataType.Long or not BlobForbidden then
Score := Score + Requirement;
if DataType.FixedLength and FixedLengthDesired then
Score := Score + Desireable;
if not DataType.Unicode or not UnicodeNotDesired then
Score := Score + Desireable;
if not DataType.FixedLength and VariableLengthDesired then
Score := Score + Desireable;
if not DataType.Long then
Score := Score + TieBreaker5;
if DataType.Unicode then
Score := Score + TieBreaker4;
if not DataType.FixedLength then
Score := Score + TieBreaker3;
if DataType.BestMatch then
Score := Score + TieBreaker2;
if DataType.ColumnSize < BestColumnSize then
Score := Score + TieBreaker1;
if Score > BestScore then
begin
BestScore := Score;
BestTypeName := DataType.TypeName;
BestColumnSize := DataType.ColumnSize;
BestIsUnicode := DataType.Unicode;
end;
end;
end;
end;
if BestScore >= 4 * Requirement then
Exit(BestTypeName)
else if not FailIfNotFound then
Exit(NullString);
Product := FReader.ProductName;
ColumnName := ColumnRow.Value[TDBXColumnsIndex.ColumnName].GetWideString('');
if BestScore < 0 then
raise TDBXMetaDataError.Create(Format(STypeNotFound, [Product,ColumnName,FContext.GetPlatformTypeName(WantedColumnType, False)]));
if BestColumnSize < PrecisionRequired then
raise TDBXMetaDataError.Create(Format(SCannotHoldWantedPrecision, [Product,ColumnName,BestTypeName,IntToStr(BestColumnSize),IntToStr(PrecisionRequired)]));
if not BestIsUnicode and UnicodeRequired then
raise TDBXMetaDataError.Create(Format(SCannotHoldUnicodeChars, [Product,ColumnName,BestTypeName]));
if BlobRequired then
raise TDBXMetaDataError.Create(Format(SNoBlobTypeFound, [Product,ColumnName,FContext.GetPlatformTypeName(WantedColumnType, False)]))
else
raise TDBXMetaDataError.Create(Format(STypeNotFound, [Product,ColumnName,FContext.GetPlatformTypeName(WantedColumnType, False)]));
end;
function TDBXBaseMetaDataWriter.CalcPrecisionColumnType(const ColumnType: Integer; const UnsignedOption: Boolean): Integer;
begin
if not UnsignedOption then
Exit(ColumnType);
case ColumnType of
TDBXDataTypes.Int8Type:
Result := TDBXDataTypes.UInt8Type;
TDBXDataTypes.Int16Type:
Result := TDBXDataTypes.UInt16Type;
TDBXDataTypes.Int32Type:
Result := TDBXDataTypes.UInt32Type;
TDBXDataTypes.Int64Type:
Result := TDBXDataTypes.UInt64Type;
else
Result := ColumnType;
end;
end;
function TDBXBaseMetaDataWriter.CalcDecimalPrecision(const ColumnType: Integer): Integer;
begin
case ColumnType of
TDBXDataTypes.Int8Type,
TDBXDataTypes.UInt8Type:
Result := 3;
TDBXDataTypes.Int16Type,
TDBXDataTypes.UInt16Type:
Result := 5;
TDBXDataTypes.Int32Type,
TDBXDataTypes.UInt32Type:
Result := 10;
TDBXDataTypes.Int64Type:
Result := 19;
TDBXDataTypes.UInt64Type:
Result := 20;
else
Result := 0;
end;
end;
function TDBXBaseMetaDataWriter.CalcBinaryPrecision(const ColumnType: Integer): Integer;
begin
case ColumnType of
TDBXDataTypes.Int8Type:
Result := 7;
TDBXDataTypes.UInt8Type:
Result := 8;
TDBXDataTypes.Int16Type:
Result := 15;
TDBXDataTypes.UInt16Type:
Result := 16;
TDBXDataTypes.Int32Type:
Result := 31;
TDBXDataTypes.UInt32Type:
Result := 32;
TDBXDataTypes.Int64Type:
Result := 63;
TDBXDataTypes.UInt64Type:
Result := 64;
else
Result := 0;
end;
end;
function TDBXBaseMetaDataWriter.IsSignedInteger(const ColumnType: Integer): Boolean;
begin
case ColumnType of
TDBXDataTypes.Int8Type,
TDBXDataTypes.Int16Type,
TDBXDataTypes.Int32Type,
TDBXDataTypes.Int64Type:
Result := True;
else
Result := False;
end;
end;
function TDBXBaseMetaDataWriter.FindIntegerTypeName(const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s; const FailIfNotFound: Boolean): string;
var
ColumnType: Integer;
RequiredBinaryPrecision: Integer;
RequiredDecimalPrecision: Integer;
SignedRequired: Boolean;
AutoIncrementRequired: Boolean;
BestScore: Integer;
BestType: Integer;
BestTypeName: string;
BestIsAutoIncrementable: Boolean;
BestIsSigned: Boolean;
DataTypes: TDBXArrayList;
Score: Integer;
ActualColumnType: Integer;
ActualBinaryPrecision: Integer;
ActualDecimalPrecision: Integer;
Index: Integer;
DataType: TDBXDataTypeDescription;
PrecisionColumnType: Integer;
Product: string;
ColumnName: string;
begin
ColumnType := ColumnRow.Value[TDBXColumnsIndex.DbxDataType].AsInt32;
RequiredBinaryPrecision := CalcBinaryPrecision(ColumnType);
RequiredDecimalPrecision := CalcDecimalPrecision(ColumnType);
SignedRequired := IsSignedInteger(ColumnType);
AutoIncrementRequired := ColumnRow.Value[TDBXColumnsIndex.IsAutoIncrement].GetBoolean(False);
BestScore := -1;
BestType := TDBXDataTypes.UnknownType;
BestTypeName := NullString;
BestIsAutoIncrementable := False;
BestIsSigned := False;
DataTypes := FReader.DataTypes;
for index := 0 to DataTypes.Count - 1 do
begin
DataType := TDBXDataTypeDescription(DataTypes[Index]);
ActualColumnType := DataType.DbxDataType;
case ActualColumnType of
TDBXDataTypes.Int8Type,
TDBXDataTypes.UInt8Type,
TDBXDataTypes.Int16Type,
TDBXDataTypes.UInt16Type,
TDBXDataTypes.Int32Type,
TDBXDataTypes.UInt32Type,
TDBXDataTypes.Int64Type,
TDBXDataTypes.UInt64Type,
TDBXDataTypes.BcdType:
begin
Score := 0;
if ActualColumnType = TDBXDataTypes.BcdType then
begin
ActualBinaryPrecision := 128;
ActualDecimalPrecision := Integer(DataType.ColumnSize);
end
else
begin
PrecisionColumnType := CalcPrecisionColumnType(ActualColumnType, DataType.UnsignedOptionSupported);
ActualBinaryPrecision := CalcBinaryPrecision(PrecisionColumnType);
ActualDecimalPrecision := CalcDecimalPrecision(PrecisionColumnType);
end;
if ActualBinaryPrecision >= RequiredBinaryPrecision then
Score := Score + Requirement + 128 - (ActualBinaryPrecision - RequiredBinaryPrecision);
if ActualDecimalPrecision >= RequiredDecimalPrecision then
Score := Score + Requirement;
if DataType.AutoIncrementable or not AutoIncrementRequired then
Score := Score + Requirement;
if not DataType.Unsigned or not SignedRequired then
Score := Score + Requirement;
if DataType.BestMatch then
Score := Score + Desireable;
if Score > BestScore then
begin
BestScore := Score;
BestType := ActualColumnType;
BestTypeName := DataType.TypeName;
BestIsAutoIncrementable := DataType.AutoIncrementable;
BestIsSigned := not DataType.Unsigned;
end;
end;
end;
end;
if BestScore >= 4 * Requirement then
begin
if (BestType = TDBXDataTypes.BcdType) and (Overrides <> nil) then
begin
Overrides[0] := RequiredDecimalPrecision;
Overrides[1] := 0;
end;
Exit(BestTypeName);
end
else if not FailIfNotFound then
Exit(NullString);
Product := FReader.ProductName;
ColumnName := ColumnRow.Value[TDBXColumnsIndex.ColumnName].GetWideString('');
if BestScore < 0 then
raise ErrorTypeNameNotFound(ColumnRow);
if not BestIsAutoIncrementable and AutoIncrementRequired then
raise TDBXMetaDataError.Create(Format(SCannotBeUsedForAutoIncrement, [Product,ColumnName,BestTypeName]));
if not BestIsSigned and SignedRequired then
raise TDBXMetaDataError.Create(Format(SNoSignedTypeFound, [Product,ColumnName,BestTypeName]))
else
raise TDBXMetaDataError.Create(Format(SNoTypeWithEnoughPrecision, [Product,ColumnName,BestTypeName]));
end;
function TDBXBaseMetaDataWriter.FindDecimalTypeName(const ColumnRow: TDBXTableRow; const FailIfNotFound: Boolean): string;
var
PrecisionRequired: Integer;
ScaleRequired: Integer;
AutoIncrementRequired: Boolean;
BestScore: Integer;
BestTypeName: string;
BestColumnSize: Int64;
BestMaxScale: Integer;
DataTypes: TDBXArrayList;
Index: Integer;
DataType: TDBXDataTypeDescription;
Score: Integer;
ColumnName: string;
Product: string;
begin
PrecisionRequired := ColumnRow.Value[TDBXColumnsIndex.Precision].GetInt64(-1);
ScaleRequired := ColumnRow.Value[TDBXColumnsIndex.Scale].GetInt32(-1);
AutoIncrementRequired := ColumnRow.Value[TDBXColumnsIndex.IsAutoIncrement].GetBoolean(False);
BestScore := -1;
BestTypeName := NullString;
BestColumnSize := -1;
BestMaxScale := -1;
DataTypes := FReader.DataTypes;
for index := 0 to DataTypes.Count - 1 do
begin
DataType := TDBXDataTypeDescription(DataTypes[Index]);
if DataType.DbxDataType = TDBXDataTypes.BcdType then
begin
Score := 0;
if DataType.ColumnSize >= PrecisionRequired then
Score := Score + Requirement + TieBreaker3;
if DataType.MaximumScale >= ScaleRequired then
Score := Score + Requirement + TieBreaker2;
if DataType.AutoIncrementable or not AutoIncrementRequired then
Score := Score + Requirement;
if DataType.BestMatch then
Score := Score + TieBreaker1;
if Score > BestScore then
begin
BestScore := Score;
BestTypeName := DataType.TypeName;
BestColumnSize := DataType.ColumnSize;
BestMaxScale := DataType.MaximumScale;
end;
end;
end;
if BestScore >= 3 * Requirement then
Exit(BestTypeName)
else if not FailIfNotFound then
Exit(NullString);
ColumnName := ColumnRow.Value[TDBXColumnsIndex.ColumnName].GetWideString('');
if BestScore < 0 then
raise ErrorTypeNameNotFound(ColumnRow);
Product := FReader.ProductName;
if BestColumnSize < PrecisionRequired then
raise TDBXMetaDataError.Create(Format(SCannotHoldWantedPrecision, [Product,ColumnName,BestTypeName,IntToStr(BestColumnSize),IntToStr(PrecisionRequired)]));
if BestMaxScale < ScaleRequired then
raise TDBXMetaDataError.Create(Format(SCannotHoldWantedScale, [Product,ColumnName,BestTypeName,IntToStr(BestMaxScale),IntToStr(ScaleRequired)]))
else
raise TDBXMetaDataError.Create(Format(SCannotBeUsedForAutoIncrement, [Product,BestTypeName,ColumnName]));
end;
function TDBXBaseMetaDataWriter.GetDefaultFloatPrecision(const ColumnType: Integer): Integer;
begin
case ColumnType of
TDBXDataTypes.SingleType:
Result := 24;
TDBXDataTypes.DoubleType:
Result := 53;
else
Result := 0;
end;
end;
function TDBXBaseMetaDataWriter.FindFloatTypeName(const ColumnRow: TDBXTableRow; const Overrides: TDBXInt32s; const FailIfNotFound: Boolean): string;
var
ActualColumnType, BestScore, Index, PrecisionRequired, Score, WantedColumnType: Integer;
BestTypeName, ColumnName, Product: string;
BestColumnSize: Int64;
BestPrecisionNeeded, PrecisionNeeded: Boolean;
DataTypes: TDBXArrayList;
DataType: TDBXDataTypeDescription;
begin
WantedColumnType := ColumnRow.Value[TDBXColumnsIndex.DbxDataType].AsInt32;
PrecisionRequired := GetDefaultFloatPrecision(WantedColumnType);
BestScore := -1;
BestTypeName := NullString;
BestColumnSize := -1;
BestPrecisionNeeded := False;
DataTypes := FReader.DataTypes;
for Index := 0 to DataTypes.Count - 1 do
begin
DataType := TDBXDataTypeDescription(DataTypes[Index]);
ActualColumnType := DataType.DbxDataType;
case ActualColumnType of
TDBXDataTypes.SingleType,
TDBXDataTypes.DoubleType:
begin
Score := 0;
PrecisionNeeded := (DataType.CreateParameters.Length > 0);
if PrecisionNeeded then
begin
if DataType.ColumnSize >= PrecisionRequired then
Score := Score + Requirement;
end
else
begin
if ActualColumnType = WantedColumnType then
Score := Score + Requirement + TieBreaker2;
end;
if DataType.BestMatch then
Score := Score + TieBreaker1;
if Score > BestScore then
begin
BestScore := Score;
BestTypeName := DataType.TypeName;
BestColumnSize := DataType.ColumnSize;
BestPrecisionNeeded := PrecisionNeeded;
end;
end;
end;
end;
if BestScore >= Requirement then
begin
if BestPrecisionNeeded then
begin
if ColumnRow.Value[TDBXColumnsIndex.Precision].IsNull or (ColumnRow.Value[TDBXColumnsIndex.Precision].AsInt64 < PrecisionRequired) then
begin
if Overrides <> nil then
Overrides[0] := PrecisionRequired;
end;
end;
Exit(BestTypeName);
end
else if not FailIfNotFound then
Exit(NullString);
ColumnName := ColumnRow.Value[TDBXColumnsIndex.ColumnName].GetWideString('');
Product := FReader.ProductName;
if BestScore < 0 then
raise ErrorTypeNameNotFound(ColumnRow)
else
raise TDBXMetaDataError.Create(string.Format(SCannotHoldWantedPrecision, [Product,ColumnName,BestTypeName,IntToStr(BestColumnSize),IntToStr(PrecisionRequired)]));
end;
function TDBXBaseMetaDataWriter.FindDateTimeTypeName(const ColumnRow: TDBXTableRow; const FailIfNotFound: Boolean): string;
var
BestScore, ColumnType, Index, Score, WantedColumnType: Integer;
BestTypeName: string;
DataTypes: TDBXArrayList;
DataType: TDBXDataTypeDescription;
begin
WantedColumnType := ColumnRow.Value[TDBXColumnsIndex.DbxDataType].AsInt32;
BestScore := -1;
BestTypeName := NullString;
DataTypes := FReader.DataTypes;
for Index := 0 to DataTypes.Count - 1 do
begin
DataType := TDBXDataTypeDescription(DataTypes[Index]);
ColumnType := DataType.DbxDataType;
case ColumnType of
TDBXDataTypes.DateType,
TDBXDataTypes.TimeType,
TDBXDataTypes.TimeStampType,
TDBXDataTypes.TimeStampOffsetType:
begin
Score := 0;
if WantedColumnType = ColumnType then
Score := Requirement + Desireable
else if ColumnType = TDBXDataTypes.TimeStampType then
Score := Requirement;
if DataType.BestMatch then
Score := Score + TieBreaker1;
if Score > BestScore then
begin
BestScore := Score;
BestTypeName := DataType.TypeName;
end;
end;
end;
end;
if BestScore >= Requirement then
Exit(BestTypeName)
else if not FailIfNotFound then
Exit(NullString);
raise ErrorTypeNameNotFound(ColumnRow);
end;
function TDBXBaseMetaDataWriter.AddToExternalStatements(const InExternalStatements: TStringBuilder; const Buffer: TStringBuilder; const StartPosition: Integer): TStringBuilder;
var
ExternalStatements: TStringBuilder;
begin
ExternalStatements := InExternalStatements;
if ExternalStatements = nil then
ExternalStatements := TStringBuilder.Create;
ExternalStatements.Append(Buffer.ToString(StartPosition, Buffer.Length - StartPosition));
Result := ExternalStatements;
end;
function TDBXBaseMetaDataWriter.IsValidSqlIdentifier(const Identifier: string): Boolean;
var
UpperOK: Boolean;
LowerOK: Boolean;
Index: Integer;
Ch: WideChar;
begin
UpperOK := FReader.UpperCaseIdentifiersSupported;
LowerOK := FReader.LowerCaseIdentifiersSupported;
//Check if the identifier is already quoted!
if (Identifier <> '') and Identifier.StartsWith(FReader.SqlIdentifierQuotePrefix) and
Identifier.EndsWith(FReader.SqlIdentifierQuoteSuffix) then
Exit(True);
if (Identifier = '') or not IsLetter(Identifier.Chars[0], UpperOK, LowerOK) then
Exit(False);
for Index := 0 to Identifier.Length - 2 do
begin
Ch := Identifier.Chars[1+Index];
if not IsLetter(Ch, UpperOK, LowerOK) and not IsDigit(Ch) and (Ch <> '_') then
Exit(False);
end;
Result := True;
end;
function TDBXBaseMetaDataWriter.IsReservedWord(const Identifier: string): Boolean;
var
LReservedWordsTable: TDBXTable;
begin
if FReservedWords = nil then
begin
LReservedWordsTable := FReader.FetchReservedWords;
FReservedWords := FReader.MakeStorage(LReservedWordsTable);
end;
Result := FReservedWords.FindStringKey(TDBXReservedWordsIndex.ReservedWord, Identifier);
end;
function TDBXBaseMetaDataWriter.IsLetter(const Ch: WideChar; const UpperOK: Boolean; const LowerOK: Boolean): Boolean;
begin
if (Ch >= 'A') and (Ch <= 'Z') then
Exit(UpperOK);
if (Ch >= 'a') and (Ch <= 'z') then
Exit(LowerOK);
Result := False;
end;
function TDBXBaseMetaDataWriter.IsDigit(const Ch: WideChar): Boolean;
begin
Result := ((Ch >= '0') and (Ch <= '9'));
end;
procedure TDBXBaseMetaDataWriter.MakeSqlTableReplacement(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Columns: TDBXTable);
var
OriginalTable: TDBXTableRow;
TableRename: Boolean;
NewCatalogName, NewSchemaName, NewTableName, TempTableName: string;
NewColumns, NewTable: TDBXTable;
begin
OriginalTable := Table.OriginalRow;
TableRename := not (Table.Value[TDBXTablesIndex.CatalogName].EqualsValue(OriginalTable.Value[TDBXTablesIndex.CatalogName]) and Table.Value[TDBXTablesIndex.SchemaName].EqualsValue(OriginalTable.Value[TDBXTablesIndex.SchemaName]) and Table.Value[TDBXTablesIndex.TableName].EqualsValue(OriginalTable.Value[TDBXTablesIndex.TableName]));
NewCatalogName := Table.Value[TDBXTablesIndex.CatalogName].GetWideString(NullString);
NewSchemaName := Table.Value[TDBXTablesIndex.SchemaName].GetWideString(NullString);
NewTableName := Table.Value[TDBXTablesIndex.TableName].GetWideString(NullString);
TempTableName := C_Conditional(TableRename, NewTableName, TDBXSQL.Temp + NewTableName);
Buffer.Append(TDBXSQL.Nl);
CreateTempOutputTable(Buffer, Table, Columns, TempTableName);
Buffer.Append(TDBXSQL.Nl);
InsertValuesFromOldTable(Buffer, Table, Columns, TempTableName);
Buffer.Append(TDBXSQL.Nl);
MakeSqlDropTable(Buffer, OriginalTable);
if not TableRename then
begin
if not SqlRenameTable.IsEmpty then
MakeSqlTableRename(Buffer, NewCatalogName, NewSchemaName, TempTableName, NewTableName)
else
begin
NewTable := CopyTable(Table, TempTableName);
NewColumns := CopyColumns(Columns);
Buffer.Append(TDBXSQL.Nl);
CreateTempOutputTable(Buffer, NewTable, NewColumns, NewTableName);
Buffer.Append(TDBXSQL.Nl);
InsertValuesFromOldTable(Buffer, NewTable, NewColumns, NewTableName);
Buffer.Append(TDBXSQL.Nl);
MakeSqlDropTable(Buffer, NewTable.OriginalRow);
end;
end;
end;
function TDBXBaseMetaDataWriter.CopyColumns(const ColumnTable: TDBXTable): TDBXTable;
var
Columns: TDBXValueTypeArray;
TableCopy: TDBXTable;
Cursor: TDBXTable;
begin
Columns := TDBXMetaDataCollectionColumns.CreateColumnsColumns;
TableCopy := FContext.CreateTableStorage(TDBXMetaDataCollectionName.Columns, Columns);
Cursor := ColumnTable.CreateTableView(TDBXColumnsColumns.Ordinal);
TableCopy.CopyFrom(Cursor);
TableCopy.AcceptChanges;
FreeAndNil(Cursor);
Result := TableCopy;
end;
function TDBXBaseMetaDataWriter.CopyTable(const Table: TDBXTableRow; const TempTableName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
TableCopy: TDBXTable;
NewTableName: string;
begin
Columns := TDBXMetaDataCollectionColumns.CreateTablesColumns;
TableCopy := FContext.CreateTableStorage(TDBXMetaDataCollectionName.Tables, Columns);
TableCopy.Insert;
CopyRow(Table, TableCopy, Length(Columns));
NewTableName := TableCopy.Value[TDBXTablesIndex.TableName].GetWideString(NullString);
TableCopy.Value[TDBXTablesIndex.TableName].AsString := TempTableName;
TableCopy.Post;
TableCopy.AcceptChanges;
TableCopy.Value[TDBXTablesIndex.TableName].AsString := NewTableName;
Result := TableCopy;
end;
function TDBXBaseMetaDataWriter.ComputeColumnMap(const Columns: TDBXTable): TDBXProperties;
var
Map: TDBXProperties;
Current: TDBXTable;
Original: TDBXTableRow;
begin
Map := TDBXProperties.Create;
Current := Columns.CreateTableView(NullString);
Current.First;
while Current.InBounds do
begin
Original := Current.OriginalRow;
if Original <> nil then
Map[Original.Value[TDBXColumnsIndex.ColumnName].AsString] := Current.Value[TDBXColumnsIndex.ColumnName].AsString;
Current.Next;
end;
FreeAndNil(Current);
Result := Map;
end;
function TDBXBaseMetaDataWriter.GetDefaults(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable;
var
LColumnConstraintsTable: TDBXTable;
begin
LColumnConstraintsTable := FReader.FetchColumnConstraints(CatalogName, SchemaName, TableName);
Result := FReader.MakeStorage(LColumnConstraintsTable);
end;
function TDBXBaseMetaDataWriter.GetIndexes(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable;
var
LIndexesTable: TDBXTable;
begin
LIndexesTable := FReader.FetchIndexes(CatalogName, SchemaName, TableName);
Result := FReader.MakeStorage(LIndexesTable);
end;
function TDBXBaseMetaDataWriter.GetIndexColumns(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable;
var
LIndexColumnsTable: TDBXTable;
begin
LIndexColumnsTable := FReader.FetchIndexColumns(CatalogName, SchemaName, TableName, NullString);
Result := FReader.MakeStorage(LIndexColumnsTable);
end;
function TDBXBaseMetaDataWriter.GetForeignKeyColumns(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable;
var
LForeignKeyColumnsTable, ForeignKeyColumns, ImportedKeyColumns: TDBXTable;
begin
LForeignKeyColumnsTable := FReader.FetchForeignKeyColumns(CatalogName, SchemaName, TableName, NullString, NullString, NullString, NullString, NullString);
ForeignKeyColumns := FReader.MakeStorage(LForeignKeyColumnsTable);
ImportedKeyColumns := FReader.FetchForeignKeyColumns(NullString, NullString, NullString, NullString, CatalogName, SchemaName, TableName, NullString);
ForeignKeyColumns.CopyFrom(ImportedKeyColumns);
ImportedKeyColumns.Close;
ImportedKeyColumns.Free;
ForeignKeyColumns.AcceptChanges;
Result := ForeignKeyColumns;
end;
procedure TDBXBaseMetaDataWriter.RemoveForeignKeyGeneratedIndexes(const Table: TDBXTableRow; const Indexes: TDBXTable; const IndexColumns: TDBXTable; const ForeignKeyColumns: TDBXTable);
var
GeneratedIndexName, Name: string;
Original: TDBXTableRow;
ConstraintNames, IndexNames: TDBXStringList;
begin
GeneratedIndexName := SqlKeyGeneratedIndexName;
if not GeneratedIndexName.IsEmpty then
begin
ConstraintNames := nil;
IndexNames := nil;
try
Original := Table.OriginalRow;
ForeignKeyColumns.First;
ConstraintNames := TDBXStringList.Create;
while ForeignKeyColumns.InBounds do
begin
if Compare(ForeignKeyColumns, TDBXForeignKeyColumnsIndex.CatalogName, Original, TDBXTablesIndex.CatalogName, (TDBXTablesIndex.TableName - TDBXTablesIndex.CatalogName) + 1) and (ForeignKeyColumns.Value[TDBXForeignKeyColumnsIndex.Ordinal].AsInt32 = 1) then
ConstraintNames.Add(ForeignKeyColumns.Value[TDBXForeignKeyColumnsIndex.ForeignKeyName].GetWideString(TDBXSQL.Empty) + GeneratedIndexName);
ForeignKeyColumns.Next;
end;
Indexes.First;
IndexNames := TDBXStringList.Create;
while Indexes.InBounds do
begin
Name := Indexes.Value[TDBXIndexesIndex.ConstraintName].GetWideString(NullString);
if Name.IsEmpty then
Name := Indexes.Value[TDBXIndexesIndex.IndexName].GetWideString(NullString);
if Name.EndsWith(GeneratedIndexName) and (ConstraintNames.IndexOf(Name) >= 0) then
begin
IndexNames.Add(Indexes.Value[TDBXIndexesIndex.IndexName].GetWideString(TDBXSQL.Empty));
Indexes.DeleteRow;
end;
Indexes.Next;
end;
Indexes.AcceptChanges;
IndexColumns.First;
while IndexColumns.InBounds do
begin
Name := IndexColumns.Value[TDBXIndexColumnsIndex.IndexName].GetWideString(TDBXSQL.Empty);
if Name.EndsWith(GeneratedIndexName) and (IndexNames.IndexOf(Name) >= 0) then
IndexColumns.DeleteRow;
IndexColumns.Next;
end;
finally
IndexNames.Free;
ConstraintNames.Free;
end;
IndexColumns.AcceptChanges;
end;
end;
procedure TDBXBaseMetaDataWriter.DropAllConstraints(const Buffer: TStringBuilder; const Defaults: TDBXTable; const Indexes: TDBXTable; const ForeignKeys: TDBXTable);
begin
if Defaults <> nil then
begin
Defaults.First;
while Defaults.InBounds do
begin
MakeSqlDropConstraint(Buffer, Defaults);
Defaults.Next;
end;
end;
ForeignKeys.First;
while ForeignKeys.InBounds do
begin
if ForeignKeys.Value[TDBXForeignKeyColumnsIndex.Ordinal].GetInt32(0) = 1 then
MakeSqlDropForeignKey(Buffer, ForeignKeys);
ForeignKeys.Next;
end;
Indexes.First;
while Indexes.InBounds do
begin
MakeSqlDropIndex(Buffer, Indexes);
Indexes.Next;
end;
end;
procedure TDBXBaseMetaDataWriter.CreateTempOutputTable(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Columns: TDBXTable; const TempTableName: string);
var
TempStorage: TDBXTable;
begin
TempStorage := FContext.CreateTableStorage(TDBXMetaDataCollectionName.Tables, TDBXMetaDataCollectionColumns.CreateTablesColumns);
TempStorage.First;
TempStorage.Insert;
TempStorage.Value[TDBXTablesIndex.CatalogName].SetValue(Table.Value[TDBXTablesIndex.CatalogName]);
TempStorage.Value[TDBXTablesIndex.SchemaName].SetValue(Table.Value[TDBXTablesIndex.SchemaName]);
TempStorage.Value[TDBXTablesIndex.TableName].AsString := TempTableName;
TempStorage.Post;
MakeSqlCreate(Buffer, TempStorage, Columns);
FreeAndNil(TempStorage);
end;
procedure TDBXBaseMetaDataWriter.SetIdentityInsert(const Buffer: TStringBuilder; const CatalogName: string; const SchemaName: string; const TableName: string; const bOn: Boolean);
var
AutoIncrementInserts: string;
begin
AutoIncrementInserts := SqlAutoIncrementInserts;
if not AutoIncrementInserts.IsEmpty then
begin
Buffer.Append(TDBXSQL.cSet);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(AutoIncrementInserts);
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, CatalogName, SchemaName, TableName);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(C_Conditional(bOn, TDBXSQL.cOn, TDBXSQL.Off));
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
end;
function TDBXBaseMetaDataWriter.CheckForAutoIncrement(const Columns: TDBXTable): Boolean;
begin
Columns.First;
while Columns.InBounds do
begin
if Columns.Value[TDBXColumnsIndex.IsAutoIncrement].GetBoolean(False) then
Exit(True);
Columns.Next;
end;
Result := False;
end;
procedure TDBXBaseMetaDataWriter.InsertValuesFromOldTable(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Columns: TDBXTable; const TempTableName: string);
var
CurrentColumns: TDBXTable;
OriginalTable: TDBXTableRow;
OldCatalogName: string;
OldSchemaName: string;
OldTableName: string;
NewCatalogName: string;
NewSchemaName: string;
HasAutoIncrementColumn: Boolean;
Original: TDBXTableRow;
Comma: string;
begin
CurrentColumns := Columns.CreateTableView(TDBXColumnsColumns.Ordinal);
OriginalTable := Table.OriginalRow;
OldCatalogName := OriginalTable.Value[TDBXTablesIndex.CatalogName].GetWideString(NullString);
OldSchemaName := OriginalTable.Value[TDBXTablesIndex.SchemaName].GetWideString(NullString);
OldTableName := OriginalTable.Value[TDBXTablesIndex.TableName].GetWideString(NullString);
NewCatalogName := Table.Value[TDBXTablesIndex.CatalogName].GetWideString(NullString);
NewSchemaName := Table.Value[TDBXTablesIndex.SchemaName].GetWideString(NullString);
HasAutoIncrementColumn := CheckForAutoIncrement(CurrentColumns);
if HasAutoIncrementColumn then
SetIdentityInsert(Buffer, NewCatalogName, NewSchemaName, TempTableName, True);
Buffer.Append(TDBXSQL.Insert);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Into);
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, NewCatalogName, NewSchemaName, TempTableName);
Buffer.Append(TDBXSQL.OpenParen);
Comma := TDBXSQL.Empty;
CurrentColumns.First;
while CurrentColumns.InBounds do
begin
Original := CurrentColumns.OriginalRow;
if Original <> nil then
begin
Buffer.Append(Comma);
Comma := TDBXSQL.Comma;
MakeSqlIdentifier(Buffer, CurrentColumns.Value[TDBXColumnsIndex.ColumnName].GetWideString(NullString));
end;
CurrentColumns.Next;
end;
Buffer.Append(TDBXSQL.CloseParen);
Buffer.Append(TDBXSQL.Nl);
Buffer.Append(TDBXSQL.Spacing);
Buffer.Append(TDBXSQL.Select);
Buffer.Append(TDBXSQL.Space);
CurrentColumns.First;
Comma := TDBXSQL.Empty;
while CurrentColumns.InBounds do
begin
Original := CurrentColumns.OriginalRow;
if Original <> nil then
begin
Buffer.Append(Comma);
Comma := TDBXSQL.Comma;
if CurrentColumns.Value[TDBXColumnsIndex.TypeName].EqualsValue(Original.Value[TDBXColumnsIndex.TypeName]) and CurrentColumns.Value[TDBXColumnsIndex.Precision].EqualsValue(Original.Value[TDBXColumnsIndex.Precision]) and CurrentColumns.Value[TDBXColumnsIndex.Scale].EqualsValue(Original.Value[TDBXColumnsIndex.Scale]) then
MakeSqlIdentifier(Buffer, Original.Value[TDBXColumnsIndex.ColumnName].GetWideString(NullString))
else
MakeSqlColumnTypeCast(Buffer, CurrentColumns);
end;
CurrentColumns.Next;
end;
FreeAndNil(CurrentColumns);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.From);
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, OldCatalogName, OldSchemaName, OldTableName);
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
if HasAutoIncrementColumn then
SetIdentityInsert(Buffer, NewCatalogName, NewSchemaName, TempTableName, False);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlColumnTypeCast(const Buffer: TStringBuilder; const Column: TDBXTable);
var
Original: TDBXTableRow;
begin
Original := Column.OriginalRow;
Buffer.Append(TDBXSQL.Cast);
Buffer.Append(TDBXSQL.OpenParen);
MakeSqlIdentifier(Buffer, Original.Value[TDBXColumnsIndex.ColumnName].GetWideString(NullString));
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.cAs);
Buffer.Append(TDBXSQL.Space);
MakeSqlDataType(Buffer, Column.Value[TDBXColumnsIndex.TypeName].AsString, Column);
Buffer.Append(TDBXSQL.CloseParen);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlDropTable(const Buffer: TStringBuilder; const Table: TDBXTableRow);
begin
Buffer.Append(TDBXSQL.Drop);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Table);
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, Table.Value[TDBXTablesIndex.CatalogName].GetWideString(NullString), Table.Value[TDBXTablesIndex.SchemaName].GetWideString(NullString), Table.Value[TDBXTablesIndex.TableName].GetWideString(NullString));
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
procedure TDBXBaseMetaDataWriter.ReplaceParameter(const Buffer: TStringBuilder; const Start: Integer; const InParameter: string; const Replacement: string);
var
Marker, Parameter: string;
begin
Parameter := InParameter;
Marker := FReader.SqlDefaultParameterMarker;
Parameter := Marker + Parameter;
if Replacement.IsEmpty or (Replacement.Length = 0) then
Parameter := Parameter + TDBXSQL.Dot;
Buffer.Replace(Parameter,Replacement,Start,Buffer.Length-Start);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlTableRename(const Buffer: TStringBuilder; const CatalogName: string; const SchemaName: string; const TableName: string; const NewTableName: string);
var
Start: Integer;
begin
Start := Buffer.Length;
Buffer.Append(SqlRenameTable);
ReplaceParameter(Buffer, Start, TDBXParameterName.CatalogName, CatalogName);
ReplaceParameter(Buffer, Start, TDBXParameterName.SchemaName, SchemaName);
ReplaceParameter(Buffer, Start, TDBXParameterName.TableName, TableName);
ReplaceParameter(Buffer, Start, TDBXParameterName.NewSchemaName, SchemaName);
ReplaceParameter(Buffer, Start, TDBXParameterName.NewTableName, NewTableName);
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
procedure TDBXBaseMetaDataWriter.CopyRow(const Source: TDBXTableRow; const Target: TDBXTable; const Columns: Integer);
var
Ordinal: Integer;
begin
for Ordinal := 0 to Columns - 1 do
Target.Value[Ordinal].SetValue(Source.Value[Ordinal]);
end;
function TDBXBaseMetaDataWriter.Compare(const Table: TDBXTable; const InStart: Integer; const Row: TDBXTableRow; const InRowStart: Integer; const Columns: Integer): Boolean;
var
Start: Integer;
RowStart: Integer;
Index: Integer;
begin
Start := InStart;
RowStart := InRowStart;
for index := 0 to Columns - 1 do
begin
if not Row.Value[RowStart].IsNull and not Table.Value[Start].EqualsValue(Row.Value[RowStart]) then
Exit(False);
IncrAfter(Start);
IncrAfter(RowStart);
end;
Result := True;
end;
function TDBXBaseMetaDataWriter.SameConstraint(const Table: TDBXTable; const Row: TDBXTableRow; const Columns: Integer): Boolean;
var
Ordinal: Integer;
begin
for Ordinal := 0 to Columns - 1 do
begin
if not Table.Value[Ordinal].EqualsValue(Row.Value[Ordinal]) then
Exit(False);
end;
Result := True;
end;
procedure TDBXBaseMetaDataWriter.MapTable(const Item: TDBXTable; const Table: TDBXTableRow);
var
Original: TDBXTableRow;
begin
Original := Table.OriginalRow;
if Compare(Item, TDBXIndexesIndex.CatalogName, Original, TDBXTablesIndex.CatalogName, TDBXTablesIndex.TableName - TDBXTablesIndex.CatalogName + 1) then
begin
Item.Value[TDBXTablesIndex.CatalogName].SetValue(Table.Value[TDBXTablesIndex.CatalogName]);
Item.Value[TDBXTablesIndex.SchemaName].SetValue(Table.Value[TDBXTablesIndex.SchemaName]);
Item.Value[TDBXTablesIndex.TableName].SetValue(Table.Value[TDBXTablesIndex.TableName]);
end;
end;
function TDBXBaseMetaDataWriter.MapColumn(const Parts: TDBXTable; const Table: TDBXTableRow; const ColumnMap: TDBXProperties; const ColIndex: Integer; const IdColumns: Integer; const DroppedColumn: string): string;
var
Original: TDBXTableRow;
ColumnName, MappedName: string;
begin
if (DroppedColumn.IsEmpty) and (ColIndex >= 0) then
begin
Original := Table.OriginalRow;
if Compare(Parts, ColIndex - IdColumns, Original, TDBXTablesIndex.CatalogName, TDBXTablesIndex.TableName - TDBXTablesIndex.CatalogName + 1) then
begin
ColumnName := Parts.Value[ColIndex].AsString;
MappedName := ColumnMap[ColumnName];
if MappedName.IsEmpty then
Exit(ColumnName);
Parts.Value[ColIndex].SetWideString(MappedName);
Parts.Value[ColIndex - IdColumns + TDBXTablesIndex.CatalogName].SetValue(Table.Value[TDBXTablesIndex.CatalogName]);
Parts.Value[ColIndex - IdColumns + TDBXTablesIndex.SchemaName].SetValue(Table.Value[TDBXTablesIndex.SchemaName]);
Parts.Value[ColIndex - IdColumns + TDBXTablesIndex.TableName].SetValue(Table.Value[TDBXTablesIndex.TableName]);
end;
end;
Result := DroppedColumn;
end;
procedure TDBXBaseMetaDataWriter.CreateConstraints(const Buffer: TStringBuilder; const Columns: TDBXValueTypeArray; const Constraints: TDBXTable; const ConstraintColumns: TDBXTable; const CollectionName: string; const IdColumns: Integer; const ItemColumns: Integer; const PartColumns: Integer; const Table: TDBXTableRow; const ColumnMap: TDBXProperties; const ColIndex1: Integer; const ColIndex2: Integer);
var
Item, ItemSource, Parts: TDBXTable;
DroppedColumn: string;
MoreColumns, MoreItems: Boolean;
begin
Item := nil;
Parts := nil;
try
Item := FContext.CreateTableStorage(CollectionName, Columns);
DroppedColumn := NullString;
Item.First;
Item.Insert;
Item.Post;
MoreItems := True;
ItemSource := ConstraintColumns;
if Constraints <> nil then
begin
ItemSource := Constraints;
MoreItems := Constraints.First;
end;
MoreColumns := ConstraintColumns.First;
Parts := FContext.CreateTableStorage(ConstraintColumns.DBXTableName, ConstraintColumns.CopyColumns);
while MoreColumns and MoreItems do
begin
CopyRow(ItemSource, Item, ItemColumns);
Parts.Clear;
while MoreColumns and SameConstraint(ConstraintColumns, Item, IdColumns) do
begin
Parts.First;
Parts.Insert;
CopyRow(ConstraintColumns, Parts, PartColumns);
DroppedColumn := MapColumn(Parts, Table, ColumnMap, ColIndex1, IdColumns, DroppedColumn);
DroppedColumn := MapColumn(Parts, Table, ColumnMap, ColIndex2, IdColumns, DroppedColumn);
Parts.Post;
MoreColumns := ConstraintColumns.Next;
end;
if Constraints <> nil then
MoreItems := Constraints.Next;
if DroppedColumn.IsEmpty then
begin
MapTable(Item, Table);
MakeSqlCreate(Buffer, Item, Parts);
end
else
begin
Buffer.Append(TDBXSQL.LineComment);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(string.Format(SCannotRecreateConstraint, [Item.Value[IdColumns - 1].AsString,DroppedColumn]));
Buffer.Append(TDBXSQL.Nl);
DroppedColumn := NullString;
end;
end;
finally
Parts.Free;
Item.Free;
end;
end;
procedure TDBXBaseMetaDataWriter.CreateIndices(const Buffer: TStringBuilder; const Table: TDBXTableRow; const Indexes: TDBXTable; const IndexColumns: TDBXTable; const ColumnMap: TDBXProperties);
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateIndexesColumns;
CreateConstraints(Buffer, Columns, Indexes, IndexColumns, TDBXMetaDataCollectionName.Indexes, TDBXIndexesIndex.IndexName + 1, TDBXIndexesIndex.IsUnique + 1, TDBXIndexColumnsIndex.IsAscending + 1, Table, ColumnMap, TDBXIndexColumnsIndex.ColumnName, -1);
end;
procedure TDBXBaseMetaDataWriter.CreateForeignKeys(const Buffer: TStringBuilder; const Table: TDBXTableRow; const ForeignKeyColumns: TDBXTable; const ColumnMap: TDBXProperties);
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateForeignKeysColumns;
CreateConstraints(Buffer, Columns, nil, ForeignKeyColumns, TDBXMetaDataCollectionName.ForeignKeys, TDBXForeignKeysIndex.ForeignKeyName + 1, TDBXForeignKeysIndex.ForeignKeyName + 1, TDBXForeignKeyColumnsIndex.Ordinal + 1, Table, ColumnMap, TDBXForeignKeyColumnsIndex.ColumnName, TDBXForeignKeyColumnsIndex.PrimaryColumnName);
end;
function TDBXBaseMetaDataWriter.CanCreateIndexAsKey(const Index: TDBXTableRow; const IndexColumns: TDBXTable): Boolean;
begin
if not DescendingIndexConstraintsSupported and (IndexColumns <> nil) then
begin
IndexColumns.First;
while IndexColumns.InBounds do
begin
if not IndexColumns.Value[TDBXIndexColumnsIndex.IsAscending].GetBoolean(True) then
Exit(False);
IndexColumns.Next;
end;
end;
if not Index.Value[TDBXIndexesIndex.IsPrimary].GetBoolean(False) and not Index.Value[TDBXIndexesIndex.IsUnique].GetBoolean(False) then
Exit(False);
Result := True;
end;
procedure TDBXBaseMetaDataWriter.MakeSqlCreateIndex(const Buffer: TStringBuilder; const Index: TDBXTableRow; const IndexColumns: TDBXTable);
begin
if CanCreateIndexAsKey(Index, IndexColumns) then
MakeSqlCreateKey(Buffer, Index, IndexColumns)
else
MakeSqlCreateSecondaryIndex(Buffer, Index, IndexColumns);
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlDropIndex(const Buffer: TStringBuilder; const Index: TDBXTableRow);
begin
if not Index.Value[TDBXIndexesIndex.ConstraintName].IsNull then
MakeSqlDropConstraint(Buffer, Index)
else
MakeSqlDropSecondaryIndex(Buffer, Index);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlCreateKey(const Buffer: TStringBuilder; const Index: TDBXTableRow; const IndexColumns: TDBXTable);
begin
MakeSqlCreateConstraint(Buffer, Index);
if Index.Value[TDBXIndexesIndex.IsPrimary].GetBoolean(False) then
begin
Buffer.Append(TDBXSQL.Primary);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Key);
end
else
Buffer.Append(TDBXSQL.Unique);
MakeSqlCreateIndexColumnList(Buffer, IndexColumns);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlCreateSecondaryIndex(const Buffer: TStringBuilder; const Index: TDBXTableRow; const IndexColumns: TDBXTable);
begin
Buffer.Append(TDBXSQL.Create);
Buffer.Append(TDBXSQL.Space);
if Index.Value[TDBXIndexesIndex.IsUnique].GetBoolean(False) or Index.Value[TDBXIndexesIndex.IsPrimary].GetBoolean(False) then
begin
Buffer.Append(TDBXSQL.Unique);
Buffer.Append(TDBXSQL.Space);
end;
if FReader.DescendingIndexSupported and not Index.Value[TDBXIndexesIndex.IsAscending].GetBoolean(True) then
begin
Buffer.Append(TDBXSQL.Descending);
Buffer.Append(TDBXSQL.Space);
end;
Buffer.Append(TDBXSQL.Index);
Buffer.Append(TDBXSQL.Space);
MakeSqlIdentifier(Buffer, Index.Value[TDBXIndexesIndex.IndexName].GetWideString(NullString));
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.cOn);
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, Index.Value[TDBXIndexesIndex.CatalogName].GetWideString(NullString), Index.Value[TDBXIndexesIndex.SchemaName].GetWideString(NullString), Index.Value[TDBXIndexesIndex.TableName].GetWideString(NullString));
MakeSqlCreateIndexColumnList(Buffer, IndexColumns);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlCreateConstraint(const Buffer: TStringBuilder; const Constraint: TDBXTableRow);
begin
MakeSqlAlterTablePrefix(Buffer, Constraint);
Buffer.Append(TDBXSQL.Add);
Buffer.Append(TDBXSQL.Space);
MakeSqlConstraintName(Buffer, Constraint);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlConstraintName(const Buffer: TStringBuilder; const Constraint: TDBXTableRow);
var
ConstraintName: string;
begin
ConstraintName := NullString;
if (Constraint.DBXTableName = TDBXMetaDataCollectionName.Indexes) then
ConstraintName := Constraint.Value[TDBXIndexesIndex.ConstraintName].GetWideString(NullString);
if ConstraintName.IsEmpty then
ConstraintName := Constraint.Value[TDBXForeignKeysIndex.ForeignKeyName].AsString;
if (not ConstraintName.IsEmpty) and (ConstraintName.Length > 0) then
begin
Buffer.Append(TDBXSQL.Constraint);
Buffer.Append(TDBXSQL.Space);
MakeSqlIdentifier(Buffer, ConstraintName);
Buffer.Append(TDBXSQL.Space);
end;
end;
procedure TDBXBaseMetaDataWriter.MakeSqlAlterTablePrefix(const Buffer: TStringBuilder; const Item: TDBXTableRow);
begin
Buffer.Append(TDBXSQL.Alter);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Table);
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, Item.Value[TDBXForeignKeysIndex.CatalogName].GetWideString(NullString), Item.Value[TDBXForeignKeysIndex.SchemaName].GetWideString(NullString), Item.Value[TDBXForeignKeysIndex.TableName].GetWideString(NullString));
Buffer.Append(TDBXSQL.Space);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlDropConstraint(const Buffer: TStringBuilder; const Constraint: TDBXTableRow);
var
ConstraintName: string;
begin
MakeSqlAlterTablePrefix(Buffer, Constraint);
ConstraintName := NullString;
if (Constraint.DBXTableName = TDBXMetaDataCollectionName.Indexes) then
ConstraintName := Constraint.Value[TDBXIndexesIndex.ConstraintName].GetWideString(NullString);
if ConstraintName.IsEmpty then
ConstraintName := Constraint.Value[TDBXForeignKeysIndex.ForeignKeyName].AsString;
Buffer.Append(TDBXSQL.Drop);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Constraint);
Buffer.Append(TDBXSQL.Space);
MakeSqlIdentifier(Buffer, ConstraintName);
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlCreateIndexColumnList(const Buffer: TStringBuilder; const IndexColumns: TDBXTable);
var
Columns: TDBXTable;
Comma: string;
begin
Buffer.Append(TDBXSQL.Nl);
Buffer.Append(TDBXSQL.Spacing);
Buffer.Append(TDBXSQL.OpenParen);
Columns := IndexColumns.CreateTableView(TDBXIndexColumnsColumns.Ordinal);
Columns.First;
Comma := TDBXSQL.Empty;
while Columns.InBounds do
begin
Buffer.Append(Comma);
Comma := TDBXSQL.Comma + TDBXSQL.Space;
MakeSqlIdentifier(Buffer, Columns.Value[TDBXIndexColumnsIndex.ColumnName].GetWideString(NullString));
if FReader.DescendingIndexColumnsSupported and not Columns.Value[TDBXIndexColumnsIndex.IsAscending].GetBoolean(True) then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Descending);
end;
Columns.Next;
end;
FreeAndNil(Columns);
Buffer.Append(TDBXSQL.CloseParen);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlDropSecondaryIndex(const Buffer: TStringBuilder; const Index: TDBXTableRow);
begin
Buffer.Append(TDBXSQL.Drop);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Index);
Buffer.Append(TDBXSQL.Space);
MakeSqlIdentifier(Buffer, Index.Value[TDBXIndexesIndex.IndexName].GetWideString(NullString));
if not IndexNamesGlobal then
begin
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.cOn);
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, Index.Value[TDBXIndexesIndex.CatalogName].GetWideString(NullString), Index.Value[TDBXIndexesIndex.SchemaName].GetWideString(NullString), Index.Value[TDBXIndexesIndex.TableName].GetWideString(NullString));
end;
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlForeignKeySyntax(const Buffer: TStringBuilder; const ForeignKey: TDBXTableRow; const ForeignKeyColumns: TDBXTable);
var
Columns: TDBXTable;
Comma: string;
begin
Buffer.Append(TDBXSQL.Foreign);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Key);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.OpenParen);
Columns := ForeignKeyColumns.CreateTableView(TDBXForeignKeyColumnsColumns.Ordinal);
Columns.First;
Comma := TDBXSQL.Empty;
while Columns.InBounds do
begin
Buffer.Append(Comma);
Comma := TDBXSQL.Comma + TDBXSQL.Space;
MakeSqlIdentifier(Buffer, Columns.Value[TDBXForeignKeyColumnsIndex.ColumnName].GetWideString(NullString));
Columns.Next;
end;
Buffer.Append(TDBXSQL.CloseParen);
Columns.First;
Buffer.Append(TDBXSQL.Nl);
Buffer.Append(TDBXSQL.Spacing);
Buffer.Append(TDBXSQL.References);
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, Columns.Value[TDBXForeignKeyColumnsIndex.PrimaryCatalogName].GetWideString(NullString), Columns.Value[TDBXForeignKeyColumnsIndex.PrimarySchemaName].GetWideString(NullString), Columns.Value[TDBXForeignKeyColumnsIndex.PrimaryTableName].GetWideString(NullString));
Buffer.Append(TDBXSQL.OpenParen);
Columns.First;
Comma := TDBXSQL.Empty;
while Columns.InBounds do
begin
Buffer.Append(Comma);
Comma := TDBXSQL.Comma + TDBXSQL.Space;
MakeSqlIdentifier(Buffer, Columns.Value[TDBXForeignKeyColumnsIndex.PrimaryColumnName].GetWideString(NullString));
Columns.Next;
end;
Buffer.Append(TDBXSQL.CloseParen);
FreeAndNil(Columns);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlCreateForeignKey(const Buffer: TStringBuilder; const ForeignKey: TDBXTableRow; const ForeignKeyColumns: TDBXTable);
begin
MakeSqlCreateConstraint(Buffer, ForeignKey);
MakeSqlForeignKeySyntax(Buffer, ForeignKey, ForeignKeyColumns);
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlDropForeignKey(const Buffer: TStringBuilder; const ForeignKey: TDBXTableRow);
begin
MakeSqlDropConstraint(Buffer, ForeignKey);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlCreateView(const Buffer: TStringBuilder; const View: TDBXTableRow; const Columns: TDBXTable);
begin
Buffer.Append(View.Value[TDBXViewsIndex.Definition].GetWideString(NullString));
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlAlterView(const Buffer: TStringBuilder; const View: TDBXTableRow; const Columns: TDBXTable);
var
Definition: string;
begin
Definition := View.Value[TDBXViewsIndex.Definition].GetWideString(NullString);
Definition := Definition.Trim;
if (Definition.Length < TDBXSQL.Create.Length) or not (Definition.Substring(0, TDBXSQL.Create.Length).ToUpper = TDBXSQL.Create) then
raise TDBXMetaDataError.Create(SWrongViewDefinition);
Buffer.Append(TDBXSQL.Alter);
Buffer.Append(Definition.Substring(TDBXSQL.Create.Length, Definition.Length - TDBXSQL.Create.Length));
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlDropView(const Buffer: TStringBuilder; const View: TDBXTableRow);
begin
Buffer.Append(TDBXSQL.Drop);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.View);
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, View.Value[TDBXViewsIndex.CatalogName].AsString, View.Value[TDBXViewsIndex.SchemaName].AsString, View.Value[TDBXViewsIndex.ViewName].AsString);
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlCreateSynonym(const Buffer: TStringBuilder; const Synonym: TDBXTableRow; const Columns: TDBXTable);
begin
Buffer.Append(TDBXSQL.Create);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Synonym);
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, Synonym.Value[TDBXSynonymsIndex.CatalogName].GetWideString(NullString), Synonym.Value[TDBXSynonymsIndex.SchemaName].GetWideString(NullString), Synonym.Value[TDBXSynonymsIndex.SynonymName].GetWideString(NullString));
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.cFor);
MakeSqlObjectName(Buffer, Synonym.Value[TDBXSynonymsIndex.TableCatalogName].GetWideString(NullString), Synonym.Value[TDBXSynonymsIndex.TableSchemaName].GetWideString(NullString), Synonym.Value[TDBXSynonymsIndex.TableName].GetWideString(NullString));
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlAlterSynonym(const Buffer: TStringBuilder; const Synonym: TDBXTableRow; const Columns: TDBXTable);
begin
MakeSqlDropSynonym(Buffer, Synonym);
MakeSqlCreateSynonym(Buffer, Synonym, Columns);
end;
procedure TDBXBaseMetaDataWriter.MakeSqlDropSynonym(const Buffer: TStringBuilder; const Synonym: TDBXTableRow);
begin
Buffer.Append(TDBXSQL.Drop);
Buffer.Append(TDBXSQL.Space);
Buffer.Append(TDBXSQL.Synonym);
Buffer.Append(TDBXSQL.Space);
MakeSqlObjectName(Buffer, Synonym.Value[TDBXSynonymsIndex.CatalogName].GetWideString(NullString), Synonym.Value[TDBXSynonymsIndex.SchemaName].GetWideString(NullString), Synonym.Value[TDBXSynonymsIndex.SynonymName].GetWideString(NullString));
Buffer.Append(TDBXSQL.Semicolon);
Buffer.Append(TDBXSQL.Nl);
end;
end.
|
unit uMAP_File;
interface
uses Windows, SysUtils;
type
tMapFileLog = procedure(msg:string) of object;
tMapFile = class
private
onLog : tMapFileLog;
handle : cardinal;
f_name : string;
f_data : pointer;
f_size : integer;
f_created : boolean;
procedure log(s:string);
function name_local : string;
function name_global : string;
function name_current : string;
public
constructor create(v_name:string; v_size:integer; v_onLog:tMapFileLog=nil);
destructor destroy; override;
function open(create_new:boolean=false; write:boolean=true) : boolean;
procedure close;
property name : string read name_current;
property data : pointer read f_data;
property size : integer read f_size;
property is_created : boolean read f_created;
end;
var
open_map_local : boolean;
implementation
uses AccCtrl, AclAPI;
constructor tMapFile.create(v_name : string; v_size : integer; v_onLog : tMapFileLog = nil);
begin
inherited create;
f_data := nil;
handle := 0;
f_name := 'SpRecordNEW_'+self.ClassName+'_'+v_name;
f_size := v_size;
onLog := v_onLog;
end;
destructor tMapFile.destroy;
begin
if self = nil then exit;
if handle <> 0 then
self.close;
inherited destroy;
end;
procedure tMapFile.log(s:string);
begin
if self = nil then exit;
if @onLog = nil then exit;
onLog(self.ClassName+#9+s);
end;
function tMapFile.name_local : string;
begin
if self = nil then exit;
result := 'Local\'+f_name;
end;
function tMapFile.name_global : string;
begin
if self = nil then exit;
result := 'Global\'+f_name;
end;
function tMapFile.name_current : string;
begin
if self = nil then exit;
if open_map_local then
result :=name_local
else
result :=name_global;
end;
function tMapFile.open(create_new : boolean = false; write : boolean = true) : boolean;
var
protect_create : cardinal;
protect_map : cardinal;
error_code : cardinal;
{ SIDAuthWorld : SID_IDENTIFIER_AUTHORITY;
everyone_sid : PSID;
ea : EXPLICIT_ACCESS;
acl : PACL;
sd : PSECURITY_DESCRIPTOR;
sa : SECURITY_ATTRIBUTES;
error : cardinal; }
const
SECURITY_WORLD_SID_AUTHORITY : _SID_IDENTIFIER_AUTHORITY = (value:(0,0,0,0,0,1));
label
go_create;
begin
result := false;
if self = nil then exit;
self.close;
{ SIDAuthWorld := SECURITY_WORLD_SID_AUTHORITY;
everyone_sid := Nil;
if not AllocateAndInitializeSid(SIDAuthWorld, 1, 0,
0, 0, 0, 0, 0, 0, 0, everyone_sid) then
log('ERROR: Map file of "'+name_current+'" AllocateAndInitializeSid: '+SysErrorMessage(GetLastError));
ZeroMemory(@ea, sizeof(ea));
ea.grfAccessPermissions := SPECIFIC_RIGHTS_ALL or STANDARD_RIGHTS_ALL;
ea.grfAccessMode := SET_ACCESS;
ea.grfInheritance := NO_INHERITANCE;
ea.Trustee.TrusteeForm := TRUSTEE_IS_SID;
ea.Trustee.TrusteeType := TRUSTEE_IS_WELL_KNOWN_GROUP;
ea.Trustee.ptstrName := everyone_sid;
acl := nil;
error := SetEntriesInAcl(1, @ea, nil, acl);
if error <> ERROR_SUCCESS then
log('ERROR: Map file of "'+name_current+'" InitializeSecurityDescriptor error: '+inttostr(error));
sd := 0;
sd := PSECURITY_DESCRIPTOR(LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH));
if not InitializeSecurityDescriptor(sd, SECURITY_DESCRIPTOR_REVISION) then
log('ERROR: Map file of "'+name_current+'" InitializeSecurityDescriptor: '+SysErrorMessage(GetLastError));
if not SetSecurityDescriptorDacl(sd, TRUE, acl, FALSE) then
log('ERROR: Map file of "'+name_current+'" SetSecurityDescriptorDacl: '+SysErrorMessage(GetLastError));
sa.nLength := sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor := sd;
sa.bInheritHandle := FALSE; }
if write then
begin
protect_map := FILE_MAP_ALL_ACCESS;
protect_create := SEC_COMMIT or PAGE_READWRITE
end
else
begin
protect_map := FILE_MAP_READ;
protect_create := SEC_COMMIT or PAGE_READONLY;
end;
if create_new then
begin
go_create:
handle := CreateFileMapping(INVALID_HANDLE_VALUE, nil, protect_create, 0, f_size, pchar(name_current));
if handle = 0 then
begin
log('ERROR: Map file of "'+name_current+'" create error: '+SysErrorMessage(GetLastError));
result := false;
exit;
end
else
f_created := true;
end
else
begin
handle := OpenFileMapping(protect_map, false, pchar(name_current));
if handle = 0 then
goto go_create
else
f_created := false;
end;
if (GetLastError = ERROR_ALREADY_EXISTS) and create_new then
begin
log('ERROR: Map file of "'+name_current+'" param create_new = TRUE, '+SysErrorMessage(GetLastError));
self.close;
result := false;
exit;
end;
{ FreeSid(everyone_sid);
LocalFree(cardinal(sd));
LocalFree(cardinal(acl));}
error_code:= SetSecurityInfo(handle,
SE_KERNEL_OBJECT,
DACL_SECURITY_INFORMATION,
nil,
nil,
nil,
nil);
if error_code <> ERROR_SUCCESS then
log('ERROR: Map file of "'+name_current+'" SetSecurityInfo return : '+inttostr(error_code));
f_data := nil;
f_data := MapViewOfFile(handle, protect_map, 0, 0, f_size);
if not Assigned(f_data) then
begin
log('ERROR: Map file of "'+name_current+'" MapViewOfFile return NULL: '+SysErrorMessage(GetLastError));
self.close;
result := false;
exit;
end;
result := true;
end;
procedure tMapFile.close;
begin
if self = nil then exit;
if f_data <> nil then
if not UnmapViewOfFile(f_data) then
log('ERROR: Map file of "'+name_current+'" UnmapViewOfFile return false: '+SysErrorMessage(GetLastError));
f_data := nil;
if handle <> 0 then
if not CloseHandle(handle) then
log('ERROR: Map file of "'+name_current+'" CloseHandle return false: '+SysErrorMessage(GetLastError));
handle := 0;
f_created := false;
end;
end.
|
unit FC.Trade.OrderCollection;
interface
uses
SysUtils, BaseUtils, Classes, Serialization, FC.Definitions;
type
{ TSCOrderCollection }
//Self Destruct | Not Self Destruct
TStockOrderCollection = class (TInterfaceProvider,IStockOrderCollection)
private
FList: TInterfaceList;
public
// IStockOrderCollection
function GetItem(Index: Integer): IStockOrder;
function Remove(const aOrder: IStockOrder): integer;
procedure Delete(index: integer);
procedure Clear;
function Add(const aOrder: IStockOrder): integer;
function Count: integer;
property Items[Index: Integer]: IStockOrder read GetItem; default;
constructor Create(aSelfDestruct: boolean=true);
destructor Destroy; override;
end;
implementation
{ TStockOrderCollection }
function TStockOrderCollection.Add(const aOrder: IStockOrder): integer;
begin
result:=FList.Add(aOrder);
end;
function TStockOrderCollection.Count: integer;
begin
result:=FList.Count;
end;
function TStockOrderCollection.GetItem(Index: Integer): IStockOrder;
begin
result:=FList[index] as IStockOrder;
end;
function TStockOrderCollection.Remove(const aOrder: IStockOrder): integer;
begin
result:=FList.IndexOf(aOrder);
if result<>-1 then
Delete(result);
end;
procedure TStockOrderCollection.Delete(index: integer);
begin
FList.Delete(index);
end;
procedure TStockOrderCollection.Clear;
begin
FList.Clear;
end;
constructor TStockOrderCollection.Create(aSelfDestruct: boolean);
begin
inherited CReate;
FSelfDestruct:=aSelfDestruct;
FList:=TInterfaceList.Create;
end;
destructor TStockOrderCollection.Destroy;
begin
FreeAndNil(FList);
inherited;
end;
end.
|
unit AblePersistencedTestMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
ListBox1: TListBox;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
uses
IniFiles,
ansoStrings,
tynList, ansoRTTIHook, RETestCases;
type
TRETestCase1 = class (TtynListItem)
protected
fInputStringBodyRepN : integer;
fInputFileName : string;
published
property InputStringBodyRepN : integer read fInputStringBodyRepN write fInputStringBodyRepN;
property InputFileName : string read fInputFileName write fInputFileName;
end;
TRETestCaseList = class (TtynList)
protected
function GetItems (AIndex: integer) : TRETestCase1;
procedure SetItems (AIndex: integer; AItem : TRETestCase1);
public
property Items [AIndex: integer]: TRETestCase1
read GetItems write SetItems; default;
end;
function TRETestCaseList.GetItems (AIndex: integer) : TRETestCase1;
begin
Result := inherited Items [AIndex] as TRETestCase1;
end;
procedure TRETestCaseList.SetItems (AIndex: integer; AItem : TRETestCase1);
begin
inherited Items [AIndex] := AItem;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
TheList : TRETestCaseList;
TheCase : TRETestCase1;
i : integer;
RTTIHook : TansoRTTIHook;
f : TIniFile;
s, n, v : string;
Cases : TRETestCases;
ACase : TRETestCase;
begin
ACase := TRETestCase.Create;
Cases := TRETestCases.Create;
TheList := TRETestCaseList.Create;
// TheList.StorageIDPrefix := '_';
{
TheCase := TRETestCase1.Create;
with TheCase do begin
InputStringBodyRepN := 3;
InputFileName := 'TheInputFileName';
end;
TheList.Add (TheCase);
TheCase := TRETestCase1.Create;
with TheCase do begin
InputStringBodyRepN := 77;
InputFileName := 'AnotherInputFileName';
end;
TheList.Add (TheCase);
TheList.SaveToFile ('c:\1.str');
}
Cases.LoadFromFile ('D:\Andrey\RegExpr\Demo\DemoREs.txt');
TheList.LoadFromFile ('c:\1.str');
for i := 0 to TheList.Count - 1 do
with TheList [i] do
ListBox1.Items.Add (Format ('RepN=%d, File:%s',
[InputStringBodyRepN, InputFileName]));
RTTIHook := TansoRTTIHook.Create (Cases [0]);
for i := 0 to RTTIHook.Count - 1 do
ListBox1.Items.Add (RTTIHook.Names [i] + '=' + RTTIHook.AsStrings [i]);
{
f := TIniFile.Create ('c:\1.str');
ListBox1.Items.Add ('-=-');
ListBox1.Items.Add (f.ReadString ('Ugly', 'Ugly', ''));
// f.WriteString ('Ugly', 'Ugly', '!!!'#$d#$a'???');
s := 'efbgebg=34564536';
ParseProfileString (s, n, v);
ListBox1.Items.Add (Format ('%s: >%s<=>%s<', [s,n,v]));
s := 'efbgebg = "34564536;" ';
ParseProfileString (s, n, v);
ListBox1.Items.Add (Format ('%s: >%s<=>%s<', [s,n,v]));
f.Free;
}
end;
initialization
RegisterItemClass (TRETestCase1);
end.
|
unit DUnitConsts;
interface
resourcestring
sTitle = 'DUnit - An Extreme Testing Framework';
sPopupTitle = 'TestCase Run-Time Applied Properties';
sPopupPrevious = ' Previous';
sPopupRun = ' Run Selected Test';
sPopupNext = ' Next';
sSetupDecorator = 'Setup decorator (%s)';
sTestMemory = 'Test memory of %s';
sMemoryChanged = 'Memory use changed by %d bytes';
sNilListener = 'listener is nil';
sFailedSetup = 'SetUp FAILED: ';
sFailedTearDown = 'TearDown FAILED: ';
sNonNilTestResult = 'Expected non nil TestResult';
sTests = 'Tests';
sIdenticalContent = 'Memory content was identical:';
sExpectedException = 'Expected exception "%s" but there was none. %s';
sEmptyTest = 'Empty test';
sExceptionNothig = 'nothing';
sAllowLeakArrayValues = 'Too many values in for AllowedLeakArray. Limit = ';
sNoChecksExecuted = 'No checks executed in TestCase';
sExceptionUnexpected = 'unexpected exception';
sMethodNotFound = 'Method not found: "';
sLoadModule = 'Could not load module %s: %s';
sExportFunction = 'Module "%s" does not export a "Test" function: %s';
sReturnInterface = 'Module "%s.Test" did not return an ITest';
sPrintError = 'There was %d error:';
sPrintErrors = 'There were %d errors:';
sFailedTestDetails = '%3d) [%s] %s.%s: %s'#13#10' at %s'#13#10' "%s"';
sPrintFailure = 'There was %d failure:';
sPrintFailures = 'There were %d failures:';
sTestResultsOk = 'OK: %d tests';
sTestResultsFailures = 'FAILURES!!!';
sTestResults = 'Test Results:';
sRunCount = 'Run: %8d';
sFailureCount = 'Failures: %8d';
sErrorsCount = 'Errors: %8d';
sDUnitTesting = 'DUnit / Testing';
sDecodeTime = 'Time: %d:%2.2d:%2.2d.%d';
sPressReturn = 'Press <RETURN> to continue.';
sUnsupportedTypeInfo = '<Unsupported type info>';
{$IFDEF CLR}
sUnkownFieldType = '<Unknown>';
{$ENDIF CLR}
implementation
end.
|
unit Cadastro.Aluno;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cadastro.modelo, Vcl.DBCtrls, Data.DB, Vcl.ComCtrls, Vcl.StdCtrls,
Vcl.Mask, J2REdit, Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.Buttons, Vcl.Imaging.pngimage, 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,
classe.aluno, Datasnap.DBClient, Generics.Collections, JvExControls, JvGradientHeaderPanel;
type
TfrmCadastroAlunos = class(TfrmCadModelo)
Label18: TLabel;
Label2: TLabel;
Label6: TLabel;
dsAlunoObs: TDataSource;
edtCodigo: TEdit;
edtNome: TEdit;
cdsPesquisa: TClientDataSet;
cdsPesquisaIdAluno: TIntegerField;
cdsPesquisaNome: TStringField;
gridDisciplinas: TDBGrid;
Label1: TLabel;
btAdd: TButton;
btRem: TButton;
pnAddDisciplinas: TPanel;
pnTitulo: TJvGradientHeaderPanel;
Label40: TLabel;
btOk: TSpeedButton;
btCanc: TSpeedButton;
DBGrid1: TDBGrid;
dsListaDisciplinas: TDataSource;
cdsListaDisciplinas: TClientDataSet;
cdsListaDisciplinasIdDisciplina: TIntegerField;
cdsListaDisciplinasDescricao: TStringField;
cdsAlunoDisc: TClientDataSet;
dsAlunoDisc: TDataSource;
cdsAlunoDiscIdAluno: TIntegerField;
cdsAlunoDiscIdDisciplina: TIntegerField;
cdsAlunoDiscDescricao: TStringField;
procedure btPesquisaInicialClick(Sender: TObject);
procedure btAlterarClick(Sender: TObject);
procedure btCancClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure gridPesquisaDblClick(Sender: TObject);
procedure btRemClick(Sender: TObject);
procedure btAddClick(Sender: TObject);
procedure btOkClick(Sender: TObject);
private
{ Private declarations }
FAluno : TAluno;
public
{ Public declarations }
FEntrarEditando : boolean;
FCodigoAluno : integer;
procedure ColocarEmEstadoInclusao; Override;
procedure ColocarEmEstadoEdicao; Override;
procedure CancelarEdicao; Override;
procedure Excluir; Override;
procedure Persistir; Override;
procedure ExecutarPesquisa; Override;
function valida(AOpcao: integer):boolean;
procedure CarregarRegistroPesquisa(AValor: String = '');
procedure RefreshListagem;
procedure CarregarDisciplinas(aIdAluno : integer);
procedure ListarDisciplinas;
procedure OcultarPainelDisciplinas;
end;
var
frmCadastroAlunos: TfrmCadastroAlunos;
implementation
{$R *.dfm}
uses Dados.Firebird, UnFuncoesAuxiliares, unConstantes, UnVariaveisGlobais, UnitPergunta, UnTipos, UnMensagem, GenericDao, classe.disciplina, classe.aluno_disciplina;
procedure TfrmCadastroAlunos.btAddClick(Sender: TObject);
begin
inherited;
if FInclusao or FEdicao then
begin
ListarDisciplinas;
pnCentralCadastro.Enabled := False;
pnAddDisciplinas.Visible := True;
pnAddDisciplinas.Top := 8;
pnAddDisciplinas.Left := 139;
end
else TFrmMensagem.ExibirMensagem(mSelecioneParaEdicao, tmAlerta);
end;
procedure TfrmCadastroAlunos.btAlterarClick(Sender: TObject);
begin
inherited;
ColocarEmEstadoEdicao;
end;
procedure TfrmCadastroAlunos.btCancClick(Sender: TObject);
begin
inherited;
OcultarPainelDisciplinas;
end;
procedure TfrmCadastroAlunos.btOkClick(Sender: TObject);
begin
inherited;
if not cdsAlunoDisc.Locate('IdDisciplina', cdsListaDisciplinasIdDisciplina.AsInteger, []) then
begin
cdsAlunoDisc.AppendRecord([StrToInt(edtCodigo.Text),
cdsListaDisciplinasIdDisciplina.AsInteger,
cdsListaDisciplinasDescricao.AsString]);
OcultarPainelDisciplinas;
end
else
TFrmMensagem.ExibirMensagem('Disciplina já inserida!', tmInformacao);
end;
procedure TfrmCadastroAlunos.btPesquisaInicialClick(Sender: TObject);
begin
inherited;
ExecutarPesquisa;
end;
procedure TfrmCadastroAlunos.btRemClick(Sender: TObject);
begin
inherited;
if not cdsPesquisa.IsEmpty then
begin
if TfrmPergunta.Pergunta('Deseja realmente excluir a disciplina?', tmPergunta) then
begin
cdsAlunoDisc.Delete;
end;
end;
end;
procedure TfrmCadastroAlunos.CancelarEdicao;
begin
if tfrmPergunta.Pergunta(mPerguntaCancela, tmPergunta) then
begin
edtCodigo.Clear;
FInclusao := False;
FEdicao := False;
inherited;
end;
end;
procedure TfrmCadastroAlunos.CarregarDisciplinas(aIdAluno: integer);
var aDadosDisc : TDataSet;
aAlnDisc : TAluno_Disciplina;
aDisc : TDisciplina;
aValorPK : integer;
begin
inherited;
aDadosDisc := TDataSet.Create(self);
aAlnDisc := TAluno_Disciplina.Create;
aDisc := TDisciplina.Create;
cdsAlunoDisc.EmptyDataSet;
try
aDadosDisc := TGenericDAO.GetPesquisa(aAlnDisc, aIdAluno);
if assigned(aDadosDisc) then
begin
aDadosDisc.First;
while not aDadosDisc.Eof do
begin
aValorPK := aDadosDisc.FieldByName('IdDisciplina').AsInteger;
cdsAlunoDisc.Append;
cdsAlunoDiscIdAluno.AsInteger := aDadosDisc.FieldByName('IDAluno').AsInteger;
cdsAlunoDiscIdDisciplina.AsInteger := aDadosDisc.FieldByName('IdDisciplina').AsInteger;
cdsAlunoDiscDescricao.AsString := TGenericDAO.GetDescricao(aDisc, aValorPK);
cdsAlunoDisc.Post;
aDadosDisc.next;
end;
end;
except on E: Exception do
begin
raise
end;
end;
end;
procedure TfrmCadastroAlunos.CarregarRegistroPesquisa(AValor: String = '');
begin
if not cdsPesquisa.IsEmpty then
begin
edtCodigo.Text := IntToStr(cdsPesquisaIdAluno.AsInteger);
edtNome.Text := trim(cdsPesquisaNome.AsString);
pgCadastro.ActivePage := tsDadosCad;
CarregarDisciplinas(cdsPesquisaIdAluno.AsInteger);
end;
end;
procedure TfrmCadastroAlunos.ColocarEmEstadoEdicao;
begin
inherited;
FEdicao := True;
edtCodigo.Enabled := False;
pgCadastro.ActivePageIndex := 1;
end;
procedure TfrmCadastroAlunos.ColocarEmEstadoInclusao;
begin
inherited;
if not Assigned(FAluno) then
FAluno := TAluno.Create();
FInclusao := True;
tsDadosCad.Enabled := True;
edtCodigo.Text := IntToStr(TGenericDAO.getID(FAluno, 'IDALUNO') + 1);
edtCodigo.Enabled := False;
pgCadastro.ActivePage := tsDadosCad;
SetarFoco(edtNome);
end;
procedure TfrmCadastroAlunos.Excluir;
begin
inherited;
if Trim(edtCodigo.Text) <> EmptyStr then
begin
if TfrmPergunta.Pergunta(mPerguntaExclusao, tmPergunta) then
begin
{
verificar condições para a exclusão
}
end
end
else TFrmMensagem.ExibirMensagem(mSelecioneParaExclusao, tmInformacao);
end;
procedure TfrmCadastroAlunos.ExecutarPesquisa;
begin
inherited;
end;
procedure TfrmCadastroAlunos.FormShow(Sender: TObject);
begin
inherited;
RefreshListagem;
end;
procedure TfrmCadastroAlunos.gridPesquisaDblClick(Sender: TObject);
begin
inherited;
CarregarRegistroPesquisa();
end;
procedure TfrmCadastroAlunos.ListarDisciplinas;
var aLstDisciplina : TDataSet;
aDisc : TDisciplina;
begin
inherited;
aLstDisciplina := TDataSet.Create(self);
aDisc := TDisciplina.Create;
try
cdsListaDisciplinas.EmptyDataSet;
aLstDisciplina := TGenericDAO.GetAll(aDisc);
aLstDisciplina.First;
while not aLstDisciplina.Eof do
begin
cdsListaDisciplinas.AppendRecord([aLstDisciplina.FieldByName('IDDisciplina').AsInteger,
aLstDisciplina.FieldByName('Descricao').AsString]);
aLstDisciplina.next;
end;
except on E: Exception do
begin
raise
end;
end;
end;
procedure TfrmCadastroAlunos.OcultarPainelDisciplinas;
begin
pnCentralCadastro.Enabled := True;
pnAddDisciplinas.Visible := False;
pgCadastro.ActivePageIndex := 1;
end;
procedure TfrmCadastroAlunos.Persistir;
var aDiscip : TAluno_disciplina;
begin
aDiscip := TAluno_disciplina.Create;
try
if not assigned(FAluno) then
FAluno := TAluno.Create;
FAluno.Codigo := StrToInt(edtCodigo.Text);
FAluno.Nome := edtNome.Text;
if FInclusao then
begin
TGenericDAO.Insert(FAluno);
end
else if FEdicao then
begin
TGenericDAO.DeleteSlaveTable(aDiscip, FAluno.Codigo );
TGenericDAO.Update(FAluno);
end;
if not cdsAlunoDisc.IsEmpty then
begin
cdsAlunoDisc.first;
while not cdsAlunoDisc.Eof do
begin
aDiscip.CodigoAluno := cdsAlunoDiscIdAluno.AsInteger;
aDiscip.CodigoDisciplina := cdsAlunoDiscIdDisciplina.AsInteger;
TGenericDAO.Insert(aDiscip);
cdsAlunoDisc.next;
end;
end;
TFrmMensagem.ExibirMensagem('Registro realizado com sucesso!',tmInformacao);
FInclusao := False;
FEdicao := False;
RefreshListagem;
inherited;
except on E: Exception do
begin
TFrmMensagem.ExibirMensagem('Problemas ao persitir aluno! '+E.Message, tmAlerta);
end;
end;
end;
procedure TfrmCadastroAlunos.RefreshListagem;
var aDadosAluno : TDataSet;
begin
inherited;
cdsPesquisa.EmptyDataSet;
aDadosAluno := TDataSet.Create(self);
if not Assigned(FAluno) then
FAluno := TAluno.Create;
try
aDadosAluno := TGenericDAO.GetAll(FAluno);
aDadosAluno.First;
while not aDadosAluno.Eof do
begin
cdsPesquisa.AppendRecord([aDadosAluno.FieldByName('IDAluno').AsInteger,
aDadosAluno.FieldByName('Nome').AsString]);
aDadosAluno.next;
end;
except on E: Exception do
begin
raise
end;
end;
end;
function TfrmCadastroAlunos.valida(AOpcao: integer): boolean;
begin
result := True;
end;
end.
|
unit Compress;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Masks, ZLibEx;
type
PCompressedItem = ^TCompressedItem;
TCompressedItem = record
Name : string;
Position, Count, SrcCount : integer;
end;
TCompressor = class(TObject)
private
FileList : TList;
FStream : TFileStream;
public
procedure Compress(Mask : string);
constructor Create(FileName : string);
destructor Destroy; override;
end;
TDeCompressor = class(TObject)
private
FileList : TList;
FStream : TFileStream;
FOnProgress: TNotifyEvent;
FPosition : integer;
FCompressedItem : PCompressedItem;
procedure DoProgress(Sender: TObject);
procedure DoDeCompress(Mask : string);
public
procedure DeCompress(Mask : string);
procedure GetFiles(Mask : string; List : TStrings);
constructor Create(FileName : string);
destructor Destroy; override;
property OnProgress: TNotifyEvent read FOnProgress write FOnProgress;
property CompressedItem : PCompressedItem read FCompressedItem;
property Position : integer read FPosition;
end;
TMyMemoryStream = class(TMemoryStream)
public
property Capacity;
end;
implementation
{ TCompressor }
procedure TDeCompressor.GetFiles(Mask : string; List : TStrings);
var I : integer;
begin
for I := 0 to FileList.Count - 1 do with PCompressedItem(FileList[ I ])^ do
if MatchesMask(Name, Mask) then
List.Add(Name);
end;
procedure TDeCompressor.DoProgress(Sender: TObject);
begin
if Assigned(OnProgress) then
begin
FPosition := (FStream.Position - CompressedItem.Position) * 100 div CompressedItem.SrcCount;
OnProgress(Self);
end;
end;
procedure TDeCompressor.DeCompress(Mask : string);
var MaskPtr : PChar;
Ptr : PChar;
begin
MaskPtr := PChar(Mask);
while MaskPtr <> nil do
begin
Ptr := StrScan(MaskPtr, ';');
if Ptr <> nil then
Ptr^ := #0;
DoDeCompress(MaskPtr);
if Ptr <> nil then
begin
Ptr^ := ';';
Inc(Ptr);
end;
MaskPtr := Ptr;
end;
end;
procedure TDeCompressor.DoDeCompress(Mask : string);
var I : integer;
Str : TFileStream;
CmpStr : TZDeCompressionStream;
begin
for I := 0 to FileList.Count - 1 do with PCompressedItem(FileList[ I ])^ do
if MatchesMask(Name, Mask) then
begin
FPosition := 0;
FCompressedItem := PCompressedItem(FileList[ I ]);
DoProgress(Self);
FStream.Seek(Position, soBeginning);
CmpStr := TZDeCompressionStream.Create(FStream);
try
CmpStr.OnProgress := DoProgress;
Str := TFileStream.Create(Name, fmCreate);
try
Str.CopyFrom(CmpStr, SrcCount);
finally
Str.Free;
end;
finally
CmpStr.Free;
end;
end;
end;
constructor TDeCompressor.Create(FileName: string);
var I, L, DirPos, Count : integer;
Item : PCompressedItem;
begin
inherited Create;
FileList := TList.Create;
FStream := TFileStream.Create(FileName, fmOpenRead);
FStream.Seek(-SizeOf(Integer), soEnd);
FStream.Read(DirPos, SizeOf(DirPos));
FStream.Seek(DirPos, soBeginning);
FStream.Read(Count, SizeOf(Count));
for I := 0 to Count - 1 do
begin
New(Item);
FileList.Add(Item);
FStream.Read(L, SizeOf(L));
with Item^ do
begin
SetLength(Name, L);
FStream.Read(Name[ 1 ], L);
FStream.Read(Position, SizeOf(Position));
FStream.Read(Count, SizeOf(Count));
FStream.Read(SrcCount, SizeOf(SrcCount));
end;
end;
end;
procedure TCompressor.Compress(Mask : string);
var MaskPtr : PChar;
Ptr : PChar;
FileInfo : TSearchRec;
Item : PCompressedItem;
begin
MaskPtr := PChar(Mask);
while MaskPtr <> nil do
begin
Ptr := StrScan (MaskPtr, ';');
if Ptr <> nil then
Ptr^ := #0;
if FindFirst(MaskPtr, faArchive, FileInfo) = 0 then
begin
repeat
New(Item);
Item.Name := FileInfo.Name;
FileList.Add(Item);
until FindNext(FileInfo) <> 0;
FindClose(FileInfo);
end;
if Ptr <> nil then
begin
Ptr^ := ';';
Inc(Ptr);
end;
MaskPtr := Ptr;
end;
end;
constructor TCompressor.Create(FileName: string);
begin
inherited Create;
FileList := TList.Create;
FStream := TFileStream.Create(FileName, fmCreate);
end;
destructor TCompressor.Destroy;
var I : integer;
Str : TFileStream;
CmpStr : TZCompressionStream;
DirPos, L : integer;
begin
for I := 0 to FileList.Count - 1 do with PCompressedItem(FileList[ I ])^ do
begin
Str := TFileStream.Create(Name, fmOpenRead);
SrcCount := Str.Size;
Position := FStream.Position;
try
CmpStr := TZCompressionStream.Create(FStream, zcDefault);
try
CmpStr.CopyFrom(Str, Str.Size);
finally
CmpStr.Free;
end;
finally
Str.Free;
end;
Count := FStream.Position - Position;
end;
DirPos := FStream.Position;
FStream.Write(FileList.Count, SizeOf(Integer));
for I := 0 to FileList.Count - 1 do with PCompressedItem(FileList[ I ])^ do
begin
L := Length(Name);
FStream.Write(L, SizeOf(Integer));
FStream.Write(Name[ 1 ], L);
FStream.Write(Position, SizeOf(Position));
FStream.Write(Count, SizeOf(Count));
FStream.Write(SrcCount, SizeOf(SrcCount));
Dispose(FileList[ I ]);
end;
FStream.Write(DirPos, SizeOf(DirPos));
FileList.Free;
FStream.Free;
inherited;
end;
destructor TDeCompressor.Destroy;
var I : integer;
begin
for I := 0 to FileList.Count - 1 do
Dispose(FileList[ I ]);
FileList.Free;
FStream.Free;
inherited;
end;
end.
|
unit Unit1;
interface
uses
System.Classes, System.SysUtils,
Vcl.Forms, Vcl.Controls, Vcl.Graphics, Vcl.Dialogs, Vcl.Menus,
Vcl.StdCtrls, Vcl.ExtCtrls,
//GLS
GLScene, GLObjects, GLSLanguage;
type
{ TForm1 }
TForm1 = class(TForm)
Button: TButton;
GLSLanguage1: TGLSLanguage;
GroupBox1: TGroupBox;
Label1: TLabel;
MainMenu1: TMainMenu;
AboutScene: TMemo;
mLanguage: TMenuItem;
mEnglish: TMenuItem;
mRussian: TMenuItem;
mOption: TMenuItem;
Panel1: TPanel;
mDeutsch: TMenuItem;
mHelp: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure mEnglishClick(Sender: TObject);
procedure mRussianClick(Sender: TObject);
procedure mDeutschClick(Sender: TObject);
private
{ private declarations }
procedure SetLanguage(const AFile: string);
public
{ public declarations }
end;
var
Form1 :TForm1;
implementation
{$R *.dfm}
{ TForm1 }
procedure TForm1.SetLanguage(const AFile: string);
begin
with GLSLanguage1 do
begin
LoadLanguageFromFile(AFile);
mOption.Caption := Translate('mOption');
mLanguage.Caption := Translate('mLanguage');
mEnglish.Caption := Translate('mEnglish');
mRussian.Caption := Translate('mRussian');
mHelp.Caption := Translate('mHelp');
Form1.Caption := Translate('Form1Caption');
GroupBox1.Caption := Translate('GroupBox1');
Button.Caption := Translate('Button');
label1.Caption := Translate('label');
Panel1.Caption := Translate('Panel1');
AboutScene.Clear;
AboutScene.Lines.Add(Translate('AboutScene'));
end;
end;
procedure TForm1.mRussianClick(Sender: TObject);
begin
SetLanguage('Russian.ini');
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetLanguage('English.ini');
end;
procedure TForm1.mEnglishClick(Sender: TObject);
begin
SetLanguage('English.ini');
end;
procedure TForm1.mDeutschClick(Sender: TObject);
begin
SetLanguage('Deutsch.ini');
end;
end.
|
(*
Window System
Original code by Alexandre de Azevedo Palmeira Filho and published at
Micro Sistemas Magazine (year XII, number 122, november 1992).
*)
Unit Window;
Interface
type
(**
* Represent the content of the screen and represents the phisical video
* memory
*)
T = array[1..4000] of char;
(**
* Make the cursor invisible.
*)
Procedure NoCursor;
(**
* Make the cursor visible (but just the bottom line).
*)
Procedure OrdinaryCursor;
(**
* Make the cursor visible (all the lines).
*)
Procedure FullCursor;
(**
* Shift up the last window content by n lines.
*)
Procedure ScrollUp(n : byte);
(**
* Shift down the last window content by n lines.
*)
Procedure ScrollDown(n : byte);
(**
* Save the current screen.
*)
Procedure SaveScreen(x : T);
(**
* Load a screen.
*)
Procedure LoadScreen(x : T);
(**
* Create a new window (with borders). The borders remove two pixels vertically
* and two pixels horizontally of the area really available to write some
* content to the window.
*
* @param x1, y1: Top left point.
* @param x2, y2: Bottom right point.
*)
Procedure OpenWindow(x1, y1, x2, y2 : byte);
(**
* Close the last window created and restore the previous one.
*)
Procedure CloseWindow;
Implementation
uses DOS, Crt;
type
c = record
WMin, Wmax : word;
end;
var
screen : T; (* absolute $b8000000; *)
R : Registers;
windows : array[1..16] of T;
coord : array[1..16] of c;
i, j : integer;
focus : integer;
(**
* The cursor (DOS) has 8 horizontal lines. This procedure let you choose
* the lines to be highlighted.
*
* @param x First line to be highlighted.
* @param y Last line to be highlighted.
*)
Procedure Cursor(x, y : byte);
begin
R.ah := 1;
R.ch := x;
R.cl := y;
Intr(16, R);
end;
Procedure NoCursor;
begin
Cursor(8, 0);
end;
Procedure OrdinaryCursor;
begin
Cursor(6, 7);
end;
Procedure FullCursor;
begin
Cursor(0, 7);
end;
Procedure Scroll(x, n : byte);
begin
R.ah := x;
R.al := n;
R.cl := lo(WindMin);
R.ch := hi(WindMin);
R.dl := lo(WindMax);
R.dh := hi(WindMax);
R.bh := 15;
Intr(16, R);
end;
Procedure ScrollUp(n : byte);
begin
Scroll(6, n);
end;
Procedure ScrollDown(n : byte);
begin
Scroll(7, n);
end;
Procedure SaveScreen(x : T);
begin
x := screen;
end;
Procedure LoadScreen(x : T);
begin
screen := x;
end;
Procedure OpenWindow(x1, y1, x2, y2 : byte);
var
i, j : integer;
begin
inc(focus);
windows[focus] := screen;
Window(x1, y1, x2, y2+1);
write(chr(201));
for j := x1 + 1 to x2 - 2 do
write(char(205));
write(char(187));
for i := y1 + 1 to y2 - 1 do
begin
write(char(186));
for j := x1 + 1 to x2 - 1 do
write(' ');
write(char(186));
end;
write(chr(200));
for j := x1 + 1 to x2 - 1 do
Write(char(205));
Write(char(188));
Window(x1 + 1, y1 + 1, x2 - 1, y2 - 1);
coord[focus].WMax := WindMax;
coord[focus].WMin := WindMin;
end;
Procedure CloseWindow;
begin
screen := windows[focus];
WindMax := coord[focus - 1].Wmax;
WindMin := coord[focus - 1].Wmin;
Window(lo(WindMin) + 1, hi(WindMin) + 1, lo(WindMax) + 1, hi(WindMax) + 1);
dec(focus);
end;
Begin
focus := 0;
End.
|
unit CP2102_classes;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, registry,
CP210xManufacturingDLL,
CP2102n_config_rec;
type
tCP210x_log_event = procedure(s:string) of object;
tCP2102_reg_item = record //Запись инЎ¦рмации Ў¦коЎ¦портах SiLabs CP2102 на базе реестрта
com_name : string; //Имя коЎ¦портЎ¦Ў¦винджО Ў¦виде "COMxxx", например "COM7"
path : string; //Ў¦ть Ў¦символьномЎ¦Ў¦йлЎ¦для открытЎ¦ устройства коЎ¦портЎ¦, рекомендуется по данномЎ¦именЎ¦открыватЎ¦Ў¦йл
serial : string; //Серийник для данногЎ¦коЎ¦портЎ¦ до 16 символов, колиЎ¦ство указанЎ¦Ў¦константжВCP210x_MAX_SERIAL_STRLEN Ў¦CP210xManufacturingDLL
end;
tCP210x_enum_item = record //Запись инЎ¦рмации Ў¦коЎ¦портах SiLabs CP2102 на базе реестрта Ў¦CP210xManufacturingDLL
com_name : string; //Имя коЎ¦портЎ¦Ў¦винджО Ў¦виде "COMxxx", например "COM7"
com_path : string; //Ў¦ть Ў¦символьномЎ¦Ў¦йлЎ¦для открытЎ¦ устройства коЎ¦портЎ¦, рекомендуется по данномЎ¦именЎ¦открыватЎ¦Ў¦йл
serial : string; //Серийник для данногЎ¦коЎ¦портЎ¦ до 16 символов, колиЎ¦ство указанЎ¦Ў¦константжВCP210x_MAX_SERIAL_STRLEN Ў¦CP210xManufacturingDLL
usb_path : string; //Ў¦ть Ў¦Ў¦йлЎ¦для настройкЎ¦Ў¦считыванЎ¦ параметров каЎ¦усвВустройства, типа дескрипторЎ¦ серийникЎ¦ их прошивки Ў¦тд, ВНИМАНИЕ! он отлиЎ¦еттЎ от com_path
description : string; //Дескриптор коЎ¦портЎ¦на уровне виндьО он отлиЎ¦еттЎ от дескрипторЎ¦на уровне настроек, Ў¦всегда равеоВтому Ў¦Ў¦прописанЎ¦Ў¦драйвераЎ¦виндьО на разных виндах по разномЎ¦ каЎ¦правилЎ¦Silicon Labs CP210x USB to UART Bridge
end;
tCP2102_reg_list = class //КластВ- список доступныЎ¦Ў¦данный момент устройстЎ¦на базе инЎ¦ тВреестр
private
v_table : array of tCP2102_reg_item;
v_Log : tCP210x_log_event;
procedure log(s:string);
function getter(index:integer):tCP2102_reg_item;
function get_count:integer;
public
constructor create(evLog:tCP210x_log_event = Nil);
destructor destroy;override;
property list[index: integer]:tCP2102_reg_item read getter; //Список подклюЎ¦нных устройстЎ¦тВинЎ¦рмациекО см описание записи tCP2102_reg_item
property count:integer read get_count; //КолиЎ¦ство записекВЎ¦списке
function find_serial(serial:string; var index:integer):boolean; //НайтЎ¦по серийномЎ¦номеру, если True то найденЎ¦Ў¦индекс Ў¦соотЎ¦ переменной
end;
tCP210x_enum = class //КластВ- список доступныЎ¦Ў¦данный момент устройстЎ¦на базе инЎ¦ тВреестрЎ¦Ў¦AN144 + CP210xManufacturingDLL
private
v_table : array of tCP210x_enum_item;
v_Log : tCP210x_log_event;
procedure log(s:string);
function getter(index:integer):tCP210x_enum_item;
function get_count:integer;
public
constructor create(evLog:tCP210x_log_event = Nil);
destructor destroy;override;
property list[index: integer]:tCP210x_enum_item read getter;
property count:integer read get_count;
end;
tCP210x_config = class //КластВдоступЎ¦Ў¦настройкам устройства на уровне УСВВ- серийник, дескриптор Ў¦тд, согласно AN144
private
handle : thandle;
v_Log : tCP210x_log_event;
procedure log(s:string);
public
function port_present:boolean;
function read_part_num:string; //СчитатЎ¦тирВустройства, = "CP2102"
function read_VID:string;
function read_PID:string;
function read_product_string:string; //Дескриптор устройства на уровне усвВЎ¦не реестр
function read_serial_string:string; //Серийник, до 16 символов
function read_device_version:string; //ВерсЎ¦ устройства, BCD Ў¦рмат, двЎ¦байтЎ¦ от 0 до 99 каждый, преобразуется Ў¦строку например вида "01.23"
function read_lock:string; //СчитатЎ¦Ў¦аг блокировки измененикО если равеоВ"True" то запись невозможна
function read_max_power:string; //Максимальное потребленижВтока Ў¦миллиамперах, Ў¦слЎ¦Ў¦виде строки напимеЎ¦"100" - 100мА
function read_port_config:tCP2103_PORT_CONFIG;
function read_confing:tCP2102n_config;
function write_confing(cfg:tCP2102n_config):boolean;
function write_product_string(value:string):boolean; //Ў¦оцедурьВзаписи. аналогично Ў¦ению, таЎ¦же принимаюЎ¦строковыжВпараметрьР если вернут True - ошибка записи.
function write_serial_string(value:string):boolean;
function write_device_version(value:string):boolean;
function write_max_power(value:string):boolean;
function write_vid(value:string):boolean;
function write_pid(value:string):boolean;
function write_port_config(port_config:tCP2103_PORT_CONFIG):boolean;
procedure Reset; //СбротВустройства, послжВсброса нужнЎ¦деинициализировать кластО дальнейшЎ¦ устройства невозможно Ў¦Ў¦ устройство переподклюЎ¦тся на усвВлогиЎ¦скЎ¦Ў¦сменит Ў¦ндмР
constructor create(num:cardinal; evLog:tCP210x_log_event = Nil); //НомеЎ¦устройства - позиЎ¦я Ў¦списке tCP210x_enum согласно AN144
destructor destroy;override;
end;
function CP210x_check_error(log:tCP210x_log_event; error_code:CP210x_STATUS):boolean; //коЎ¦статусЎ¦проверяет на ошибку Ў¦если онЎ¦есть вывыодит Ў¦лодВЎ¦возвращает True, если ошибки неЎ¦то False
function connected_com_ports(evLog:tCP210x_log_event):tstringlist; //Строит общикВсписок всех доступныЎ¦коЎ¦портов Ў¦системме, неважнЎ¦какиЎ¦коЎ¦портов, любыжР
implementation
function CP210x_check_error(log:tCP210x_log_event; error_code:CP210x_STATUS):boolean;
begin
result:=false;
if error_code=CP210x_SUCCESS then exit;
case error_code of
CP210x_DEVICE_NOT_FOUND : log('Error #'+inttostr(error_code)+' CP210x_DEVICE_NOT_FOUND');
CP210x_INVALID_HANDLE : log('Error #'+inttostr(error_code)+' CP210x_INVALID_HANDLE');
CP210x_INVALID_PARAMETER : log('Error #'+inttostr(error_code)+' CP210x_INVALID_PARAMETER');
CP210x_DEVICE_IO_FAILED : log('Error #'+inttostr(error_code)+' CP210x_DEVICE_IO_FAILED');
CP210x_FUNCTION_NOT_SUPPORTED : log('Error #'+inttostr(error_code)+' CP210x_FUNCTION_NOT_SUPPORTED');
CP210x_GLOBAL_DATA_ERROR : log('Error #'+inttostr(error_code)+' CP210x_GLOBAL_DATA_ERROR');
CP210x_FILE_ERROR : log('Error #'+inttostr(error_code)+' CP210x_FILE_ERROR');
CP210x_COMMAND_FAILED : log('Error #'+inttostr(error_code)+' CP210x_COMMAND_FAILED');
CP210x_INVALID_ACCESS_TYPE : log('Error #'+inttostr(error_code)+' CP210x_INVALID_ACCESS_TYPE');
else
log('Error #'+inttostr(error_code));
end;
result:=true;
end;
procedure tCP210x_config.log(s:string);
begin
// assert(self<>nil, 'tCP210x_config.log self=nil');
if @v_Log=nil then exit;
v_Log(s);
end;
constructor tCP210x_config.create(num:cardinal; evLog:tCP210x_log_event = Nil);
var
err:CP210x_STATUS;
begin
v_Log := evLog;
handle := 0;
err:=CP210x_Open(num, @handle);
log('');
log('CP210x_Open('+inttostr(num)+', @handle), handle='+inttohex(handle, 8));
if CP210x_check_error(log, err) then fail;
end;
destructor tCP210x_config.destroy;
var
err:CP210x_STATUS;
begin
err:=CP210x_Close(handle);
log('CP210x_Close('+inttohex(handle, 8)+')');
CP210x_check_error(log, err);
log('');
end;
function tCP210x_config.read_part_num:string;
var
Part_Num:byte;
err:integer;
begin
Part_Num:=$FF;
err:=CP210x_GetPartNumber(handle, @Part_Num);
log('CP210x_PartNum = '+'CP21'+inttohex(Part_Num, 2));
if CP210x_check_error(log, err) or (Part_Num>$7F) then
result:='_ERROR_'
else
result:='CP21'+inttohex(Part_Num, 2);
end;
function tCP210x_config.read_VID:string;
var
err:integer;
VID:word;
begin
VID:=$FF;
err:=CP210x_GetDeviceVid(handle, @VID);
log('CP210x_VID = '+inttohex(VID, 4));
if CP210x_check_error(log, err) then
result:='_ERROR_'
else
result:=inttohex(VID, 2);
end;
function tCP210x_config.read_PID:string;
var
err:integer;
PID:word;
begin
PID:=$FF;
err:=CP210x_GetDevicePid(handle, @PID);
log('CP210x_PID = '+inttohex(PID, 4));
if CP210x_check_error(log, err) then
result:='_ERROR_'
else
result:=inttohex(PID, 2);
end;
function tCP210x_config.read_product_string:string;
var
err:integer;
info:array [0 .. (CP210x_MAX_PRODUCT_STRLEN*2)] of char;
info_length:byte;
begin
info_length:=0;
FillChar(info, sizeof(info), 0);
err:=CP210x_GetDeviceProductString(handle, info, @info_length);
log('CP210x_ProductString = "'+info+'"');
if CP210x_check_error(log, err) then
result:='_ERROR_'
else
result:=info;
end;
function tCP210x_config.read_serial_string:string;
var
err:integer;
info:array [0 .. (CP210x_MAX_SERIAL_STRLEN*2)] of char;
info_length:byte;
begin
info_length:=0;
FillChar(info, sizeof(info), 0);
err:=CP210x_GetDeviceSerialNumber(handle, info, @info_length);
log('CP210x_SerialNumber = "'+info+'"');
if CP210x_check_error(log, err) then
result:='_ERROR_'
else
result:=info;
end;
function tCP210x_config.read_device_version:string;
var
err:integer;
DeviceVersion:word;
begin
DeviceVersion:=$AAAA;
err:=CP210x_GetDeviceVersion(handle, @DeviceVersion);
log('CP210x_DeviceVersion = '+copy(IntTohex(DeviceVersion,4),1,2)+'.'+copy(IntTohex(DeviceVersion,4),3,2));
if CP210x_check_error(log, err) then
result:='_ERROR_'
else
result:=copy(IntTohex(DeviceVersion,4),1,2)+'.'+copy(IntTohex(DeviceVersion,4),3,2);
end;
function tCP210x_config.read_lock:string;
var
err:integer;
Lock:byte;
begin
Lock:=0;
err:=CP210x_GetLockValue(handle, @Lock);
log('CP210x_Lock = '+booltostr(Lock<>0,true));
if CP210x_check_error(log, err) then
result:='_ERROR_'
else
result:=booltostr(Lock<>0,true);
end;
function tCP210x_config.read_max_power:string;
var
err:integer;
power:byte;
begin
power:=0;
err:=CP210x_GetMaxPower(handle, @power);
log('CP210x_GetMaxPower = '+inttostr(power*2));
if CP210x_check_error(log, err) then
result:='_ERROR_'
else
result:=inttostr(power*2);
end;
function tCP210x_config.port_present:boolean;
var
name : string;
begin
name := read_part_num;
result := not ((read_part_num = 'CP2102') or (read_part_num = 'CP2101'));
end;
function tCP210x_config.read_port_config:tCP2103_PORT_CONFIG;
var
err : integer;
port_config : tCP2103_PORT_CONFIG;
begin
ZeroMemory(@port_config, sizeof(port_config));
if not port_present then
begin
result := port_config;
exit;
end;
err:=CP210x_GetPortConfig(handle, @port_config);
log('CP210x_GetPortConfig:');
log(#9'Mode : ' + IntToHex(port_config.Mode, 4));
log(#9'Reset : ' + IntToHex(port_config.Reset_Latch, 4));
log(#9'Suspend : ' + IntToHex(port_config.Suspend_Latch, 4));
log(#9'EngFxn : ' + IntToHex(port_config.EnhancedFxn, 2));
if CP210x_check_error(log, err) then
ZeroMemory(@port_config, sizeof(port_config));
result := port_config;
end;
function tCP210x_config.write_product_string(value:string):boolean;
var
err:integer;
info:array [0 .. CP210x_MAX_PRODUCT_STRLEN] of char;
info_length:byte;
begin
FillChar(info, sizeof(info), 0);
StrPLCopy(info, pchar(value), sizeof(info));
info_length:=StrLen(info);
err:=CP210x_SetProductString(handle, info, info_length, TRUE);
log('CP210x_SetProductString("'+inttohex(handle,8)+', '+info+', '+inttostr(info_length)+', TRUE);');
if CP210x_check_error(log, err) then
result:=true
else
result:=false;
end;
function tCP210x_config.read_confing:tCP2102n_config;
var
err:integer;
fs : tfilestream;
begin
result := nil;
if read_part_num <> 'CP2120' then exit;
result := tCP2102n_config.create;
err:=CP210x_GetConfig(handle, @result.rec, sizeof(result.rec));
log('CP210x_GetConfig('+inttohex(handle,8)+', "@result.rec", '+inttostr(sizeof(result.rec))+');');
if CP210x_check_error(log, err) then
FreeAndNil(result)
else
begin
fs := tfilestream.Create('cp2102n_backup.bin', fmCreate or fmOpenwrite);
fs.Write(result.rec, sizeof(result.rec));
FreeAndNil(fs);
if result.rec.FLETCHER_CHECKSUM <> result.calc_crc then
begin
log('rec.FLETCHER_CHECKSUM = ' + inttohex(result.rec.FLETCHER_CHECKSUM, 4));
log('result.calc_crc = ' + inttohex(result.calc_crc, 4));
log('CHECK SUM ERRORR!!!');
FreeAndNil(result);
end;
end;
end;
function tCP210x_config.write_confing(cfg:tCP2102n_config):boolean;
var
err:integer;
begin
if cfg = nil then exit;
if read_part_num <> 'CP2120' then exit;
cfg.update_crc;
err:=CP210x_SetConfig(handle, @cfg.rec, sizeof(cfg.rec));
log('CP210x_SETConfig('+inttohex(handle,8)+', "@cfg.rec", '+inttostr(sizeof(cfg.rec))+');');
if CP210x_check_error(log, err) then
result:=true
else
result:=false;
end;
function tCP210x_config.write_serial_string(value:string):boolean;
var
err:integer;
info:array [0 .. CP210x_MAX_SERIAL_STRLEN] of char;
info_length:byte;
begin
FillChar(info, sizeof(info), 0);
StrPLCopy(info, pchar(value), sizeof(info));
info_length:=StrLen(info);
err:=CP210x_SetSerialNumber(handle, info, info_length, TRUE);
log('CP210x_SetSerialNumber('+inttohex(handle,8)+', "'+info+'", '+inttostr(info_length)+', TRUE);');
if CP210x_check_error(log, err) then
result:=true
else
result:=false;
end;
function tCP210x_config.write_device_version(value:string):boolean;
var
err:integer;
v1,v2:string;
b1,b2:byte;
pos:integer;
version:word;
begin
result:=true;
pos:=system.pos('.', value);
if pos<2 then exit;
v1:=copy(value, 1, pos-1);
v2:=copy(value, pos+1, 255);
val(v1, b1, err); if err<>0 then exit;
val(v2, b2, err); if err<>0 then exit;
if b1>99 then exit;
if b2>99 then exit;
b1:=(b1 mod 10) or ((b1 div 10) shl 4);
b2:=(b2 mod 10) or ((b2 div 10) shl 4);
version:=b1*256 + b2;
err:=CP210x_SetDeviceVersion(handle, version);
log('CP210x_SetDeviceVersion('+inttohex(handle,8)+', '+inttohex(version,4)+');');
if CP210x_check_error(log, err) then exit;
result:=false;
end;
function tCP210x_config.write_max_power(value:string):boolean;
var
err:integer;
max_power:integer;
b:byte;
begin
result:=true;
val(value, max_power, err);
if err<>0 then exit;
if max_power<50 then max_power:=50;
if max_power>CP210x_MAX_MAXPOWER then max_power:=CP210x_MAX_MAXPOWER;
b:=max_power div 2;
err:=CP210x_SetMaxPower(handle, b);
log('CP210x_SetMaxPower('+inttohex(handle,8)+', '+inttostr(b)+');');
if CP210x_check_error(log, err) then exit;
result:=false;
end;
function tCP210x_config.write_vid(value:string):boolean;
var
err:integer;
w:word;
begin
result:=true;
value := '0x'+value;
try
w := StrToInt(value);
except
exit;
end;
err:=CP210x_SetVid(handle, w);
log('CP210x_SetVid('+inttohex(handle,8)+', '+inttohex(w, 4)+');');
if CP210x_check_error(log, err) then exit;
result:=false;
end;
function tCP210x_config.write_pid(value:string):boolean;
var
err:integer;
w:word;
begin
result:=true;
value := '0x'+value;
try
w := StrToInt(value);
except
exit;
end;
err:=CP210x_SetPid(handle, w);
log('CP210x_SetPid('+inttohex(handle,8)+', '+inttohex(w, 4)+');');
if CP210x_check_error(log, err) then exit;
result:=false;
end;
function tCP210x_config.write_port_config(port_config:tCP2103_PORT_CONFIG):boolean;
var
err:integer;
begin
result:=true;
err:=CP210x_SetPortConfig(handle, @port_config);
log('CP210x_SetPortConfig('+inttohex(handle,8)+', '+
inttohex(port_config.Mode, 4) + ', '+
inttohex(port_config.Reset_Latch, 4)+', '+
inttohex(port_config.Suspend_Latch, 4)+', '+
inttohex(port_config.EnhancedFxn, 2)+');');
if CP210x_check_error(log, err) then exit;
result:=false;
end;
procedure tCP210x_config.reset;
var
err:integer;
begin
err:=CP210x_Reset(handle);
log('CP210x_Reset('+inttohex(handle,8)+');');
CP210x_check_error(log, err);
end;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
function connected_com_ports(evLog:tCP210x_log_event):tstringlist;
procedure log(s:string);
begin
if @evLog<>nil then evLog(s);
end;
var
reg:TRegistry;
list:tstrings;
k:integer;
s:string;
const
path = 'HARDWARE\DEVICEMAP\SERIALCOMM';
begin
log('');
result:=TStringlist.Create;
result.Sorted := true;
list:=TStringlist.Create;
reg:=TRegistry.Create;
reg.RootKey := HKEY_LOCAL_MACHINE;
reg.Access := KEY_READ;
if not reg.OpenKey(path, false) then
begin
log('Error: Can''t open HKEY_LOCAL_MACHINE\'+path);
exit;
end;
reg.GetValueNames(list);
if list.Count<>0 then
log('=== Com port list ===');
for k:=0 to list.Count-1 do
begin
s:=reg.ReadString(list.Strings[k]);
result.Add(s);
log(s+#9+list.Strings[k]);
end;
if list.Count<>0 then
log('');
list.free;
reg.Free;
end;
procedure tCP210x_enum.log(s:string);
begin
assert(self<>nil, 'tCP210x_enum.log self=nil');
if @v_Log=nil then exit;
v_Log(s);
end;
function tCP210x_enum.get_count:integer;
begin
assert(self<>nil, 'tCP210x_enum.log self=nil');
result := length(v_table);
end;
function tCP210x_enum.getter(index:integer):tCP210x_enum_item;
begin
assert(self<>nil, 'tCP210x_enum.getter self=nil');
assert(index>=0, 'tCP210x_enum.getter index<0');
assert(index<length(v_table), 'tCP210x_enum.getter index>=length(v_table)');
result := v_table[index];
end;
destructor tCP210x_enum.destroy;
begin
SetLength(v_table, 0);
v_Log := nil;
end;
constructor tCP210x_enum.create(evLog:tCP210x_log_event = Nil);
var
dev_count:DWORD;
count:integer;
err:CP210x_STATUS;
info:array [0..4096] of char;
num:integer;
reg_list : tCP2102_reg_list;
index : integer;
begin
v_Log := evLog;
reg_list := tCP2102_reg_list.create(v_log);
dev_count:=$FFFFFFFF;
err:=CP210x_GetNumDevices(@dev_count);
log('CP210x_GetNumDevices(dev_count), dev_count='+inttohex(dev_count, 8));
if CP210x_check_error(log, err) then fail;
log('');
setlength(v_table, dev_count);
count:=dev_count;
for num:=0 to count-1 do
begin
log(' === Device #'+inttostr(num)+' ===');
FillChar(info, sizeof(info), 0);
err:=CP210x_GetProductString(num, @info, CP210x_RETURN_FULL_PATH);
CP210x_check_error(log, err);
log('USB_PATH = '+info);
v_table[num].usb_path := info;
FillChar(info, sizeof(info), 0);
err:=CP210x_GetProductString(num, @info, CP210x_RETURN_SERIAL_NUMBER);
CP210x_check_error(log, err);
log('SERIAL_NUMBER = '+info);
v_table[num].serial := info;
FillChar(info, sizeof(info), 0);
err:=CP210x_GetProductString(num, @info, CP210x_RETURN_DESCRIPTION);
CP210x_check_error(log, err);
log('DESCRIPTION = '+info);
v_table[num].description := info;
if reg_list.find_serial(v_table[num].serial, index) then
begin
v_table[num].com_name := reg_list.list[index].com_name;
v_table[num].com_path := reg_list.list[index].path;
v_table[num].serial := reg_list.list[index].serial;
end;
log('');
end;
reg_list.Free;
end;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
procedure tCP2102_reg_list.log(s:string);
begin
assert(self<>nil, 'tCP2102_reg_list.log self=nil');
if @v_Log=nil then exit;
v_Log(s);
end;
function tCP2102_reg_list.get_count:integer;
begin
assert(self<>nil, 'tCP2102_reg_list.log self=nil');
result := length(v_table);
end;
function tCP2102_reg_list.getter(index:integer):tCP2102_reg_item;
begin
assert(self<>nil, 'tCP2102_reg_list.getter self=nil');
assert(index>=0, 'tCP2102_reg_list.getter index<0');
assert(index<length(v_table), 'tCP2102_reg_list.getter index>=length(v_table)');
result := v_table[index];
end;
destructor tCP2102_reg_list.destroy;
begin
assert(self<>nil, 'tCP2102_reg_list.destroy self=nil');
SetLength(v_table, 0);
v_Log := nil;
end;
constructor tCP2102_reg_list.create(evLog:tCP210x_log_event = Nil);
{
https://www.silabs.com/pages/DownloadDoc.aspx?FILEURL=Support%20Documents/TechnicalDocs/an197.pdf&src=DocumentationWebPart
AN197 SERIAL COMMUNICATIONS GUIDE FOR THE CP210X
7. Discovering CP210x COM Port
To use the described functionality with a COM port, the number of the COM port needs to be known. In order to find
out the COM port number of a CP210x device, the VID, PID, and serial number are used to lookup a registry key.
This key is different between Windows XP/2000/Server 2003/Vista and Windows 98. Here are the keys that will
need to be looked up:
WinXP/2000/Server 2003/Vista/7 (Driver Version 5.0 and higher):
HKLM\System\CurrentControlSet\Enum\USB\Vid_xxxx&Pid_yyyy\zzzz\Device Parameters\PortName
where for CP2102 string Vid_xxxx&Pid_yyyy is VID_10C4&PID_EA60
}
var
reg:TRegistry;
list:tstrings;
k:integer;
index:integer;
port_serial:string;
port_name:string;
port_path:string;
s:string;
com_list:tstringlist;
const
path = 'SYSTEM\CurrentControlSet\Enum\USB\VID_10C4&PID_EA60';
label
go_end;
begin
list := nil;
v_Log := evLog;
com_list := connected_com_ports(evlog);
reg:=TRegistry.Create;
reg.RootKey := HKEY_LOCAL_MACHINE;
reg.Access := KEY_READ;
s:=path;
if not reg.OpenKey(s, false) then
begin
log('Error: Can''t open HKEY_LOCAL_MACHINE\'+s);
// fail;
goto go_end;
end;
SetLength(v_table, 0);
list:=TStringlist.Create;
reg.GetKeyNames(list);
for k:=0 to list.Count-1 do
begin
port_serial := list.Strings[k];
reg.CloseKey;
if not reg.OpenKey(path+'\'+list.Strings[k]+'\'+'Device Parameters', false) then
begin
log('Error: Can''t open HKEY_LOCAL_MACHINE\'+path+'\'+list.Strings[k]+'\'+'Device Parameters');
Continue;
end;
if not reg.ValueExists('PortName') then
begin
log('Error: Can''t open value PortName');
Continue;
end;
if reg.ValueExists('SymbolicName') then
port_path:=reg.ReadString('SymbolicName')
else
port_path := '';
port_name:=reg.ReadString('PortName');
if com_list.Find(port_name, index) then
begin
SetLength(v_table, length(v_table)+1);
{log('SN# ' + port_serial);
log(#9' PortName = '+port_name);
log(#9' SymbolicName = '+port_path);}
log('++# ' + ' ['+port_name+'] '#9 + port_serial + #9 + port_path);
v_table[length(v_table)-1].serial := port_serial;
v_table[length(v_table)-1].com_name := port_name;
v_table[length(v_table)-1].path := port_path;
end
else
begin
{log('--# ' + port_serial);
log(#9' PortName = '+port_name);
log(#9' SymbolicName = '+port_path);}
log(' # ' + ' ['+port_name+'] '#9 + port_serial + #9 + port_path);
end;
end;
go_end:
log('');
reg.Free;
if list<>nil then list.Free;
com_list.Free;
end;
function tCP2102_reg_list.find_serial(serial:string; var index:integer):boolean;
var
k:integer;
begin
assert(self<>nil, 'tCP2102_reg_list.find_serial self=nil');
for k:=0 to length(v_table)-1 do
if UpperCase(v_table[k].serial) = UpperCase(serial) then
begin
index := k;
result := true;
exit;
end;
result := false;
index := -1;
end;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
end.
|
unit SynLCCompletion;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, LCLProc,
Fgl, LCLType, LazUTF8, Menus,
SynEdit, SynEditPlugins,
SynEditKeyCmds, SynCompletion;
type
{ TLCCompletionItem }
TLCCompletionItem = class
private
FCaption : string;
fColorKind : TColor;
FDescKind : string;
FDescription : string;
FTextToReplace : string;
public
property Caption: string read FCaption write FCaption;
property TextToReplace: string read FTextToReplace write FTextToReplace;
property Description: string read FDescription write FDescription;
property DescKind: string read FDescKind write FDescKind;
property ColorKind: TColor read fColorKind write fColorKind;
end;
TLCCompletionItems = specialize TFPGObjectList<TLCCompletionItem>;
{ TLCCompletionList }
TLCCompletionList = class
private
fBiggerCaption : String;
fBiggestDescKind : String;
fItems: TLCCompletionItems;
procedure AddItem(pCaption:String; pDescKind:String; pColorKind: TColor; pTextToReplace:String = ''; pDescription:String = '');
public
constructor Create;
destructor Destroy; override;
procedure Clear;
property Items: TLCCompletionItems read fItems;
property BiggestCaption:String read fBiggerCaption;
property BiggestDescKind:String read fBiggestDescKind;
end;
{ TSynLCCompletion }
TSynLCCompletion = class(TSynCompletion)
private
fItems: TLCCompletionList;
function GetItemListCount: integer;
function OnLCSynCompletionPaintItem(const {%H-}AKey: string; ACanvas: TCanvas; X,
Y: integer; {%H-}IsSelected: boolean; Index: integer): boolean;
procedure OnLCSynCompletionCodeCompletion(var Value: string; {%H-}SourceValue: string;
var {%H-}SourceStart, {%H-}SourceEnd: TPoint; {%H-}KeyChar: TUTF8Char; {%H-}Shift: TShiftState);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddItem(pCaption : String; pDescKind : String; pColorKind : TColor; pTextToReplace : String = '';
pDescription : String = '');
procedure Clear;
property Items: TLCCompletionList read fItems;
published
end;
{ TSynLCAutoComplete }
TSynLCAutoComplete = class(TLazSynMultiEditPlugin)
private
FExecCommandID: TSynEditorCommand;
FShortCut: TShortCut;
fAutoCompleteList: TStrings;
FEndOfTokenChr: string;
procedure SetAutoCompleteList(List: TStrings);
protected
procedure DoEditorAdded(AValue: TCustomSynEdit); override;
procedure DoEditorRemoving(AValue: TCustomSynEdit); override;
procedure SetShortCut(Value: TShortCut);
function GetPreviousToken(aEditor: TCustomSynEdit): string;
procedure TranslateKey(Sender: TObject; Code: word; SState: TShiftState;
var {%H-}Data: pointer; var {%H-}IsStartOfCombo: boolean; var Handled: boolean;
var Command: TSynEditorCommand; FinishComboOnly: Boolean;
var {%H-}ComboKeyStrokes: TSynEditKeyStrokes);
procedure ProcessSynCommand(Sender: TObject; {%H-}AfterProcessing: boolean;
var Handled: boolean; var Command: TSynEditorCommand;
var {%H-}AChar: TUTF8Char; {%H-}Data: pointer; {%H-}HandlerData: pointer);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Execute(token: string; aEditor: TCustomSynEdit); virtual;
function EditorsCount: integer;
function GetTokenList: string;
function GetTokenValue(Token: string): string;
published
property AutoCompleteList: TStrings read fAutoCompleteList
write SetAutoCompleteList;
property EndOfTokenChr: string read FEndOfTokenChr write FEndOfTokenChr;
property ShortCut: TShortCut read FShortCut write SetShortCut;
property ExecCommandID: TSynEditorCommand read FExecCommandID write FExecCommandID;
property Editor;
end;
implementation
Uses
SynLCHighlighter;
{ TSynLCAutoComplete }
procedure TSynLCAutoComplete.SetAutoCompleteList(List: TStrings);
begin
fAutoCompleteList.Assign(List);
end;
procedure TSynLCAutoComplete.DoEditorAdded(AValue: TCustomSynEdit);
begin
inherited DoEditorAdded(AValue);
AValue.RegisterCommandHandler(@ProcessSynCommand, nil);
AValue.RegisterKeyTranslationHandler(@TranslateKey);
end;
procedure TSynLCAutoComplete.DoEditorRemoving(AValue: TCustomSynEdit);
begin
inherited DoEditorRemoving(AValue);
AValue.UnregisterCommandHandler(@ProcessSynCommand);
AValue.UnRegisterKeyTranslationHandler(@TranslateKey);
end;
procedure TSynLCAutoComplete.SetShortCut(Value: TShortCut);
begin
FShortCut := Value;
end;
function TSynLCAutoComplete.GetPreviousToken(aEditor: TCustomSynEdit): string;
var
s: string;
i: integer;
begin
if aEditor <> nil then begin
s := aEditor.LineText;
i := aEditor.LogicalCaretXY.X - 1;
if i > length(s) then
result := ''
else begin
while (i > 0) and (s[i] > ' ') and (pos(s[i], FEndOfTokenChr) = 0) do
dec(i);
result := copy(s, i + 1, aEditor.LogicalCaretXY.X - i - 1);
end;
end
else
result := '';
end;
procedure TSynLCAutoComplete.TranslateKey(Sender: TObject; Code: word;
SState: TShiftState; var Data: pointer; var IsStartOfCombo: boolean;
var Handled: boolean; var Command: TSynEditorCommand;
FinishComboOnly: Boolean; var ComboKeyStrokes: TSynEditKeyStrokes);
var
i: integer;
ShortCutKey: Word;
ShortCutShift: TShiftState;
begin
if (Code = VK_UNKNOWN) or Handled or FinishComboOnly or (FExecCommandID = ecNone) then exit;
i := IndexOfEditor(Sender as TCustomSynEdit);
if i >= 0 then begin
ShortCutToKey(FShortCut, ShortCutKey, ShortCutShift);
if (SState = ShortCutShift) and (Code = ShortCutKey) then begin
Command := FExecCommandID;
Handled := True;
end;
end;
end;
procedure TSynLCAutoComplete.ProcessSynCommand(Sender: TObject;
AfterProcessing: boolean; var Handled: boolean;
var Command: TSynEditorCommand; var AChar: TUTF8Char; Data: pointer;
HandlerData: pointer);
var
i: integer;
begin
if Handled or (Command <> FExecCommandID) then
exit;
i := IndexOfEditor(Sender as TCustomSynEdit);
if i >= 0 then begin
with sender as TCustomSynEdit do begin
if not ReadOnly then begin
Editor := Sender as TCustomSynEdit; // Will set Form.SetCurrentEditor
Execute(GetPreviousToken(Sender as TCustomSynEdit), Sender as TCustomSynEdit);
Handled := True;
end;
end;
end;
end;
constructor TSynLCAutoComplete.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEndOfTokenChr := '()[].';
fAutoCompleteList := TStringList.Create;
fShortCut := Menus.ShortCut(Ord(' '), [ssShift]);
FExecCommandID := ecSynAutoCompletionExecute;
end;
destructor TSynLCAutoComplete.Destroy;
begin
FreeAndNil(fAutoCompleteList);
inherited Destroy;
end;
procedure TSynLCAutoComplete.Execute(token: string; aEditor: TCustomSynEdit);
var
Temp: string;
PosX, // llutti
i, j, prevspace: integer;
StartOfBlock: tpoint;
begin
//Writeln('[TSynAutoComplete.Execute] Token is "',Token,'"');
i := AutoCompleteList.IndexOf(token);
if i <> -1 then begin
for j := 1 to length(token) do
aEditor.CommandProcessor(ecDeleteLastChar, ' ', nil);
inc(i);
PosX := aEditor.CaretX; // llutti
StartOfBlock := Point(-1, -1);
PrevSpace := 0;
while (i < AutoCompleteList.Count) and
(length(AutoCompleteList[i]) > 0) and
(AutoCompleteList[i][1] = '=') do
begin
aEditor.CaretX := PosX; // llutti
for j := 0 to PrevSpace - 1 do
aEditor.CommandProcessor(ecDeleteLastChar, ' ', nil);
Temp := AutoCompleteList[i];
PrevSpace := 0;
//while (length(temp) >= PrevSpace + 2) and (temp[PrevSpace + 2] <= ' ') do // llutti
// inc(PrevSpace); // llutti
for j := 2 to length(Temp) do begin
aEditor.CommandProcessor(ecChar, Temp[j], nil);
if Temp[j] = '|' then
StartOfBlock := aEditor.CaretXY
end;
inc(i);
if (i < AutoCompleteList.Count) and
(length(AutoCompleteList[i]) > 0) and
(AutoCompleteList[i][1] = '=') then
aEditor.CommandProcessor(ecLineBreak, ' ', nil);
end;
if (StartOfBlock.x <> -1) and (StartOfBlock.y <> -1) then begin
aEditor.CaretXY := StartOfBlock;
aEditor.CommandProcessor(ecDeleteLastChar, ' ', nil);
end;
end;
end;
function TSynLCAutoComplete.EditorsCount: integer;
begin
Result := EditorCount;
end;
function TSynLCAutoComplete.GetTokenList: string;
var
List: TStringList;
i: integer;
begin
Result := '';
if AutoCompleteList.Count < 1 then Exit;
List := TStringList.Create;
i := 0;
while (i < AutoCompleteList.Count) do begin
if (length(AutoCompleteList[i]) > 0) and (AutoCompleteList[i][1] <> '=') then
List.Add(Trim(AutoCompleteList[i]));
inc(i);
end;
Result := List.Text;
List.Free;
end;
function TSynLCAutoComplete.GetTokenValue(Token: string): string;
var
i: integer;
List: TStringList;
begin
Result := '';
i := AutoCompleteList.IndexOf(Token);
if i <> -1 then begin
List := TStringList.Create;
Inc(i);
while (i < AutoCompleteList.Count) and
(length(AutoCompleteList[i]) > 0) and
(AutoCompleteList[i][1] = '=') do begin
if Length(AutoCompleteList[i]) = 1 then
List.Add('')
else
List.Add(Copy(AutoCompleteList[i], 2, Length(AutoCompleteList[i])));
inc(i);
end;
Result := List.Text;
List.Free;
end;
end;
{ TLCCompletionList }
procedure TLCCompletionList.AddItem(pCaption : String; pDescKind : String; pColorKind : TColor;
pTextToReplace : String; pDescription : String);
var
item:TLCCompletionItem;
begin
if pCaption.IsEmpty then
begin
exit;
end;
item := TLCCompletionItem.Create;
item.Caption := pCaption;
item.Description := pDescription;
item.TextToReplace := pTextToReplace;
item.DescKind := pDescKind;
item.ColorKind := pColorKind;
if length(fBiggestDescKind) < length(pDescKind) then
begin
fBiggestDescKind := pDescKind;
end;
if length(fBiggerCaption) < length(pCaption) then
begin
fBiggerCaption := pCaption;
end;
fItems.Add(item);
end;
constructor TLCCompletionList.Create;
begin
fBiggerCaption := '';
fBiggestDescKind := '';
fItems:= TLCCompletionItems.Create(true);
end;
destructor TLCCompletionList.Destroy;
begin
fItems.Destroy;
inherited Destroy;
end;
procedure TLCCompletionList.Clear;
begin
fBiggerCaption := '';
fBiggestDescKind := '';
fItems.Clear;
end;
{ TSynLCCompletion }
function TSynLCCompletion.GetItemListCount: integer;
begin
result := ItemList.Count;
end;
function TSynLCCompletion.OnLCSynCompletionPaintItem(const AKey : string; ACanvas : TCanvas; X, Y : integer;
IsSelected : boolean; Index : integer) : boolean;
var
item: TLCCompletionItem;
begin
Result := true;
if Index > fItems.Items.Count then
begin
ACanvas.Font.Color := clBlack;
ACanvas.TextOut(X+10, Y, ItemList[Index]);
exit;
end;
item := fItems.Items[Index];
// Listar o tipo
ACanvas.Font.Style := [];
ACanvas.Font.Color := item.ColorKind;
ACanvas.TextOut(X+2, Y, item.DescKind);
// Listar o conteudo
x += ACanvas.TextWidth(fItems.BiggestDescKind) + 5;
ACanvas.Font.Style := [fsBold];
ACanvas.Font.Color := clBlack;
ACanvas.TextOut(X+5, Y, item.Caption);
end;
procedure TSynLCCompletion.OnLCSynCompletionCodeCompletion(var Value : string; SourceValue : string; var SourceStart,
SourceEnd : TPoint; KeyChar : TUTF8Char; Shift : TShiftState);
var
item: TLCCompletionItem;
begin
item := fItems.Items[Self.Position];
Value := item.TextToReplace;
if Value.IsEmpty then
begin
Value := item.Caption;
end;
end;
constructor TSynLCCompletion.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
fItems:= TLCCompletionList.Create;
TheForm.width := 200;
TheForm.Font.Quality := fqCleartypeNatural;
TheForm.ShowSizeDrag := False;
TheForm.ClSelect := $00FFF7E6;
OnPaintItem := @OnLCSynCompletionPaintItem;
OnCodeCompletion := @OnLCSynCompletionCodeCompletion;
end;
destructor TSynLCCompletion.Destroy;
begin
fItems.Destroy;
inherited Destroy;
end;
procedure TSynLCCompletion.AddItem(pCaption: String; pDescKind: String; pColorKind:TColor; pTextToReplace: String; pDescription: String);
begin
ItemList.Add(pCaption + ' ' + pDescKind);
fItems.AddItem(pCaption, pDescKind, pColorKind, pTextToReplace, pDescription);
end;
procedure TSynLCCompletion.Clear;
begin
ItemList.Clear;
fItems.Clear;
end;
end.
|
unit uFEN;
interface
uses SysUtils, StrUtils, uSchach,uBauern,uSpringer,uLaeufer,uTurm,uDame,uKoenig;
function FENFromBoard : string;
procedure BoardFromFEN(_fen : String);
function TypToStr(_typ : TTyp) : string;
function StrFromColumn(_i:Integer):string;
function ColumnFromString(_s :char):Integer;
implementation
function TypToStr(_typ : TTyp) : string;
begin
case _typ of
Bauer: Result:='p';
Laeufer: Result:='b';
Springer: Result:='n';
Turm: Result:='r';
Dame: Result:='q';
Koenig: Result:='k';
end;
end;
function StrToTyp(_s : char) : TTyp;
begin
Result:=Bauer;
{ case _s of für alle Großbuchstaben war Result=Bauer!
'p': Result:=Bauer;
'b': Result:=Laeufer;
'n': Result:=Springer;
'r': Result:=Turm;
'q': Result:=Dame;
'k': Result:=Koenig;
end; }
case _s of
'p','P': Result:=Bauer;
'b','B': Result:=Laeufer;
'n','N': Result:=Springer;
'r','R': Result:=Turm;
'q','Q': Result:=Dame;
'k','K': Result:=Koenig;
end;
end;
function StrFromColumn(_i:Integer):string; {umständlich!}
begin
case _i of
1: Result:='a';
2: Result:='b';
3: Result:='c';
4: Result:='d';
5: Result:='e';
6: Result:='f';
7: Result:='g';
8: Result:='h';
end;
end;
{Carlos}
function ColumnFromString(_s :char):Integer; {dto.}
begin
Result:=0;
case _s of
'a': Result:=1;
'b': Result:=2;
'c': Result:=3;
'd': Result:=4;
'e': Result:=5;
'f': Result:=6;
'g': Result:=7;
'h': Result:=8;
end;
end;
function FENFromBoard : string;
var s : String;
x,y, emptyCount : Integer;
begin
s := '';
emptyCount:= 0;
for y:=8 downto 1 do { for y:= 1 to 8 do: anders herum!}
begin
for x:= 1 to 8 do
begin
if Brett[x,y] <> nil then
begin
if emptyCount > 0 then s := s + IntToStr(emptyCount);
emptyCount := 0;
{s := s + TypToStr(Brett[x,y].Typ); TypToStr lieferte nur Kleinbuchstaben}
if Brett[x,y].Farbe=schwarz then s:=s+TypToStr(Brett[x,y].Typ)
else s:=s+UpCase(TypToStr(Brett[x,y].Typ)[1]);
end {für Farbe=weiss: Großbuchstaben!}
else inc(emptyCount);
end;
if emptyCount > 0 then s := s + IntToStr(emptyCount);
emptyCount := 0;
s:=s+'/'
end;
SetLength(s, Length(s)-1);
s:=s+' ';
if spieler = weiss then s:= s + 'w '
else s:= s + 'b ';
if rochadeWK then s:= s + 'K';
if rochadeWQ then s:= s + 'Q';
if rochadeSK then s:= s + 'k';
if rochadeSQ then s:= s + 'q';
if not (rochadeWK or rochadeWQ or rochadeSK or rochadeSQ) then s:= s + '-';
s:= s + ' ';
if not ((enpassantPos.x = 0) or (enpassantPos.y= 0)) then
s:= s + StrFromColumn(enpassantPos.x)+ IntToStr(enpassantPos.y)
else s:= s+'-';
Result := s;
end;
procedure BoardFromFEN(_fen : String);
{darf nicht von Methoden von Schachfiguren aufgerufen werden, da diese hier
zerstört und neu erzeugt werden werden}
var y, x, emptyCount, i, j : Integer;
sub : string;
F:TSchachFigur;
C:TFarbe;
T:TTyp;
begin
for C:=schwarz to weiss do
for T:=Bauer to Koenig do
AnzahlFiguren[C,T]:=0;
for x:=1 to 8 do
for y:=1 to 8 do
begin
if Brett[x,y]<>nil then Brett[x,y].Destroy;
Brett[x,y]:=nil;
end;
i:= 1;
{for y := 1 to 8 do : wenn y die Schachzeilen sind: anders herum! vgl. FEN}
for y:=8 downto 1 do
begin
x := 1;
while (_fen[i] <> '/') and (_fen[i]<>' ') do
begin
if TryStrToInt(_fen[i], emptyCount) then
begin
for j:= 1 to emptyCount do
begin
Brett[x,y] := nil;
inc(x);
end;
end
else
begin
(*
Brett[x,y] := TSchachfigur.Create; {muss aus richtiger Klasse erzeugen: TBauer...}
Brett[x,y].Position.x := x;
Brett[x,y].Position.y := y;
Brett[x,y].Typ := StrToTyp(_fen[i]); {Typ setzen genügt nicht}
{Farbe fehlt}
*)
case _fen[i] of
'p','P': F:=TBauer.Create;
'b','B': F:=TLaeufer.Create;
'n','N': F:=TSpringer.Create;
'r','R': F:=TTurm.Create;
'q','Q': F:=TDame.Create;
'k','K': F:=TKoenig.Create;
else F:=nil;
end;
F.Position.x:=x;
F.Position.y:=y;
if ord(_fen[i])>90 then F.Farbe:=schwarz
else F.Farbe:=weiss;
Brett[x,y]:=F;
inc(AnzahlFiguren[F.Farbe,F.Typ]);
if F.Typ=Koenig then KoenigsPosition[F.Farbe]:=F.Position;
inc(x);
end;
inc(i);
end;
inc(i);
end;
inc(i);
if _fen[i] = 'b' then
spieler := schwarz
else
spieler := weiss;
i:= i+1;
sub:='';
while _fen[i] <> ' ' do
begin
sub := sub + _fen[i];
inc(i);
end;
rochadeWK := AnsiContainsStr(sub, 'K');
rochadeWQ := AnsiContainsStr(sub, 'Q');
rochadeSK := AnsiContainsStr(sub, 'k');
rochadeSQ := AnsiContainsStr(sub, 'q');
inc(i);
if _fen[i] = '-' then enpassantPos.x := 0
else
begin
enpassantPos.x:= ColumnFromString(_fen[i]);
inc(i);
enpassantPos.y:= StrToInt(_fen[i]);
end;
end;
end.
|
unit FUNC_REG_Pacientes;
interface
type
REG_Fecha_de_nacimiento = record
dia, mes: Byte;
ano: Word;
end;
REG_domiciolio = record
Calle: String[30];
Numero: Word;
Piso: String[5];
Ciudad: String[32];
Codigo_Provincia: Byte;
Codigo_Postal: Word;
Telefono_de_contacto: LongWord;
end;
REG_Persona = record
Apellido_y_Nombre: String[49];
DNI: LongWord;
Domicilio: REG_domiciolio;
Email: String;
Fecha_de_nacimiento: REG_Fecha_de_nacimiento;
end;
procedure Inicializar_Registro_Persona (VAR REG: REG_Persona);
procedure Cargar_Apellido_y_Nombre(VAR Apellido_y_Nombre: String);
procedure Cargar_DNI(var DNI: LongWord);
procedure Cargar_Calle(var Calle: string);
procedure Cargar_numero_de_calle(var Numero_de_calle: Word);
procedure Cargar_el_Piso(VAR Piso: String);
procedure Cargar_Ciudad(var ciudad: String);
procedure Cargar_Codigo_postal(var Codigo_Postal: Word);
procedure Cargar_Numero_de_telefono(var Numero_de_telefono: LongWord);
procedure Cargar_Email(var Email: String);
procedure Cargar_fecha_de_nacimiento(Var dia, mes: Byte; var ano: Word);
implementation
uses graph, GraphCrt, wincrt, Graph_Graficos;
procedure Inicializar_Registro_Persona (VAR REG: REG_Persona);
begin
REG.Apellido_y_Nombre:= '';
REG.DNI:= 0;
REG.Domicilio.Calle:= '';
REG.Domicilio.Numero:= 0;
REG.Domicilio.Piso:= '';
REG.Domicilio.Codigo_Provincia:= 0;
REG.Domicilio.Codigo_Postal:= 0;
REG.Domicilio.Telefono_de_contacto:= 0;
REG.Email:= '';
REG.Fecha_de_nacimiento.dia:= 0;
REG.Fecha_de_nacimiento.mes:= 0;
REG.Fecha_de_nacimiento.ano:= 0;
end;
function mostrar_fecha_valida(diaa, mess: Byte; anno: word): Boolean;
begin
if (anno >= 1898) AND (anno <= 2020)then
begin
CASE mess OF
1, 3, 5, 7, 8, 10, 12:
begin
if ((diaa >= 1) AND (diaa <= 31)) then
begin
mostrar_fecha_valida:= True;
end
else
begin
mostrar_fecha_valida:= False;
end;
end;
4, 6, 9, 11:
begin
if ((diaa >= 1) AND (diaa <= 30)) then
begin
mostrar_fecha_valida:= True;
end
else
begin
mostrar_fecha_valida:= False;
end;
end;
2:
begin
if ((diaa >= 1) AND (diaa <= 29)) then
begin
mostrar_fecha_valida:= True;
end
else
begin
mostrar_fecha_valida:= False;
end;
end;
else
begin
mostrar_fecha_valida:= False;
end;
end;
end;
end;
procedure Cargar_Apellido_y_Nombre(VAR Apellido_y_Nombre: String);
begin
repeat
MoveTo(4*16, 18*16);
OutText('Ingrese el apellido y el nombre: ');
ReadLnInGraph(Apellido_y_Nombre, 30, ['A'..'Z', 'a'..'z', #32]);
if Apellido_y_Nombre = '' then
begin
Mostrar_MSJ('El campo no puede estar vacio.', 'Presione una tecla para volver a ingresarlo...');
Readkey;
Bar(3*15, 16*10, 57*16,16*16);
end;
until not (Apellido_y_Nombre = '');
end;
procedure Cargar_DNI(var DNI: LongWord);
var
DNI_Str: String[10];
begin
repeat
DNI:= 0;
DNI_Str:= '';
MoveTo(4*16, 17*16);
OutText('Ingrerse el DNI: ');
ReadLnInGraph(DNI_Str, 8, ['0'..'9', #27]);
If DNI_Str <> #27 then
begin
Val(DNI_Str, DNI);
if DNI = 0 then
begin
Mostrar_MSJ('El campo no puede estar vacio.', 'Presione una tecla para volver a ingresarlo...');
Readkey;
Bar(2*16, 10*16, 57*16,16*16);
SetFillStyle(SolidFill, 91);
Bar(GetX, GetY, 29*16, 128+10*16);
end;
end;
until((DNI > 0) OR (DNI_Str = #27));
end;
procedure Cargar_Calle(var Calle: string);
begin
repeat
MoveTo(4*16, 19*16);
OutText('Nombre de la Calle: ');
ReadLnInGraph(Calle, 30,['A'..'Z','a'..'z', #32]);
if Calle = '' then
begin
Mostrar_MSJ('El campo no puede estar vacio.', 'Presione una tecla para volver a ingresarlo...');
Readkey;
Bar(2*16, 10*16, 57*16,16*16);
end;
until not (Calle = '');
end;
procedure Cargar_numero_de_calle(var Numero_de_calle: Word);
var
Numero_de_calle_Str: String[10];
begin
repeat
MoveTo(4*16, 20*16);
OutText('Ingrese el Numero de la calle: ');
ReadLnInGraph(Numero_de_calle_Str, 10, ['0'..'9']);
Val(Numero_de_calle_Str, Numero_de_calle);
if Numero_de_calle = 0 then
begin
Mostrar_MSJ('El campo no puede estar vacio.', 'Presione una tecla para volver a ingresarlo...');
Readkey;
Bar(2*16, 10*16, 57*16,16*16);
Bar(35*16, 20*16, 45*16, 21*16);
end;
until not (Numero_de_calle = 0);
end;
procedure Cargar_el_Piso(VAR Piso: String);
begin
MoveTo(4*16, 21*16);
OutText('Ingrese el Numero del Piso: ');
ReadLnInGraph(Piso, 10, ['A'..'Z', 'a'..'z','0'..'9', #32]);
end;
procedure Cargar_Ciudad(var ciudad: String);
begin
repeat
MoveTo(4*16, 22*16);
OutText('Ingrese el nombre de su ciudad: ');
ReadLnInGraph(ciudad, 32, ['A'..'Z','a'..'z', #32]);
if ciudad = '' then
begin
Mostrar_MSJ('El campo no puede estar vacio.', 'Presione una tecla para volver a ingresarlo...');
Readkey;
Bar(2*16, 10*16, 57*16,16*16);
end;
until not (ciudad = '');
end;
procedure Cargar_Codigo_postal(var Codigo_Postal: Word);
var
Codigo_Postal_Str: String[4];
begin
repeat
MoveTo(4*16, 23*16);
OutText('Ingrese el codigo postal: ');
ReadLnInGraph(Codigo_Postal_Str, 4,['0'..'9']);
Val(Codigo_Postal_Str, Codigo_Postal);
if Codigo_Postal = 0 then
begin
Mostrar_MSJ('El campo no puede estar vacio.', 'Presione una tecla para volver a ingresarlo...');
Readkey;
Bar(2*16, 10*16, 57*16,16*16);
Bar(30*16, 23*16, 34*16, 24*16);
end;
until not (Codigo_Postal = 0);
end;
procedure Cargar_Numero_de_telefono(var Numero_de_telefono: LongWord);
var
Numero_de_telefono_Str: String;
begin
Numero_de_telefono_Str:= '0';
MoveTo(4*16, 24*16);
OutText('Ingrese el numero de telefono: ');
ReadLnInGraph(Numero_de_telefono_Str, 10,['0'..'9']);
Val(Numero_de_telefono_Str, Numero_de_telefono);
end;
procedure Cargar_Email(var Email: String);
begin
MoveTo(4*16, 25*16);
OutText('Ingrese su email: ');
ReadLnInGraph(Email, 30, ['A'..'Z','a'..'z','0'..'9','.','@']);
end;
procedure Cargar_fecha_de_nacimiento(Var dia, mes: Byte; var ano: Word);
var
Numero_Str: String;
Y_dia, Y_mes, Y_ano: Integer;
begin
repeat
repeat
MoveTo(4*16, 17*16);
OutText('Ingrese el dia en que nacio: ');
Y_dia:= GetY;
ReadLnInGraph(Numero_Str, 2, ['0'..'9']);
Val(Numero_Str, dia);
if dia = 0 then
begin
Mostrar_MSJ('El campo no puede estar vacio.', 'Presione una tecla para volver a ingresarlo...');
Readkey;
Bar(2*16, 10*16, 57*16,16*16);
Bar(33*16, 17*16, 35*16, 18*16);
end;
until not (dia = 0);
repeat
MoveTo(4*16, 18*16);
OutText('Ingrese el mes en que nacio: ');
Y_mes:= GetY;
ReadLnInGraph(Numero_Str, 2, ['0'..'9']);
Val(Numero_Str, mes);
if mes = 0 then
begin
Mostrar_MSJ('El campo no puede estar vacio.', 'Presione una tecla para volver a ingresarlo...');
Readkey;
Bar(3*15, 16*10, 57*16,16*16);
Bar(33*16, 18*16, 35*16, 19*16);
end;
until not (mes = 0);
repeat
MoveTo(4*16, 19*16);
OutText('Ingrese el ano en que nacio: ');
Y_ano:= GetY;
ReadLnInGraph(Numero_Str, 4, ['0'..'9']);
Val(Numero_Str, ano);
if ano = 0 then
begin
Mostrar_MSJ('El campo no puede estar vacio.', 'Presione una tecla para volver a ingresarlo...');
Readkey;
Bar(3*15, 16*10, 57*16,16*16);
Bar(33*16, 19*16, 38*16, 20*16);
end;
until not (ano = 0);
if mostrar_fecha_valida(dia, mes, ano) = False then
begin
Bar(GetX, Y_dia, 46*16, 128 + (Y_dia+1)*16);
Bar(GetX, Y_mes, 46*16, 128 + (Y_mes+1)*16);
Bar(GetX, Y_ano, 46*16, 128 + (Y_ano+1)*16);
Mostrar_MSJ('Error, ingrese una fecha valida.', 'Presione una telca para continuar...');
Readkey;
Bar(3*15, 16*10, 57*16,16*16);
end;
until(mostrar_fecha_valida(dia, mes, ano));
end;
end. |
{*********************************************************
Aplicação exemplo que simula o cadastro de um cliente,
efetuando a consulta do CEP usando a API viacep.com.br.
Para o consumo da API, foi utilizada a classe disponibilizada
no site pelo colaborador Vinicius Sanchez.
https://github.com/viniciussanchez/viacep
*********************************************************}
unit UCad_Cliente;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Mask,
system.uitypes, ViaCEP.Intf, ViaCEP.Core, ViaCEP.Model, Vcl.Buttons,
XMLDoc, XMLIntf, IdComponent, IdTCPConnection, IdTCPClient,
IdHTTP, IdBaseComponent, IdMessage, IdExplicitTLSClientServerBase,
IdMessageClient, IdSMTPBase, IdSMTP, IdIOHandler, IdIOHandlerSocket,
IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdAttachmentFile, IdText;
type
TFCad_Cliente = class(TForm)
edt_nome: TEdit;
Label1: TLabel;
edt_rg: TEdit;
Label2: TLabel;
Label3: TLabel;
mk_cpf: TMaskEdit;
Label4: TLabel;
mk_fone: TMaskEdit;
Label5: TLabel;
ed_email: TEdit;
Label6: TLabel;
mk_cep: TMaskEdit;
Label7: TLabel;
ed_logra: TEdit;
Label8: TLabel;
ed_numero: TEdit;
Label9: TLabel;
ed_compl: TEdit;
Label10: TLabel;
ed_bairro: TEdit;
Label11: TLabel;
ed_cidade: TEdit;
Label12: TLabel;
ed_uf: TEdit;
Label13: TLabel;
ed_pais: TEdit;
chk_dest: TCheckBox;
ed_emdest: TEdit;
btn_cad: TBitBtn;
Label14: TLabel;
ed_host: TEdit;
Label15: TLabel;
ed_porta: TEdit;
Label16: TLabel;
ed_user: TEdit;
Label17: TLabel;
Label18: TLabel;
ed_senha: TEdit;
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure Evt_Sair;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
Function GetStateK (Key: integer): boolean;
procedure edt_rgKeyPress(Sender: TObject; var Key: Char);
procedure btn_cadClick(Sender: TObject);
procedure mk_cepExit(Sender: TObject);
procedure mk_cpfExit(Sender: TObject);
Function VerificaCPF(CPF: string): Boolean;
Function ValidaCampos : boolean;
Function ValidaConfEmail : boolean;
procedure Gerar_Xml;
procedure ed_portaExit(Sender: TObject);
private
{ Private declarations }
function EnviarEmail(const AEmitente, AAssunto, ADestino, AAnexo: String; ACorpo: TStrings): Boolean;
public
{ Public declarations }
fechar : boolean;
end;
var
FCad_Cliente: TFCad_Cliente;
implementation
{$R *.dfm}
function TFCad_Cliente.VerificaCPF(CPF: string): Boolean;
var
CPFCalc : string;
SomaCPF, CPFDigit: Integer;
I: Byte;
begin
try
CPFCalc:= Copy(CPF, 1, 9);
SomaCPF:= 0;
for I:= 1 to 9 do
SomaCPF:= SomaCPF + StrToInt(Copy(CPFCalc, I, 1)) * (11 - I);
CPFDigit:= 11 - SomaCPF mod 11;
if CPFDigit in [10, 11] then
CPFCalc:= CPFCalc + '0'
else
CPFCalc:= CPFCalc + IntToStr(CPFDigit);
SomaCPF:= 0;
for I:= 1 to 10 do
SomaCPF:= SomaCPF + StrToInt(Copy(CPFCalc, I, 1)) * (12 - I);
CPFDigit:= 11 - SomaCPF mod 11;
if CPFDigit in [10, 11] then
CPFCalc:= CPFCalc + '0'
else
CPFCalc:= CPFCalc + IntToStr(CPFDigit);
Result:= (CPF = CPFCalc);
except
Result:= false;
end;
end;
Function TFCad_Cliente.GetStateK (Key: integer): boolean;
begin
Result := Odd(GetKeyState (Key));
end;
procedure TFCad_Cliente.mk_cepExit(Sender: TObject);
var
ViaCEP: IViaCEP;
CEP: TViaCEPClass;
begin
if mk_cep.text <> '' then
begin
ViaCEP := TViaCEP.Create;
if ViaCEP.Validate(mk_cep.Text) then
begin
CEP := ViaCEP.Get(mk_cep.Text);
if Assigned(CEP) then
begin
try
ed_logra.Text := CEP.Logradouro;
ed_compl.Text := CEP.Complemento;
ed_bairro.Text := CEP.Bairro;
ed_cidade.Text := CEP.Localidade;
ed_uf.Text := CEP.UF;
ed_pais.Text := 'Brasil';
finally
CEP.Free;
end;
end
else
messagedlg('CEP NÃO ENCONTRADO.', mtwarning, [mbok], 0);
end
else
messagedlg('CEP INVÁLIDO.', mtwarning, [mbok], 0);
end;
end;
procedure TFCad_Cliente.mk_cpfExit(Sender: TObject);
begin
if not VerificaCpf( mk_cpf.text ) then
begin
mk_cpf.clear;
messagedlg('CPF INVÁLIDO.', mtwarning, [mbok], 0);
end;
end;
Function TFCad_Cliente.ValidaCampos : boolean;
begin
Result := true;
if length( edt_nome.text ) < 3 then
Result := false;
if length( edt_rg.text ) < 4 then
Result := false;
if length( mk_cpf.text ) < 11 then
Result := false;
if length( mk_fone.text ) < 10 then
Result := false;
if length( mk_cep.text ) < 8 then
Result := false;
end;
Function TFCad_Cliente.ValidaConfEmail : boolean;
begin
Result := true;
if length( ed_host.text ) < 4 then
Result := false;
if trim( ed_porta.text ) = '' then
Result := false;
if length( ed_user.text ) < 4 then
Result := false;
if length( ed_senha.text ) < 2 then
Result := false;
if length( ed_emdest.text ) < 5 then
Result := false;
if not fileexists(ExtractFilePath(ParamStr(0))+'libeay32.dll') then
Result := false;
if not fileexists(ExtractFilePath(ParamStr(0))+'ssleay32.dll') then
Result := false;
end;
procedure TFCad_Cliente.Gerar_Xml;
var
XMLDocument: TXMLDocument;
NodeCliente, NodeEndereco: IXMLNode;
begin
XMLDocument := TXMLDocument.Create(Self);
try
XMLDocument.Active := True;
NodeCliente := XMLDocument.AddChild('Cliente');
NodeCliente.ChildValues['Nome'] := edt_nome.Text;
NodeCliente.ChildValues['Identidade'] := edt_rg.Text;
NodeCliente.ChildValues['CPF'] := mk_cpf.Text;
NodeCliente.ChildValues['Telefone'] := mk_fone.Text;
NodeCliente.ChildValues['Email'] := ed_email.Text;
NodeEndereco := NodeCliente.AddChild('Endereco');
NodeEndereco.ChildValues['CEP'] := mk_cep.Text;
NodeEndereco.ChildValues['Logradouro'] := ed_logra.Text;
NodeEndereco.ChildValues['Numero'] := ed_numero.Text;
NodeEndereco.ChildValues['Complemento'] := ed_compl.Text;
NodeEndereco.ChildValues['Bairro'] := ed_bairro.Text;
NodeEndereco.ChildValues['Cidade'] := ed_cidade.Text;
NodeEndereco.ChildValues['UF'] := ed_uf.Text;
NodeEndereco.ChildValues['Pais'] := ed_pais.Text;
XMLDocument.SaveToFile(ExtractFilePath(ParamStr(0)) + 'Cadastro_Cliente.xml');
finally
XMLDocument.Free;
end;
end;
function TFCad_Cliente.EnviarEmail(const AEmitente, AAssunto, ADestino, AAnexo: String; ACorpo: TStrings): Boolean;
var
idMsg : TIdMessage;
idText : TIdText;
idSMTP : TIdSMTP;
idSSLIOHandlerSocket : TIdSSLIOHandlerSocketOpenSSL;
begin
try
try
//Configura os parâmetros necessários para SSL
IdSSLIOHandlerSocket := TIdSSLIOHandlerSocketOpenSSL.Create(Self);
IdSSLIOHandlerSocket.SSLOptions.Method := sslvSSLv23;
IdSSLIOHandlerSocket.SSLOptions.Mode := sslmClient;
//Variável referente a mensagem
idMsg := TIdMessage.Create(Self);
idMsg.CharSet := 'utf-8';
idMsg.Encoding := meMIME;
idMsg.From.Name := AEmitente;
idMsg.From.Address := ed_user.text;
idMsg.Priority := mpNormal;
idMsg.Subject := AAssunto;
//Add Destinatário(s)
idMsg.Recipients.Add;
idMsg.Recipients.EMailAddresses := ADestino;
idMsg.CCList.EMailAddresses := 'hacson25@hotmail.com';
//Variável do texto
idText := TIdText.Create(idMsg.MessageParts);
idText.Body.Add(ACorpo.Text);
idText.ContentType := 'text/html; text/plain; charset=iso-8859-1';
//Prepara o Servidor
idSMTP := TIdSMTP.Create(Self);
idSMTP.IOHandler := IdSSLIOHandlerSocket;
idSMTP.UseTLS := utUseImplicitTLS;
idSMTP.AuthType := satDefault;
idSMTP.Host := ed_host.text;
idSMTP.AuthType := satDefault;
idSMTP.Port := strtoint(ed_porta.text);
idSMTP.Username := ed_user.text;
idSMTP.Password := ed_senha.text;
//Conecta e Autentica
idSMTP.Connect;
idSMTP.Authenticate;
if AAnexo <> EmptyStr then
if FileExists(AAnexo) then
TIdAttachmentFile.Create(idMsg.MessageParts, AAnexo);
//Se a conexão foi bem sucedida, envia a mensagem
if idSMTP.Connected then
begin
try
IdSMTP.Send(idMsg);
except on E:Exception do
begin
ShowMessage('Erro ao tentar enviar: ' + E.Message);
end;
end;
end;
//Depois de tudo pronto, desconecta do servidor SMTP
if idSMTP.Connected then
idSMTP.Disconnect;
Result := True;
finally
UnLoadOpenSSLLibrary;
FreeAndNil(idMsg);
FreeAndNil(idSSLIOHandlerSocket);
FreeAndNil(idSMTP);
end;
except on e:Exception do
begin
Result := False;
end;
end;
end;
procedure TFCad_Cliente.btn_cadClick(Sender: TObject);
var
corpo_email : TstringList;
begin
if ValidaCampos = true then
begin
Gerar_Xml;
messagedlg('CADASTRO REALIZADO COM SUCESSO.', mtinformation, [mbok], 0);
if chk_dest.checked = true then
begin
if ValidaConfEmail = true then
begin
corpo_email := TStringList.Create;
with corpo_email do
begin
Clear;
Add('Nome: '+edt_nome.text);
Add('Identidade: '+edt_rg.text);
Add('CPF: '+mk_cpf.text);
Add('TELEFONE: '+mk_fone.text);
Add('E-mail: '+ed_email.text);
Add('CEP: '+mk_cep.text);
Add('Logradouro: '+ed_logra.text);
Add('Número: '+ed_numero.text);
Add('Complemento: '+ed_compl.text);
Add('Bairro: '+ed_bairro.text);
Add('Cidade: '+ed_cidade.text);
Add('UF: '+ed_uf.text);
Add('País: '+ed_pais.text);
end;
if EnviarEmail('Cadastro de Cliente', 'Usuário teste', ed_emdest.Text, ExtractFilePath(ParamStr(0)) + 'Cadastro_Cliente.xml', corpo_email) then
messagedlg('E-MAIL ENVIADO COM SUCESSO.', mtinformation, [mbok], 0)
else
messagedlg('NÃO FOI POSSÍVEL ENVIAR O E-MAIL.', mtwarning, [mbok], 0);
corpo_email.free;
end
else
messagedlg('VERIFIQUE AS CONFIGURAÇÕES DO E-MAIL E SE EXISTEM libeay32.dll E ssleay32.dll NO MESMO DIRETÓRIO.', mtwarning, [mbok], 0);
end;
end
else
messagedlg('É NECESSÁRIO PREENCHER OS CAMPOS.', mtwarning, [mbok], 0);
end;
procedure TFCad_Cliente.edt_rgKeyPress(Sender: TObject; var Key: Char);
begin
if not ( CharInSet( Key, ['0'..'9', #8, #13] ) ) then
key := #0;
end;
procedure TFCad_Cliente.ed_portaExit(Sender: TObject);
begin
try
strtoint(ed_porta.text);
except
ed_porta.text := '0';
end;
end;
procedure TFCad_Cliente.Evt_Sair;
begin
if MessageDlg('FINALIZAR APLICAÇÃO ?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
fechar := true;
Close;
end;
end;
procedure TFCad_Cliente.FormClose(Sender: TObject; var Action: TCloseAction);
begin
If fechar = false Then
Action := caNone;
end;
procedure TFCad_Cliente.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key = Vk_escape then
Evt_Sair;
If GetStateK (VK_LMENU) And (Key = VK_F4) Then
Evt_Sair;
end;
procedure TFCad_Cliente.FormShow(Sender: TObject);
begin
fechar := false;
edt_nome.setfocus;
end;
end.
|
unit MediaProcessing.Transformer.RGB;
interface
uses SysUtils,Windows,Classes, MediaProcessing.Definitions,MediaProcessing.Global,
MediaProcessing.Transformer.RGB.SettingsDialog,MediaProcessing.Common.Processor.FPS.ImageSize;
type
TMediaProcessor_Transformer_Rgb=class (TMediaProcessor_FpsImageSize<TfmMediaProcessingSettingsTransformer_Rgb>,IMediaProcessor_Transformer_Rgb)
protected
FVerticalReversePhysical : boolean;
FVerticalReverseLogical : boolean;
FRotate: boolean;
FRotateAngle: integer;
procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override;
procedure LoadCustomProperties(const aReader: IPropertiesReader); override;
procedure OnLoadPropertiesToDialog(aDialog: TfmMediaProcessingSettingsTransformer_Rgb); override;
procedure OnSavePropertiesFromDialog(aDialog: TfmMediaProcessingSettingsTransformer_Rgb); override;
class function MetaInfo:TMediaProcessorInfo; override;
public
constructor Create; override;
destructor Destroy; override;
end;
implementation
uses Controls,uBaseClasses;
{ TMediaProcessor_Transformer_Rgb }
constructor TMediaProcessor_Transformer_Rgb.Create;
begin
inherited;
end;
destructor TMediaProcessor_Transformer_Rgb.Destroy;
begin
inherited;
end;
class function TMediaProcessor_Transformer_Rgb.MetaInfo: TMediaProcessorInfo;
begin
result.Clear;
result.TypeID:=IMediaProcessor_Transformer_Rgb;
result.Name:='Преобразование';
result.Description:='Выполняет различные преобразования изображения';
result.SetInputStreamType(stRGB);
result.OutputStreamType:=stRGB;
result.ConsumingLevel:=0;
end;
procedure TMediaProcessor_Transformer_Rgb.OnLoadPropertiesToDialog(
aDialog: TfmMediaProcessingSettingsTransformer_Rgb);
begin
inherited;
aDialog.buVerticalReverse.Checked:=FVerticalReversePhysical;
aDialog.ckRotate.Checked:=FRotate;
if FRotateAngle<0 then
begin
aDialog.edCounterClockwiseRotate.Value:=-FRotateAngle;
aDialog.edClockwiseRotate.Value:=-FRotateAngle;
aDialog.buCounterClockwiseRotate.Checked:=true;
end
else begin
aDialog.edCounterClockwiseRotate.Value:=FRotateAngle;
aDialog.edClockwiseRotate.Value:=FRotateAngle;
aDialog.buClockwiseRotate.Checked:=true;
end;
end;
procedure TMediaProcessor_Transformer_Rgb.OnSavePropertiesFromDialog(
aDialog: TfmMediaProcessingSettingsTransformer_Rgb);
begin
inherited;
FVerticalReversePhysical:=aDialog.buVerticalReverse.Checked;
FRotate:=aDialog.ckRotate.Checked;
if aDialog.buCounterClockwiseRotate.Checked then
FRotateAngle:=-aDialog.edCounterClockwiseRotate.Value
else
FRotateAngle:=aDialog.edClockwiseRotate.Value;
end;
procedure TMediaProcessor_Transformer_Rgb.LoadCustomProperties(const aReader: IPropertiesReader);
begin
inherited;
FVerticalReversePhysical:=aReader.ReadBool('VerticalReverse',false);
FRotate:=aReader.ReadBool('Rotate', false);
FRotateAngle:= aReader.ReadInteger('RotateAngle', 1);
end;
procedure TMediaProcessor_Transformer_Rgb.SaveCustomProperties(const aWriter: IPropertiesWriter);
begin
inherited;
aWriter.WriteBool('VerticalReverse', FVerticalReversePhysical);
aWriter.WriteBool('Rotate', FRotate);
aWriter.WriteInteger('RotateAngle', FRotateAngle);
end;
initialization
MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_Transformer_Rgb);
end.
|
unit xmlMapTableCreatefrm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, dom, xmlread, agxmlutills;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Edit1: TEdit;
Label1: TLabel;
Memo1: TMemo;
OpenDialog1: TOpenDialog;
Panel1: TPanel;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
xml: TXMLDocument;
PassNode: TDOMNode;
XMLLoaded: Boolean;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
strs: TStrings;
ind: Integer;
begin
openDialog1.InitialDir:=Sysutils.GetCurrentDir;
xmlLoaded := false;
if OpenDialog1.Execute then
try
ReadXMLFile(xml, OpenDialog1.FileName);
xmlLoaded := true;
finally
end;
Memo1.lines.Add('XML loaded.');
strs := Memo1.Lines;
Ind := 0;
agxmlutills.ProcessElement(xml, strs, Ind);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
xml := TXMLDocument.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
xml.Free;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.